repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
siddharthdangwal/qiskit-terra
[ "af34eb06f28de18ef276e1e9029c62a4e35dd6a9", "af34eb06f28de18ef276e1e9029c62a4e35dd6a9" ]
[ "qiskit/visualization/pulse/matplotlib.py", "qiskit/circuit/library/standard_gates/swap.py" ]
[ "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2019.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n# pylint: disable=invalid-name\n\n\"\"\"Matplotlib classes for pulse visualization.\"\"\"\n\nimport collections\nimport warnings\nfrom typing import Dict, List, Tuple, Callable, Union, Any\n\nimport numpy as np\n\ntry:\n from matplotlib import pyplot as plt, gridspec\n HAS_MATPLOTLIB = True\nexcept ImportError:\n HAS_MATPLOTLIB = False\n\nfrom qiskit.visualization.pulse.qcstyle import PulseStyle, SchedStyle\nfrom qiskit.visualization.pulse.interpolation import step_wise\nfrom qiskit.pulse.channels import (DriveChannel, ControlChannel,\n MeasureChannel, AcquireChannel,\n SnapshotChannel, Channel)\nfrom qiskit.pulse.commands import FrameChangeInstruction\nfrom qiskit.pulse import (Waveform, SamplePulse, FrameChange, PersistentValue, Snapshot, Play,\n Acquire, PulseError, ParametricPulse, SetFrequency, ShiftPhase,\n Instruction, ScheduleComponent, ShiftFrequency, SetPhase)\n\n\nclass EventsOutputChannels:\n \"\"\"Pulse dataset for channel.\"\"\"\n\n def __init__(self, t0: int, tf: int):\n \"\"\"Create new channel dataset.\n\n TODO: remove PV\n\n Args:\n t0: starting time of plot\n tf: ending time of plot\n \"\"\"\n self.pulses = {}\n self.t0 = t0\n self.tf = tf\n\n self._waveform = None\n self._framechanges = None\n self._setphase = None\n self._frequencychanges = None\n self._conditionals = None\n self._snapshots = None\n self._labels = None\n self.enable = False\n\n def add_instruction(self, start_time: int, instruction: Instruction):\n \"\"\"Add new pulse instruction to channel.\n\n Args:\n start_time: Starting time of instruction\n instruction: Instruction object to be added\n \"\"\"\n if instruction.command is not None:\n pulse = instruction.command\n elif isinstance(instruction, Play):\n pulse = instruction.pulse\n else:\n pulse = instruction\n if start_time in self.pulses.keys():\n self.pulses[start_time].append(pulse)\n else:\n self.pulses[start_time] = [pulse]\n\n @property\n def waveform(self) -> np.ndarray:\n \"\"\"Get waveform.\"\"\"\n if self._waveform is None:\n self._build_waveform()\n\n return self._waveform[self.t0:self.tf]\n\n @property\n def framechanges(self) -> Dict[int, FrameChangeInstruction]:\n \"\"\"Get frame changes.\"\"\"\n if self._framechanges is None:\n self._build_waveform()\n\n return self._trim(self._framechanges)\n\n @property\n def setphase(self) -> Dict[int, SetPhase]:\n \"\"\"Get the SetPhase phase values.\"\"\"\n if self._setphase is None:\n self._build_waveform()\n\n return self._trim(self._setphase)\n\n @property\n def frequencychanges(self) -> Dict[int, SetFrequency]:\n \"\"\"Get the frequency changes.\"\"\"\n if self._frequencychanges is None:\n self._build_waveform()\n\n return self._trim(self._frequencychanges)\n\n @property\n def frequencyshift(self) -> Dict[int, ShiftFrequency]:\n \"\"\"Set the frequency changes.\"\"\"\n if self._frequencychanges is None:\n self._build_waveform()\n\n return self._trim(self._frequencychanges)\n\n @property\n def conditionals(self) -> Dict[int, str]:\n \"\"\"Get conditionals.\"\"\"\n if self._conditionals is None:\n self._build_waveform()\n\n return self._trim(self._conditionals)\n\n @property\n def snapshots(self) -> Dict[int, Snapshot]:\n \"\"\"Get snapshots.\"\"\"\n if self._snapshots is None:\n self._build_waveform()\n\n return self._trim(self._snapshots)\n\n @property\n def labels(self) -> Dict[int, Union[Waveform, Acquire]]:\n \"\"\"Get labels.\"\"\"\n if self._labels is None:\n self._build_waveform()\n\n return self._trim(self._labels)\n\n def is_empty(self) -> bool:\n \"\"\"Return if pulse is empty.\n\n Returns:\n bool: if the channel has nothing to plot\n \"\"\"\n if (any(self.waveform) or self.framechanges or self.setphase or\n self.conditionals or self.snapshots):\n return False\n\n return True\n\n def to_table(self, name: str) -> List[Tuple[int, str, str]]:\n \"\"\"Get table contains.\n\n Args:\n name (str): name of channel\n\n Returns:\n A list of events in the channel\n \"\"\"\n time_event = []\n\n framechanges = self.framechanges\n setphase = self.setphase\n conditionals = self.conditionals\n snapshots = self.snapshots\n frequencychanges = self.frequencychanges\n\n for key, val in framechanges.items():\n data_str = 'shift phase: %.2f' % val\n time_event.append((key, name, data_str))\n for key, val in setphase.items():\n data_str = 'set phase: %.2f' % val\n time_event.append((key, name, data_str))\n for key, val in conditionals.items():\n data_str = 'conditional, %s' % val\n time_event.append((key, name, data_str))\n for key, val in snapshots.items():\n data_str = 'snapshot: %s' % val\n time_event.append((key, name, data_str))\n for key, val in frequencychanges.items():\n data_str = 'frequency: %.4e' % val\n time_event.append((key, name, data_str))\n\n return time_event\n\n def _build_waveform(self):\n \"\"\"Create waveform from stored pulses.\n \"\"\"\n self._framechanges = {}\n self._setphase = {}\n self._frequencychanges = {}\n self._conditionals = {}\n self._snapshots = {}\n self._labels = {}\n fc = 0\n pv = np.zeros(self.tf + 1, dtype=np.complex128)\n wf = np.zeros(self.tf + 1, dtype=np.complex128)\n last_pv = None\n for time, commands in sorted(self.pulses.items()):\n if time > self.tf:\n break\n tmp_fc = 0\n tmp_set_phase = 0\n tmp_sf = None\n for command in commands:\n if isinstance(command, (FrameChange, ShiftPhase)):\n tmp_fc += command.phase\n pv[time:] = 0\n elif isinstance(command, SetPhase):\n tmp_set_phase = command.phase\n pv[time:] = 0\n elif isinstance(command, SetFrequency):\n tmp_sf = command.frequency\n elif isinstance(command, ShiftFrequency):\n tmp_sf = command.frequency\n elif isinstance(command, Snapshot):\n self._snapshots[time] = command.name\n if tmp_fc != 0:\n self._framechanges[time] = tmp_fc\n fc += tmp_fc\n if tmp_set_phase != 0:\n self._setphase[time] = tmp_set_phase\n fc = tmp_set_phase\n if tmp_sf is not None:\n self._frequencychanges[time] = tmp_sf\n for command in commands:\n if isinstance(command, PersistentValue):\n pv[time:] = np.exp(1j*fc) * command.value\n last_pv = (time, command)\n break\n\n for command in commands:\n duration = command.duration\n tf = min(time + duration, self.tf)\n if isinstance(command, ParametricPulse):\n command = command.get_sample_pulse()\n if isinstance(command, (Waveform, SamplePulse)):\n wf[time:tf] = np.exp(1j*fc) * command.samples[:tf-time]\n pv[time:] = 0\n self._labels[time] = (tf, command)\n if last_pv is not None:\n pv_cmd = last_pv[1]\n self._labels[last_pv[0]] = (time, pv_cmd)\n last_pv = None\n\n elif isinstance(command, Acquire):\n wf[time:tf] = np.ones(tf - time)\n self._labels[time] = (tf, command)\n self._waveform = wf + pv\n\n def _trim(self, events: Dict[int, Any]) -> Dict[int, Any]:\n \"\"\"Return events during given `time_range`.\n\n Args:\n events: time and operation of events.\n\n Returns:\n Events within the specified time range.\n \"\"\"\n events_in_time_range = {}\n\n for k, v in events.items():\n if self.t0 <= k <= self.tf:\n events_in_time_range[k] = v\n\n return events_in_time_range\n\n\nclass SamplePulseDrawer:\n \"\"\"A class to create figure for sample pulse.\"\"\"\n\n def __init__(self, style: PulseStyle):\n \"\"\"Create new figure.\n\n Args:\n style: Style sheet for pulse visualization.\n \"\"\"\n self.style = style or PulseStyle()\n\n def draw(self, pulse: Waveform,\n dt: float = 1.0,\n interp_method: Callable = None,\n scale: float = 1, scaling: float = None):\n \"\"\"Draw figure.\n\n Args:\n pulse: Waveform to draw.\n dt: time interval.\n interp_method: interpolation function.\n scale: Relative visual scaling of waveform amplitudes.\n scaling: Deprecated, see `scale`.\n\n Returns:\n matplotlib.figure.Figure: A matplotlib figure object of the pulse envelope.\n \"\"\"\n if scaling is not None:\n warnings.warn('The parameter \"scaling\" is being replaced by \"scale\"',\n DeprecationWarning, 3)\n scale = scaling\n # If these self.style.dpi or self.style.figsize are None, they will\n # revert back to their default rcParam keys.\n figure = plt.figure(dpi=self.style.dpi, figsize=self.style.figsize)\n\n interp_method = interp_method or step_wise\n\n ax = figure.add_subplot(111)\n ax.set_facecolor(self.style.bg_color)\n\n samples = pulse.samples\n time = np.arange(0, len(samples) + 1, dtype=float) * dt\n\n time, re, im = interp_method(time, samples, self.style.num_points)\n\n # plot\n ax.fill_between(x=time, y1=re, y2=np.zeros_like(time),\n facecolor=self.style.wave_color[0], alpha=0.3,\n edgecolor=self.style.wave_color[0], linewidth=1.5,\n label='real part')\n ax.fill_between(x=time, y1=im, y2=np.zeros_like(time),\n facecolor=self.style.wave_color[1], alpha=0.3,\n edgecolor=self.style.wave_color[1], linewidth=1.5,\n label='imaginary part')\n\n ax.set_xlim(0, pulse.duration * dt)\n if scale:\n ax.set_ylim(-1/scale, 1/scale)\n else:\n v_max = max(max(np.abs(re)), max(np.abs(im)))\n ax.set_ylim(-1.2 * v_max, 1.2 * v_max)\n\n bbox = ax.get_position()\n\n # This check is here for backwards compatibility. Before, the check was around\n # the suptitle line, however since the font style can take on a type of None\n # we need to unfortunately check both the type and the value of the object.\n if isinstance(self.style.title_font_size, int) and self.style.title_font_size > 0:\n figure.suptitle(str(pulse.name),\n fontsize=self.style.title_font_size,\n y=bbox.y1 + 0.02,\n va='bottom')\n\n return figure\n\n\nclass ScheduleDrawer:\n \"\"\"A class to create figure for schedule and channel.\"\"\"\n\n def __init__(self, style: SchedStyle):\n \"\"\"Create new figure.\n\n Args:\n style: Style sheet for pulse schedule visualization.\n \"\"\"\n self.style = style or SchedStyle()\n\n def _build_channels(self, schedule: ScheduleComponent,\n channels: List[Channel],\n t0: int, tf: int,\n show_framechange_channels: bool = True\n ) -> Tuple[Dict[Channel, EventsOutputChannels],\n Dict[Channel, EventsOutputChannels],\n Dict[Channel, EventsOutputChannels]]:\n \"\"\"Create event table of each pulse channels in the given schedule.\n\n Args:\n schedule: Schedule object to plot.\n channels: Channels to plot.\n t0: Start time of plot.\n tf: End time of plot.\n show_framechange_channels: Plot channels only with FrameChanges.\n\n Returns:\n channels: All channels.\n output_channels: All (D, M, U, A) channels.\n snapshot_channels: Snapshots.\n \"\"\"\n # prepare waveform channels\n drive_channels = collections.OrderedDict()\n measure_channels = collections.OrderedDict()\n control_channels = collections.OrderedDict()\n acquire_channels = collections.OrderedDict()\n snapshot_channels = collections.OrderedDict()\n _channels = set()\n if show_framechange_channels:\n _channels.update(schedule.channels)\n # take channels that do not only contain framechanges\n else:\n for start_time, instruction in schedule.instructions:\n if not isinstance(instruction, (FrameChangeInstruction, ShiftPhase, SetPhase)):\n _channels.update(instruction.channels)\n\n _channels.update(channels)\n for chan in _channels:\n if isinstance(chan, DriveChannel):\n try:\n drive_channels[chan] = EventsOutputChannels(t0, tf)\n except PulseError:\n pass\n elif isinstance(chan, MeasureChannel):\n try:\n measure_channels[chan] = EventsOutputChannels(t0, tf)\n except PulseError:\n pass\n elif isinstance(chan, ControlChannel):\n try:\n control_channels[chan] = EventsOutputChannels(t0, tf)\n except PulseError:\n pass\n elif isinstance(chan, AcquireChannel):\n try:\n acquire_channels[chan] = EventsOutputChannels(t0, tf)\n except PulseError:\n pass\n elif isinstance(chan, SnapshotChannel):\n try:\n snapshot_channels[chan] = EventsOutputChannels(t0, tf)\n except PulseError:\n pass\n\n output_channels = {**drive_channels, **measure_channels,\n **control_channels, **acquire_channels}\n channels = {**output_channels, **snapshot_channels}\n # sort by index then name to group qubits together.\n output_channels = collections.OrderedDict(sorted(output_channels.items(),\n key=lambda x: (x[0].index, x[0].name)))\n channels = collections.OrderedDict(sorted(channels.items(),\n key=lambda x: (x[0].index, x[0].name)))\n\n for start_time, instruction in schedule.instructions:\n for channel in instruction.channels:\n if channel in output_channels:\n output_channels[channel].add_instruction(start_time, instruction)\n elif channel in snapshot_channels:\n snapshot_channels[channel].add_instruction(start_time, instruction)\n return channels, output_channels, snapshot_channels\n\n @staticmethod\n def _scale_channels(output_channels: Dict[Channel, EventsOutputChannels],\n scale: float,\n channel_scales: Dict[Channel, float] = None,\n channels: List[Channel] = None,\n plot_all: bool = False) -> Dict[Channel, float]:\n \"\"\"Count number of channels that contains any instruction to show\n and find scale factor of that channel.\n\n Args:\n output_channels: Event table of channels to show.\n scale: Global scale factor.\n channel_scales: Channel specific scale factors.\n channels: Specified channels to plot.\n plot_all: Plot empty channel.\n\n Returns:\n scale_dict: Scale factor of each channel.\n \"\"\"\n # count numbers of valid waveform\n scale_dict = {chan: 0 for chan in output_channels.keys()}\n for channel, events in output_channels.items():\n v_max = 0\n if channels:\n if channel in channels:\n waveform = events.waveform\n v_max = max(v_max,\n max(np.abs(np.real(waveform))),\n max(np.abs(np.imag(waveform))))\n events.enable = True\n else:\n if not events.is_empty() or plot_all:\n waveform = events.waveform\n v_max = max(v_max,\n max(np.abs(np.real(waveform))),\n max(np.abs(np.imag(waveform))))\n events.enable = True\n\n scale_val = channel_scales.get(channel, scale)\n if not scale_val:\n # when input schedule is empty or comprises only frame changes,\n # we need to overwrite maximum amplitude by a value greater than zero,\n # otherwise auto axis scaling will fail with zero division.\n v_max = v_max or 1\n scale_dict[channel] = 1 / v_max\n else:\n scale_dict[channel] = scale_val\n\n return scale_dict\n\n def _draw_table(self, figure,\n channels: Dict[Channel, EventsOutputChannels],\n dt: float):\n \"\"\"Draw event table if events exist.\n\n Args:\n figure (matpotlib.figure.Figure): Figure object\n channels: Dictionary of channel and event table\n dt: Time interval\n\n Returns:\n Tuple[matplotlib.axes.Axes]: Axis objects for table and canvas of pulses.\n \"\"\"\n # create table\n table_data = []\n if self.style.use_table:\n for channel, events in channels.items():\n if events.enable:\n table_data.extend(events.to_table(channel.name))\n table_data = sorted(table_data, key=lambda x: x[0])\n\n # plot table\n if table_data:\n # table area size\n ncols = self.style.table_columns\n nrows = int(np.ceil(len(table_data)/ncols))\n max_size = self.style.max_table_ratio * figure.get_size_inches()[1]\n max_rows = np.floor(max_size/self.style.fig_unit_h_table/ncols)\n nrows = int(min(nrows, max_rows))\n # don't overflow plot with table data\n table_data = table_data[:int(nrows*ncols)]\n # fig size\n h_table = nrows * self.style.fig_unit_h_table\n h_waves = (figure.get_size_inches()[1] - h_table)\n\n # create subplots\n gs = gridspec.GridSpec(2, 1, height_ratios=[h_table, h_waves], hspace=0)\n tb = plt.subplot(gs[0])\n ax = plt.subplot(gs[1])\n\n # configure each cell\n tb.axis('off')\n cell_value = [['' for _kk in range(ncols * 3)] for _jj in range(nrows)]\n cell_color = [self.style.table_color * ncols for _jj in range(nrows)]\n cell_width = [*([0.2, 0.2, 0.5] * ncols)]\n for ii, data in enumerate(table_data):\n # pylint: disable=unbalanced-tuple-unpacking\n r, c = np.unravel_index(ii, (nrows, ncols), order='f')\n # pylint: enable=unbalanced-tuple-unpacking\n time, ch_name, data_str = data\n # item\n cell_value[r][3 * c + 0] = 't = %s' % time * dt\n cell_value[r][3 * c + 1] = 'ch %s' % ch_name\n cell_value[r][3 * c + 2] = data_str\n table = tb.table(cellText=cell_value,\n cellLoc='left',\n rowLoc='center',\n colWidths=cell_width,\n bbox=[0, 0, 1, 1],\n cellColours=cell_color)\n table.auto_set_font_size(False)\n table.set_fontsize = self.style.table_font_size\n else:\n tb = None\n ax = figure.add_subplot(111)\n\n return tb, ax\n\n @staticmethod\n def _draw_snapshots(ax,\n snapshot_channels: Dict[Channel, EventsOutputChannels],\n y0: float) -> None:\n \"\"\"Draw snapshots to given mpl axis.\n\n Args:\n ax (matplotlib.axes.Axes): axis object to draw snapshots.\n snapshot_channels: Event table of snapshots.\n y0: vertical position to draw the snapshots.\n \"\"\"\n for events in snapshot_channels.values():\n snapshots = events.snapshots\n if snapshots:\n for time in snapshots:\n ax.annotate(s=u\"\\u25D8\", xy=(time, y0), xytext=(time, y0+0.08),\n arrowprops={'arrowstyle': 'wedge'}, ha='center')\n\n def _draw_framechanges(self, ax,\n fcs: Dict[int, FrameChangeInstruction],\n y0: float) -> bool:\n \"\"\"Draw frame change of given channel to given mpl axis.\n\n Args:\n ax (matplotlib.axes.Axes): axis object to draw frame changes.\n fcs: Event table of frame changes.\n y0: vertical position to draw the frame changes.\n \"\"\"\n for time in fcs.keys():\n ax.text(x=time, y=y0, s=r'$\\circlearrowleft$',\n fontsize=self.style.icon_font_size,\n ha='center', va='center')\n\n def _draw_frequency_changes(self, ax,\n sf: Dict[int, SetFrequency],\n y0: float) -> bool:\n \"\"\"Draw set frequency of given channel to given mpl axis.\n\n Args:\n ax (matplotlib.axes.Axes): axis object to draw frame changes.\n sf: Event table of set frequency.\n y0: vertical position to draw the frame changes.\n \"\"\"\n for time in sf.keys():\n ax.text(x=time, y=y0, s=r'$\\leftrightsquigarrow$',\n fontsize=self.style.icon_font_size,\n ha='center', va='center', rotation=90)\n\n def _get_channel_color(self, channel: Channel) -> str:\n \"\"\"Lookup table for waveform color.\n\n Args:\n channel: Type of channel.\n\n Return:\n Color code or name of color.\n \"\"\"\n # choose color\n if isinstance(channel, DriveChannel):\n color = self.style.d_ch_color\n elif isinstance(channel, ControlChannel):\n color = self.style.u_ch_color\n elif isinstance(channel, MeasureChannel):\n color = self.style.m_ch_color\n elif isinstance(channel, AcquireChannel):\n color = self.style.a_ch_color\n else:\n color = 'black'\n return color\n\n @staticmethod\n def _prev_label_at_time(prev_labels: List[Dict[int, Union[Waveform, Acquire]]],\n time: int) -> bool:\n \"\"\"Check overlap of pulses with pervious channels.\n\n Args:\n prev_labels: List of labels in previous channels.\n time: Start time of current pulse instruction.\n\n Returns:\n `True` if current instruction overlaps with others.\n \"\"\"\n for labels in prev_labels:\n for t0, (tf, _) in labels.items():\n if time in (t0, tf):\n return True\n return False\n\n def _draw_labels(self, ax,\n labels: Dict[int, Union[Waveform, Acquire]],\n prev_labels: List[Dict[int, Union[Waveform, Acquire]]],\n y0: float) -> None:\n \"\"\"Draw label of pulse instructions on given mpl axis.\n\n Args:\n ax (matplotlib.axes.Axes): axis object to draw labels.\n labels: Pulse labels of channel.\n prev_labels: Pulse labels of previous channels.\n y0: vertical position to draw the labels.\n \"\"\"\n for t0, (tf, cmd) in labels.items():\n if isinstance(cmd, PersistentValue):\n name = cmd.name if cmd.name else 'pv'\n elif isinstance(cmd, Acquire):\n name = cmd.name if cmd.name else 'acquire'\n else:\n name = cmd.name\n\n ax.annotate(r'%s' % name,\n xy=((t0+tf)//2, y0),\n xytext=((t0+tf)//2, y0-0.07),\n fontsize=self.style.label_font_size,\n ha='center', va='center')\n\n linestyle = self.style.label_ch_linestyle\n alpha = self.style.label_ch_alpha\n color = self.style.label_ch_color\n\n if not self._prev_label_at_time(prev_labels, t0):\n ax.axvline(t0, -1, 1, color=color,\n linestyle=linestyle, alpha=alpha)\n if not (self._prev_label_at_time(prev_labels, tf) or tf in labels):\n ax.axvline(tf, -1, 1, color=color,\n linestyle=linestyle, alpha=alpha)\n\n def _draw_channels(self, ax,\n output_channels: Dict[Channel, EventsOutputChannels],\n interp_method: Callable,\n t0: int, tf: int,\n scale_dict: Dict[Channel, float],\n label: bool = False,\n framechange: bool = True,\n frequencychange: bool = True) -> float:\n \"\"\"Draw pulse instructions on given mpl axis.\n\n Args:\n ax (matplotlib.axes.Axes): axis object to draw pulses.\n output_channels: Event table of channels.\n interp_method: Callback function for waveform interpolation.\n t0: Start time of schedule.\n tf: End time of schedule.\n scale_dict: Scale factor for each channel.\n label: When set `True` draw labels.\n framechange: When set `True` draw frame change symbols.\n frequencychange: When set `True` draw frequency change symbols.\n\n Return:\n Value of final vertical axis of canvas.\n \"\"\"\n y0 = 0\n prev_labels = []\n for channel, events in output_channels.items():\n if events.enable:\n # scaling value of this channel\n scale = 0.5 * scale_dict.get(channel, 0.5)\n # plot waveform\n waveform = events.waveform\n time = np.arange(t0, tf + 1, dtype=float)\n if waveform.any():\n time, re, im = interp_method(time, waveform, self.style.num_points)\n else:\n # when input schedule is empty or comprises only frame changes,\n # we should avoid interpolation due to lack of data points.\n # instead, it just returns vector of zero.\n re, im = np.zeros_like(time), np.zeros_like(time)\n color = self._get_channel_color(channel)\n # Minimum amplitude scaled\n amp_min = scale * abs(min(0, np.nanmin(re), np.nanmin(im)))\n # scaling and offset\n re = scale * re + y0\n im = scale * im + y0\n offset = np.zeros_like(time) + y0\n # plot\n ax.fill_between(x=time, y1=re, y2=offset,\n facecolor=color[0], alpha=0.3,\n edgecolor=color[0], linewidth=1.5,\n label='real part')\n ax.fill_between(x=time, y1=im, y2=offset,\n facecolor=color[1], alpha=0.3,\n edgecolor=color[1], linewidth=1.5,\n label='imaginary part')\n ax.plot((t0, tf), (y0, y0), color='#000000', linewidth=1.0)\n\n # plot frame changes\n fcs = events.framechanges\n if fcs and framechange:\n self._draw_framechanges(ax, fcs, y0)\n # plot frequency changes\n sf = events.frequencychanges\n if sf and frequencychange:\n self._draw_frequency_changes(ax, sf, y0 + scale)\n # plot labels\n labels = events.labels\n if labels and label:\n self._draw_labels(ax, labels, prev_labels, y0)\n prev_labels.append(labels)\n\n else:\n continue\n\n # plot label\n ax.text(x=t0, y=y0, s=channel.name,\n fontsize=self.style.axis_font_size,\n ha='right', va='center')\n # show scaling factor\n ax.text(x=t0, y=y0 - 0.1, s='x%.1f' % (2 * scale),\n fontsize=0.7*self.style.axis_font_size,\n ha='right', va='top')\n\n # change the y0 offset for removing spacing when a channel has negative values\n if self.style.remove_spacing:\n y0 -= 0.5 + amp_min\n else:\n y0 -= 1\n return y0\n\n def draw(self, schedule: ScheduleComponent,\n dt: float, interp_method: Callable,\n plot_range: Tuple[Union[int, float], Union[int, float]],\n scale: float = None,\n channel_scales: Dict[Channel, float] = None,\n plot_all: bool = True, table: bool = False,\n label: bool = False, framechange: bool = True,\n scaling: float = None, channels: List[Channel] = None,\n show_framechange_channels: bool = True):\n \"\"\"Draw figure.\n\n Args:\n schedule: schedule object to plot.\n dt: Time interval of samples. Pulses are visualized in the unit of\n cycle time if not provided.\n interp_method: Interpolation function. See example.\n Interpolation is disabled in default.\n See `qiskit.visualization.pulse.interpolation` for more information.\n plot_range: A tuple of time range to plot.\n scale: Scaling of waveform amplitude. Pulses are automatically\n scaled channel by channel if not provided.\n channel_scales: Dictionary of scale factor for specific channels.\n Scale of channels not specified here is overwritten by `scale`.\n plot_all: When set `True` plot empty channels.\n table: When set `True` draw event table for supported commands.\n label: When set `True` draw label for individual instructions.\n framechange: When set `True` draw framechange indicators.\n scaling: Deprecated, see `scale`.\n channels: A list of channel names to plot.\n All non-empty channels are shown if not provided.\n show_framechange_channels: When set `True` plot channels\n with only framechange instructions.\n\n Returns:\n matplotlib.figure.Figure: A matplotlib figure object for the pulse envelope.\n\n Raises:\n VisualizationError: When schedule cannot be drawn\n \"\"\"\n if scaling is not None:\n warnings.warn('The parameter \"scaling\" is being replaced by \"scale\"',\n DeprecationWarning, 3)\n scale = scaling\n figure = plt.figure(dpi=self.style.dpi, figsize=self.style.figsize)\n\n if channels is None:\n channels = []\n interp_method = interp_method or step_wise\n\n if channel_scales is None:\n channel_scales = {}\n\n # setup plot range\n if plot_range:\n t0 = int(np.floor(plot_range[0]))\n tf = int(np.floor(plot_range[1]))\n else:\n t0 = 0\n # when input schedule is empty or comprises only frame changes,\n # we need to overwrite pulse duration by an integer greater than zero,\n # otherwise waveform returns empty array and matplotlib will be crashed.\n if channels:\n tf = schedule.ch_duration(*channels)\n else:\n tf = schedule.stop_time\n tf = tf or 1\n\n # prepare waveform channels\n (schedule_channels, output_channels,\n snapshot_channels) = self._build_channels(schedule, channels, t0, tf,\n show_framechange_channels)\n\n # count numbers of valid waveform\n scale_dict = self._scale_channels(output_channels,\n scale=scale,\n channel_scales=channel_scales,\n channels=channels,\n plot_all=plot_all)\n\n if table:\n tb, ax = self._draw_table(figure, schedule_channels, dt)\n else:\n tb = None\n ax = figure.add_subplot(111)\n\n ax.set_facecolor(self.style.bg_color)\n\n y0 = self._draw_channels(ax, output_channels, interp_method,\n t0, tf, scale_dict, label=label,\n framechange=framechange)\n\n y_ub = 0.5 + self.style.vertical_span\n y_lb = y0 + 0.5 - self.style.vertical_span\n\n self._draw_snapshots(ax, snapshot_channels, y_lb)\n\n ax.set_xlim(t0, tf)\n tick_labels = np.linspace(t0, tf, 5)\n ax.set_xticks(tick_labels)\n ax.set_xticklabels([self.style.axis_formatter % label for label in tick_labels * dt],\n fontsize=self.style.axis_font_size)\n ax.set_ylim(y_lb, y_ub)\n ax.set_yticklabels([])\n\n if tb is not None:\n bbox = tb.get_position()\n else:\n bbox = ax.get_position()\n\n # This check is here for backwards compatibility. Before, the check was around\n # the suptitle line, however since the font style can take on a type of None\n # we need to unfortunately check both the type and the value of the object.\n if isinstance(self.style.title_font_size, int) and self.style.title_font_size > 0:\n figure.suptitle(str(schedule.name),\n fontsize=self.style.title_font_size,\n y=bbox.y1 + 0.02,\n va='bottom')\n\n return figure\n", "# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Swap gate.\"\"\"\n\nimport numpy\nfrom qiskit.circuit.controlledgate import ControlledGate\nfrom qiskit.circuit.gate import Gate\nfrom qiskit.circuit.quantumregister import QuantumRegister\n\n\nclass SwapGate(Gate):\n r\"\"\"The SWAP gate.\n\n This is a symmetric and Clifford gate.\n\n **Circuit symbol:**\n\n .. parsed-literal::\n\n q_0: ─X─\n │\n q_1: ─X─\n\n **Matrix Representation:**\n\n .. math::\n\n SWAP =\n \\begin{pmatrix}\n 1 & 0 & 0 & 0 \\\\\n 0 & 0 & 1 & 0 \\\\\n 0 & 1 & 0 & 0 \\\\\n 0 & 0 & 0 & 1\n \\end{pmatrix}\n\n The gate is equivalent to a state swap and is a classical logic gate.\n\n .. math::\n\n |a, b\\rangle \\rightarrow |b, a\\rangle\n \"\"\"\n\n def __init__(self, label=None):\n \"\"\"Create new SWAP gate.\"\"\"\n super().__init__('swap', 2, [], label=label)\n\n def _define(self):\n \"\"\"\n gate swap a,b { cx a,b; cx b,a; cx a,b; }\n \"\"\"\n # pylint: disable=cyclic-import\n from qiskit.circuit.quantumcircuit import QuantumCircuit\n from .x import CXGate\n q = QuantumRegister(2, 'q')\n qc = QuantumCircuit(q, name=self.name)\n rules = [\n (CXGate(), [q[0], q[1]], []),\n (CXGate(), [q[1], q[0]], []),\n (CXGate(), [q[0], q[1]], [])\n ]\n qc.data = rules\n self.definition = qc\n\n def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None):\n \"\"\"Return a (multi-)controlled-SWAP gate.\n\n One control returns a CSWAP (Fredkin) gate.\n\n Args:\n num_ctrl_qubits (int): number of control qubits.\n label (str or None): An optional label for the gate [Default: None]\n ctrl_state (int or str or None): control state expressed as integer,\n string (e.g. '110'), or None. If None, use all 1s.\n\n Returns:\n ControlledGate: controlled version of this gate.\n \"\"\"\n if num_ctrl_qubits == 1:\n gate = CSwapGate(label=label, ctrl_state=ctrl_state)\n gate.base_gate.label = self.label\n return gate\n return super().control(num_ctrl_qubits=num_ctrl_qubits, label=label, ctrl_state=ctrl_state)\n\n def inverse(self):\n \"\"\"Return inverse Swap gate (itself).\"\"\"\n return SwapGate() # self-inverse\n\n def to_matrix(self):\n \"\"\"Return a numpy.array for the SWAP gate.\"\"\"\n return numpy.array([[1, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1]], dtype=complex)\n\n\nclass CSwapMeta(type):\n \"\"\"A Metaclass to ensure that CSwapGate and FredkinGate are of the same type.\n\n Can be removed when FredkinGate gets removed.\n \"\"\"\n @classmethod\n def __instancecheck__(mcs, inst):\n return type(inst) in {CSwapGate, FredkinGate} # pylint: disable=unidiomatic-typecheck\n\n\nclass CSwapGate(ControlledGate, metaclass=CSwapMeta):\n r\"\"\"Controlled-X gate.\n\n **Circuit symbol:**\n\n .. parsed-literal::\n\n q_0: ─X─\n │\n q_1: ─X─\n │\n q_2: ─■─\n\n\n **Matrix representation:**\n\n .. math::\n\n CSWAP\\ q_0, q_1, q_2 =\n |0 \\rangle \\langle 0| \\otimes I \\otimes I +\n |1 \\rangle \\langle 1| \\otimes SWAP =\n \\begin{pmatrix}\n 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\\\\n 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\\\\n \\end{pmatrix}\n\n .. note::\n\n In Qiskit's convention, higher qubit indices are more significant\n (little endian convention). In many textbooks, controlled gates are\n presented with the assumption of more significant qubits as control,\n which in our case would be q_2. Thus a textbook matrix for this\n gate will be:\n\n .. parsed-literal::\n\n q_0: ─■─\n │\n q_1: ─X─\n │\n q_2: ─X─\n\n .. math::\n\n CSWAP\\ q_2, q_1, q_0 =\n |0 \\rangle \\langle 0| \\otimes I \\otimes I +\n |1 \\rangle \\langle 1| \\otimes SWAP =\n \\begin{pmatrix}\n 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 \\\\\n 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\\\\n 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1 \\\\\n \\end{pmatrix}\n\n In the computational basis, this gate swaps the states of\n the two target qubits if the control qubit is in the\n :math:`|1\\rangle` state.\n\n .. math::\n |0, b, c\\rangle \\rightarrow |0, b, c\\rangle\n |1, b, c\\rangle \\rightarrow |1, c, b\\rangle\n \"\"\"\n # Define class constants. This saves future allocation time.\n _matrix1 = numpy.array([[1, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1]], dtype=complex)\n _matrix0 = numpy.array([[1, 0, 0, 0, 0, 0, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1]], dtype=complex)\n\n def __init__(self, label=None, ctrl_state=None):\n \"\"\"Create new CSWAP gate.\"\"\"\n super().__init__('cswap', 3, [], num_ctrl_qubits=1, label=label,\n ctrl_state=ctrl_state)\n self.base_gate = SwapGate()\n\n def _define(self):\n \"\"\"\n gate cswap a,b,c\n { cx c,b;\n ccx a,b,c;\n cx c,b;\n }\n \"\"\"\n # pylint: disable=cyclic-import\n from qiskit.circuit.quantumcircuit import QuantumCircuit\n from .x import CXGate, CCXGate\n q = QuantumRegister(3, 'q')\n qc = QuantumCircuit(q, name=self.name)\n rules = [\n (CXGate(), [q[2], q[1]], []),\n (CCXGate(), [q[0], q[1], q[2]], []),\n (CXGate(), [q[2], q[1]], [])\n ]\n qc.data = rules\n self.definition = qc\n\n def inverse(self):\n \"\"\"Return inverse CSwap gate (itself).\"\"\"\n return CSwapGate() # self-inverse\n\n def to_matrix(self):\n \"\"\"Return a numpy.array for the Fredkin (CSWAP) gate.\"\"\"\n if self.ctrl_state:\n return self._matrix1\n else:\n return self._matrix0\n\n\nclass FredkinGate(CSwapGate, metaclass=CSwapMeta):\n \"\"\"The deprecated CSwapGate class.\"\"\"\n\n def __init__(self):\n import warnings\n warnings.warn('The class FredkinGate is deprecated as of 0.14.0, and '\n 'will be removed no earlier than 3 months after that release date. '\n 'You should use the class CSwapGate instead.',\n DeprecationWarning, stacklevel=2)\n super().__init__()\n" ]
[ [ "numpy.unravel_index", "numpy.imag", "numpy.abs", "numpy.linspace", "numpy.arange", "numpy.nanmin", "numpy.ones", "numpy.real", "matplotlib.pyplot.subplot", "numpy.zeros_like", "matplotlib.gridspec.GridSpec", "numpy.floor", "numpy.exp", "numpy.zeros", "matplotlib.pyplot.figure" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
perimosocordiae/numpylint
[ "67e6c077b393760bffe59524ede1d4904476a1ce" ]
[ "numpylint/lintbits.py" ]
[ "import numpy as np\n\n# Dict of all the patterns with their replacements.\n# Structure:\n# name of replacement -> list of (pattern, replacement, kwargs) tuples\n\nLINTBITS = {\n 'diagonal matrix dot product': [\n # diag(x).dot(y)\n ('${diag}(${x}).dot(${y})', '((${x}) * (${y}).T).T',\n dict(diag='name=numpy.diag')),\n # dot(diag(x), y)\n ('${dot}(${diag}(${x}), ${y})', '((${x}) * (${y}).T).T',\n dict(diag='name=numpy.diag', dot='name=numpy.dot')),\n # x.dot(diag(y))\n ('${x}.dot(${diag}(${y}))', '((${x}) * (${y}))',\n dict(diag='name=numpy.diag')),\n # dot(x, diag(y))\n ('${dot}(${x}, ${diag}(${y}))', '((${x}) * (${y}))',\n dict(diag='name=numpy.diag', dot='name=numpy.dot')),\n ],\n 'inverting result of in1d': [\n # ~np.in1d(x, y)\n ('~${in1d}(${x}, ${y})', '${in1d}(${x}, ${y}, invert=True)',\n dict(in1d='name=numpy.in1d')),\n # ~np.in1d(x, y, assume_unique=z)\n ('~${in1d}(${x}, ${y}, assume_unique=${z})',\n '${in1d}(${x}, ${y}, assume_unique=${z}, invert=True)',\n dict(in1d='name=numpy.in1d')),\n ],\n}\n\nif np.lib.NumpyVersion(np.__version__) < '1.3.0':\n # this bug was fixed in numpy 1.3.0\n LINTBITS['in-place transpose'] = [\n # x += x.T\n ('${x} += ${x}.T', '${x} = ${x} + ${x}.T', dict()),\n # x += x.transpose()\n ('${x} += ${x}.transpose()', '${x} = ${x} + ${x}.T', dict()),\n ]\n" ]
[ [ "numpy.lib.NumpyVersion" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.15", "1.14", "1.17" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
vecent-don/bert4keras
[ "3c31cbbf87d6574ddad038e4ea17a941ddd027dc", "3c31cbbf87d6574ddad038e4ea17a941ddd027dc" ]
[ "bert4keras/snippets.py", "bert4keras/models.py" ]
[ "#! -*- coding: utf-8 -*-\n# 代码合集\n\nimport os, sys, six, re, json\nimport logging\nimport numpy as np\nfrom collections import defaultdict\nfrom bert4keras.backend import K, keras, tf\n\n_open_ = open\nis_py2 = six.PY2\n\nif not is_py2:\n basestring = str\n\n\ndef to_array(*args):\n \"\"\"批量转numpy的array\n \"\"\"\n results = [np.array(a) for a in args]\n if len(args) == 1:\n return results[0]\n else:\n return results\n\n\ndef is_string(s):\n \"\"\"判断是否是字符串\n \"\"\"\n return isinstance(s, basestring)\n\n\ndef strQ2B(ustring):\n \"\"\"全角符号转对应的半角符号\n \"\"\"\n rstring = ''\n for uchar in ustring:\n inside_code = ord(uchar)\n # 全角空格直接转换\n if inside_code == 12288:\n inside_code = 32\n # 全角字符(除空格)根据关系转化\n elif (inside_code >= 65281 and inside_code <= 65374):\n inside_code -= 65248\n rstring += unichr(inside_code)\n return rstring\n\n\ndef string_matching(s, keywords):\n \"\"\"判断s是否至少包含keywords中的至少一个字符串\n \"\"\"\n for k in keywords:\n if re.search(k, s):\n return True\n return False\n\n\ndef convert_to_unicode(text, encoding='utf-8', errors='ignore'):\n \"\"\"字符串转换为unicode格式(假设输入为utf-8格式)\n \"\"\"\n if is_py2:\n if isinstance(text, str):\n text = text.decode(encoding, errors=errors)\n else:\n if isinstance(text, bytes):\n text = text.decode(encoding, errors=errors)\n return text\n\n\ndef convert_to_str(text, encoding='utf-8', errors='ignore'):\n \"\"\"字符串转换为str格式(假设输入为utf-8格式)\n \"\"\"\n if is_py2:\n if isinstance(text, unicode):\n text = text.encode(encoding, errors=errors)\n else:\n if isinstance(text, bytes):\n text = text.decode(encoding, errors=errors)\n return text\n\n\nclass open:\n \"\"\"模仿python自带的open函数\n 作用:1.主要是为了同时兼容py2和py3;2.增加了索引功能,方便读取大文件。\n \"\"\"\n def __init__(\n self, name, mode='r', encoding=None, errors='strict', indexable=False\n ):\n self.name = name\n if is_py2:\n self.file = _open_(name, mode)\n else:\n self.file = _open_(name, mode, encoding=encoding, errors=errors)\n self.encoding = encoding\n self.errors = errors\n self.iterator = None\n if indexable:\n if is_string(indexable) and os.path.exists(indexable):\n self.offsets = json.load(_open_(indexable))\n else:\n self.create_indexes()\n if is_string(indexable):\n json.dump(self.offsets, _open_(indexable, 'w'))\n\n def create_indexes(self):\n print('creating indexes ...')\n self.offsets, offset = [], 0\n pbar = keras.utils.Progbar(os.path.getsize(self.name))\n while self.readline():\n self.offsets.append(offset)\n offset = self.tell()\n pbar.update(offset)\n self.seek(0)\n print('indexes created.')\n\n def __getitem__(self, key):\n self.seek(self.offsets[key])\n l = self.readline()\n if self.encoding:\n l = convert_to_unicode(l, self.encoding, self.errors)\n return l\n\n def __len__(self):\n return len(self.offsets)\n\n def __iter__(self):\n if hasattr(self, 'offsets'):\n for i in range(len(self)):\n yield self[i]\n else:\n for l in self.file:\n if self.encoding:\n l = convert_to_unicode(l, self.encoding, self.errors)\n yield l\n\n def next(self):\n if self.iterator is None:\n self.iterator = self.__iter__()\n return next(self.iterator)\n\n def __next__(self):\n return self.next()\n\n def read(self):\n text = self.file.read()\n if self.encoding:\n text = convert_to_unicode(text, self.encoding, self.errors)\n return text\n\n def readline(self):\n text = self.file.readline()\n if self.encoding:\n text = convert_to_unicode(text, self.encoding, self.errors)\n return text\n\n def readlines(self):\n if self.encoding:\n return [\n convert_to_unicode(text, self.encoding, self.errors)\n for text in self.file.readlines()\n ]\n else:\n return self.file.readlines()\n\n def write(self, text):\n if self.encoding:\n text = convert_to_str(text, self.encoding, self.errors)\n self.file.write(text)\n\n def flush(self):\n self.file.flush()\n\n def close(self):\n self.file.close()\n\n def tell(self):\n return self.file.tell()\n\n def seek(self, offset=0):\n return self.file.seek(offset)\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, tb):\n self.close()\n\n\ndef parallel_apply(\n func,\n iterable,\n workers,\n max_queue_size,\n callback=None,\n dummy=False,\n random_seeds=True\n):\n \"\"\"多进程或多线程地将func应用到iterable的每个元素中。\n 注意这个apply是异步且无序的,也就是说依次输入a,b,c,但是\n 输出可能是func(c), func(a), func(b)。\n 参数:\n callback: 处理单个输出的回调函数;\n dummy: False是多进程/线性,True则是多线程/线性;\n random_seeds: 每个进程的随机种子。\n \"\"\"\n if dummy:\n from multiprocessing.dummy import Pool, Queue\n else:\n from multiprocessing import Pool, Queue\n\n in_queue, out_queue, seed_queue = Queue(max_queue_size), Queue(), Queue()\n if random_seeds is True:\n random_seeds = [None] * workers\n elif random_seeds is None or random_seeds is False:\n random_seeds = []\n for seed in random_seeds:\n seed_queue.put(seed)\n\n def worker_step(in_queue, out_queue):\n \"\"\"单步函数包装成循环执行\n \"\"\"\n if not seed_queue.empty():\n np.random.seed(seed_queue.get())\n while True:\n i, d = in_queue.get()\n r = func(d)\n out_queue.put((i, r))\n\n # 启动多进程/线程\n pool = Pool(workers, worker_step, (in_queue, out_queue))\n\n if callback is None:\n results = []\n\n # 后处理函数\n def process_out_queue():\n out_count = 0\n for _ in range(out_queue.qsize()):\n i, d = out_queue.get()\n out_count += 1\n if callback is None:\n results.append((i, d))\n else:\n callback(d)\n return out_count\n\n # 存入数据,取出结果\n in_count, out_count = 0, 0\n for i, d in enumerate(iterable):\n in_count += 1\n while True:\n try:\n in_queue.put((i, d), block=False)\n break\n except six.moves.queue.Full:\n out_count += process_out_queue()\n if in_count % max_queue_size == 0:\n out_count += process_out_queue()\n\n while out_count != in_count:\n out_count += process_out_queue()\n\n pool.terminate()\n\n if callback is None:\n results = sorted(results, key=lambda r: r[0])\n return [r[1] for r in results]\n\n\ndef sequence_padding(inputs, length=None, value=0, seq_dims=1, mode='post'):\n \"\"\"Numpy函数,将序列padding到同一长度\n \"\"\"\n if length is None:\n length = np.max([np.shape(x)[:seq_dims] for x in inputs], axis=0)\n elif not hasattr(length, '__getitem__'):\n length = [length]\n\n slices = [np.s_[:length[i]] for i in range(seq_dims)]\n slices = tuple(slices) if len(slices) > 1 else slices[0]\n pad_width = [(0, 0) for _ in np.shape(inputs[0])]\n\n outputs = []\n for x in inputs:\n x = x[slices]\n for i in range(seq_dims):\n if mode == 'post':\n pad_width[i] = (0, length[i] - np.shape(x)[i])\n elif mode == 'pre':\n pad_width[i] = (length[i] - np.shape(x)[i], 0)\n else:\n raise ValueError('\"mode\" argument must be \"post\" or \"pre\".')\n x = np.pad(x, pad_width, 'constant', constant_values=value)\n outputs.append(x)\n\n return np.array(outputs)\n\n\ndef truncate_sequences(maxlen, indices, *sequences):\n \"\"\"截断总长度至不超过maxlen\n \"\"\"\n sequences = [s for s in sequences if s]\n if not isinstance(indices, (list, tuple)):\n indices = [indices] * len(sequences)\n\n while True:\n lengths = [len(s) for s in sequences]\n if sum(lengths) > maxlen:\n i = np.argmax(lengths)\n sequences[i].pop(indices[i])\n else:\n return sequences\n\n\ndef text_segmentate(text, maxlen, seps='\\n', strips=None):\n \"\"\"将文本按照标点符号划分为若干个短句\n \"\"\"\n text = text.strip().strip(strips)\n if seps and len(text) > maxlen:\n pieces = text.split(seps[0])\n text, texts = '', []\n for i, p in enumerate(pieces):\n if text and p and len(text) + len(p) > maxlen - 1:\n texts.extend(text_segmentate(text, maxlen, seps[1:], strips))\n text = ''\n if i + 1 == len(pieces):\n text = text + p\n else:\n text = text + p + seps[0]\n if text:\n texts.extend(text_segmentate(text, maxlen, seps[1:], strips))\n return texts\n else:\n return [text]\n\n\ndef is_one_of(x, ys):\n \"\"\"判断x是否在ys之中\n 等价于x in ys,但有些情况下x in ys会报错\n \"\"\"\n for y in ys:\n if x is y:\n return True\n return False\n\n\nclass DataGenerator(object):\n \"\"\"数据生成器模版\n \"\"\"\n def __init__(self, data, batch_size=32, buffer_size=None):\n self.data = data\n self.batch_size = batch_size\n if hasattr(self.data, '__len__'):\n self.steps = len(self.data) // self.batch_size\n if len(self.data) % self.batch_size != 0:\n self.steps += 1\n else:\n self.steps = None\n self.buffer_size = buffer_size or batch_size * 1000\n\n def __len__(self):\n return self.steps\n\n def sample(self, random=False):\n \"\"\"采样函数,每个样本同时返回一个is_end标记\n \"\"\"\n if random:\n if self.steps is None:\n\n def generator():\n caches, isfull = [], False\n for d in self.data:\n caches.append(d)\n if isfull:\n i = np.random.randint(len(caches))\n yield caches.pop(i)\n elif len(caches) == self.buffer_size:\n isfull = True\n while caches:\n i = np.random.randint(len(caches))\n yield caches.pop(i)\n\n else:\n\n def generator():\n for i in np.random.permutation(len(self.data)):\n yield self.data[i]\n\n data = generator()\n else:\n data = iter(self.data)\n\n d_current = next(data)\n for d_next in data:\n yield False, d_current\n d_current = d_next\n\n yield True, d_current\n\n def __iter__(self, random=False):\n raise NotImplementedError\n\n def forfit(self, random=True):\n while True:\n for d in self.__iter__(random):\n yield d\n\n def to_dataset(self, types, shapes, names=None, padded_batch=False):\n \"\"\"转为tf.data.Dataset格式\n 如果传入names的话,自动把数据包装成dict形式。\n \"\"\"\n if names is None:\n\n generator = self.forfit\n\n else:\n\n if is_string(names):\n warps = lambda k, v: {k: v}\n elif is_string(names[0]):\n warps = lambda k, v: dict(zip(k, v))\n else:\n warps = lambda k, v: tuple(\n dict(zip(i, j)) for i, j in zip(k, v)\n )\n\n def generator():\n for d in self.forfit():\n yield warps(names, d)\n\n types = warps(names, types)\n shapes = warps(names, shapes)\n\n if padded_batch:\n dataset = tf.data.Dataset.from_generator(\n generator, output_types=types\n )\n dataset = dataset.padded_batch(self.batch_size, shapes)\n else:\n dataset = tf.data.Dataset.from_generator(\n generator, output_types=types, output_shapes=shapes\n )\n dataset = dataset.batch(self.batch_size)\n\n return dataset\n\n\nclass ViterbiDecoder(object):\n \"\"\"Viterbi解码算法基类\n \"\"\"\n def __init__(self, trans, starts=None, ends=None):\n self.trans = trans\n self.num_labels = len(trans)\n self.non_starts = []\n self.non_ends = []\n if starts is not None:\n for i in range(self.num_labels):\n if i not in starts:\n self.non_starts.append(i)\n if ends is not None:\n for i in range(self.num_labels):\n if i not in ends:\n self.non_ends.append(i)\n\n def decode(self, nodes):\n \"\"\"nodes.shape=[seq_len, num_labels]\n \"\"\"\n # 预处理\n nodes[0, self.non_starts] -= np.inf\n nodes[-1, self.non_ends] -= np.inf\n\n # 动态规划\n labels = np.arange(self.num_labels).reshape((1, -1))\n scores = nodes[0].reshape((-1, 1))\n paths = labels\n for l in range(1, len(nodes)):\n M = scores + self.trans + nodes[l].reshape((1, -1))\n idxs = M.argmax(0)\n scores = M.max(0).reshape((-1, 1))\n paths = np.concatenate([paths[:, idxs], labels], 0)\n\n # 最优路径\n return paths[:, scores[:, 0].argmax()]\n\n\ndef softmax(x, axis=-1):\n \"\"\"numpy版softmax\n \"\"\"\n x = x - x.max(axis=axis, keepdims=True)\n x = np.exp(x)\n return x / x.sum(axis=axis, keepdims=True)\n\n\nclass AutoRegressiveDecoder(object):\n \"\"\"通用自回归生成模型解码基类\n 包含beam search和random sample两种策略\n \"\"\"\n def __init__(self, start_id, end_id, maxlen, minlen=1):\n self.start_id = start_id\n self.end_id = end_id\n self.maxlen = maxlen\n self.minlen = minlen\n self.models = {}\n if start_id is None:\n self.first_output_ids = np.empty((1, 0), dtype=int)\n else:\n self.first_output_ids = np.array([[self.start_id]])\n\n @staticmethod\n def wraps(default_rtype='probas', use_states=False):\n \"\"\"用来进一步完善predict函数\n 目前包含:1. 设置rtype参数,并做相应处理;\n 2. 确定states的使用,并做相应处理;\n 3. 设置温度参数,并做相应处理。\n \"\"\"\n def actual_decorator(predict):\n def new_predict(\n self,\n inputs,\n output_ids,\n states,\n temperature=1,\n rtype=default_rtype\n ):\n assert rtype in ['probas', 'logits']\n prediction = predict(self, inputs, output_ids, states)\n\n if not use_states:\n prediction = (prediction, None)\n\n if default_rtype == 'logits':\n prediction = (\n softmax(prediction[0] / temperature), prediction[1]\n )\n elif temperature != 1:\n probas = np.power(prediction[0], 1.0 / temperature)\n probas = probas / probas.sum(axis=-1, keepdims=True)\n prediction = (probas, prediction[1])\n\n if rtype == 'probas':\n return prediction\n else:\n return np.log(prediction[0] + 1e-12), prediction[1]\n\n return new_predict\n\n return actual_decorator\n\n def last_token(self, model):\n \"\"\"创建一个只返回最后一个token输出的新Model\n \"\"\"\n if model not in self.models:\n outputs = [\n keras.layers.Lambda(lambda x: x[:, -1])(output)\n for output in model.outputs\n ]\n self.models[model] = keras.models.Model(model.inputs, outputs)\n\n return self.models[model]\n\n def predict(self, inputs, output_ids, states=None):\n \"\"\"用户需自定义递归预测函数\n 说明:定义的时候,需要用wraps方法进行装饰,传入default_rtype和use_states,\n 其中default_rtype为字符串logits或probas,probas时返回归一化的概率,\n rtype=logits时则返回softmax前的结果或者概率对数。\n 返回:二元组 (得分或概率, states)\n \"\"\"\n raise NotImplementedError\n\n def beam_search(self, inputs, topk, states=None, temperature=1, min_ends=1):\n \"\"\"beam search解码\n 说明:这里的topk即beam size;\n 返回:最优解码序列。\n \"\"\"\n inputs = [np.array([i]) for i in inputs]\n output_ids, output_scores = self.first_output_ids, np.zeros(1)\n for step in range(self.maxlen):\n scores, states = self.predict(\n inputs, output_ids, states, temperature, 'logits'\n ) # 计算当前得分\n if step == 0: # 第1步预测后将输入重复topk次\n inputs = [np.repeat(i, topk, axis=0) for i in inputs]\n scores = output_scores.reshape((-1, 1)) + scores # 综合累积得分\n indices = scores.argpartition(-topk, axis=None)[-topk:] # 仅保留topk\n indices_1 = indices // scores.shape[1] # 行索引\n indices_2 = (indices % scores.shape[1]).reshape((-1, 1)) # 列索引\n output_ids = np.concatenate([output_ids[indices_1], indices_2],\n 1) # 更新输出\n output_scores = np.take_along_axis(\n scores, indices, axis=None\n ) # 更新得分\n end_counts = (output_ids == self.end_id).sum(1) # 统计出现的end标记\n if output_ids.shape[1] >= self.minlen: # 最短长度判断\n best_one = output_scores.argmax() # 得分最大的那个\n if end_counts[best_one] == min_ends: # 如果已经终止\n return output_ids[best_one] # 直接输出\n else: # 否则,只保留未完成部分\n flag = (end_counts < min_ends) # 标记未完成序列\n if not flag.all(): # 如果有已完成的\n inputs = [i[flag] for i in inputs] # 扔掉已完成序列\n output_ids = output_ids[flag] # 扔掉已完成序列\n output_scores = output_scores[flag] # 扔掉已完成序列\n end_counts = end_counts[flag] # 扔掉已完成end计数\n topk = flag.sum() # topk相应变化\n # 达到长度直接输出\n return output_ids[output_scores.argmax()]\n\n def random_sample(\n self,\n inputs,\n n,\n topk=None,\n topp=None,\n states=None,\n temperature=1,\n min_ends=1\n ):\n \"\"\"随机采样n个结果\n 说明:非None的topk表示每一步只从概率最高的topk个中采样;而非None的topp\n 表示每一步只从概率最高的且概率之和刚好达到topp的若干个token中采样。\n 返回:n个解码序列组成的list。\n \"\"\"\n inputs = [np.array([i]) for i in inputs]\n output_ids = self.first_output_ids\n results = []\n for step in range(self.maxlen):\n probas, states = self.predict(\n inputs, output_ids, states, temperature, 'probas'\n ) # 计算当前概率\n probas /= probas.sum(axis=1, keepdims=True) # 确保归一化\n if step == 0: # 第1步预测后将结果重复n次\n probas = np.repeat(probas, n, axis=0)\n inputs = [np.repeat(i, n, axis=0) for i in inputs]\n output_ids = np.repeat(output_ids, n, axis=0)\n if topk is not None:\n k_indices = probas.argpartition(-topk,\n axis=1)[:, -topk:] # 仅保留topk\n probas = np.take_along_axis(probas, k_indices, axis=1) # topk概率\n probas /= probas.sum(axis=1, keepdims=True) # 重新归一化\n if topp is not None:\n p_indices = probas.argsort(axis=1)[:, ::-1] # 从高到低排序\n probas = np.take_along_axis(probas, p_indices, axis=1) # 排序概率\n cumsum_probas = np.cumsum(probas, axis=1) # 累积概率\n flag = np.roll(cumsum_probas >= topp, 1, axis=1) # 标记超过topp的部分\n flag[:, 0] = False # 结合上面的np.roll,实现平移一位的效果\n probas[flag] = 0 # 后面的全部置零\n probas /= probas.sum(axis=1, keepdims=True) # 重新归一化\n sample_func = lambda p: np.random.choice(len(p), p=p) # 按概率采样函数\n sample_ids = np.apply_along_axis(sample_func, 1, probas) # 执行采样\n sample_ids = sample_ids.reshape((-1, 1)) # 对齐形状\n if topp is not None:\n sample_ids = np.take_along_axis(\n p_indices, sample_ids, axis=1\n ) # 对齐原id\n if topk is not None:\n sample_ids = np.take_along_axis(\n k_indices, sample_ids, axis=1\n ) # 对齐原id\n output_ids = np.concatenate([output_ids, sample_ids], 1) # 更新输出\n end_counts = (output_ids == self.end_id).sum(1) # 统计出现的end标记\n if output_ids.shape[1] >= self.minlen: # 最短长度判断\n flag = (end_counts == min_ends) # 标记已完成序列\n if flag.any(): # 如果有已完成的\n for ids in output_ids[flag]: # 存好已完成序列\n results.append(ids)\n flag = (flag == False) # 标记未完成序列\n inputs = [i[flag] for i in inputs] # 只保留未完成部分输入\n output_ids = output_ids[flag] # 只保留未完成部分候选集\n end_counts = end_counts[flag] # 只保留未完成部分end计数\n if len(output_ids) == 0:\n break\n # 如果还有未完成序列,直接放入结果\n for ids in output_ids:\n results.append(ids)\n # 返回结果\n return results\n\n\ndef insert_arguments(**arguments):\n \"\"\"装饰器,为类方法增加参数\n (主要用于类的__init__方法)\n \"\"\"\n def actual_decorator(func):\n def new_func(self, *args, **kwargs):\n for k, v in arguments.items():\n if k in kwargs:\n v = kwargs.pop(k)\n setattr(self, k, v)\n return func(self, *args, **kwargs)\n\n return new_func\n\n return actual_decorator\n\n\ndef delete_arguments(*arguments):\n \"\"\"装饰器,为类方法删除参数\n (主要用于类的__init__方法)\n \"\"\"\n def actual_decorator(func):\n def new_func(self, *args, **kwargs):\n for k in arguments:\n if k in kwargs:\n raise TypeError(\n '%s got an unexpected keyword argument \\'%s\\'' %\n (self.__class__.__name__, k)\n )\n return func(self, *args, **kwargs)\n\n return new_func\n\n return actual_decorator\n\n\ndef longest_common_substring(source, target):\n \"\"\"最长公共子串(source和target的最长公共切片区间)\n 返回:子串长度, 所在区间(四元组)\n 注意:最长公共子串可能不止一个,所返回的区间只代表其中一个。\n \"\"\"\n c, l, span = defaultdict(int), 0, (0, 0, 0, 0)\n for i, si in enumerate(source, 1):\n for j, tj in enumerate(target, 1):\n if si == tj:\n c[i, j] = c[i - 1, j - 1] + 1\n if c[i, j] > l:\n l = c[i, j]\n span = (i - l, i, j - l, j)\n return l, span\n\n\ndef longest_common_subsequence(source, target):\n \"\"\"最长公共子序列(source和target的最长非连续子序列)\n 返回:子序列长度, 映射关系(映射对组成的list)\n 注意:最长公共子序列可能不止一个,所返回的映射只代表其中一个。\n \"\"\"\n c = defaultdict(int)\n for i, si in enumerate(source, 1):\n for j, tj in enumerate(target, 1):\n if si == tj:\n c[i, j] = c[i - 1, j - 1] + 1\n elif c[i, j - 1] > c[i - 1, j]:\n c[i, j] = c[i, j - 1]\n else:\n c[i, j] = c[i - 1, j]\n l, mapping = c[len(source), len(target)], []\n i, j = len(source) - 1, len(target) - 1\n while len(mapping) < l:\n if source[i] == target[j]:\n mapping.append((i, j))\n i, j = i - 1, j - 1\n elif c[i + 1, j] > c[i, j + 1]:\n j = j - 1\n else:\n i = i - 1\n return l, mapping[::-1]\n\n\nclass WebServing(object):\n \"\"\"简单的Web接口\n 用法:\n arguments = {'text': (None, True), 'n': (int, False)}\n web = WebServing(port=8864)\n web.route('/gen_synonyms', gen_synonyms, arguments)\n web.start()\n # 然后访问 http://127.0.0.1:8864/gen_synonyms?text=你好\n 说明:\n 基于bottlepy简单封装,仅作为临时测试使用,不保证性能。\n 目前仅保证支持 Tensorflow 1.x + Keras <= 2.3.1。\n 欢迎有经验的开发者帮忙改进。\n 依赖:\n pip install bottle\n pip install paste\n (如果不用 server='paste' 的话,可以不装paste库)\n \"\"\"\n def __init__(self, host='0.0.0.0', port=8000, server='paste'):\n\n import bottle\n\n self.host = host\n self.port = port\n self.server = server\n self.graph = tf.get_default_graph()\n self.sess = K.get_session()\n self.set_session = K.set_session\n self.bottle = bottle\n\n def wraps(self, func, arguments, method='GET'):\n \"\"\"封装为接口函数\n 参数:\n func:要转换为接口的函数,需要保证输出可以json化,即需要\n 保证 json.dumps(func(inputs)) 能被执行成功;\n arguments:声明func所需参数,其中key为参数名,value[0]为\n 对应的转换函数(接口获取到的参数值都是字符串\n 型),value[1]为该参数是否必须;\n method:GET或者POST。\n \"\"\"\n def new_func():\n outputs = {'code': 0, 'desc': u'succeeded', 'data': {}}\n kwargs = {}\n for key, value in arguments.items():\n if method == 'GET':\n result = self.bottle.request.GET.getunicode(key)\n else:\n result = self.bottle.request.POST.getunicode(key)\n if result is None:\n if value[1]:\n outputs['code'] = 1\n outputs['desc'] = 'lack of \"%s\" argument' % key\n return json.dumps(outputs, ensure_ascii=False)\n else:\n if value[0] is not None:\n result = value[0](result)\n kwargs[key] = result\n try:\n with self.graph.as_default():\n self.set_session(self.sess)\n outputs['data'] = func(**kwargs)\n except Exception as e:\n outputs['code'] = 2\n outputs['desc'] = str(e)\n return json.dumps(outputs, ensure_ascii=False)\n\n return new_func\n\n def route(self, path, func, arguments, method='GET'):\n \"\"\"添加接口\n \"\"\"\n func = self.wraps(func, arguments, method)\n self.bottle.route(path, method=method)(func)\n\n def start(self):\n \"\"\"启动服务\n \"\"\"\n self.bottle.run(host=self.host, port=self.port, server=self.server)\n\n\nclass Hook:\n \"\"\"注入uniout模块,实现import时才触发\n \"\"\"\n def __init__(self, module):\n self.module = module\n\n def __getattr__(self, attr):\n \"\"\"使得 from bert4keras.backend import uniout\n 等效于 import uniout (自动识别Python版本,Python3\n 下则无操作。)\n \"\"\"\n if attr == 'uniout':\n if is_py2:\n import uniout\n else:\n return getattr(self.module, attr)\n\n\nHook.__name__ = __name__\nsys.modules[__name__] = Hook(sys.modules[__name__])\ndel Hook\n", "#! -*- coding: utf-8 -*-\n# 主要模型\n\nimport numpy as np\nfrom bert4keras.layers import *\nfrom bert4keras.snippets import insert_arguments\nfrom bert4keras.snippets import delete_arguments\nfrom bert4keras.snippets import is_string, is_one_of\nfrom keras.models import Model\nimport json\n\n\nclass Transformer(object):\n \"\"\"模型基类\n \"\"\"\n def __init__(\n self,\n vocab_size, # 词表大小\n hidden_size, # 编码维度\n num_hidden_layers, # Transformer总层数\n num_attention_heads, # Attention的头数\n intermediate_size, # FeedForward的隐层维度\n hidden_act, # FeedForward隐层的激活函数\n dropout_rate=None, # Dropout比例\n embedding_size=None, # 是否指定embedding_size\n attention_head_size=None, # Attention中V的head_size\n attention_key_size=None, # Attention中Q,K的head_size\n sequence_length=None, # 是否固定序列长度\n keep_tokens=None, # 要保留的词ID列表\n compound_tokens=None, # 扩展Embedding\n residual_attention_scores=False, # Attention矩阵加残差\n ignore_invalid_weights=False, # 允许跳过不存在的权重\n layers=None, # 外部传入的Keras层\n prefix=None, # 层名前缀\n name=None, # 模型名称\n **kwargs\n ):\n if keep_tokens is not None:\n vocab_size = len(keep_tokens)\n if compound_tokens is not None:\n vocab_size += len(compound_tokens)\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.attention_head_size = attention_head_size or hidden_size // num_attention_heads\n self.attention_key_size = attention_key_size or self.attention_head_size\n self.intermediate_size = intermediate_size\n self.dropout_rate = dropout_rate or 0\n self.hidden_act = hidden_act\n self.embedding_size = embedding_size or hidden_size\n self.sequence_length = sequence_length\n self.keep_tokens = keep_tokens\n self.compound_tokens = compound_tokens\n self.attention_bias = None\n self.position_bias = None\n self.attention_scores = None\n self.residual_attention_scores = residual_attention_scores\n self.ignore_invalid_weights = ignore_invalid_weights\n self.layers = {} if layers is None else layers\n self.prefix = prefix or ''\n self.name = name\n self.built = False\n\n def build(\n self,\n attention_caches=None,\n layer_norm_cond=None,\n layer_norm_cond_hidden_size=None,\n layer_norm_cond_hidden_act=None,\n additional_input_layers=None,\n **kwargs\n ):\n \"\"\"模型构建函数\n attention_caches:为Attention的K,V的缓存序列字典,格式为\n {Attention层名: [K缓存, V缓存]};\n layer_norm_*系列参数:实现Conditional Layer Normalization时使用,\n 用来实现以“固定长度向量”为条件的条件Bert。\n \"\"\"\n if self.built:\n return None\n # Input\n inputs = self.get_inputs()\n self.set_inputs(inputs, additional_input_layers)\n # Other\n self.attention_caches = attention_caches or {}\n self.layer_norm_conds = [\n layer_norm_cond,\n layer_norm_cond_hidden_size,\n layer_norm_cond_hidden_act or 'linear',\n ]\n # Call\n outputs = self.call(inputs)\n self.set_outputs(outputs)\n # Model\n self.model = Model(self.inputs, self.outputs, name=self.name)\n self.built = True\n\n def call(self, inputs):\n \"\"\"定义模型的执行流程\n \"\"\"\n # Embedding\n outputs = self.apply_embeddings(inputs)\n # Main\n for i in range(self.num_hidden_layers):\n outputs = self.apply_main_layers(outputs, i)\n # Final\n outputs = self.apply_final_layers(outputs)\n return outputs\n\n def prefixed(self, name):\n \"\"\"给名字加前缀\n \"\"\"\n if name is not None:\n return self.prefix + name\n\n def apply(self, inputs=None, layer=None, arguments=None, **kwargs):\n \"\"\"通过apply调用层会自动重用同名层\n inputs: 上一层的输出;\n layer: 要调用的层类名;\n arguments: 传递给layer.call的参数;\n kwargs: 传递给层初始化的参数。\n \"\"\"\n if layer is Dropout and self.dropout_rate == 0:\n return inputs\n\n if layer is MultiHeadAttention and self.residual_attention_scores:\n kwargs['return_attention_scores'] = True\n\n arguments = arguments or {}\n name = self.prefixed(kwargs.get('name'))\n kwargs['name'] = name\n if name not in self.layers:\n layer = layer(**kwargs)\n name = layer.name\n self.layers[name] = layer\n\n if inputs is None:\n return self.layers[name]\n else:\n if isinstance(self.layers[name], MultiHeadAttention):\n if name in self.attention_caches:\n # 如果检测到Cache的传入,那么自动在Key,Value处拼接起来\n k_cache, v_cache = self.attention_caches[name]\n k_name, v_name = name + '-Cached-Key', name + '-Cached-Value'\n k = Concatenate1D(name=k_name)([k_cache, inputs[1]])\n v = Concatenate1D(name=v_name)([v_cache, inputs[2]])\n inputs = inputs[:1] + [k, v] + inputs[3:]\n if self.residual_attention_scores:\n # 如果使用残差Attention矩阵,则给每个Attention矩阵加上前上一层的Attention\n # 矩阵,这对应RealFormer设计(https://arxiv.org/abs/2012.11747)。目前\n # 该实现还相对粗糙,可能欠缺通用性。\n if self.attention_scores is not None:\n if arguments.get('a_bias'):\n a_bias = Add(name=name + '-Attention-Bias'\n )([inputs[3], self.attention_scores])\n inputs = inputs[:3] + [a_bias] + inputs[4:]\n else:\n a_bias = self.attention_scores\n inputs = inputs[:3] + [a_bias] + inputs[3:]\n arguments['a_bias'] = True\n o, a = self.layers[name](inputs, **arguments)\n self.attention_scores = a\n return o\n return self.layers[name](inputs, **arguments)\n\n def get_inputs(self):\n raise NotImplementedError\n\n def apply_embeddings(self, inputs):\n raise NotImplementedError\n\n def apply_main_layers(self, inputs, index):\n raise NotImplementedError\n\n def apply_final_layers(self, inputs):\n raise NotImplementedError\n\n def compute_attention_bias(self, inputs=None):\n \"\"\"定义每一层的Attention Bias\n \"\"\"\n return self.attention_bias\n\n def compute_position_bias(self, inputs=None):\n \"\"\"定义每一层的Position Bias(一般相对位置编码用)\n \"\"\"\n return self.position_bias\n\n def set_inputs(self, inputs, additional_input_layers=None):\n \"\"\"设置input和inputs属性\n \"\"\"\n if inputs is None:\n inputs = []\n elif not isinstance(inputs, list):\n inputs = [inputs]\n\n inputs = inputs[:]\n if additional_input_layers is not None:\n if not isinstance(additional_input_layers, list):\n additional_input_layers = [additional_input_layers]\n inputs.extend(additional_input_layers)\n\n self.inputs = inputs\n if len(inputs) > 1:\n self.input = inputs\n else:\n self.input = inputs[0]\n\n def set_outputs(self, outputs):\n \"\"\"设置output和oututs属性\n \"\"\"\n if not isinstance(outputs, list):\n outputs = [outputs]\n\n outputs = outputs[:]\n self.outputs = outputs\n if len(outputs) > 1:\n self.output = outputs\n else:\n self.output = outputs[0]\n\n @property\n def initializer(self):\n \"\"\"默认使用截断正态分布初始化\n \"\"\"\n return keras.initializers.TruncatedNormal(stddev=0.02)\n\n def simplify(self, inputs):\n \"\"\"将list中的None过滤掉\n \"\"\"\n inputs = [i for i in inputs if i is not None]\n if len(inputs) == 1:\n inputs = inputs[0]\n\n return inputs\n\n def load_embeddings(self, embeddings):\n \"\"\"处理Embedding层权重\n \"\"\"\n embeddings = embeddings.astype(K.floatx()) # 防止np.average报错\n\n if self.keep_tokens is not None:\n embeddings = embeddings[self.keep_tokens]\n\n if self.compound_tokens is not None:\n ext_embeddings = []\n for item in self.compound_tokens:\n if isinstance(item, list):\n item = (item, [1] * len(item))\n ext_embeddings.append(\n np.average(embeddings[item[0]], 0, item[1])\n )\n embeddings = np.concatenate([embeddings, ext_embeddings], 0)\n\n return embeddings\n\n def load_variable(self, checkpoint, name):\n \"\"\"加载单个变量的函数\n \"\"\"\n if isinstance(checkpoint, dict):\n return checkpoint[name]\n else:\n return tf.train.load_variable(checkpoint, name)\n\n def create_variable(self, name, value, dtype=None):\n \"\"\"创建一个变量\n \"\"\"\n dtype = dtype or K.floatx()\n return K.variable(\n self.initializer(value.shape, dtype), dtype, name=name\n ), value\n\n def variable_mapping(self):\n \"\"\"构建keras层与checkpoint的变量名之间的映射表\n \"\"\"\n return {}\n\n def load_weights_from_checkpoint(self, checkpoint, mapping=None):\n \"\"\"根据mapping从checkpoint加载权重\n \"\"\"\n mapping = mapping or self.variable_mapping()\n mapping = {self.prefixed(k): v for k, v in mapping.items()}\n mapping = {k: v for k, v in mapping.items() if k in self.layers}\n\n weight_value_pairs = []\n for layer, variables in mapping.items():\n layer = self.layers[layer]\n weights, values = [], []\n\n for w, v in zip(layer.trainable_weights, variables): # 允许跳过不存在的权重\n try:\n values.append(self.load_variable(checkpoint, v))\n weights.append(w)\n except Exception as e:\n if self.ignore_invalid_weights:\n print('%s, but ignored.' % e.message)\n else:\n raise e\n\n if isinstance(layer, MultiHeadAttention):\n \"\"\"如果key_size不等于head_size,则可以通过\n 正交矩阵将相应的权重投影到合适的shape。\n \"\"\"\n count = 2\n if layer.use_bias:\n count += 2\n heads = self.num_attention_heads\n head_size = self.attention_head_size\n key_size = self.attention_key_size\n W = np.linalg.qr(np.random.randn(key_size, head_size))[0].T\n if layer.attention_scale:\n W = W * key_size**0.25 / head_size**0.25\n for w, v in zip(weights, values):\n if is_one_of(w, layer.trainable_weights[:count]):\n w_shape, v_shape = K.int_shape(w), v.shape\n if w_shape[-1] != v_shape[-1]:\n pre_shape = w_shape[:-1]\n v = v.reshape(pre_shape + (heads, head_size))\n v = np.dot(v, W)\n v = v.reshape(pre_shape + (heads * key_size,))\n values[weights.index(w)] = v\n\n weight_value_pairs.extend(zip(weights, values))\n\n K.batch_set_value(weight_value_pairs)\n\n def save_weights_as_checkpoint(self, filename, mapping=None, dtype=None):\n \"\"\"根据mapping将权重保存为checkpoint格式\n \"\"\"\n mapping = mapping or self.variable_mapping()\n mapping = {self.prefixed(k): v for k, v in mapping.items()}\n mapping = {k: v for k, v in mapping.items() if k in self.layers}\n\n with tf.Graph().as_default():\n all_variables, all_values = [], []\n for layer, variables in mapping.items():\n layer = self.layers[layer]\n values = K.batch_get_value(layer.trainable_weights)\n for name, value in zip(variables, values):\n variable, value = self.create_variable(name, value, dtype)\n all_variables.append(variable)\n all_values.append(value)\n with tf.Session() as sess:\n K.batch_set_value(zip(all_variables, all_values))\n saver = tf.train.Saver()\n saver.save(sess, filename)\n\n\nclass LM_Mask(object):\n \"\"\"定义下三角Attention Mask(语言模型用)\n \"\"\"\n def compute_attention_bias(self, inputs=None):\n \"\"\"通过idxs序列的比较来得到对应的mask\n \"\"\"\n if self.attention_bias is None:\n\n def lm_mask(s):\n seq_len = K.shape(s)[1]\n idxs = K.arange(0, seq_len)\n mask = idxs[None, :] <= idxs[:, None]\n mask = K.cast(mask, K.floatx())\n return -(1 - mask[None, None]) * 1e12\n\n self.attention_bias = self.apply(\n inputs=self.inputs[0],\n layer=Lambda,\n function=lm_mask,\n name='Attention-LM-Mask'\n )\n\n return self.attention_bias\n\n\nclass UniLM_Mask(object):\n \"\"\"定义UniLM的Attention Mask(Seq2Seq模型用)\n 其中source和target的分区,由segment_ids来表示。\n UniLM: https://arxiv.org/abs/1905.03197\n \"\"\"\n def compute_attention_bias(self, inputs=None):\n \"\"\"通过idxs序列的比较来得到对应的mask\n \"\"\"\n if self.attention_bias is None:\n\n def unilm_mask(s):\n idxs = K.cumsum(s, axis=1)\n mask = idxs[:, None, :] <= idxs[:, :, None]\n mask = K.cast(mask, K.floatx())\n return -(1 - mask[:, None]) * 1e12\n\n self.attention_bias = self.apply(\n inputs=self.inputs[1],\n layer=Lambda,\n function=unilm_mask,\n name='Attention-UniLM-Mask'\n )\n\n return self.attention_bias\n\n\nclass BERT(Transformer):\n \"\"\"构建BERT模型\n \"\"\"\n def __init__(\n self,\n max_position, # 序列最大长度\n segment_vocab_size=2, # segment总数目\n with_pool=False, # 是否包含Pool部分\n with_nsp=False, # 是否包含NSP部分\n with_mlm=False, # 是否包含MLM部分\n hierarchical_position=None, # 是否层次分解位置编码\n custom_position_ids=False, # 是否自行传入位置id\n shared_segment_embeddings=False, # 若True,则segment跟token共用embedding\n **kwargs # 其余参数\n ):\n super(BERT, self).__init__(**kwargs)\n self.max_position = max_position\n self.segment_vocab_size = segment_vocab_size\n self.with_pool = with_pool\n self.with_nsp = with_nsp\n self.with_mlm = with_mlm\n self.hierarchical_position = hierarchical_position\n self.custom_position_ids = custom_position_ids\n self.shared_segment_embeddings = shared_segment_embeddings\n if self.with_nsp and not self.with_pool:\n self.with_pool = True\n\n def get_inputs(self):\n \"\"\"BERT的输入是token_ids和segment_ids\n (但允许自行传入位置id,以实现一些特殊需求)\n \"\"\"\n x_in = self.apply(\n layer=Input, shape=(self.sequence_length,), name='Input-Token'\n )\n inputs = [x_in]\n\n if self.segment_vocab_size > 0:\n s_in = self.apply(\n layer=Input,\n shape=(self.sequence_length,),\n name='Input-Segment'\n )\n inputs.append(s_in)\n\n if self.custom_position_ids:\n p_in = self.apply(\n layer=Input,\n shape=(self.sequence_length,),\n name='Input-Position'\n )\n inputs.append(p_in)\n\n return inputs\n\n def apply_embeddings(self, inputs):\n \"\"\"BERT的embedding是token、position、segment三者embedding之和\n \"\"\"\n inputs = inputs[:]\n x = inputs.pop(0)\n if self.segment_vocab_size > 0:\n s = inputs.pop(0)\n if self.custom_position_ids:\n p = inputs.pop(0)\n else:\n p = None\n z = self.layer_norm_conds[0]\n\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n if self.segment_vocab_size > 0:\n if self.shared_segment_embeddings:\n name = 'Embedding-Token'\n else:\n name = 'Embedding-Segment'\n s = self.apply(\n inputs=s,\n layer=Embedding,\n input_dim=self.segment_vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n name=name\n )\n x = self.apply(\n inputs=[x, s], layer=Add, name='Embedding-Token-Segment'\n )\n x = self.apply(\n inputs=self.simplify([x, p]),\n layer=PositionEmbedding,\n input_dim=self.max_position,\n output_dim=self.embedding_size,\n merge_mode='add',\n hierarchical=self.hierarchical_position,\n embeddings_initializer=self.initializer,\n custom_position_ids=self.custom_position_ids,\n name='Embedding-Position'\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='Embedding-Norm'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Embedding-Dropout'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Embedding-Mapping'\n )\n\n return x\n\n def apply_main_layers(self, inputs, index):\n \"\"\"BERT的主体是基于Self-Attention的模块\n 顺序:Att --> Add --> LN --> FFN --> Add --> LN\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Transformer-%d-MultiHeadSelfAttention' % index\n feed_forward_name = 'Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n\n # Self Attention\n xi, x, arguments = x, [x, x, x], {'a_bias': None}\n if attention_mask is not None:\n arguments['a_bias'] = True\n x.append(attention_mask)\n\n x = self.apply(\n inputs=x,\n layer=MultiHeadAttention,\n arguments=arguments,\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n\n return x\n\n def apply_final_layers(self, inputs):\n \"\"\"根据剩余参数决定输出\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n outputs = [x]\n\n if self.with_pool:\n # Pooler部分(提取CLS向量)\n x = outputs[0]\n x = self.apply(\n inputs=x,\n layer=Lambda,\n function=lambda x: x[:, 0],\n name='Pooler'\n )\n pool_activation = 'tanh' if self.with_pool is True else self.with_pool\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n activation=pool_activation,\n kernel_initializer=self.initializer,\n name='Pooler-Dense'\n )\n if self.with_nsp:\n # Next Sentence Prediction部分\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=2,\n activation='softmax',\n kernel_initializer=self.initializer,\n name='NSP-Proba'\n )\n outputs.append(x)\n\n if self.with_mlm:\n # Masked Language Model部分\n x = outputs[0]\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.embedding_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name='MLM-Dense'\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='MLM-Norm'\n )\n x = self.apply(\n inputs=x,\n layer=Embedding,\n arguments={'mode': 'dense'},\n name='Embedding-Token'\n )\n x = self.apply(inputs=x, layer=BiasAdd, name='MLM-Bias')\n mlm_activation = 'softmax' if self.with_mlm is True else self.with_mlm\n x = self.apply(\n inputs=x,\n layer=Activation,\n activation=mlm_activation,\n name='MLM-Activation'\n )\n outputs.append(x)\n\n if len(outputs) == 1:\n outputs = outputs[0]\n elif len(outputs) == 2:\n outputs = outputs[1]\n else:\n outputs = outputs[1:]\n\n return outputs\n\n def load_variable(self, checkpoint, name):\n \"\"\"加载单个变量的函数\n \"\"\"\n variable = super(BERT, self).load_variable(checkpoint, name)\n if name in [\n 'bert/embeddings/word_embeddings',\n 'cls/predictions/output_bias',\n ]:\n return self.load_embeddings(variable)\n elif name == 'cls/seq_relationship/output_weights':\n return variable.T\n else:\n return variable\n\n def create_variable(self, name, value, dtype=None):\n \"\"\"在tensorflow中创建一个变量\n \"\"\"\n if name == 'cls/seq_relationship/output_weights':\n value = value.T\n return super(BERT, self).create_variable(name, value, dtype)\n\n def variable_mapping(self):\n \"\"\"映射到官方BERT权重格式\n \"\"\"\n mapping = {\n 'Embedding-Token': ['bert/embeddings/word_embeddings'],\n 'Embedding-Segment': ['bert/embeddings/token_type_embeddings'],\n 'Embedding-Position': ['bert/embeddings/position_embeddings'],\n 'Embedding-Norm': [\n 'bert/embeddings/LayerNorm/beta',\n 'bert/embeddings/LayerNorm/gamma',\n ],\n 'Embedding-Mapping': [\n 'bert/encoder/embedding_hidden_mapping_in/kernel',\n 'bert/encoder/embedding_hidden_mapping_in/bias',\n ],\n 'Pooler-Dense': [\n 'bert/pooler/dense/kernel',\n 'bert/pooler/dense/bias',\n ],\n 'NSP-Proba': [\n 'cls/seq_relationship/output_weights',\n 'cls/seq_relationship/output_bias',\n ],\n 'MLM-Dense': [\n 'cls/predictions/transform/dense/kernel',\n 'cls/predictions/transform/dense/bias',\n ],\n 'MLM-Norm': [\n 'cls/predictions/transform/LayerNorm/beta',\n 'cls/predictions/transform/LayerNorm/gamma',\n ],\n 'MLM-Bias': ['cls/predictions/output_bias'],\n }\n\n for i in range(self.num_hidden_layers):\n prefix = 'bert/encoder/layer_%d/' % i\n mapping.update({\n 'Transformer-%d-MultiHeadSelfAttention' % i: [\n prefix + 'attention/self/query/kernel',\n prefix + 'attention/self/query/bias',\n prefix + 'attention/self/key/kernel',\n prefix + 'attention/self/key/bias',\n prefix + 'attention/self/value/kernel',\n prefix + 'attention/self/value/bias',\n prefix + 'attention/output/dense/kernel',\n prefix + 'attention/output/dense/bias',\n ],\n 'Transformer-%d-MultiHeadSelfAttention-Norm' % i: [\n prefix + 'attention/output/LayerNorm/beta',\n prefix + 'attention/output/LayerNorm/gamma',\n ],\n 'Transformer-%d-FeedForward' % i: [\n prefix + 'intermediate/dense/kernel',\n prefix + 'intermediate/dense/bias',\n prefix + 'output/dense/kernel',\n prefix + 'output/dense/bias',\n ],\n 'Transformer-%d-FeedForward-Norm' % i: [\n prefix + 'output/LayerNorm/beta',\n prefix + 'output/LayerNorm/gamma',\n ],\n })\n\n return mapping\n\n\nclass ALBERT(BERT):\n \"\"\"构建ALBERT模型\n \"\"\"\n def apply_main_layers(self, inputs, index):\n \"\"\"ALBERT的主体是基于Self-Attention的模块\n 顺序:Att --> Add --> LN --> FFN --> Add --> LN\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Transformer-MultiHeadSelfAttention'\n feed_forward_name = 'Transformer-FeedForward'\n attention_mask = self.compute_attention_bias(index)\n\n # Self Attention\n xi, x, arguments = x, [x, x, x], {'a_bias': None}\n if attention_mask is not None:\n arguments['a_bias'] = True\n x.append(attention_mask)\n\n x = self.apply(\n inputs=x,\n layer=MultiHeadAttention,\n arguments=arguments,\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n\n return x\n\n def variable_mapping(self):\n \"\"\"映射到官方ALBERT权重格式\n \"\"\"\n mapping = super(ALBERT, self).variable_mapping()\n\n prefix = 'bert/encoder/transformer/group_0/inner_group_0/'\n mapping.update({\n 'Transformer-MultiHeadSelfAttention': [\n prefix + 'attention_1/self/query/kernel',\n prefix + 'attention_1/self/query/bias',\n prefix + 'attention_1/self/key/kernel',\n prefix + 'attention_1/self/key/bias',\n prefix + 'attention_1/self/value/kernel',\n prefix + 'attention_1/self/value/bias',\n prefix + 'attention_1/output/dense/kernel',\n prefix + 'attention_1/output/dense/bias',\n ],\n 'Transformer-MultiHeadSelfAttention-Norm': [\n prefix + 'LayerNorm/beta',\n prefix + 'LayerNorm/gamma',\n ],\n 'Transformer-FeedForward': [\n prefix + 'ffn_1/intermediate/dense/kernel',\n prefix + 'ffn_1/intermediate/dense/bias',\n prefix + 'ffn_1/intermediate/output/dense/kernel',\n prefix + 'ffn_1/intermediate/output/dense/bias',\n ],\n 'Transformer-FeedForward-Norm': [\n prefix + 'LayerNorm_1/beta',\n prefix + 'LayerNorm_1/gamma',\n ],\n })\n\n return mapping\n\n\nclass ALBERT_Unshared(BERT):\n \"\"\"解开ALBERT共享约束,当成BERT用\n \"\"\"\n def variable_mapping(self):\n \"\"\"映射到官方ALBERT权重格式\n \"\"\"\n mapping = super(ALBERT_Unshared, self).variable_mapping()\n\n prefix = 'bert/encoder/transformer/group_0/inner_group_0/'\n for i in range(self.num_hidden_layers):\n mapping.update({\n 'Transformer-%d-MultiHeadSelfAttention' % i: [\n prefix + 'attention_1/self/query/kernel',\n prefix + 'attention_1/self/query/bias',\n prefix + 'attention_1/self/key/kernel',\n prefix + 'attention_1/self/key/bias',\n prefix + 'attention_1/self/value/kernel',\n prefix + 'attention_1/self/value/bias',\n prefix + 'attention_1/output/dense/kernel',\n prefix + 'attention_1/output/dense/bias',\n ],\n 'Transformer-%d-MultiHeadSelfAttention-Norm' % i: [\n prefix + 'LayerNorm/beta',\n prefix + 'LayerNorm/gamma',\n ],\n 'Transformer-%d-FeedForward' % i: [\n prefix + 'ffn_1/intermediate/dense/kernel',\n prefix + 'ffn_1/intermediate/dense/bias',\n prefix + 'ffn_1/intermediate/output/dense/kernel',\n prefix + 'ffn_1/intermediate/output/dense/bias',\n ],\n 'Transformer-%d-FeedForward-Norm' % i: [\n prefix + 'LayerNorm_1/beta',\n prefix + 'LayerNorm_1/gamma',\n ],\n })\n\n return mapping\n\n\nclass NEZHA(BERT):\n \"\"\"华为推出的NAZHA模型\n 链接:https://arxiv.org/abs/1909.00204\n \"\"\"\n def apply_embeddings(self, inputs):\n \"\"\"NEZHA的embedding是token、segment两者embedding之和\n \"\"\"\n inputs = inputs[:]\n x = inputs.pop(0)\n if self.segment_vocab_size > 0:\n s = inputs.pop(0)\n z = self.layer_norm_conds[0]\n\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n if self.segment_vocab_size > 0:\n if self.shared_segment_embeddings:\n name = 'Embedding-Token'\n else:\n name = 'Embedding-Segment'\n s = self.apply(\n inputs=s,\n layer=Embedding,\n input_dim=2,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n name=name\n )\n x = self.apply(\n inputs=[x, s], layer=Add, name='Embedding-Token-Segment'\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='Embedding-Norm'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Embedding-Dropout'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Embedding-Mapping'\n )\n\n return x\n\n def apply_main_layers(self, inputs, index):\n \"\"\"NEZHA的主体是基于Self-Attention的模块\n 顺序:Att --> Add --> LN --> FFN --> Add --> LN\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Transformer-%d-MultiHeadSelfAttention' % index\n feed_forward_name = 'Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n position_bias = self.compute_position_bias(x)\n\n # Self Attention\n xi, x = x, [x, x, x, position_bias]\n arguments = {'a_bias': None, 'p_bias': 'typical_relative'}\n if attention_mask is not None:\n arguments['a_bias'] = True\n x.insert(3, attention_mask)\n\n x = self.apply(\n inputs=x,\n layer=MultiHeadAttention,\n arguments=arguments,\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n\n return x\n\n def compute_position_bias(self, inputs=None):\n \"\"\"经典相对位置编码\n \"\"\"\n if self.position_bias is None:\n\n x = inputs\n self.position_bias = self.apply(\n inputs=[x, x],\n layer=RelativePositionEmbedding,\n input_dim=2 * 64 + 1,\n output_dim=self.attention_key_size,\n embeddings_initializer='Sinusoidal',\n name='Embedding-Relative-Position',\n trainable=False\n )\n\n return self.position_bias\n\n\nclass RoFormer(NEZHA):\n \"\"\"旋转式位置编码的BERT模型\n 链接:https://kexue.fm/archives/8265\n \"\"\"\n def apply_main_layers(self, inputs, index):\n \"\"\"RoFormer的主体是基于Self-Attention的模块\n 顺序:Att --> Add --> LN --> FFN --> Add --> LN\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Transformer-%d-MultiHeadSelfAttention' % index\n feed_forward_name = 'Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n position_bias = self.compute_position_bias(x)\n\n # Self Attention\n xi, x = x, [x, x, x, position_bias]\n arguments = {'a_bias': None, 'p_bias': 'rotary'}\n if attention_mask is not None:\n arguments['a_bias'] = True\n x.insert(3, attention_mask)\n\n x = self.apply(\n inputs=x,\n layer=MultiHeadAttention,\n arguments=arguments,\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n\n return x\n\n def compute_position_bias(self, inputs=None):\n \"\"\"Sinusoidal位置编码(直接返回)\n \"\"\"\n if self.position_bias is None:\n\n x = inputs\n self.position_bias = self.apply(\n inputs=x,\n layer=SinusoidalPositionEmbedding,\n output_dim=self.attention_key_size,\n merge_mode='zero',\n name='Embedding-Rotary-Position'\n )\n\n return self.position_bias\n\n\nclass ELECTRA(BERT):\n \"\"\"Google推出的ELECTRA模型\n 链接:https://arxiv.org/abs/2003.10555\n \"\"\"\n @insert_arguments(with_discriminator=False)\n @delete_arguments('with_pool', 'with_mlm')\n def __init__(\n self,\n max_position, # 序列最大长度\n **kwargs # 其余参数\n ):\n super(ELECTRA, self).__init__(max_position, **kwargs)\n\n def apply_final_layers(self, inputs):\n x = inputs\n\n if self.with_discriminator:\n if self.with_discriminator is True:\n final_activation = 'sigmoid'\n else:\n final_activation = self.with_discriminator\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name='Discriminator-Dense'\n )\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=1,\n activation=final_activation,\n kernel_initializer=self.initializer,\n name='Discriminator-Prediction'\n )\n\n return x\n\n def load_variable(self, checkpoint, name):\n \"\"\"加载单个变量的函数\n \"\"\"\n variable = super(ELECTRA, self).load_variable(checkpoint, name)\n if name == 'electra/embeddings/word_embeddings':\n return self.load_embeddings(variable)\n else:\n return variable\n\n def variable_mapping(self):\n mapping = super(ELECTRA, self).variable_mapping()\n mapping['Embedding-Mapping'] = [\n 'electra/embeddings_project/kernel',\n 'electra/embeddings_project/bias',\n ]\n mapping = {\n k: [i.replace('bert/', 'electra/') for i in v]\n for k, v in mapping.items()\n }\n mapping['Discriminator-Dense'] = [\n 'discriminator_predictions/dense/kernel',\n 'discriminator_predictions/dense/bias',\n ]\n mapping['Discriminator-Prediction'] = [\n 'discriminator_predictions/dense_1/kernel',\n 'discriminator_predictions/dense_1/bias',\n ]\n return mapping\n\n\nclass GPT(LM_Mask, BERT):\n \"\"\"构建GPT模型\n 链接:https://github.com/openai/finetune-transformer-lm\n \"\"\"\n @insert_arguments(final_activation='softmax')\n @delete_arguments('with_pool', 'with_mlm')\n def __init__(self, **kwargs):\n super(GPT, self).__init__(**kwargs)\n\n def apply_embeddings(self, inputs):\n \"\"\"GPT的embedding是token、position、segment三者embedding之和\n 跟BERT的主要区别是三者相加之后没有加LayerNormalization层。\n \"\"\"\n inputs = inputs[:]\n x = inputs.pop(0)\n if self.segment_vocab_size > 0:\n s = inputs.pop(0)\n if self.custom_position_ids:\n p = inputs.pop(0)\n else:\n p = None\n\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n if self.segment_vocab_size > 0:\n if self.shared_segment_embeddings:\n name = 'Embedding-Token'\n else:\n name = 'Embedding-Segment'\n s = self.apply(\n inputs=s,\n layer=Embedding,\n input_dim=self.segment_vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n name=name\n )\n x = self.apply(\n inputs=[x, s], layer=Add, name='Embedding-Token-Segment'\n )\n x = self.apply(\n inputs=self.simplify([x, p]),\n layer=PositionEmbedding,\n input_dim=self.max_position,\n output_dim=self.embedding_size,\n merge_mode='add',\n hierarchical=self.hierarchical_position,\n embeddings_initializer=self.initializer,\n custom_position_ids=self.custom_position_ids,\n name='Embedding-Position'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Embedding-Dropout'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Embedding-Mapping'\n )\n\n return x\n\n def apply_final_layers(self, inputs):\n \"\"\"剩余部分\n \"\"\"\n x = inputs\n\n # Language Model部分\n x = self.apply(\n inputs=x,\n layer=Embedding,\n arguments={'mode': 'dense'},\n name='Embedding-Token'\n )\n x = self.apply(\n inputs=x,\n layer=Activation,\n activation=self.final_activation,\n name='LM-Activation'\n )\n\n return x\n\n def load_variable(self, checkpoint, name):\n \"\"\"加载单个变量的函数\n \"\"\"\n variable = super(GPT, self).load_variable(checkpoint, name)\n if name == 'gpt/embeddings/word_embeddings':\n return self.load_embeddings(variable)\n else:\n return variable\n\n def variable_mapping(self):\n \"\"\"映射到TF版GPT权重格式\n \"\"\"\n mapping = super(GPT, self).variable_mapping()\n mapping = {\n k: [\n i.replace('bert/', 'gpt/').replace('encoder', 'transformer')\n for i in v\n ]\n for k, v in mapping.items()\n }\n return mapping\n\n\nclass GPT2(GPT):\n \"\"\"构建GPT2模型\n 链接: https://github.com/openai/gpt-2\n \"\"\"\n def get_inputs(self):\n \"\"\"GPT2的输入是token_ids\n \"\"\"\n x_in = self.apply(\n layer=Input, shape=(self.sequence_length,), name='Input-Token'\n )\n return x_in\n\n def apply_embeddings(self, inputs):\n \"\"\"GPT2的embedding是token、position两者embedding之和\n \"\"\"\n x = inputs\n\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n x = self.apply(\n inputs=x,\n layer=PositionEmbedding,\n input_dim=self.max_position,\n output_dim=self.embedding_size,\n merge_mode='add',\n hierarchical=self.hierarchical_position,\n embeddings_initializer=self.initializer,\n name='Embedding-Position'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Embedding-Mapping'\n )\n\n return x\n\n def apply_main_layers(self, inputs, index):\n \"\"\"GPT2的主体是基于Self-Attention的模块\n 顺序:LN --> Att --> Add --> LN --> FFN --> Add\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Transformer-%d-MultiHeadSelfAttention' % index\n feed_forward_name = 'Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n\n # Self Attention\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n epsilon=1e-5,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % attention_name\n )\n x = self.apply(\n inputs=[x, x, x, attention_mask],\n layer=MultiHeadAttention,\n arguments={'a_bias': True},\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n epsilon=1e-5,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n return x\n\n def apply_final_layers(self, inputs):\n \"\"\"剩余部分\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n epsilon=1e-5,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='Output-Norm'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Output-Dropout'\n )\n x = super(GPT2, self).apply_final_layers(x)\n\n return x\n\n def variable_mapping(self):\n \"\"\"映射到TF版GPT2权重格式\n \"\"\"\n mapping = super(GPT2, self).variable_mapping()\n mapping = {\n k: [i.replace('output/LayerNorm', 'input/LayerNorm') for i in v]\n for k, v in mapping.items()\n }\n mapping['Output-Norm'] = [\n 'gpt/output/LayerNorm/beta',\n 'gpt/output/LayerNorm/gamma',\n ]\n\n return mapping\n\n\nclass GPT2_ML(GPT):\n \"\"\"构建GPT2_ML模型\n 链接: https://github.com/imcaspar/gpt2-ml\n 注意:GPT2_ML虽然号称GPT2,但是它的结构其实更接近GPT,它自称GPT2的\n 原因大概是因为它开源的版本参数量达到了GPT2的15亿参数。\n \"\"\"\n def get_inputs(self):\n \"\"\"GPT2_ML的输入是token_ids\n \"\"\"\n x_in = self.apply(\n layer=Input, shape=(self.sequence_length,), name='Input-Token'\n )\n return x_in\n\n def apply_embeddings(self, inputs):\n \"\"\"GPT2_ML的embedding是token、position两者embedding之和\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n x = self.apply(\n inputs=x,\n layer=PositionEmbedding,\n input_dim=self.max_position,\n output_dim=self.embedding_size,\n merge_mode='add',\n hierarchical=self.hierarchical_position,\n embeddings_initializer=self.initializer,\n name='Embedding-Position'\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n epsilon=1e-5,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='Embedding-Norm'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Embedding-Mapping'\n )\n\n return x\n\n def apply_main_layers(self, inputs, index):\n \"\"\"GPT2_ML的主体是基于Self-Attention的模块\n 顺序:Att --> LN --> FFN --> Add --> LN\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Transformer-%d-MultiHeadSelfAttention' % index\n feed_forward_name = 'Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n\n # Self Attention\n xi, x, arguments = x, [x, x, x, attention_mask], {'a_bias': True}\n\n x = self.apply(\n inputs=x,\n layer=MultiHeadAttention,\n arguments=arguments,\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n epsilon=1e-5,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm-0' % feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n epsilon=1e-5,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm-1' % feed_forward_name\n )\n\n return x\n\n def load_variable(self, checkpoint, name):\n \"\"\"加载单个变量的函数\n \"\"\"\n variable = super(GPT2_ML, self).load_variable(checkpoint, name)\n if name == 'newslm/embeddings/word_embed':\n return self.load_embeddings(variable)\n else:\n return variable\n\n def variable_mapping(self):\n \"\"\"映射到官方GPT2_ML权重格式\n \"\"\"\n mapping = {\n 'Embedding-Token': ['newslm/embeddings/word_embed'],\n 'Embedding-Position': ['newslm/embeddings/pos_embed'],\n 'Embedding-Norm': [\n 'newslm/embeddings/LayerNorm_embed_norm/beta',\n 'newslm/embeddings/LayerNorm_embed_norm/gamma',\n ],\n }\n\n for i in range(self.num_hidden_layers):\n prefix = 'newslm/layer%02d/' % i\n mapping.update({\n 'Transformer-%d-MultiHeadSelfAttention' % i: [\n prefix + 'query_layer/kernel',\n prefix + 'query_layer/bias',\n prefix + 'key_layer/kernel',\n prefix + 'key_layer/bias',\n prefix + 'value_layer/kernel',\n prefix + 'value_layer/bias',\n prefix + 'context_projection_layer/kernel',\n prefix + 'context_projection_layer/bias',\n ],\n 'Transformer-%d-FeedForward-Norm-0' % i: [\n prefix + 'LayerNorm_mlp_ln0/beta',\n prefix + 'LayerNorm_mlp_ln0/gamma',\n ],\n 'Transformer-%d-FeedForward' % i: [\n prefix + 'intermediate/kernel',\n prefix + 'intermediate/bias',\n prefix + 'output/kernel',\n prefix + 'output/bias',\n ],\n 'Transformer-%d-FeedForward-Norm-1' % i: [\n prefix + 'LayerNorm_mlp_ln1/beta',\n prefix + 'LayerNorm_mlp_ln1/gamma',\n ],\n })\n\n return mapping\n\n\nclass T5_Base(Transformer):\n \"\"\"Google的T5模型(基类)\n 注意T5有两个版本,一开始放出来的版本称为t5.1.0,而后来放出了一个升级\n 版本称为t5.1.1,两者结构略有不同,包括后来放出来的多国语言版T5也采用\n 了t5.1.1的结构。\n t5.1.0: https://github.com/google-research/text-to-text-transfer-transformer\n t5.1.1: https://github.com/google-research/text-to-text-transfer-transformer/blob/master/released_checkpoints.md#t511\n multilingual-t5: https://github.com/google-research/multilingual-t5\n \"\"\"\n @insert_arguments(version='t5.1.0')\n def __init__(self, **kwargs):\n super(T5_Base, self).__init__(**kwargs)\n\n def load_variable(self, checkpoint, name):\n \"\"\"加载单个变量的函数\n \"\"\"\n variable = super(T5_Base, self).load_variable(checkpoint, name)\n if name == 'shared/embedding':\n return self.load_embeddings(variable)\n elif name == 'decoder/logits/kernel':\n return self.load_embeddings(variable.T).T\n elif 'relative_attention_bias' in name:\n return variable.T\n else:\n return variable\n\n def create_variable(self, name, value, dtype=None):\n \"\"\"在tensorflow中创建一个变量\n \"\"\"\n if 'relative_attention_bias' in name:\n value = value.T\n return super(T5_Base, self).create_variable(name, value, dtype)\n\n def variable_mapping(self):\n \"\"\"映射到官方T5权重格式\n \"\"\"\n mapping = {\n 'Embedding-Token': ['shared/embedding'],\n 'Encoder-Embedding-Relative-Position': [\n 'encoder/block_000/layer_000/SelfAttention/relative_attention_bias'\n ],\n 'Encoder-Output-Norm': ['encoder/final_layer_norm/scale'],\n 'Decoder-Embedding-Relative-Position': [\n 'decoder/block_000/layer_000/SelfAttention/relative_attention_bias',\n ],\n 'Decoder-Output-Norm': ['decoder/final_layer_norm/scale'],\n }\n\n for i in range(self.num_hidden_layers):\n # Encoder主体\n prefix = 'encoder/block_%03d/' % i\n mapping.update({\n 'Encoder-Transformer-%d-MultiHeadSelfAttention' % i: [\n prefix + 'layer_000/SelfAttention/q',\n prefix + 'layer_000/SelfAttention/k',\n prefix + 'layer_000/SelfAttention/v',\n prefix + 'layer_000/SelfAttention/o',\n ],\n 'Encoder-Transformer-%d-MultiHeadSelfAttention-Norm' % i: [\n prefix + 'layer_000/layer_norm/scale',\n ],\n 'Encoder-Transformer-%d-FeedForward' % i: [\n prefix + 'layer_001/DenseReluDense/wi/kernel',\n prefix + 'layer_001/DenseReluDense/wo/kernel',\n ],\n 'Encoder-Transformer-%d-FeedForward-Norm' % i: [\n prefix + 'layer_001/layer_norm/scale',\n ],\n })\n # Decoder主体\n prefix = 'decoder/block_%03d/' % i\n mapping.update({\n 'Decoder-Transformer-%d-MultiHeadSelfAttention' % i: [\n prefix + 'layer_000/SelfAttention/q',\n prefix + 'layer_000/SelfAttention/k',\n prefix + 'layer_000/SelfAttention/v',\n prefix + 'layer_000/SelfAttention/o',\n ],\n 'Decoder-Transformer-%d-MultiHeadSelfAttention-Norm' % i: [\n prefix + 'layer_000/layer_norm/scale',\n ],\n 'Decoder-Transformer-%d-MultiHeadCrossAttention' % i: [\n prefix + 'layer_001/EncDecAttention/q',\n prefix + 'layer_001/EncDecAttention/k',\n prefix + 'layer_001/EncDecAttention/v',\n prefix + 'layer_001/EncDecAttention/o',\n ],\n 'Decoder-Transformer-%d-MultiHeadCrossAttention-Norm' % i: [\n prefix + 'layer_001/layer_norm/scale',\n ],\n 'Decoder-Transformer-%d-FeedForward' % i: [\n prefix + 'layer_002/DenseReluDense/wi/kernel',\n prefix + 'layer_002/DenseReluDense/wo/kernel',\n ],\n 'Decoder-Transformer-%d-FeedForward-Norm' % i: [\n prefix + 'layer_002/layer_norm/scale',\n ],\n })\n\n if self.version == 't5.1.1':\n mapping['Encoder-Output-Norm'] = ['encoder/rms_norm/scale']\n mapping['Decoder-Output-Norm'] = ['decoder/rms_norm/scale']\n mapping['Decoder-Output-LM'] = ['decoder/logits/kernel']\n mapping = {\n k: [i.replace('layer_norm', 'rms_norm') for i in v]\n for k, v in mapping.items()\n }\n for i in range(self.num_hidden_layers):\n for layer in [\n 'Encoder-Transformer-%d-FeedForward' % i,\n 'Decoder-Transformer-%d-FeedForward' % i\n ]:\n mapping[layer] = [\n mapping[layer][0][:-7] + '_0' + mapping[layer][0][-7:],\n mapping[layer][0][:-7] + '_1' + mapping[layer][0][-7:],\n mapping[layer][1]\n ]\n\n return mapping\n\n\nclass T5_Encoder(T5_Base):\n \"\"\"Google的T5模型(Encoder)\n \"\"\"\n def get_inputs(self):\n \"\"\"T5的Encoder的输入只有token_ids\n \"\"\"\n x_in = self.apply(\n layer=Input,\n shape=(self.sequence_length,),\n name='Encoder-Input-Token'\n )\n return x_in\n\n def apply_embeddings(self, inputs):\n \"\"\"T5的embedding只有token embedding,\n 并把relative position embedding准备好,待attention使用。\n \"\"\"\n x = inputs\n\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Encoder-Embedding-Dropout'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Encoder-Embedding-Mapping'\n )\n\n return x\n\n def apply_main_layers(self, inputs, index):\n \"\"\"T5的Encoder的主体是基于Self-Attention的模块\n 顺序:LN --> Att --> Add --> LN --> FFN --> Add\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n attention_name = 'Encoder-Transformer-%d-MultiHeadSelfAttention' % index\n feed_forward_name = 'Encoder-Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n position_bias = self.compute_position_bias(x)\n\n # Self Attention\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % attention_name\n )\n x = self.apply(\n inputs=[x, x, x, position_bias],\n layer=MultiHeadAttention,\n arguments={'p_bias': 't5_relative'},\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n use_bias=False,\n attention_scale=False,\n kernel_initializer=self.initializer,\n name=attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n use_bias=False,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n\n return x\n\n def apply_final_layers(self, inputs):\n \"\"\"剩余部分\n \"\"\"\n x = inputs\n z = self.layer_norm_conds[0]\n\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='Encoder-Output-Norm'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Encoder-Output-Dropout'\n )\n\n return x\n\n def compute_position_bias(self, inputs=None):\n \"\"\"T5相对位置编码\n \"\"\"\n if self.position_bias is None:\n\n x = inputs\n p = self.apply(\n inputs=[x, x],\n layer=RelativePositionEmbeddingT5,\n input_dim=32,\n output_dim=self.num_attention_heads,\n bidirectional=True,\n embeddings_initializer=self.initializer,\n name='Encoder-Embedding-Relative-Position'\n )\n self.position_bias = p\n\n return self.position_bias\n\n\nclass T5_Decoder(LM_Mask, T5_Base):\n \"\"\"Google的T5模型(Decoder)\n \"\"\"\n def __init__(self, with_lm=True, **kwargs):\n super(T5_Decoder, self).__init__(**kwargs)\n self.with_lm = with_lm\n\n def get_inputs(self):\n \"\"\"T5的Decoder的输入为context序列和token_ids\n \"\"\"\n c_in = self.apply(\n layer=Input,\n shape=(self.sequence_length, self.hidden_size),\n name='Input-Context'\n )\n x_in = self.apply(\n layer=Input,\n shape=(self.sequence_length,),\n name='Decoder-Input-Token'\n )\n return [c_in, x_in]\n\n def apply_embeddings(self, inputs):\n \"\"\"T5的embedding只有token embedding,\n 并把relative position embedding准备好,待attention使用。\n \"\"\"\n c, x = inputs\n\n c = self.apply(\n inputs=c, layer=Masking, mask_value=0.0, name='Masked-Context'\n )\n x = self.apply(\n inputs=x,\n layer=Embedding,\n input_dim=self.vocab_size,\n output_dim=self.embedding_size,\n embeddings_initializer=self.initializer,\n mask_zero=True,\n name='Embedding-Token'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Decoder-Embedding-Dropout'\n )\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.hidden_size,\n kernel_initializer=self.initializer,\n name='Decoder-Embedding-Mapping'\n )\n\n return [c, x]\n\n def apply_main_layers(self, inputs, index):\n \"\"\"T5的Dencoder主体是基于Self-Attention、Cross-Attention的模块\n 顺序:LN --> Att1 --> Add --> LN --> Att2 --> Add --> LN --> FFN --> Add\n \"\"\"\n c, x = inputs\n z = self.layer_norm_conds[0]\n\n self_attention_name = 'Decoder-Transformer-%d-MultiHeadSelfAttention' % index\n cross_attention_name = 'Decoder-Transformer-%d-MultiHeadCrossAttention' % index\n feed_forward_name = 'Decoder-Transformer-%d-FeedForward' % index\n attention_mask = self.compute_attention_bias(index)\n position_bias = self.compute_position_bias([x, c])\n\n # Self Attention\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % self_attention_name\n )\n x = self.apply(\n inputs=[x, x, x, attention_mask, position_bias[0]],\n layer=MultiHeadAttention,\n arguments={\n 'a_bias': True,\n 'p_bias': 't5_relative'\n },\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n use_bias=False,\n attention_scale=False,\n kernel_initializer=self.initializer,\n name=self_attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % self_attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % self_attention_name\n )\n\n # Cross Attention\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % cross_attention_name\n )\n x = self.apply(\n inputs=[x, c, c, position_bias[1]],\n layer=MultiHeadAttention,\n arguments={\n 'a_bias': None,\n 'p_bias': 't5_relative'\n },\n heads=self.num_attention_heads,\n head_size=self.attention_head_size,\n out_dim=self.hidden_size,\n key_size=self.attention_key_size,\n use_bias=False,\n attention_scale=False,\n kernel_initializer=self.initializer,\n name=cross_attention_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % cross_attention_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % cross_attention_name\n )\n\n # Feed Forward\n xi = x\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='%s-Norm' % feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=FeedForward,\n units=self.intermediate_size,\n activation=self.hidden_act,\n use_bias=False,\n kernel_initializer=self.initializer,\n name=feed_forward_name\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='%s-Dropout' % feed_forward_name\n )\n x = self.apply(\n inputs=[xi, x], layer=Add, name='%s-Add' % feed_forward_name\n )\n\n return [c, x]\n\n def apply_final_layers(self, inputs):\n \"\"\"剩余部分\n \"\"\"\n c, x = inputs\n z = self.layer_norm_conds[0]\n\n x = self.apply(\n inputs=self.simplify([x, z]),\n layer=LayerNormalization,\n center=False,\n epsilon=1e-6,\n conditional=(z is not None),\n hidden_units=self.layer_norm_conds[1],\n hidden_activation=self.layer_norm_conds[2],\n hidden_initializer=self.initializer,\n name='Decoder-Output-Norm'\n )\n x = self.apply(\n inputs=x,\n layer=Dropout,\n rate=self.dropout_rate,\n name='Decoder-Output-Dropout'\n )\n x = self.apply(\n inputs=x,\n layer=Lambda,\n function=lambda x: x / self.hidden_size**0.5,\n mask=lambda i, m: m,\n name='Decoder-Output-Scale'\n )\n\n if self.with_lm:\n # 预测token概率部分\n if self.embedding_size != self.hidden_size:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.embedding_size,\n kernel_initializer=self.initializer,\n name='Decoder-Output-Mapping'\n )\n lm_activation = 'softmax' if self.with_lm is True else self.with_lm\n if self.version == 't5.1.0':\n x = self.apply(\n inputs=x,\n layer=Embedding,\n arguments={'mode': 'dense'},\n name='Embedding-Token'\n )\n x = self.apply(\n inputs=x,\n layer=Activation,\n activation=lm_activation,\n name='Dencoder-Output-LM-Activation'\n )\n else:\n x = self.apply(\n inputs=x,\n layer=Dense,\n units=self.vocab_size,\n activation=lm_activation,\n use_bias=False,\n kernel_initializer=self.initializer,\n name='Decoder-Output-LM'\n )\n\n return x\n\n def compute_attention_bias(self, inputs=None):\n \"\"\"修改LM Mask的序列长度(从 self.inputs[0] 改为 self.inputs[1] )\n \"\"\"\n old_inputs = self.inputs[:]\n self.inputs = [old_inputs[1]]\n mask = super(T5_Decoder, self).compute_attention_bias(inputs)\n self.inputs = old_inputs\n return mask\n\n def compute_position_bias(self, inputs=None):\n \"\"\"T5相对位置编码\n \"\"\"\n if self.position_bias is None:\n\n x, c = inputs\n p1 = self.apply(\n inputs=[x, x],\n layer=RelativePositionEmbeddingT5,\n input_dim=32,\n output_dim=self.num_attention_heads,\n bidirectional=False,\n embeddings_initializer=self.initializer,\n name='Decoder-Embedding-Relative-Position'\n )\n p2 = self.apply(\n inputs=[x, c],\n layer=RelativePositionEmbeddingT5,\n input_dim=32,\n output_dim=self.num_attention_heads,\n bidirectional=False,\n embeddings_initializer=self.initializer,\n name='Decoder-Embedding-Relative-Position'\n )\n self.position_bias = (p1, p2)\n\n return self.position_bias\n\n\nclass T5(T5_Base):\n \"\"\"Google的T5模型(Encoder-Decoder)\n \"\"\"\n def __init__(self, **kwargs):\n super(T5, self).__init__(**kwargs)\n kwargs['layers'] = self.layers\n e_name, d_name = 'Encoder', 'Decoder'\n if 'name' in kwargs:\n e_name = '%s_%s' % (kwargs['name'], e_name)\n d_name = '%s_%s' % (kwargs['name'], d_name)\n del kwargs['name'] # 防止重复传参\n self._encoder = T5_Encoder(name=e_name, **kwargs)\n self._decoder = T5_Decoder(name=d_name, **kwargs)\n\n def build(self, **kwargs):\n \"\"\"同时构建Encoder和Decoder\n \"\"\"\n self._encoder.build(**kwargs)\n self._decoder.build(**kwargs)\n self.encoder = self._encoder.model\n self.decoder = self._decoder.model\n self.inputs = self.encoder.inputs + self.decoder.inputs[1:]\n self.outputs = self.decoder(\n self.encoder.outputs + self.decoder.inputs[1:]\n )\n self.model = Model(self.inputs, self.outputs)\n\n\ndef extend_with_language_model(BaseModel):\n \"\"\"添加下三角的Attention Mask(语言模型用)\n \"\"\"\n class LanguageModel(LM_Mask, BaseModel):\n \"\"\"带下三角Attention Mask的派生模型\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(LanguageModel, self).__init__(*args, **kwargs)\n self.with_mlm = self.with_mlm or True\n\n return LanguageModel\n\n\ndef extend_with_unified_language_model(BaseModel):\n \"\"\"添加UniLM的Attention Mask(Seq2Seq模型用)\n \"\"\"\n class UnifiedLanguageModel(UniLM_Mask, BaseModel):\n \"\"\"带UniLM的Attention Mask的派生模型\n UniLM: https://arxiv.org/abs/1905.03197\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(UnifiedLanguageModel, self).__init__(*args, **kwargs)\n self.with_mlm = self.with_mlm or True\n\n return UnifiedLanguageModel\n\n\ndef build_transformer_model(\n config_path=None,\n checkpoint_path=None,\n model='bert',\n application='encoder',\n return_keras_model=True,\n **kwargs\n):\n \"\"\"根据配置文件构建模型,可选加载checkpoint权重\n \"\"\"\n configs = {}\n if config_path is not None:\n configs.update(json.load(open(config_path)))\n configs.update(kwargs)\n if 'max_position' not in configs:\n configs['max_position'] = configs.get('max_position_embeddings', 512)\n if 'dropout_rate' not in configs:\n configs['dropout_rate'] = configs.get('hidden_dropout_prob')\n if 'segment_vocab_size' not in configs:\n configs['segment_vocab_size'] = configs.get('type_vocab_size', 2)\n\n models = {\n 'bert': BERT,\n 'albert': ALBERT,\n 'albert_unshared': ALBERT_Unshared,\n 'roberta': BERT,\n 'nezha': NEZHA,\n 'roformer': RoFormer,\n 'electra': ELECTRA,\n 'gpt': GPT,\n 'gpt2': GPT2,\n 'gpt2_ml': GPT2_ML,\n 't5': T5,\n 't5_encoder': T5_Encoder,\n 't5_decoder': T5_Decoder,\n 't5.1.0': T5,\n 't5.1.0_encoder': T5_Encoder,\n 't5.1.0_decoder': T5_Decoder,\n 't5.1.1': T5,\n 't5.1.1_encoder': T5_Encoder,\n 't5.1.1_decoder': T5_Decoder,\n }\n\n if is_string(model):\n model = model.lower()\n MODEL = models[model]\n if model.startswith('t5.1.1'):\n configs['version'] = 't5.1.1'\n else:\n MODEL = model\n\n application = application.lower()\n if application in ['lm', 'unilm'] and model in ['electra', 't5']:\n raise ValueError(\n '\"%s\" model can not be used as \"%s\" application.\\n' %\n (model, application)\n )\n\n if application == 'lm':\n MODEL = extend_with_language_model(MODEL)\n elif application == 'unilm':\n MODEL = extend_with_unified_language_model(MODEL)\n\n transformer = MODEL(**configs)\n transformer.build(**configs)\n\n if checkpoint_path is not None:\n transformer.load_weights_from_checkpoint(checkpoint_path)\n\n if return_keras_model:\n return transformer.model\n else:\n return transformer\n" ]
[ [ "numpy.take_along_axis", "numpy.log", "numpy.pad", "numpy.power", "numpy.arange", "numpy.repeat", "numpy.cumsum", "numpy.concatenate", "numpy.argmax", "numpy.shape", "numpy.apply_along_axis", "numpy.array", "numpy.exp", "numpy.zeros", "numpy.roll", "numpy.empty" ], [ "numpy.concatenate", "numpy.dot", "numpy.average", "numpy.random.randn" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lucainnocenti/ultrafast-critical-ground-state-preparation-2007.07381
[ "29f80dcf914096555cee9bc2e18249a2c95d6a50", "29f80dcf914096555cee9bc2e18249a2c95d6a50", "29f80dcf914096555cee9bc2e18249a2c95d6a50", "29f80dcf914096555cee9bc2e18249a2c95d6a50" ]
[ "results/rabi_and_lmg_optimizations_20190227/script_rabi_bangramp_neldermead.py", "results/rabi_and_lmg_optimizations_crossingcriticalphase_20190305/insufficient_tf_optimizations/script_lmg_doublebang_powell_50spins_bound04.py", "src/hamiltonians.py", "results/lmg_optimizations_4spins_criticalpoint_fixed_20191018/script_lmg_crab4freq_neldermead_bound04_tf20_precise_fixedinitpoints.py" ]
[ "import os\nimport sys\nimport numpy as np\nimport pandas as pd\n\nimport logging\n\nif '../../' not in sys.path:\n sys.path.append('../../')\nimport src.optimization as optimization\n\n\nmodel = 'rabi'\nmodel_parameters = dict(N=100, Omega=100, omega_0=1.)\nprotocol = 'bangramp'\noptimization_method = 'Nelder-Mead'\n\n# ------ build and check name for output file\nadditional_file_name_qualifiers = None\noutput_file_name = (model + '_' + protocol + '_' +\n optimization_method.replace('-', '').lower())\nif additional_file_name_qualifiers is not None:\n output_file_name += '_' + additional_file_name_qualifiers\nfilenum = 1\n_output_file_name = output_file_name\nwhile os.path.isfile(_output_file_name + '.csv'):\n _output_file_name = output_file_name + '({:02})'.format(filenum)\n filenum += 1\noutput_file_name = _output_file_name + '.csv'\n\n# ------ set up logger\nlogFormatter = logging.Formatter(\"%(asctime)s [%(threadName)-12.12s]\"\n \"[%(levelname)-5.5s] %(message)s\")\nrootLogger = logging.getLogger()\nrootLogger.setLevel(logging.DEBUG)\n# consoleHandler = logging.StreamHandler()\n# consoleHandler.setFormatter(logFormatter)\n# rootLogger.addHandler(consoleHandler)\nfileHandler = logging.FileHandler(output_file_name[:-4] + '.log')\nfileHandler.setFormatter(logFormatter)\nfileHandler.setLevel(logging.DEBUG)\nrootLogger.addHandler(fileHandler)\n\n\nlogging.info('Output file name will be \"{}\"'.format(output_file_name))\n\n# ------ start optimization\nresults = optimization.find_best_protocol(\n problem_specification=dict(\n model=model,\n model_parameters=model_parameters,\n task='critical point state generation'\n ),\n optimization_specs=dict(\n protocol=protocol,\n optimization_method=optimization_method\n ),\n other_options=dict(\n scan_times=np.linspace(0.1, 4, 100)\n )\n)\n\n# ------ save results to file\nresults.to_csv(output_file_name)\n\n", "import os\nimport sys\nimport numpy as np\nimport pandas as pd\n\nimport logging\n\nif '../../' not in sys.path:\n sys.path.append('../../')\nimport src.optimization as optimization\n\n\nmodel = 'lmg'\nmodel_parameters = dict(num_spins=50)\nprotocol = 'doublebang'\noptimization_method = 'Powell'\nparameters_constraints = [-4, 4]\ntask=dict(initial_intensity=0, final_intensity=2)\n\n# ------ build and check name for output file\nadditional_file_name_qualifiers = '50spins'\noutput_file_name = (model + '_' + protocol + '_' +\n optimization_method.replace('-', '').lower() +\n '_bound{:02}'.format(parameters_constraints[1]))\nif additional_file_name_qualifiers is not None:\n output_file_name += '_' + additional_file_name_qualifiers\nfilenum = 1\n_output_file_name = output_file_name\nwhile os.path.isfile(_output_file_name + '.csv'):\n _output_file_name = output_file_name + '({:02})'.format(filenum)\n filenum += 1\noutput_file_name = _output_file_name + '.csv'\n\n# ------ set up logger\nlogFormatter = logging.Formatter(\"%(asctime)s [%(threadName)-12.12s]\"\n \"[%(levelname)-5.5s] %(message)s\")\nrootLogger = logging.getLogger()\nrootLogger.setLevel(logging.DEBUG)\n# consoleHandler = logging.StreamHandler()\n# consoleHandler.setFormatter(logFormatter)\n# rootLogger.addHandler(consoleHandler)\nfileHandler = logging.FileHandler(output_file_name[:-4] + '.log')\nfileHandler.setFormatter(logFormatter)\nfileHandler.setLevel(logging.DEBUG)\nrootLogger.addHandler(fileHandler)\n\n\nlogging.info('Output file name will be \"{}\"'.format(output_file_name))\n\n# ------ start optimization\nresults = optimization.find_best_protocol(\n problem_specification=dict(\n model=model,\n model_parameters=model_parameters,\n task=task\n ),\n optimization_specs=dict(\n protocol=protocol,\n optimization_method=optimization_method,\n parameters_constraints=parameters_constraints\n ),\n other_options=dict(\n scan_times=np.linspace(0.1, 4, 200)\n )\n)\n\n# ------ save results to file\nresults.to_csv(output_file_name)\n\n", "import datetime\nimport logging\nimport os\nimport pickle\nimport functools\nimport sys\nimport numbers\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport qutip\n\nfrom src.utils import ground_state\nimport src.protocol_ansatz as protocol_ansatz\n\n\nclass TimeDependentHamiltonian:\n def __init__(self, model_parameters):\n \"\"\"Should involve initialization of core model parameters.\n \n Define time-independent and time-dependent components (`H0` and `H1`),\n name of the model, and time-dependent protocol (as ProtocolAnsatz obj\n instance).\n \"\"\"\n self.H0 = None\n self.H1 = None\n self.td_protocol = None # a ProtocolAnsatz object\n self.model_parameters = None\n raise NotImplementedError('Children must override this.')\n \n def hamiltonian(self, parameter):\n \"\"\"Return the Hamiltonian for a given value of the parameter.\"\"\"\n return self.H0 + parameter * self.H1\n \n def ground_state(self, parameter):\n return ground_state(self.hamiltonian(parameter))\n \n def _parse_td_protocol(self, td_protocol_name):\n \"\"\"Input must be a string, parsed to figure out the protocol to use.\"\"\"\n if td_protocol_name == 'doublebang':\n self.td_protocol = protocol_ansatz.DoubleBangProtocolAnsatz()\n elif td_protocol_name == 'bangramp':\n self.td_protocol = protocol_ansatz.BangRampProtocolAnsatz()\n elif td_protocol_name == 'triplebang':\n self.td_protocol = protocol_ansatz.TripleBangProtocolAnsatz()\n else:\n raise ValueError('Other protocols must be given explicitly.')\n \n def critical_hamiltonian(self):\n return self.hamiltonian(self.critical_value)\n \n def critical_ground_state(self):\n return ground_state(self.critical_hamiltonian)\n \n def evolve_state(self, state, tlist, td_protocol_parameters,\n return_all_states=False, solver_options=None):\n if self.td_protocol is None:\n raise ValueError('The protocol must be specified first.')\n if isinstance(tlist, numbers.Number):\n tlist = np.linspace(0, tlist, 40)\n\n protocol = self.td_protocol # a protocol_ansatz.ProtocolAntatz object\n # we outsource evolving the states to the ProtocolAnsatz object (this\n # is because different protocols might prefer different ways to solve\n # the dynamics)\n return protocol.evolve_state(\n time_independent_ham=self.H0,\n time_dependent_ham=self.H1,\n protocol_parameters=td_protocol_parameters,\n initial_state=state, tlist=tlist,\n return_all_states=return_all_states, solver_options=solver_options\n )\n\n", "import os\nimport sys\nimport numpy as np\nimport pandas as pd\n\nimport logging\n\nif '../../' not in sys.path:\n sys.path.append('../../')\nimport src.utils\nimport src.optimization as optimization\nimport src.protocol_ansatz as protocol_ansatz\n\n\nmodel = 'lmg'\nmodel_parameters = dict(num_spins=4)\noptimization_method = 'Nelder-Mead'\nprotocol = 'crab'\nnum_frequencies = 4\n\nparameters_constraints = [-4, 4]\ninitial_parameters = [0] * (2 * num_frequencies)\n\n# ------ build and check name for output file\noutput_file_name = src.utils.make_new_data_filename(\n model=model, protocol=protocol, num_frequencies=num_frequencies,\n optim_method=optimization_method.replace('-', '').lower(),\n bound=parameters_constraints[1],\n other_stuff='tf20_precise_fixedinitpoints'\n)\n# ------ set up logger\nsrc.utils.basic_logger_configuration(filename=output_file_name[:-4] + '.log')\n# logFormatter = logging.Formatter(\"%(asctime)s [%(threadName)-12.12s]\"\n# \"[%(levelname)-5.5s] %(message)s\")\n# rootLogger = logging.getLogger()\n# rootLogger.setLevel(logging.DEBUG)\n# # consoleHandler = logging.StreamHandler()\n# # consoleHandler.setFormatter(logFormatter)\n# # rootLogger.addHandler(consoleHandler)\n# fileHandler = logging.FileHandler(output_file_name[:-4] + '.log')\n# fileHandler.setFormatter(logFormatter)\n# fileHandler.setLevel(logging.DEBUG)\n# rootLogger.addHandler(fileHandler)\n\n\nlogging.info('Output file name will be \"{}\"'.format(output_file_name))\n\n# ------ start optimization\nresults = optimization.find_best_protocol(\n problem_specification=dict(\n model=model,\n model_parameters=model_parameters,\n task='critical point'\n ),\n optimization_specs=dict(\n protocol=protocol, protocol_options=dict(num_frequencies=num_frequencies),\n optimization_method=optimization_method,\n initial_parameters=initial_parameters,\n parameters_constraints=parameters_constraints,\n optimization_options=dict(xatol=1e-16, fatol=1e-16, disp=True)\n ),\n other_options=dict(\n scan_times=np.linspace(0.1, 20, 1000)\n )\n)\n\n# ------ save results to file\nresults.to_csv(output_file_name)\n\n" ]
[ [ "numpy.linspace" ], [ "numpy.linspace" ], [ "numpy.linspace" ], [ "numpy.linspace" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wainshine/tensorflow
[ "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d", "dc7a8dc8546c679b9c7b3df7494ce4506bfc1a6d" ]
[ "tensorflow/python/tpu/device_assignment.py", "tensorflow/python/tpu/tpu_embedding_v2_utils.py", "tensorflow/python/distribute/collective_util.py", "tensorflow/python/data/experimental/kernel_tests/optimization/optimization_test.py", "tensorflow/lite/testing/op_tests/pool3d.py", "tensorflow/python/data/kernel_tests/iterator_test.py", "tensorflow/python/debug/cli/curses_ui.py", "tensorflow/lite/tools/flatbuffer_utils_test.py", "tensorflow/python/kernel_tests/sparse_ops/sparse_to_dense_op_py_test.py" ]
[ "# Copyright 2017 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\"\"\"Library of TPU helper functions.\"\"\"\n\nimport enum\nimport math\nfrom typing import List, Optional, Text, Tuple\n\nimport numpy as np\n\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.tpu.topology import Topology\nfrom tensorflow.python.util.tf_export import tf_export\n\n\nSINGLE_CORE_ASSIGNMENT = [[[0, 0, 0, 0]]]\n\n\ndef _compute_task_and_cores_to_replicas(core_assignment, topology):\n \"\"\"Computes a nested dict which maps task and logical core to replicas.\"\"\"\n task_and_cores_to_replicas = {}\n for replica in range(core_assignment.shape[0]):\n for logical_core in range(core_assignment.shape[1]):\n coordinates = core_assignment[replica, logical_core, :]\n task_id = topology.task_ordinal_at_coordinates(coordinates)\n if task_id not in task_and_cores_to_replicas:\n task_and_cores_to_replicas[task_id] = {}\n if logical_core not in task_and_cores_to_replicas[task_id]:\n task_and_cores_to_replicas[task_id][logical_core] = set()\n\n task_and_cores_to_replicas[task_id][logical_core].add(replica)\n\n task_to_sorted_replica_id = {}\n\n for task, core_to_replicas in task_and_cores_to_replicas.items():\n core_to_sorted_replicas = {}\n for core, replicas in core_to_replicas.items():\n core_to_sorted_replicas[core] = sorted(replicas)\n\n task_to_sorted_replica_id[task] = core_to_sorted_replicas\n return task_to_sorted_replica_id\n\n\n@tf_export(\"tpu.experimental.DeviceAssignment\")\nclass DeviceAssignment(object):\n \"\"\"Mapping from logical cores in a computation to the physical TPU topology.\n\n Prefer to use the `DeviceAssignment.build()` helper to construct a\n `DeviceAssignment`; it is easier if less flexible than constructing a\n `DeviceAssignment` directly.\n \"\"\"\n\n def __init__(self, topology: Topology, core_assignment: np.ndarray):\n \"\"\"Constructs a `DeviceAssignment` object.\n\n Args:\n topology: A `Topology` object that describes the physical TPU topology.\n core_assignment: A logical to physical core mapping, represented as a\n rank 3 numpy array. See the description of the `core_assignment`\n property for more details.\n\n Raises:\n ValueError: If `topology` is not `Topology` object.\n ValueError: If `core_assignment` is not a rank 3 numpy array.\n \"\"\"\n if not isinstance(topology, Topology):\n raise ValueError(\"topology must be a Topology object, got {}\".format(\n type(topology)))\n core_assignment = np.asarray(core_assignment, dtype=np.int32)\n\n self._topology = topology\n\n if core_assignment.ndim != 3:\n raise ValueError(\"core_assignment must be a rank 3 numpy array, \"\n f\"got shape {core_assignment.shape}\")\n\n self._num_replicas = core_assignment.shape[0]\n self._num_cores_per_replica = core_assignment.shape[1]\n\n if core_assignment.shape[-1] != topology.mesh_rank:\n raise ValueError(\n \"core_assignment.shape[-1] must have size equal to topology \"\n f\"rank ({topology.mesh_rank}), got \"\n f\"core_assignment.shape={core_assignment.shape}\")\n\n self._core_assignment = core_assignment\n self._task_and_cores_to_replicas = _compute_task_and_cores_to_replicas(\n self._core_assignment, topology)\n\n @property\n def topology(self) -> Topology:\n \"\"\"A `Topology` that describes the TPU topology.\"\"\"\n return self._topology\n\n @property\n def num_cores_per_replica(self) -> int:\n \"\"\"The number of cores per replica.\"\"\"\n return self._num_cores_per_replica\n\n @property\n def num_replicas(self) -> int:\n \"\"\"The number of replicas of the computation.\"\"\"\n return self._num_replicas\n\n @property\n def core_assignment(self) -> np.ndarray:\n \"\"\"The logical to physical core mapping.\n\n Returns:\n An integer numpy array of rank 3, with shape\n `[num_replicas, num_cores_per_replica, topology_rank]`. Maps\n (replica, logical core) pairs to physical topology coordinates.\n \"\"\"\n return self._core_assignment\n\n def coordinates(self, replica: int, logical_core: int) -> Tuple: # pylint:disable=g-bare-generic\n \"\"\"Returns the physical topology coordinates of a logical core.\"\"\"\n return tuple(self.core_assignment[replica, logical_core, :])\n\n def lookup_replicas(self, task_id: int, logical_core: int) -> List[int]:\n \"\"\"Lookup replica ids by task number and logical core.\n\n Args:\n task_id: TensorFlow task number.\n logical_core: An integer, identifying a logical core.\n Returns:\n A sorted list of the replicas that are attached to that task and\n logical_core.\n Raises:\n ValueError: If no replica exists in the task which contains the logical\n core.\n \"\"\"\n try:\n return self._task_and_cores_to_replicas[task_id][logical_core]\n except KeyError:\n raise ValueError(\n \"Can not find any replica in task: {} contains logical_core: {} \".\n format(task_id, logical_core))\n\n def tpu_ordinal(self, replica: int = 0, logical_core: int = 0) -> int:\n \"\"\"Returns the ordinal of the TPU device assigned to a logical core.\"\"\"\n coordinates = self.coordinates(replica, logical_core)\n return self._topology.tpu_device_ordinal_at_coordinates(coordinates)\n\n def host_device(self,\n replica: int = 0,\n logical_core: int = 0,\n job: Optional[Text] = None) -> Text:\n \"\"\"Returns the CPU device attached to a logical core.\"\"\"\n coordinates = self.coordinates(replica, logical_core)\n return self._topology.cpu_device_name_at_coordinates(coordinates, job=job)\n\n def tpu_device(self,\n replica: int = 0,\n logical_core: int = 0,\n job: Optional[Text] = None) -> Text:\n \"\"\"Returns the name of the TPU device assigned to a logical core.\"\"\"\n coordinates = self.coordinates(replica, logical_core)\n return self._topology.tpu_device_name_at_coordinates(coordinates, job=job)\n\n @staticmethod\n def build(topology: Topology,\n computation_shape: Optional[np.ndarray] = None,\n computation_stride: Optional[np.ndarray] = None,\n num_replicas: int = 1) -> \"DeviceAssignment\":\n return device_assignment(topology, computation_shape, computation_stride,\n num_replicas)\n\n\ndef _open_ring_2d(x_size: int, y_size: int,\n z_coord: int) -> List[Tuple[int, int, int]]:\n \"\"\"Ring-order of a X by Y mesh, with a fixed Z coordinate.\n\n For example, in a 4x4 mesh, this returns the following order.\n 0 -- 1 -- 2 -- 3\n | | | |\n 15-- 6 -- 5 -- 4\n | | | |\n 14-- 7 -- 8 -- 9\n | | | |\n 13-- 12-- 11-- 10\n\n Note that chip 0 is not included in the output.\n\n Args:\n x_size: An integer represents the mesh size in the x-dimension. Must be\n larger than 1.\n y_size: An integer represents the mesh size in the y-dimension. Must be\n larger than 1.\n z_coord: An integer represents the z-coordinate to use for the chips in the\n ring.\n\n Returns:\n A list of (x,y,z) triples in ring order.\n \"\"\"\n ret = []\n for i in range(y_size // 2):\n for j in range(1, x_size):\n ret.append((j, 2 * i, z_coord))\n for j in range(x_size - 1, 0, -1):\n ret.append((j, 2 * i + 1, z_coord))\n for i in range(y_size - 1, 0, -1):\n ret.append((0, i, z_coord))\n return ret\n\n\ndef _ring_3d(x_size: int, y_size: int,\n z_size: int) -> List[Tuple[int, int, int]]:\n \"\"\"Ring-order of a X by Y by Z mesh.\n\n Constructs the 3d ring from 2d rings that are stacked in the Z dimension and\n joined in one corner.\n\n z == 0:\n 0 -- 1 -- 2 -- 3\n | | | |\n 15 - 6 -- 5 -- 4\n | | | |\n 14 - 7 -- 8 -- 9\n | | | |\n 13 - 12 - 11 - 10\n z == 1:\n 63 - 30 - 29 - 28\n | | | |\n 16 - 25 - 26 - 27\n | | | |\n 17 - 24 - 23 - 22\n | | | |\n 18 - 19 - 20 - 21\n z == 2:\n 62 - 31 - 32 - 33\n | | | |\n 45 - 36 - 35 - 34\n | | | |\n 44 - 37 - 38 - 39\n | | | |\n 43 - 42 - 41 - 40\n z == 3:\n 61 - 60 - 59 - 58\n | | | |\n 46 - 55 - 56 - 57\n | | | |\n 47 - 54 - 53 - 52\n | | | |\n 48 - 49 - 50 - 51\n\n Args:\n x_size: An integer represents the mesh size in the x-dimension. Must be\n larger than 1.\n y_size: An integer represents the mesh size in the y-dimension. Must be\n larger than 1.\n z_size: An integer represents the mesh size in the z-dimension. Must be\n larger than 1. For example, in a 4x4x4 mesh, this returns the following\n order.\n\n Returns:\n A list of (x,y,z) triples in ring order.\n \"\"\"\n\n # Handle the case where 2 dimensions are size 1.\n if x_size == 1 and y_size == 1:\n return [(0, 0, i) for i in range(z_size)]\n if x_size == 1 and z_size == 1:\n return [(0, i, 0) for i in range(y_size)]\n if y_size == 1 and z_size == 1:\n return [(i, 0, 0) for i in range(x_size)]\n\n # Handle odd mesh dimensions. This never happens in practice, so we don't\n # bother to try building something optimal.\n if (x_size > 1 and x_size % 2 != 0) or (y_size > 1 and\n y_size % 2 != 0) or (z_size > 1 and\n z_size % 2 != 0):\n logging.warning(\"Odd dimension\")\n ret = []\n for z in range(z_size):\n for y in range(y_size):\n ret.extend((x, y, z) for x in range(x_size))\n return ret\n\n # Always start with chip 0.\n ret = [(0, 0, 0)]\n # Handle the case where one dimension is size 1. We just build a flat, 2d\n # ring.\n if z_size == 1:\n ret.extend(_open_ring_2d(x_size, y_size, 0))\n return ret\n if y_size == 1:\n ret = [(0, 0, 0)]\n ret.extend((x, y, z) for (x, z, y) in _open_ring_2d(x_size, z_size, 0))\n return ret\n if x_size == 1:\n ret = [(0, 0, 0)]\n ret.extend((x, y, z) for (y, z, x) in _open_ring_2d(y_size, z_size, 0))\n return ret\n\n # Handle the case where all dimensions have size > 1 and even.\n ret = [(0, 0, 0)]\n for i in range(0, z_size):\n r = _open_ring_2d(x_size, y_size, i)\n if i % 2 == 0:\n ret.extend(r)\n else:\n ret.extend(reversed(r))\n for i in range(z_size - 1, 0, -1):\n ret.append((0, 0, i))\n return ret\n\n\nclass DeviceOrderMode(enum.IntEnum):\n \"\"\"The way of determining device orders when computing device assignment.\"\"\"\n # By default the mode is set to AUTO, the library will choose to form rings\n # when that is possible.\n AUTO = 0\n # Form rings for replicas and model-parallel cores.\n RING = 1\n # Form meshes for replicas and/or model-parallel cores.\n MESH = 2\n\n\ndef device_assignment(\n topology: Topology,\n computation_shape: Optional[np.ndarray] = None,\n computation_stride: Optional[np.ndarray] = None,\n num_replicas: int = 1,\n device_order_mode: DeviceOrderMode = DeviceOrderMode.AUTO\n) -> DeviceAssignment:\n \"\"\"Computes a device_assignment of a computation across a TPU topology.\n\n Attempts to choose a compact grid of cores for locality.\n\n Returns a `DeviceAssignment` that describes the cores in the topology assigned\n to each core of each replica.\n\n `computation_shape` and `computation_stride` values should be powers of 2 for\n optimal packing.\n\n Args:\n topology: A `Topology` object that describes the TPU cluster topology. To\n obtain a TPU topology, evaluate the `Tensor` returned by\n `initialize_system` using `Session.run`. Either a serialized\n `TopologyProto` or a `Topology` object may be passed. Note: you must\n evaluate the `Tensor` first; you cannot pass an unevaluated `Tensor`\n here.\n computation_shape: A rank 1 int32 numpy array with size equal to the\n topology rank, describing the shape of the computation's block of cores.\n If None, the `computation_shape` is `[1] * topology_rank`.\n computation_stride: A rank 1 int32 numpy array of size `topology_rank`,\n describing the inter-core spacing of the `computation_shape` cores in the\n TPU topology. If None, the `computation_stride` is `[1] * topology_rank`.\n num_replicas: The number of computation replicas to run. The replicas will\n be packed into the free spaces of the topology.\n device_order_mode: An enum of `DeviceOrderMode` class which indicates\n whether to assign devices to form rings or meshes, or let the library to\n choose.\n\n Returns:\n A DeviceAssignment object, which describes the mapping between the logical\n cores in each computation replica and the physical cores in the TPU\n topology.\n\n Raises:\n ValueError: If `topology` is not a valid `Topology` object.\n ValueError: If `computation_shape` or `computation_stride` are not 1D int32\n numpy arrays with shape [3] where all values are positive.\n ValueError: If computation's replicas cannot fit into the TPU topology.\n \"\"\"\n # Deserialize the Topology proto, if it is a string.\n if isinstance(topology, bytes):\n topology = Topology(serialized=topology)\n\n if not isinstance(topology, Topology):\n raise ValueError(\n f\"`topology` is not a Topology object; got {type(topology)}\")\n\n topology_rank = len(topology.mesh_shape)\n mesh_shape = topology.mesh_shape\n if computation_shape is None:\n computation_shape = np.array([1] * topology_rank, dtype=np.int32)\n else:\n computation_shape = np.asarray(computation_shape, dtype=np.int32)\n\n if computation_stride is None:\n computation_stride = np.array([1] * topology_rank, dtype=np.int32)\n else:\n computation_stride = np.asarray(computation_stride, dtype=np.int32)\n\n if computation_shape.shape != (topology_rank,):\n raise ValueError(\n f\"computation_shape must have shape [{topology_rank}]; \"\n f\"got {computation_shape.shape}\"\n )\n if computation_stride.shape != (topology_rank,):\n raise ValueError(\n f\"computation_stride must have shape [{topology_rank}]; \"\n f\"got {computation_stride.shape}\"\n )\n\n if any(computation_shape < 1):\n raise ValueError(\n \"computation_shape must be positive; got computation_shape={}\".format(\n computation_shape))\n if any(computation_stride < 1):\n raise ValueError(\n \"computation_stride must be positive; got computation_stride={}\".format(\n computation_stride))\n\n # Computes the physical size of one computation instance.\n computation_footprint = computation_shape * computation_stride\n if any(computation_footprint > mesh_shape):\n raise ValueError(\n \"computation footprint {} does not fit in TPU topology shape {}\".format(\n computation_footprint, mesh_shape))\n\n # Computes how many copies of the computation footprint fit in the mesh.\n block_counts = mesh_shape // computation_footprint\n\n replica_counts = block_counts * computation_stride\n max_replicas = np.prod(replica_counts)\n if num_replicas > max_replicas:\n raise ValueError(\n \"requested {} replicas but only {} replicas with shape {} and \"\n \"computation_stride {} fit in a TPU mesh of shape {}\".format(\n num_replicas, max_replicas, computation_shape, computation_stride,\n mesh_shape))\n\n def ceil_of_ratio(n, m):\n return (n + m - 1) // m\n\n if topology.missing_devices.size == 0:\n replica_shape = [0] * topology_rank\n if num_replicas > 0:\n remaining_replicas = num_replicas\n remaining_dims = topology_rank\n\n # Choose dimensions as close to an equal cube as possible,\n # in order of increasing dimension size. By visiting dimensions\n # in increasing size, we assign the most constrained dimension\n # first, so we won't make infeasible choices.\n #\n # As a secondary sort order, visit the last dimension (core index) first,\n # then the other dimensions in increasing order. This means we try to use\n # both cores on the same chip in preference to two cores on different\n # chips. We visit the x dimension first, and the z dimension last, so\n # that we prefer to arrange adjacent replicas on the same machine when\n # possible.\n #\n # For example, if num_replicas == 4, we prefer to use a replica_shape of\n # (2,1,1,2) over (1,1,2,2).\n\n for x, ni in sorted(((x, ((i + 1) % topology_rank))\n for (i, x) in enumerate(replica_counts))):\n i = (ni + topology_rank - 1) % topology_rank\n target_size = int(math.ceil(remaining_replicas**(1.0 / remaining_dims)))\n replica_shape[i] = min(target_size, x)\n remaining_replicas = ceil_of_ratio(remaining_replicas, replica_shape[i])\n remaining_dims -= 1\n\n assert remaining_replicas == 1 and remaining_dims == 0\n\n # Assigns an offset to each replica such that no two replicas overlap.\n replica_offsets = np.full([num_replicas, topology_rank], -1, dtype=np.int32)\n\n enable_3d_tiling = (\n topology_rank == 4 and\n computation_shape[-1] == mesh_shape[-1] # Only handle 3D case.\n and np.prod(computation_stride) == 1 # Ensure no stride.\n and num_replicas == max_replicas) # Full replication.\n\n if device_order_mode != DeviceOrderMode.AUTO:\n if device_order_mode == DeviceOrderMode.RING and not enable_3d_tiling:\n raise ValueError(\n \"device_order_mode=DeviceOrderMode.RING is not compatible with the \"\n \"3D tiling current topology. Try setting \"\n \"device_order_mode=DeviceOrderMode.AUTO\"\n )\n enable_3d_tiling = device_order_mode == DeviceOrderMode.RING\n\n if enable_3d_tiling:\n assignment = []\n inner_ring = _ring_3d(computation_shape[0], computation_shape[1],\n computation_shape[2])\n outer_ring = _ring_3d(replica_shape[0], replica_shape[1],\n replica_shape[2])\n\n for replica in range(num_replicas):\n outer_x, outer_y, outer_z = outer_ring[replica]\n per_replica_assignment = []\n for index in range(np.prod(computation_shape)):\n inner_x, inner_y, inner_z = inner_ring[index // mesh_shape[-1]]\n px = outer_x * computation_shape[0] + inner_x\n py = outer_y * computation_shape[1] + inner_y\n pz = outer_z * computation_shape[2] + inner_z\n pi = index % mesh_shape[-1]\n per_replica_assignment.append([px, py, pz, pi])\n assignment.append(per_replica_assignment)\n else:\n for replica in range(num_replicas):\n # Chooses a replica number in each axis.\n t = replica\n pos = []\n # Visit the core number first.\n for dim in np.concatenate([[replica_shape[-1]], replica_shape[:-1]]):\n pos.append(t % dim)\n t //= dim\n replica_pos = np.concatenate([pos[1:], [pos[0]]])\n\n # Determines where that replica starts in each axis.\n outer = replica_pos // computation_stride\n inner = replica_pos % computation_stride\n replica_offsets[replica, :] = outer * computation_footprint + inner\n\n # Computes a logical core -> physical core mapping for each replica.\n indices = [\n np.arange(0, computation_shape[i] * computation_stride[i],\n computation_stride[i]) for i in range(topology_rank)\n ]\n indices = np.concatenate(\n [i[..., np.newaxis] for i in np.meshgrid(*indices, indexing=\"ij\")],\n axis=-1)\n indices = indices.reshape((-1, topology_rank))\n assignment = indices + replica_offsets[:, np.newaxis, :]\n else:\n # We have a slice with missing chips. We define a simple assignment by\n # ignoring computation stride. This assignment should enable a consistent\n # and correct device assignment on degraded slices. It is optimal when\n # weights are not sharded. But this device assignment may be sub-optimal for\n # other model parallelism scenarios.\n assert np.prod(computation_stride) == 1\n # Next, we check if we have sufficient devices.\n assert num_replicas * np.prod(\n computation_shape) <= topology.num_tasks * topology.num_tpus_per_task\n # Map replicas to physical devices in task order.\n device_coordinates = topology.device_coordinates\n assignment = []\n devices_per_replica = np.prod(computation_shape)\n for rindex in range(num_replicas):\n replica_assignment = []\n for index in range(devices_per_replica):\n logical_id = rindex * devices_per_replica + index\n # Pick logical cores in task order\n task = logical_id // topology.num_tpus_per_task\n device = logical_id % topology.num_tpus_per_task\n # Append physical cores to the replica assignment\n replica_assignment.append(device_coordinates[task, device, :])\n assignment.append(replica_assignment)\n\n return DeviceAssignment(topology, core_assignment=assignment)\n", "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Companion classes for mid level API for TPU Embeddings in TF2.\"\"\"\n\nimport abc\nimport math\nimport typing\nfrom typing import Any, Dict, Callable, List, Optional, Text, Tuple, TypeVar, Union\n\nfrom absl import logging\nimport six\n\nfrom tensorflow.core.protobuf.tpu import optimization_parameters_pb2\nfrom tensorflow.core.protobuf.tpu import tpu_embedding_configuration_pb2\nfrom tensorflow.python.distribute import sharded_variable\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework.tensor_shape import TensorShape\nfrom tensorflow.python.ops import init_ops_v2\nfrom tensorflow.python.ops import variables as tf_variables\nfrom tensorflow.python.tpu.ops import tpu_ops\nfrom tensorflow.python.types import core\nfrom tensorflow.python.util.tf_export import tf_export\n\n\nTableVariable = TypeVar(\"TableVariable\", sharded_variable.ShardedVariable,\n tf_variables.Variable)\nSlotVarCreationFnType = Callable[\n [TableVariable, List[Text], List[init_ops_v2.Initializer]],\n Dict[Text, TableVariable]]\nClipValueType = Union[Tuple[float, float], float]\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass _Optimizer(object):\n \"\"\"Base class for all optimizers, with common parameters.\"\"\"\n\n def __init__(\n self,\n learning_rate: Union[float, Callable[[], float]],\n use_gradient_accumulation: bool,\n clip_weight_min: Optional[float],\n clip_weight_max: Optional[float],\n weight_decay_factor: Optional[float],\n multiply_weight_decay_factor_by_learning_rate: bool,\n clipvalue: Optional[ClipValueType] = None,\n slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None):\n self.learning_rate = learning_rate\n self.use_gradient_accumulation = use_gradient_accumulation\n self.clip_weight_min = clip_weight_min\n self.clip_weight_max = clip_weight_max\n if not use_gradient_accumulation and clipvalue is not None:\n raise ValueError(\n f\"When `use_gradient_accumulation` is False, gradient clipping \"\n f\"cannot be used and `clipvalue` should be left as None. \"\n f\"Received value {clipvalue} for argument `clipvalue`.\")\n if clipvalue is None:\n clipvalue = (None, None)\n elif not isinstance(clipvalue, tuple):\n clipvalue = (-1. * clipvalue, clipvalue)\n self.clip_gradient_min, self.clip_gradient_max = clipvalue\n\n self.weight_decay_factor = weight_decay_factor\n self.multiply_weight_decay_factor_by_learning_rate = (\n multiply_weight_decay_factor_by_learning_rate)\n\n if (slot_variable_creation_fn is not None and\n not callable(slot_variable_creation_fn)):\n raise ValueError(\n f\"Argument `slot_variable_creation_fn` must be either None or a \"\n f\"callable. Received: {slot_variable_creation_fn}\")\n self.slot_variable_creation_fn = slot_variable_creation_fn\n\n @abc.abstractmethod\n def _slot_names(self) -> List[Text]:\n \"\"\"Returns the name of all the slot variables.\n\n This does not include the 'parameters' variable and these names must match\n the names of the slots variables as used in the corresponding\n `tpu_ops.load_tpu_embedding_*` ops.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def _slot_initializers(self) -> List[init_ops_v2.Initializer]:\n \"\"\"Returns initializers for slot variables.\n\n This returns a parallel list to self._slot_names().\n \"\"\"\n raise NotImplementedError\n\n def _set_optimization_parameters(\n self, parameters: optimization_parameters_pb2.OptimizationParameters):\n \"\"\"Sets the optimizer fields in the OptimizationParameters.\"\"\"\n if self.use_gradient_accumulation:\n parameters.gradient_accumulation_status = (\n optimization_parameters_pb2.GradientAccumulationStatus.ENABLED)\n else:\n parameters.gradient_accumulation_status = (\n optimization_parameters_pb2.GradientAccumulationStatus.DISABLED)\n\n if self.clip_weight_min is not None:\n parameters.clipping_limits.lower.value = self.clip_weight_min\n\n if self.clip_weight_max is not None:\n parameters.clipping_limits.upper.value = self.clip_weight_max\n\n if self.clip_gradient_min is not None:\n parameters.gradient_clipping_limits.lower.value = self.clip_gradient_min\n\n if self.clip_gradient_max is not None:\n parameters.gradient_clipping_limits.upper.value = self.clip_gradient_max\n\n if self.weight_decay_factor:\n parameters.weight_decay_factor = self.weight_decay_factor\n if self.multiply_weight_decay_factor_by_learning_rate:\n parameters.multiply_weight_decay_factor_by_learning_rate = True\n\n @abc.abstractmethod\n def _load(self) -> Callable[..., ops.Operation]:\n \"\"\"Returns the load function for the optimizer.\"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def _retrieve(self) -> Callable[..., core.Tensor]:\n \"\"\"Returns the retrieve function for the optimizer.\"\"\"\n raise NotImplementedError\n\n def _create_slots(\n self, table: \"TableConfig\",\n variable_creator: Callable[[Text, init_ops_v2.Initializer],\n tf_variables.Variable]\n ) -> Dict[Text, tf_variables.Variable]:\n \"\"\"Creates slot variables for table.\n\n Args:\n table: The table variable to create slots for.\n variable_creator: A function which creates variables. Takes parameters\n 'name', 'initializer'.\n\n Returns:\n A dict of variables, keyed by self._slot_names().\n \"\"\"\n if self.slot_variable_creation_fn is not None:\n return self.slot_variable_creation_fn(table, self._slot_names(),\n self._slot_initializers())\n else:\n slots = {}\n for slot, initializer in zip(self._slot_names(),\n self._slot_initializers()):\n slots[slot] = variable_creator(slot, initializer)\n return slots\n\n\n@tf_export(\"tpu.experimental.embedding.SGD\")\nclass SGD(_Optimizer):\n \"\"\"Optimization parameters for stochastic gradient descent for TPU embeddings.\n\n Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`\n argument to set the global optimizer and its parameters:\n\n ```\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n ...\n optimizer=tf.tpu.experimental.embedding.SGD(0.1))\n ```\n\n This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the\n optimizer parameter to set a table specific optimizer. This will override the\n optimizer and parameters for global embedding optimizer defined above:\n\n ```\n table_one = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...,\n optimizer=tf.tpu.experimental.embedding.SGD(0.2))\n table_two = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n\n feature_config = (\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_one),\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_two))\n\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n feature_config=feature_config,\n batch_size=...\n optimizer=tf.tpu.experimental.embedding.SGD(0.1))\n ```\n\n In the above example, the first feature will be looked up in a table that has\n a learning rate of 0.2 while the second feature will be looked up in a table\n that has a learning rate of 0.1.\n\n See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a\n complete description of these parameters and their impacts on the optimizer\n algorithm.\n \"\"\"\n\n def __init__(self,\n learning_rate: Union[float, Callable[[], float]] = 0.01,\n clip_weight_min: Optional[float] = None,\n clip_weight_max: Optional[float] = None,\n weight_decay_factor: Optional[float] = None,\n multiply_weight_decay_factor_by_learning_rate: bool = None,\n clipvalue: Optional[ClipValueType] = None):\n \"\"\"Optimization parameters for stochastic gradient descent.\n\n Args:\n learning_rate: The learning rate. It should be a floating point value or a\n callable taking no arguments for a dynamic learning rate.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n weight_decay_factor: amount of weight decay to apply; None means that the\n weights are not decayed. Weights are decayed by multiplying the weight\n by this factor each step.\n multiply_weight_decay_factor_by_learning_rate: if true,\n `weight_decay_factor` is multiplied by the current learning rate.\n clipvalue: Controls clipping of the gradient. Set to either a single\n positive scalar value to get clipping or a tiple of scalar values (min,\n max) to set a separate maximum or minimum. If one of the two entries is\n None, then there will be no clipping that direction. Note if this is\n set, you may see a decrease in performance as gradient accumulation\n will be enabled (it is normally off for SGD as it has no affect on\n accuracy). See\n 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for more\n information on gradient accumulation and its impact on tpu embeddings.\n \"\"\"\n use_gradient_accumulation = clipvalue is not None\n\n super(SGD, self).__init__(\n learning_rate, use_gradient_accumulation, clip_weight_min,\n clip_weight_max, weight_decay_factor,\n multiply_weight_decay_factor_by_learning_rate, clipvalue)\n\n def _slot_names(self) -> List[Text]:\n return []\n\n def _slot_initializers(self) -> List[init_ops_v2.Initializer]:\n return []\n\n def _set_optimization_parameters(\n self, parameters: optimization_parameters_pb2.OptimizationParameters):\n super(SGD, self)._set_optimization_parameters(parameters)\n parameters.stochastic_gradient_descent.SetInParent()\n\n def _load(self) -> Callable[..., ops.Operation]:\n return tpu_ops.load_tpu_embedding_stochastic_gradient_descent_parameters\n\n def _retrieve(self) -> Callable[..., core.Tensor]:\n return tpu_ops.retrieve_tpu_embedding_stochastic_gradient_descent_parameters\n\n\n@tf_export(\"tpu.experimental.embedding.Adagrad\")\nclass Adagrad(_Optimizer):\n \"\"\"Optimization parameters for Adagrad with TPU embeddings.\n\n Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`\n argument to set the global optimizer and its parameters:\n\n ```python\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n ...\n optimizer=tf.tpu.experimental.embedding.Adagrad(0.1))\n ```\n\n This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the\n optimizer parameter to set a table specific optimizer. This will override the\n optimizer and parameters for global embedding optimizer defined above:\n\n ```python\n table_one = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...,\n optimizer=tf.tpu.experimental.embedding.Adagrad(0.2))\n table_two = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n\n feature_config = (\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_one),\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_two))\n\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n feature_config=feature_config,\n batch_size=...\n optimizer=tf.tpu.experimental.embedding.Adagrad(0.1))\n ```\n\n In the above example, the first feature will be looked up in a table that has\n a learning rate of 0.2 while the second feature will be looked up in a table\n that has a learning rate of 0.1.\n\n See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a\n complete description of these parameters and their impacts on the optimizer\n algorithm.\n \"\"\"\n\n def __init__(\n self,\n learning_rate: Union[float, Callable[[], float]] = 0.001,\n initial_accumulator_value: float = 0.1,\n use_gradient_accumulation: bool = True,\n clip_weight_min: Optional[float] = None,\n clip_weight_max: Optional[float] = None,\n weight_decay_factor: Optional[float] = None,\n multiply_weight_decay_factor_by_learning_rate: bool = None,\n slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None,\n clipvalue: Optional[ClipValueType] = None):\n \"\"\"Optimization parameters for Adagrad.\n\n Args:\n learning_rate: The learning rate. It should be a floating point value or a\n callable taking no arguments for a dynamic learning rate.\n initial_accumulator_value: initial accumulator for Adagrad.\n use_gradient_accumulation: setting this to `False` makes embedding\n gradients calculation less accurate but faster.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n weight_decay_factor: amount of weight decay to apply; None means that the\n weights are not decayed.\n multiply_weight_decay_factor_by_learning_rate: if true,\n `weight_decay_factor` is multiplied by the current learning rate.\n slot_variable_creation_fn: If you wish do directly control the creation of\n the slot variables, set this to a callable taking three parameters: a\n table variable, a list of slot names to create for it, and a list of\n initializers. This function should return a dict with the slot names\n as keys and the created variables as values with types matching the\n table variable. When set to None (the default), uses the built-in\n variable creation.\n clipvalue: Controls clipping of the gradient. Set to either a single\n positive scalar value to get clipping or a tuple of scalar values (min,\n max) to set a separate maximum or minimum. If one of the two entries is\n None, then there will be no clipping that direction.\n \"\"\"\n super(Adagrad, self).__init__(\n learning_rate, use_gradient_accumulation, clip_weight_min,\n clip_weight_max, weight_decay_factor,\n multiply_weight_decay_factor_by_learning_rate, clipvalue,\n slot_variable_creation_fn)\n if initial_accumulator_value <= 0:\n raise ValueError(\n f\"Argument `initial_accumulator_value` must be a positive float. \"\n f\"Received: {initial_accumulator_value}\")\n self.initial_accumulator_value = initial_accumulator_value\n\n def _slot_names(self) -> List[Text]:\n return [\"accumulators\"]\n\n def _slot_initializers(self) -> List[init_ops_v2.Initializer]:\n return [init_ops_v2.Constant(self.initial_accumulator_value)]\n\n def _set_optimization_parameters(\n self, parameters: optimization_parameters_pb2.OptimizationParameters):\n super(Adagrad, self)._set_optimization_parameters(parameters)\n parameters.adagrad.SetInParent()\n\n def _load(self) -> Callable[..., ops.Operation]:\n return tpu_ops.load_tpu_embedding_adagrad_parameters\n\n def _retrieve(self) -> Callable[..., core.Tensor]:\n return tpu_ops.retrieve_tpu_embedding_adagrad_parameters\n\n\n@tf_export(\"tpu.experimental.embedding.FTRL\")\nclass FTRL(_Optimizer):\n \"\"\"Optimization parameters for FTRL with TPU embeddings.\n\n See Algorithm 1 of this\n [paper](https://research.google.com/pubs/archive/41159.pdf).\n\n Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`\n argument to set the global optimizer and its parameters:\n\n ```python\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n ...\n optimizer=tf.tpu.experimental.embedding.FTRL(0.1))\n ```\n\n This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the\n optimizer parameter to set a table specific optimizer. This will override the\n optimizer and parameters for global embedding optimizer defined above:\n\n ```python\n table_one = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...,\n optimizer=tf.tpu.experimental.embedding.FTRL(0.2))\n table_two = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n\n feature_config = (\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_one),\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_two))\n\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n feature_config=feature_config,\n batch_size=...\n optimizer=tf.tpu.experimental.embedding.FTRL(0.1))\n ```\n\n In the above example, the first feature will be looked up in a table that has\n a learning rate of 0.2 while the second feature will be looked up in a table\n that has a learning rate of 0.1.\n\n See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a\n complete description of these parameters and their impacts on the optimizer\n algorithm.\n \"\"\"\n\n def __init__(\n self,\n learning_rate: Union[float, Callable[[], float]] = 0.001,\n learning_rate_power: float = -0.5,\n l1_regularization_strength: float = 0.0,\n l2_regularization_strength: float = 0.0,\n beta: float = 0.0,\n initial_accumulator_value: float = 0.1,\n use_gradient_accumulation: bool = True,\n clip_weight_min: Optional[float] = None,\n clip_weight_max: Optional[float] = None,\n weight_decay_factor: Optional[float] = None,\n multiply_weight_decay_factor_by_learning_rate: bool = None,\n slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None,\n clipvalue: Optional[ClipValueType] = None,\n multiply_linear_by_learning_rate: bool = False,\n allow_zero_accumulator: bool = False):\n \"\"\"Optimization parameters for Adagrad.\n\n Args:\n learning_rate: The learning rate. It should be a floating point value or a\n callable taking no arguments for a dynamic learning rate.\n learning_rate_power: A float value, must be less or equal to zero.\n Controls how the learning rate decreases during training. Use zero for a\n fixed learning rate.\n l1_regularization_strength: A float value, must be greater than or equal\n to zero.\n l2_regularization_strength: A float value, must be greater than or equal\n to zero.\n beta: A float value, representing the beta value from the paper.\n initial_accumulator_value: The starting value for accumulators. Only zero\n or positive values are allowed.\n use_gradient_accumulation: setting this to `False` makes embedding\n gradients calculation less accurate but faster.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n weight_decay_factor: amount of weight decay to apply; None means that the\n weights are not decayed.\n multiply_weight_decay_factor_by_learning_rate: if true,\n `weight_decay_factor` is multiplied by the current learning rate.\n slot_variable_creation_fn: If you wish do directly control the creation of\n the slot variables, set this to a callable taking three parameters: a\n table variable, a list of slot names to create for it, and a list of\n initializers. This function should return a dict with the slot names\n as keys and the created variables as values with types matching the\n table variable. When set to None (the default), uses the built-in\n variable creation.\n clipvalue: Controls clipping of the gradient. Set to either a single\n positive scalar value to get clipping or a tuple of scalar values (min,\n max) to set a separate maximum or minimum. If one of the two entries is\n None, then there will be no clipping that direction.\n multiply_linear_by_learning_rate: If set to True, a modified formula is\n used for FTRL that treats the \"linear\" accumulator as being\n pre-multiplied by the learning rate (i.e., the accumulator named\n \"linear\" actually stores \"linear * learning_rate\"). Other than\n checkpoint compatibility, this is mathematically equivalent for a static\n learning rate; for a dynamic learning rate, it is nearly the same as\n long as the learning rate does not change quickly. The benefit of this\n is that the modified formula handles zero and near-zero learning rates\n without producing NaNs, improving flexibility for learning rate ramp-up.\n allow_zero_accumulator: If set to True, changes some internal formulas to\n allow zero and near-zero accumulator values at the cost of some\n performance; this only needs to be set if you are using an initial\n accumulator value of zero, which is uncommon.\n \"\"\"\n super().__init__(learning_rate, use_gradient_accumulation, clip_weight_min,\n clip_weight_max, weight_decay_factor,\n multiply_weight_decay_factor_by_learning_rate, clipvalue,\n slot_variable_creation_fn)\n if initial_accumulator_value <= 0:\n raise ValueError(\n f\"Argument `initial_accumulator_value` must be a positive float. \"\n f\"Received: {initial_accumulator_value}\")\n self.initial_accumulator_value = initial_accumulator_value\n self.learning_rate_power = learning_rate_power\n self.l1_regularization_strength = l1_regularization_strength\n self.l2_regularization_strength = l2_regularization_strength\n self.beta = beta\n self.multiply_linear_by_learning_rate = multiply_linear_by_learning_rate\n self.allow_zero_accumulator = allow_zero_accumulator\n\n def _slot_names(self) -> List[Text]:\n return [\"accumulators\", \"linears\"]\n\n def _slot_initializers(self) -> List[init_ops_v2.Initializer]:\n return [\n init_ops_v2.Constant(self.initial_accumulator_value),\n init_ops_v2.Constant()\n ]\n\n def _set_optimization_parameters(\n self, parameters: optimization_parameters_pb2.OptimizationParameters):\n super()._set_optimization_parameters(parameters)\n ftrl = parameters.ftrl\n ftrl.l1 = self.l1_regularization_strength\n ftrl.l2 = self.l2_regularization_strength\n ftrl.lr_power = self.learning_rate_power\n ftrl.beta = self.beta\n ftrl.multiply_linear_by_lr = self.multiply_linear_by_learning_rate\n ftrl.allow_zero_accumulator = self.allow_zero_accumulator\n\n def _load(self) -> Callable[..., ops.Operation]:\n return tpu_ops.load_tpu_embedding_ftrl_parameters\n\n def _retrieve(self) -> Callable[..., core.Tensor]:\n return tpu_ops.retrieve_tpu_embedding_ftrl_parameters\n\n\n@tf_export(\"tpu.experimental.embedding.Adam\")\nclass Adam(_Optimizer):\n \"\"\"Optimization parameters for Adam with TPU embeddings.\n\n Pass this to `tf.tpu.experimental.embedding.TPUEmbedding` via the `optimizer`\n argument to set the global optimizer and its parameters:\n\n NOTE: By default this optimizer is lazy, i.e. it will not apply the gradient\n update of zero to rows that were not looked up. You can change this behavior\n by setting `lazy_adam` to `False`.\n\n ```python\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n ...\n optimizer=tf.tpu.experimental.embedding.Adam(0.1))\n ```\n\n This can also be used in a `tf.tpu.experimental.embedding.TableConfig` as the\n optimizer parameter to set a table specific optimizer. This will override the\n optimizer and parameters for global embedding optimizer defined above:\n\n ```python\n table_one = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...,\n optimizer=tf.tpu.experimental.embedding.Adam(0.2))\n table_two = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n\n feature_config = (\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_one),\n tf.tpu.experimental.embedding.FeatureConfig(\n table=table_two))\n\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n feature_config=feature_config,\n batch_size=...\n optimizer=tf.tpu.experimental.embedding.Adam(0.1))\n ```\n\n In the above example, the first feature will be looked up in a table that has\n a learning rate of 0.2 while the second feature will be looked up in a table\n that has a learning rate of 0.1.\n\n See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a\n complete description of these parameters and their impacts on the optimizer\n algorithm.\n \"\"\"\n\n def __init__(\n self,\n learning_rate: Union[float, Callable[[], float]] = 0.001,\n beta_1: float = 0.9,\n beta_2: float = 0.999,\n epsilon: float = 1e-07,\n lazy_adam: bool = True,\n sum_inside_sqrt: bool = True,\n use_gradient_accumulation: bool = True,\n clip_weight_min: Optional[float] = None,\n clip_weight_max: Optional[float] = None,\n weight_decay_factor: Optional[float] = None,\n multiply_weight_decay_factor_by_learning_rate: bool = None,\n slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None,\n clipvalue: Optional[ClipValueType] = None):\n \"\"\"Optimization parameters for Adam.\n\n See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a\n complete description of these parameters and their impacts on the optimizer\n algorithm.\n\n Args:\n learning_rate: The learning rate. It should be a floating point value or a\n callable taking no arguments for a dynamic learning rate.\n beta_1: A float value. The exponential decay rate for the 1st moment\n estimates.\n beta_2: A float value. The exponential decay rate for the 2nd moment\n estimates.\n epsilon: A small constant for numerical stability.\n lazy_adam: Use lazy Adam instead of Adam. Lazy Adam trains faster.\n sum_inside_sqrt: When this is true, the Adam update formula is changed\n from `m / (sqrt(v) + epsilon)` to `m / sqrt(v + epsilon**2)`. This\n option improves the performance of TPU training and is not expected to\n harm model quality.\n use_gradient_accumulation: Setting this to `False` makes embedding\n gradients calculation less accurate but faster.\n clip_weight_min: the minimum value to clip by; None means -infinity.\n clip_weight_max: the maximum value to clip by; None means +infinity.\n weight_decay_factor: amount of weight decay to apply; None means that the\n weights are not decayed.\n multiply_weight_decay_factor_by_learning_rate: if true,\n `weight_decay_factor` is multiplied by the current learning rate.\n slot_variable_creation_fn: If you wish do directly control the creation of\n the slot variables, set this to a callable taking three parameters: a\n table variable, a list of slot names to create for it, and a list of\n initializers. This function should return a dict with the slot names\n as keys and the created variables as values with types matching the\n table variable. When set to None (the default), uses the built-in\n variable creation.\n clipvalue: Controls clipping of the gradient. Set to either a single\n positive scalar value to get clipping or a tiple of scalar values (min,\n max) to set a separate maximum or minimum. If one of the two entries is\n None, then there will be no clipping that direction.\n \"\"\"\n super(Adam, self).__init__(\n learning_rate, use_gradient_accumulation, clip_weight_min,\n clip_weight_max, weight_decay_factor,\n multiply_weight_decay_factor_by_learning_rate, clipvalue,\n slot_variable_creation_fn)\n if beta_1 < 0. or beta_1 >= 1.:\n raise ValueError(\n f\"Argument `beta_1` must be >= 0 and < 1. Received: {beta_1}.\")\n if beta_2 < 0. or beta_2 >= 1.:\n raise ValueError(\n f\"Argument `beta_2` must be >= 0 and < 1. Received: {beta_1}.\")\n if epsilon <= 0.:\n raise ValueError(\"epsilon must be positive; got {}.\".format(epsilon))\n if not use_gradient_accumulation and not lazy_adam:\n raise ValueError(\n \"When disabling lazy Adam (`lazy_adam=False`), \"\n \"gradient accumulation must be used. \"\n \"Set `use_gradient_accumulation` to False.\")\n\n self.beta_1 = beta_1\n self.beta_2 = beta_2\n self.epsilon = epsilon\n self.lazy_adam = lazy_adam\n self.sum_inside_sqrt = sum_inside_sqrt\n\n def _slot_names(self) -> List[Text]:\n return [\"momenta\", \"velocities\"]\n\n def _slot_initializers(self) -> List[init_ops_v2.Initializer]:\n return [init_ops_v2.Constant(), init_ops_v2.Constant()]\n\n def _set_optimization_parameters(\n self, parameters: optimization_parameters_pb2.OptimizationParameters):\n super(Adam, self)._set_optimization_parameters(parameters)\n parameters.adam.beta1 = self.beta_1\n parameters.adam.beta2 = self.beta_2\n parameters.adam.epsilon = self.epsilon\n parameters.adam.use_non_lazy_adam = not self.lazy_adam\n parameters.adam.use_sum_inside_sqrt = self.sum_inside_sqrt\n\n def _load(self) -> Callable[..., ops.Operation]:\n return tpu_ops.load_tpu_embedding_adam_parameters\n\n def _retrieve(self) -> Callable[..., core.Tensor]:\n return tpu_ops.retrieve_tpu_embedding_adam_parameters\n\n\n@tf_export(\"tpu.experimental.embedding.TableConfig\")\nclass TableConfig(object):\n \"\"\"Configuration data for one embedding table.\n\n This class holds the configuration data for a single embedding table. It is\n used as the `table` parameter of a\n `tf.tpu.experimental.embedding.FeatureConfig`. Multiple\n `tf.tpu.experimental.embedding.FeatureConfig` objects can use the same\n `tf.tpu.experimental.embedding.TableConfig` object. In this case a shared\n table will be created for those feature lookups.\n\n ```python\n table_config_one = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n table_config_two = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n feature_config = {\n 'feature_one': tf.tpu.experimental.embedding.FeatureConfig(\n table=table_config_one),\n 'feature_two': tf.tpu.experimental.embedding.FeatureConfig(\n table=table_config_one),\n 'feature_three': tf.tpu.experimental.embedding.FeatureConfig(\n table=table_config_two)}\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n feature_config=feature_config,\n batch_size=...\n optimizer=tf.tpu.experimental.embedding.Adam(0.1))\n ```\n\n The above configuration has 2 tables, and three features. The first two\n features will be looked up in the first table and the third feature will be\n looked up in the second table.\n\n \"\"\"\n\n def __init__(self,\n vocabulary_size: int,\n dim: int,\n initializer: Optional[Callable[[Any], None]] = None,\n optimizer: Optional[_Optimizer] = None,\n combiner: Text = \"mean\",\n name: Optional[Text] = None):\n \"\"\"Embedding table configuration.\n\n Args:\n vocabulary_size: Size of the table's vocabulary (number of rows).\n dim: The embedding dimension (width) of the table.\n initializer: A callable initializer taking one parameter, the shape of the\n variable that will be initialized. Will be called once per task, to\n initialize that task's shard of the embedding table. If not specified,\n defaults to `truncated_normal_initializer` with mean `0.0` and standard\n deviation `1/sqrt(dim)`.\n optimizer: An optional instance of an optimizer parameters class, instance\n of one of `tf.tpu.experimental.embedding.SGD`,\n `tf.tpu.experimental.embedding.Adagrad` or\n `tf.tpu.experimental.embedding.Adam`. It set will override the global\n optimizer passed to `tf.tpu.experimental.embedding.TPUEmbedding`.\n combiner: A string specifying how to reduce if there are multiple entries\n in a single row. Currently 'mean', 'sqrtn', 'sum' are supported, with\n 'mean' the default. 'sqrtn' often achieves good accuracy, in particular\n with bag-of-words columns. For more information, see\n `tf.nn.embedding_lookup_sparse`.\n name: An optional string used to name the table. Useful for debugging.\n\n Returns:\n `TableConfig`.\n\n Raises:\n ValueError: if `vocabulary_size` is not a positive integer.\n ValueError: if `dim` is not a positive integer.\n ValueError: if `initializer` is specified and is not callable.\n ValueError: if `combiner` is not supported.\n \"\"\"\n if not isinstance(vocabulary_size, int) or vocabulary_size < 1:\n raise ValueError(\n f\"Argument `vocabulary_size` must be an int and must be >= 1. \"\n f\"Received: {vocabulary_size}\")\n\n if not isinstance(dim, int) or dim < 1:\n raise ValueError(\n f\"Argument `dim` (embedding dimension) \"\n f\"must be an int and must be >= 1. Received: {dim}\")\n\n if (initializer is not None) and (not callable(initializer)):\n raise ValueError(\n f\"Argument `initializer` must be a callable (or None). \"\n f\"Received: {initializer}\")\n if initializer is None:\n initializer = init_ops_v2.TruncatedNormal(mean=0.0,\n stddev=1/math.sqrt(dim))\n accepted_combiners = (\"mean\", \"sum\", \"sqrtn\")\n if combiner not in accepted_combiners:\n raise ValueError(\n f\"Argument `combiner` must be one of {accepted_combiners}. \"\n f\"Received: {combiner}\")\n\n self.vocabulary_size = vocabulary_size\n self.dim = dim\n self.initializer = initializer\n self.optimizer = optimizer\n self.combiner = combiner\n self.name = name\n\n def __repr__(self):\n # If using the default initializer, just print \"None\" for clarity.\n initializer = self.initializer\n\n if isinstance(initializer, init_ops_v2.TruncatedNormal):\n # PY2 type checking can't infer type of initializer even after if.\n initializer = typing.cast(init_ops_v2.TruncatedNormal, initializer)\n if (initializer.mean == 0.0\n and math.isclose(initializer.stddev, 1/math.sqrt(self.dim))): # pytype: disable=module-attr (math.isclose not in PY2)\n initializer = None\n\n return (\n \"TableConfig(vocabulary_size={vocabulary_size!r}, dim={dim!r}, \"\n \"initializer={initializer!r}, optimizer={optimizer!r}, \"\n \"combiner={combiner!r}, name={name!r})\".format(\n vocabulary_size=self.vocabulary_size,\n dim=self.dim,\n initializer=initializer,\n optimizer=self.optimizer,\n combiner=self.combiner,\n name=self.name,)\n )\n\n\n@tf_export(\"tpu.experimental.embedding.FeatureConfig\")\nclass FeatureConfig(object):\n \"\"\"Configuration data for one embedding feature.\n\n This class holds the configuration data for a single embedding feature. The\n main use is to assign features to `tf.tpu.experimental.embedding.TableConfig`s\n via the table parameter:\n\n ```python\n table_config_one = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n table_config_two = tf.tpu.experimental.embedding.TableConfig(\n vocabulary_size=...,\n dim=...)\n feature_config = {\n 'feature_one': tf.tpu.experimental.embedding.FeatureConfig(\n table=table_config_one),\n 'feature_two': tf.tpu.experimental.embedding.FeatureConfig(\n table=table_config_one),\n 'feature_three': tf.tpu.experimental.embedding.FeatureConfig(\n table=table_config_two)}\n embedding = tf.tpu.experimental.embedding.TPUEmbedding(\n feature_config=feature_config,\n batch_size=...\n optimizer=tf.tpu.experimental.embedding.Adam(0.1))\n ```\n\n The above configuration has 2 tables, and three features. The first two\n features will be looked up in the first table and the third feature will be\n looked up in the second table.\n\n You can also specify the output shape for each feature. The output shape\n should be the expected activation shape excluding the table dimension. For\n dense and sparse tensor, the output shape should be the same as the input\n shape excluding the last dimension. For ragged tensor, the output shape can\n mismatch the input shape.\n\n NOTE: The `max_sequence_length` will be only used when the input tensor has\n rank 2 and the `output_shape` is not set in the feature config.\n\n When feeding features into `embedding.enqueue` they can be `tf.Tensor`s,\n `tf.SparseTensor`s or `tf.RaggedTensor`s. When the argument\n `max_sequence_length` is 0, the default, you should expect a output of\n `embedding.dequeue` for this feature of shape `(batch_size, dim)`. If\n `max_sequence_length` is greater than 0, the feature is embedded as a sequence\n and padded up to the given length. The shape of the output for this feature\n will be `(batch_size, max_sequence_length, dim)`.\n \"\"\"\n\n def __init__(self,\n table: TableConfig,\n max_sequence_length: int = 0,\n validate_weights_and_indices: bool = True,\n output_shape: Optional[Union[List[int], TensorShape]] = None,\n name: Optional[Text] = None):\n \"\"\"Feature configuration.\n\n Args:\n table: An instance of `tf.tpu.experimental.embedding.TableConfig`,\n describing the table in which this feature should be looked up.\n max_sequence_length: If positive, the feature is a sequence feature with\n the corresponding maximum sequence length. If the sequence is longer\n than this, it will be truncated. If 0, the feature is not a sequence\n feature.\n validate_weights_and_indices: If true, uses safe_embedding_lookup during\n serving which ensures there are no empty rows and all weights and ids\n are positive at the expense of extra compute cost.\n output_shape: Optional argument to config the output shape of the feature\n activation. If provided, the feature feeding to the `embedding.enqueue`\n has to match the shape (for ragged tensor, the input shape and output\n shape can mismatch). If not provided, the shape can be either provided\n to the `embedding.build` or auto detected at the runtime.\n name: An optional name for the feature, useful for debugging.\n\n Returns:\n `FeatureConfig`.\n\n Raises:\n ValueError: if `table` is not an instance of\n `tf.tpu.experimental.embedding.TableConfig`.\n ValueError: if `max_sequence_length` not an integer or is negative.\n \"\"\"\n if not isinstance(table, TableConfig):\n raise ValueError(f\"Argument `table` has invalid type {type(table)}. \"\n \"Expected `tf.tpu.experimental.embedding.TableConfig`.\")\n\n if not isinstance(max_sequence_length, int) or max_sequence_length < 0:\n raise ValueError(\n f\"Argument `max_sequence_length` must be an int and must be >= 0. \"\n f\"Received: {max_sequence_length}\")\n\n self.table = table\n self.max_sequence_length = max_sequence_length\n self.name = name\n self.output_shape = TensorShape(output_shape)\n\n if not isinstance(\n validate_weights_and_indices, bool):\n raise ValueError(\n f\"Argument `validate_weights_and_indices` must be a boolean. \"\n f\"Received: {validate_weights_and_indices}\")\n\n self.validate_weights_and_indices = validate_weights_and_indices\n\n def __repr__(self):\n return (\"FeatureConfig(table={table!r}, \"\n \"max_sequence_length={max_sequence_length!r}, \"\n \"validate_weights_and_indices={\"\n \"validate_weights_and_indices!r}, name={name!r})\".format(\n table=self.table,\n max_sequence_length=self.max_sequence_length,\n validate_weights_and_indices=self.validate_weights_and_indices,\n name=self.name))\n\n\ndef log_tpu_embedding_configuration(\n config: tpu_embedding_configuration_pb2.TPUEmbeddingConfiguration) -> None:\n \"\"\"Logs a TPUEmbeddingConfiguration proto across multiple statements.\n\n Args:\n config: TPUEmbeddingConfiguration proto to log. Necessary because\n logging.info has a maximum length to each log statement, which\n particularly large configs can exceed.\n \"\"\"\n logging.info(\"Beginning log of TPUEmbeddingConfiguration.\")\n for line in str(config).splitlines():\n logging.info(line)\n logging.info(\"Done with log of TPUEmbeddingConfiguration.\")\n", "# coding=utf-8\n# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utilities for collectives.\"\"\"\n\nimport copy\nimport enum\n\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# TODO(b/170340570): print deprecation warning for CollectiveCommunication.\n@tf_export(\"distribute.experimental.CommunicationImplementation\",\n \"distribute.experimental.CollectiveCommunication\")\nclass CommunicationImplementation(enum.Enum):\n \"\"\"Cross device communication implementation.\n\n Warning: The alias `tf.distribute.experimental.CollectiveCommunication` is\n deprecated and will be removed in a future version. Use\n `tf.distribute.experimental.CommunicationImplementation` instead.\n\n * `AUTO`: Automatically chosen by Tensorflow.\n * `RING`: TensorFlow's ring algorithms for all-reduce and\n all-gather.\n * `NCCL`: NVIDIA®'s NCCL library. This is now only used for all-reduce on\n GPUs; all-reduce on CPU, all-gather and broadcast fallbacks to RING.\n \"\"\"\n AUTO = \"AUTO\"\n RING = \"RING\"\n NCCL = \"NCCL\"\n # TODO(ayushd): add ncclAllGather implementation.\n\n\nCollectiveCommunication = CommunicationImplementation\n\n\n@tf_export(\"distribute.experimental.CommunicationOptions\")\nclass _OptionsExported(object):\n \"\"\"Options for cross device communications like All-reduce.\n\n This can be passed to methods like\n `tf.distribute.get_replica_context().all_reduce()` to optimize collective\n operation performance. Note that these are only hints, which may or may not\n change the actual behavior. Some options only apply to certain strategy and\n are ignored by others.\n\n One common optimization is to break gradients all-reduce into multiple packs\n so that weight updates can overlap with gradient all-reduce.\n\n Examples:\n\n ```python\n options = tf.distribute.experimental.CommunicationOptions(\n bytes_per_pack=50 * 1024 * 1024,\n timeout_seconds=120.0,\n implementation=tf.distribute.experimental.CommunicationImplementation.NCCL\n )\n grads = tf.distribute.get_replica_context().all_reduce(\n 'sum', grads, options=options)\n optimizer.apply_gradients(zip(grads, vars),\n experimental_aggregate_gradients=False)\n ```\n\n \"\"\"\n\n def __new__(cls, *args, **kwargs):\n # We expose a dummy class so that we can separate internal and public APIs.\n # Note that __init__ won't be called on the returned object if it's a\n # different class [1].\n # [1] https://docs.python.org/3/reference/datamodel.html#object.__new__\n return Options(*args, **kwargs)\n\n def __init__(self,\n bytes_per_pack=0,\n timeout_seconds=None,\n implementation=CommunicationImplementation.AUTO):\n \"\"\"Creates a CollectiveHints.\n\n Args:\n bytes_per_pack: a non-negative integer. Breaks collective operations into\n packs of certain size. If it's zero, the value is determined\n automatically. This hint is respected by all multi-replica strategies\n except `TPUStrategy`.\n timeout_seconds: a float or None, timeout in seconds. If not None, the\n collective raises `tf.errors.DeadlineExceededError` if it takes longer\n than this timeout. Zero disables timeout. This can be useful when\n debugging hanging issues. This should only be used for debugging since\n it creates a new thread for each collective, i.e. an overhead of\n `timeout_seconds * num_collectives_per_second` more threads. This only\n works for `tf.distribute.experimental.MultiWorkerMirroredStrategy`.\n implementation: a\n `tf.distribute.experimental.CommunicationImplementation`. This is a hint\n on the preferred communication implementation. Possible values include\n `AUTO`, `RING`, and `NCCL`. NCCL is generally more performant for GPU,\n but doesn't work for CPU. This only works for\n `tf.distribute.experimental.MultiWorkerMirroredStrategy`.\n\n Raises:\n ValueError: When arguments have invalid value.\n \"\"\"\n pass\n\n\nclass Options(object):\n \"\"\"Implementation of OptionsInterface.\"\"\"\n\n def __init__(self,\n bytes_per_pack=0,\n timeout_seconds=None,\n implementation=CommunicationImplementation.AUTO):\n if bytes_per_pack < 0:\n raise ValueError(\n f\"Argument `bytes_per_pack` must be >=0, Received {bytes_per_pack}.\")\n if isinstance(implementation, str):\n implementation = CommunicationImplementation(implementation.upper())\n if not isinstance(implementation, CommunicationImplementation):\n raise ValueError(\n \"Argument `implementation` must be instance of \"\n \"`tf.distribute.experimental.CommunicationImplementation`.\")\n self.bytes_per_pack = bytes_per_pack\n self.timeout_seconds = timeout_seconds\n self.implementation = implementation\n\n __init__.__doc__ = _OptionsExported.__init__.__doc__\n\n def merge(self, options):\n \"\"\"Merges with another options and returns a new one.\n\n Values specified in the `options` takes precedence if they're not the\n default.\n\n Args:\n options: a `tf.distribute.experimental.CollectiveCommunication`.\n\n Returns:\n A new `tf.distribute.experimental.CollectiveCommunication`.\n \"\"\"\n merged = copy.deepcopy(self)\n if options is None:\n return merged\n if options.bytes_per_pack != 0:\n merged.bytes_per_pack = options.bytes_per_pack\n if options.timeout_seconds is not None:\n merged.timeout_seconds = options.timeout_seconds\n if options.implementation != CommunicationImplementation.AUTO:\n merged.implementation = options.implementation\n return merged\n\n\n@tf_export(\"distribute.experimental.CollectiveHints\")\nclass Hints(object):\n \"\"\"Hints for collective operations like AllReduce.\n\n This can be passed to methods like\n `tf.distribute.get_replica_context().all_reduce()` to optimize collective\n operation performance. Note that these are only hints, which may or may not\n change the actual behavior. Some options only apply to certain strategy and\n are ignored by others.\n\n One common optimization is to break gradients all-reduce into multiple packs\n so that weight updates can overlap with gradient all-reduce.\n\n Examples:\n\n - bytes_per_pack\n\n ```python\n hints = tf.distribute.experimental.CollectiveHints(\n bytes_per_pack=50 * 1024 * 1024)\n grads = tf.distribute.get_replica_context().all_reduce(\n 'sum', grads, experimental_hints=hints)\n optimizer.apply_gradients(zip(grads, vars),\n experimental_aggregate_gradients=False)\n ```\n\n - timeout_seconds\n\n ```python\n strategy = tf.distribute.MirroredStrategy()\n hints = tf.distribute.experimental.CollectiveHints(\n timeout_seconds=120.0)\n try:\n strategy.reduce(\"sum\", v, axis=None, experimental_hints=hints)\n except tf.errors.DeadlineExceededError:\n do_something()\n ```\n\n \"\"\"\n\n @deprecation.deprecated(\n None, \"use distribute.experimental.CommunicationOptions instead\")\n def __new__(cls, bytes_per_pack=0, timeout_seconds=None):\n return Options(\n bytes_per_pack=bytes_per_pack, timeout_seconds=timeout_seconds)\n\n def __init__(self, bytes_per_pack=0, timeout_seconds=None):\n \"\"\"Creates a CollectiveHints.\n\n Args:\n bytes_per_pack: a non-negative integer. Breaks collective operations into\n packs of certain size. If it's zero, the value is determined\n automatically. This only applies to all-reduce with\n `MultiWorkerMirroredStrategy` currently.\n timeout_seconds: a float or None, timeout in seconds. If not None, the\n collective raises `tf.errors.DeadlineExceededError` if it takes longer\n than this timeout. This can be useful when debugging hanging issues.\n This should only be used for debugging since it creates a new thread for\n each collective, i.e. an overhead of `timeout_seconds *\n num_collectives_per_second` more threads. This only works for\n `tf.distribute.experimental.MultiWorkerMirroredStrategy`.\n\n Raises:\n ValueError: When arguments have invalid value.\n \"\"\"\n pass\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for the static tf.data optimizations.\"\"\"\nimport functools\nimport os\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.data.experimental.ops import batching\nfrom tensorflow.python.data.experimental.ops import grouping\nfrom tensorflow.python.data.experimental.ops import scan_ops\nfrom tensorflow.python.data.experimental.ops import testing\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import options as options_lib\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import test\n\n\ndef _captured_refvar_test_combinations():\n\n def make_map_dataset(var):\n return dataset_ops.Dataset.from_tensors(0).map(lambda x: x + var)\n\n def make_flat_map_dataset(var):\n return dataset_ops.Dataset.from_tensors(\n 0).flat_map(lambda _: dataset_ops.Dataset.from_tensors(var))\n\n def make_filter_dataset(var):\n return dataset_ops.Dataset.from_tensors(0).filter(lambda x: x < var)\n\n def make_map_and_batch_dataset(var):\n\n def map_fn(x):\n return x + var\n\n return dataset_ops.Dataset.from_tensors(0).apply(\n batching.map_and_batch(map_fn, 1))\n\n def make_group_by_reducer_dataset(var):\n reducer = grouping.Reducer(\n init_func=lambda _: 0,\n reduce_func=lambda x, y: x,\n finalize_func=lambda _: var)\n return dataset_ops.Dataset.range(5).apply(\n grouping.group_by_reducer(lambda x: x % 2, reducer))\n\n def make_group_by_window_dataset(var):\n\n def reduce_fn(key, bucket):\n del key, bucket\n return dataset_ops.Dataset.from_tensors(var)\n\n return dataset_ops.Dataset.from_tensors(0).repeat(10).apply(\n grouping.group_by_window(lambda _: 0, reduce_fn, 10))\n\n def make_scan_dataset(var):\n return dataset_ops.Dataset.from_tensors(0).apply(\n scan_ops.scan(\n 0, lambda old_state, elem: (old_state + 1, elem + old_state + var)))\n\n cases = [\n # Core datasets\n (\"Map\", make_map_dataset),\n (\"FlatMap\", make_flat_map_dataset),\n (\"Filter\", make_filter_dataset),\n # Experimental datasets\n (\"MapAndBatch\", make_map_and_batch_dataset),\n (\"GroupByReducer\", make_group_by_reducer_dataset),\n (\"GroupByWindow\", make_group_by_window_dataset),\n (\"Scan\", make_scan_dataset)\n ]\n\n def reduce_fn(x, y):\n name, dataset_fn = y\n return x + combinations.combine(\n dataset_fn=combinations.NamedObject(name, dataset_fn))\n\n return functools.reduce(reduce_fn, cases, [])\n\n\nclass OptimizationTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationStatefulFunction(self):\n dataset = dataset_ops.Dataset.range(\n 10).map(lambda _: random_ops.random_uniform([])).batch(10)\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = False\n dataset = dataset.with_options(options)\n get_next = self.getNext(dataset)\n self.evaluate(get_next())\n\n # TODO(b/123354468)\n @combinations.generate(test_base.graph_only_combinations())\n def testOptimizationLargeInputFromTensor(self):\n input_t = array_ops.placeholder(dtypes.int32, (None, None, None))\n dataset = dataset_ops.Dataset.from_tensors(input_t)\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = False\n dataset = dataset.with_options(options)\n iterator = dataset_ops.make_initializable_iterator(dataset)\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.cached_session() as sess:\n sess.run(init_op, {input_t: np.ones([512, 1024, 1025], np.int32)})\n self.evaluate(get_next)\n\n # TODO(b/123354468)\n @combinations.generate(test_base.graph_only_combinations())\n def testOptimizationLargeInputFromTensorSlices(self):\n input_t = array_ops.placeholder(dtypes.int32, (None, None, None, None))\n dataset = dataset_ops.Dataset.from_tensor_slices(input_t)\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = False\n dataset = dataset.with_options(options)\n iterator = dataset_ops.make_initializable_iterator(dataset)\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.cached_session() as sess:\n sess.run(init_op, {input_t: np.ones([1, 512, 1024, 1025], np.int32)})\n self.evaluate(get_next)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationNestedDataset(self):\n\n def flat_map_fn(_):\n dataset = dataset_ops.Dataset.from_tensors(0)\n dataset = dataset.apply(testing.assert_next([\"MemoryCacheImpl\"]))\n dataset = dataset.skip(0) # Should be removed by noop elimination\n dataset = dataset.cache()\n return dataset\n\n dataset = dataset_ops.Dataset.range(1)\n dataset = dataset.flat_map(flat_map_fn)\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.noop_elimination = True\n dataset = dataset.with_options(options)\n self.assertDatasetProduces(dataset, expected_output=[0])\n\n @combinations.generate(test_base.default_test_combinations())\n def testOptimizationNestedDatasetWithModifiedRetval(self):\n\n def flat_map_fn(_):\n dataset = dataset_ops.Dataset.from_tensors(0)\n dataset = dataset.apply(testing.assert_next([\"MapAndBatch\"]))\n # Should be fused by map and batch fusion\n dataset = dataset.map(lambda x: x)\n dataset = dataset.batch(1)\n return dataset\n\n dataset = dataset_ops.Dataset.range(1)\n dataset = dataset.flat_map(flat_map_fn)\n\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.map_and_batch_fusion = True\n dataset = dataset.with_options(options)\n self.assertDatasetProduces(dataset, expected_output=[[0]])\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(autotune=[True, False, None]),\n combinations.combine(map_parallelization=[True, False, None])))\n def testOptimizationMapParallelization(self, autotune, map_parallelization):\n dataset = dataset_ops.Dataset.range(5)\n if autotune is not False and map_parallelization is not False: # pylint: disable=g-bool-id-comparison\n dataset = dataset.apply(testing.assert_next([\"ParallelMap\"]))\n else:\n dataset = dataset.apply(testing.assert_next([\"Map\"]))\n dataset = dataset.map(lambda x: x + 1)\n\n options = options_lib.Options()\n if autotune is not None:\n options.autotune.enabled = autotune\n if map_parallelization is not None:\n options.experimental_optimization.map_parallelization = (\n map_parallelization)\n dataset = dataset.with_options(options)\n\n self.assertDatasetProduces(dataset, expected_output=list(range(1, 6)))\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n combinations.combine(existing_prefetch=[True, False]),\n combinations.combine(autotune=[True, False]),\n combinations.combine(set_env=[True, False])))\n def testOptimizationInjectPrefetch(self, existing_prefetch, autotune,\n set_env):\n if set_env:\n os.environ[\"TF_DATA_EXPERIMENT_OPT_IN\"] = \"inject_prefetch\"\n os.environ[\"TF_JOB_NAME\"] = \"test_job\"\n\n dataset = dataset_ops.Dataset.range(5)\n dataset = dataset.map(\n lambda x: x + 1, num_parallel_calls=dataset_ops.AUTOTUNE)\n dataset = dataset.batch(1)\n if existing_prefetch:\n dataset = dataset.prefetch(1)\n if autotune and set_env and not existing_prefetch:\n dataset = dataset.apply(testing.assert_next([\"Prefetch\", \"Root\"]))\n else:\n dataset = dataset.apply(testing.assert_next([\"Root\"]))\n\n options = options_lib.Options()\n options.autotune.enabled = autotune\n dataset = dataset.with_options(options)\n\n self.assertDatasetProduces(dataset, expected_output=[np.array([x]) for x in\n range(1, 6)])\n\n if set_env:\n del os.environ[\"TF_DATA_EXPERIMENT_OPT_IN\"]\n del os.environ[\"TF_JOB_NAME\"]\n\n # Reference variables are not supported in eager mode.\n @combinations.generate(\n combinations.times(test_base.graph_only_combinations(),\n _captured_refvar_test_combinations()))\n def testOptimizationWithCapturedRefVar(self, dataset_fn):\n \"\"\"Tests that default optimizations are disabled with ref variables.\"\"\"\n variable = variable_scope.get_variable(\n \"v\", initializer=0, use_resource=False)\n assign_op = variable.assign_add(1)\n unoptimized_dataset = dataset_fn(variable)\n\n options = options_lib.Options()\n options.experimental_optimization.apply_default_optimizations = False\n options.experimental_optimization.noop_elimination = True\n options.experimental_optimization.map_and_batch_fusion = True\n optimized_dataset = unoptimized_dataset.with_options(options)\n optimized_it = dataset_ops.make_initializable_iterator(optimized_dataset)\n\n # Check that outputs are the same in the optimized and unoptimized cases,\n # when the variable value is changing.\n unoptimized_it = dataset_ops.make_initializable_iterator(\n unoptimized_dataset)\n with ops.control_dependencies([assign_op]):\n unoptimized_output = unoptimized_it.get_next()\n optimized_output = optimized_it.get_next()\n\n self.evaluate(variable.initializer)\n self.evaluate((unoptimized_it.initializer, optimized_it.initializer))\n while True:\n try:\n unoptimized, optimized = self.evaluate((unoptimized_output,\n optimized_output))\n self.assertEqual(unoptimized, optimized)\n except errors.OutOfRangeError:\n break\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test configs for pool operators.\"\"\"\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.lite.testing.zip_test_utils import create_tensor_data\nfrom tensorflow.lite.testing.zip_test_utils import ExtraConvertOptions\nfrom tensorflow.lite.testing.zip_test_utils import make_zip_of_tests\nfrom tensorflow.lite.testing.zip_test_utils import register_make_test_function\n\n\ndef make_pool3d_tests(pool_op):\n \"\"\"Make a set of tests to do pooling.\n\n Args:\n pool_op: TensorFlow pooling operation to test i.e. `tf.nn.max_pool3d`.\n\n Returns:\n A function representing the true generator (after curried pool_op).\n \"\"\"\n\n def f(options, expected_tf_failures=0):\n \"\"\"Actual function that generates examples.\n\n Args:\n options: An Options instance.\n expected_tf_failures: number of expected tensorflow failures.\n \"\"\"\n\n # Chose a set of parameters\n test_parameters = [\n {\n \"ksize\": [[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 4, 1]],\n \"strides\": [[1, 1, 1, 1, 1], [1, 2, 1, 2, 1], [1, 2, 2, 4, 1]],\n \"input_shape\": [[1, 1, 1, 1, 1], [1, 16, 15, 14, 1],\n [3, 16, 15, 14, 3]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NDHWC\"],\n },\n ]\n\n def build_graph(parameters):\n input_tensor = tf.compat.v1.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = pool_op(\n input_tensor,\n ksize=parameters[\"ksize\"],\n strides=parameters[\"strides\"],\n data_format=parameters[\"data_format\"],\n padding=parameters[\"padding\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n extra_convert_options = ExtraConvertOptions()\n extra_convert_options.allow_custom_ops = True\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n extra_convert_options,\n expected_tf_failures=expected_tf_failures)\n\n return f\n\n\n@register_make_test_function()\ndef make_avg_pool3d_tests(options):\n make_pool3d_tests(tf.nn.avg_pool3d)(options, expected_tf_failures=6)\n\n\n@register_make_test_function()\ndef make_max_pool3d_tests(options):\n make_pool3d_tests(tf.nn.max_pool3d)(options, expected_tf_failures=6)\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `tf.data.Iterator`.\"\"\"\nimport warnings\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.core.protobuf import cluster_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.data.util import structure\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.util import compat\n\n\n@test_util.with_eager_op_as_function\nclass IteratorTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n @combinations.generate(test_base.graph_only_combinations())\n def testNoGradients(self):\n component = constant_op.constant([1.])\n side = constant_op.constant(0.)\n add = lambda x: x + side\n dataset = dataset_ops.Dataset.from_tensor_slices(component).map(add)\n value = dataset_ops.make_one_shot_iterator(dataset).get_next()\n self.assertIsNone(gradients_impl.gradients(value, component)[0])\n self.assertIsNone(gradients_impl.gradients(value, side)[0])\n self.assertIsNone(gradients_impl.gradients(value, [component, side])[0])\n\n @combinations.generate(test_base.graph_only_combinations())\n def testCapturingStateInOneShotRaisesException(self):\n var = variables.Variable(37.0, name=\"myvar\")\n dataset = (\n dataset_ops.Dataset.from_tensor_slices([0.0, 1.0, 2.0])\n .map(lambda x: x + var))\n with self.assertRaisesRegex(\n ValueError, r\"A likely cause of this error is that the dataset for \"\n r\"which you are calling `make_one_shot_iterator\\(\\)` captures a \"\n r\"stateful object, such as a `tf.Variable` or \"\n r\"`tf.lookup.StaticHashTable`, which is not supported. Use \"\n r\"`make_initializable_iterator\\(\\)` instead.\"):\n dataset_ops.make_one_shot_iterator(dataset)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testOneShotIterator(self):\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n\n def _map_fn(x, y, z):\n return math_ops.square(x), math_ops.square(y), math_ops.square(z)\n\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensor_slices(components).map(_map_fn)\n .repeat(14))\n get_next = iterator.get_next()\n\n self.assertEqual([c.shape[1:] for c in components],\n [t.shape for t in get_next])\n\n with self.cached_session() as sess:\n for _ in range(14):\n for i in range(7):\n result = sess.run(get_next)\n for component, result_component in zip(components, result):\n self.assertAllEqual(component[i]**2, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testOneShotIteratorCaptureByValue(self):\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n tensor_components = tuple([ops.convert_to_tensor(c) for c in components])\n\n def _map_fn(x, y, z):\n return math_ops.square(x), math_ops.square(y), math_ops.square(z)\n\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensor_slices(tensor_components)\n .map(_map_fn).repeat(14))\n get_next = iterator.get_next()\n\n self.assertEqual([c.shape[1:] for c in components],\n [t.shape for t in get_next])\n\n with self.cached_session() as sess:\n for _ in range(14):\n for i in range(7):\n result = sess.run(get_next)\n for component, result_component in zip(components, result):\n self.assertAllEqual(component[i]**2, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n @combinations.generate(test_base.default_test_combinations())\n def testOneShotIteratorInsideContainer(self):\n components = (np.arange(7),\n np.array([[1, 2, 3]]) * np.arange(7)[:, np.newaxis],\n np.array(37.0) * np.arange(7))\n\n def within_container():\n\n def _map_fn(x, y, z):\n return math_ops.square(x), math_ops.square(y), math_ops.square(z)\n\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensor_slices(components)\n .map(_map_fn).repeat(14))\n return iterator.get_next()\n\n server = server_lib.Server.create_local_server()\n\n # Create two iterators within unique containers, and run them to\n # make sure that the resources aren't shared.\n #\n # The test below would fail if cname were the same across both\n # sessions.\n for j in range(2):\n with session.Session(server.target) as sess:\n cname = \"iteration%d\" % j\n with ops.container(cname):\n get_next = within_container()\n\n for _ in range(14):\n for i in range(7):\n result = sess.run(get_next)\n for component, result_component in zip(components, result):\n self.assertAllEqual(component[i]**2, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testOneShotIteratorNonBlocking(self):\n dataset = dataset_ops.Dataset.from_tensors([1, 2, 3]).map(lambda x: x * x)\n iterator = dataset_ops.make_one_shot_iterator(dataset)\n next_element = iterator.get_next()\n\n # Create a session with a single thread to ensure that the\n # one-shot iterator initializer does not deadlock.\n config = config_pb2.ConfigProto(\n inter_op_parallelism_threads=1, use_per_session_threads=True)\n with session.Session(config=config) as sess:\n self.assertAllEqual([1, 4, 9], sess.run(next_element))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n # Test with multiple threads invoking the one-shot iterator concurrently.\n with session.Session(config=config) as sess:\n results = []\n\n def consumer_thread():\n try:\n results.append(sess.run(next_element))\n except errors.OutOfRangeError:\n results.append(None)\n\n num_threads = 8\n threads = [\n self.checkedThread(consumer_thread) for _ in range(num_threads)\n ]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n self.assertLen(results, num_threads)\n self.assertLen([None for r in results if r is None], num_threads - 1)\n self.assertAllEqual([[1, 4, 9]], [r for r in results if r is not None])\n\n @combinations.generate(test_base.graph_only_combinations())\n def testOneShotIteratorInitializerFails(self):\n # Define a dataset whose initialization will always fail.\n dataset = dataset_ops.Dataset.from_tensors(array_ops.gather([0], [4]))\n iterator = dataset_ops.make_one_shot_iterator(dataset)\n next_element = iterator.get_next()\n\n with self.cached_session() as sess:\n with self.assertRaisesRegex(errors.InvalidArgumentError, \"\"):\n sess.run(next_element)\n\n # Test that subsequent attempts to use the iterator also fail.\n with self.assertRaisesRegex(errors.InvalidArgumentError, \"\"):\n sess.run(next_element)\n\n with self.cached_session() as sess:\n\n def consumer_thread():\n with self.assertRaisesRegex(errors.InvalidArgumentError, \"\"):\n sess.run(next_element)\n\n num_threads = 8\n threads = [\n self.checkedThread(consumer_thread) for _ in range(num_threads)\n ]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n @combinations.generate(test_base.default_test_combinations())\n def testOneShotIteratorEmptyDataset(self):\n dataset = dataset_ops.Dataset.range(0)\n iterator = dataset_ops.make_one_shot_iterator(dataset)\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(iterator.get_next())\n\n @combinations.generate(test_base.graph_only_combinations())\n def testSimpleSharedResource(self):\n components = (np.array(1, dtype=np.int64),\n np.array([1, 2, 3], dtype=np.int64),\n np.array(37.0, dtype=np.float64))\n\n server = server_lib.Server.create_local_server()\n\n # Create two non-overlapping sessions that share the same iterator\n # resource on the same server, and verify that an action of the\n # first session (initializing the iterator) is visible in the\n # second session.\n with ops.Graph().as_default():\n iterator = dataset_ops.make_initializable_iterator(\n dataset_ops.Dataset.from_tensors(\n components).map(lambda x, y, z: (x, y, z)),\n shared_name=\"shared_iterator\")\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with session.Session(server.target) as sess:\n sess.run(init_op)\n results = sess.run(get_next)\n for component, result_component in zip(components, results):\n self.assertAllEqual(component, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Re-initialize the iterator in the first session.\n sess.run(init_op)\n\n with ops.Graph().as_default():\n # Re-define the iterator manually, without defining any of the\n # functions in this graph, to ensure that we are not\n # accidentally redefining functions with the same names in the\n # new graph.\n iterator = iterator_ops.Iterator.from_structure(\n shared_name=\"shared_iterator\",\n output_types=(dtypes.int64, dtypes.int64, dtypes.float64),\n output_shapes=([], [3], []))\n get_next = iterator.get_next()\n\n with session.Session(server.target) as sess:\n # Use the iterator without re-initializing in the second session.\n results = sess.run(get_next)\n for component, result_component in zip(components, results):\n self.assertAllEqual(component, result_component)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testNotInitializedError(self):\n components = (np.array(1), np.array([1, 2, 3]), np.array(37.0))\n iterator = dataset_ops.make_initializable_iterator(\n dataset_ops.Dataset.from_tensors(components))\n get_next = iterator.get_next()\n\n with self.cached_session() as sess:\n with self.assertRaisesRegex(errors.FailedPreconditionError,\n \"iterator has not been initialized\"):\n sess.run(get_next)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testReinitializableIterator(self):\n dataset_3 = dataset_ops.Dataset.from_tensors(\n constant_op.constant([1, 2, 3]))\n dataset_4 = dataset_ops.Dataset.from_tensors(\n constant_op.constant([4, 5, 6, 7]))\n iterator = iterator_ops.Iterator.from_structure(\n dataset_ops.get_legacy_output_types(dataset_3), [None])\n\n dataset_3_init_op = iterator.make_initializer(dataset_3)\n dataset_4_init_op = iterator.make_initializer(dataset_4)\n get_next = iterator.get_next()\n\n self.assertEqual(\n dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_types(iterator))\n self.assertEqual(\n dataset_ops.get_legacy_output_types(dataset_4),\n dataset_ops.get_legacy_output_types(iterator))\n self.assertEqual(\n [None], dataset_ops.get_legacy_output_shapes(iterator).as_list())\n\n with self.cached_session() as sess:\n # The iterator is initially uninitialized.\n with self.assertRaises(errors.FailedPreconditionError):\n sess.run(get_next)\n\n # Initialize with one dataset.\n sess.run(dataset_3_init_op)\n self.assertAllEqual([1, 2, 3], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Initialize with a different dataset.\n sess.run(dataset_4_init_op)\n self.assertAllEqual([4, 5, 6, 7], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # Reinitialize with the first dataset.\n sess.run(dataset_3_init_op)\n self.assertAllEqual([1, 2, 3], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testReinitializableIteratorWithFunctions(self):\n\n def g():\n for i in range(10):\n yield i\n\n iterator = iterator_ops.Iterator.from_structure(dtypes.int64, [])\n next_element = iterator.get_next()\n\n with self.cached_session() as sess:\n dataset_1 = dataset_ops.Dataset.from_generator(\n g, output_types=dtypes.int64)\n sess.run(iterator.make_initializer(dataset_1))\n for expected in range(10):\n self.assertEqual(expected, sess.run(next_element))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n dataset_2 = dataset_ops.Dataset.from_generator(\n g, output_types=dtypes.int64)\n sess.run(iterator.make_initializer(dataset_2))\n for expected in range(10):\n self.assertEqual(expected, sess.run(next_element))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(next_element)\n\n @combinations.generate(test_base.default_test_combinations())\n def testReinitializableIteratorStaticErrors(self):\n # Non-matching structure for types and shapes.\n with self.assertRaises(TypeError):\n iterator = iterator_ops.Iterator.from_structure(\n (dtypes.int64, dtypes.float64), [None])\n\n # Test validation of dataset argument.\n iterator = iterator_ops.Iterator.from_structure((dtypes.int64,\n dtypes.float64))\n\n # Incompatible structure.\n with self.assertRaisesRegex(\n ValueError, \"The two structures don't have the same nested structure.\"):\n iterator.make_initializer(\n dataset_ops.Dataset.from_tensors(((constant_op.constant(\n [1, 2, 3], dtype=dtypes.int64),), (constant_op.constant(\n [4., 5., 6., 7.], dtype=dtypes.float64),))))\n\n # Incompatible types.\n with self.assertRaisesRegex(\n TypeError,\n r\"Expected output types \\(tf.int64, tf.float64\\) but got dataset with \"\n r\"output types \\(tf.int32, tf.float32\\).\"):\n iterator.make_initializer(\n dataset_ops.Dataset.from_tensors(\n (constant_op.constant([1, 2, 3], dtype=dtypes.int32),\n constant_op.constant([4., 5., 6., 7.], dtype=dtypes.float32))))\n\n # Incompatible shapes.\n iterator = iterator_ops.Iterator.from_structure(\n (dtypes.int64, dtypes.float64), ([None], []))\n with self.assertRaisesRegex(\n TypeError,\n r\"Expected output shapes compatible with .* but got dataset with \"\n r\"output shapes.*\"):\n iterator.make_initializer(\n dataset_ops.Dataset.from_tensors(\n (constant_op.constant([1, 2, 3], dtype=dtypes.int64),\n constant_op.constant([4., 5., 6., 7.], dtype=dtypes.float64))))\n\n @combinations.generate(test_base.default_test_combinations())\n def testReinitializableIteratorEmptyDataset(self):\n dataset = dataset_ops.Dataset.range(0)\n iterator = iterator_ops.Iterator.from_structure(\n dataset_ops.get_legacy_output_types(dataset), [])\n init_op = iterator.make_initializer(dataset)\n\n with self.cached_session() as sess:\n sess.run(init_op)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(iterator.get_next())\n\n @combinations.generate(test_base.graph_only_combinations())\n def testIteratorStringHandle(self):\n dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n dataset_4 = dataset_ops.Dataset.from_tensor_slices([10, 20, 30, 40])\n\n iterator_3 = dataset_ops.make_one_shot_iterator(dataset_3)\n iterator_4 = dataset_ops.make_one_shot_iterator(dataset_4)\n\n handle_placeholder = array_ops.placeholder(dtypes.string, shape=[])\n feedable_iterator = iterator_ops.Iterator.from_string_handle(\n handle_placeholder, dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_shapes(dataset_3))\n next_element = feedable_iterator.get_next()\n\n self.assertTrue(\n structure.are_compatible(\n dataset_ops.get_structure(dataset_3),\n dataset_ops.get_structure(feedable_iterator)))\n\n with self.cached_session() as sess:\n iterator_3_handle = sess.run(iterator_3.string_handle())\n iterator_4_handle = sess.run(iterator_4.string_handle())\n\n self.assertEqual(10,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n self.assertEqual(1,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_3_handle}))\n self.assertEqual(20,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n self.assertEqual(2,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_3_handle}))\n self.assertEqual(30,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n self.assertEqual(3,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_3_handle}))\n self.assertEqual(40,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(\n next_element, feed_dict={handle_placeholder: iterator_3_handle})\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(\n next_element, feed_dict={handle_placeholder: iterator_4_handle})\n\n @combinations.generate(test_base.graph_only_combinations())\n def testIteratorStringHandleFuture(self):\n dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n dataset_4 = dataset_ops.Dataset.from_tensor_slices([10, 20, 30, 40])\n\n iterator_3 = dataset_ops.make_one_shot_iterator(dataset_3)\n iterator_4 = dataset_ops.make_one_shot_iterator(dataset_4)\n\n handle_placeholder = array_ops.placeholder(dtypes.string, shape=[])\n feedable_iterator = iterator_ops.Iterator.from_string_handle(\n handle_placeholder, dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_shapes(dataset_3))\n next_element = feedable_iterator.get_next()\n\n self.assertTrue(\n structure.are_compatible(\n dataset_ops.get_structure(dataset_3),\n dataset_ops.get_structure(feedable_iterator)))\n\n with self.cached_session() as sess:\n iterator_3_handle = sess.run(iterator_3.string_handle())\n iterator_4_handle = sess.run(iterator_4.string_handle())\n\n self.assertEqual(\n 10,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n self.assertEqual(\n 1,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_3_handle}))\n self.assertEqual(\n 20,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n self.assertEqual(\n 2,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_3_handle}))\n self.assertEqual(\n 30,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n self.assertEqual(\n 3,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_3_handle}))\n self.assertEqual(\n 40,\n sess.run(\n next_element,\n feed_dict={handle_placeholder: iterator_4_handle}))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(\n next_element, feed_dict={handle_placeholder: iterator_3_handle})\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(\n next_element, feed_dict={handle_placeholder: iterator_4_handle})\n\n @combinations.generate(test_base.graph_only_combinations())\n def testIteratorStringHandleReuseTensorObject(self):\n dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n one_shot_iterator = dataset_ops.make_one_shot_iterator(dataset)\n initializable_iterator = dataset_ops.make_initializable_iterator(dataset)\n structure_iterator = iterator_ops.Iterator.from_structure(\n dataset_ops.get_legacy_output_types(dataset))\n\n created_ops = len(ops.get_default_graph().get_operations())\n\n self.assertIs(one_shot_iterator.string_handle(),\n one_shot_iterator.string_handle())\n self.assertIs(initializable_iterator.string_handle(),\n initializable_iterator.string_handle())\n self.assertIs(structure_iterator.string_handle(),\n structure_iterator.string_handle())\n\n # Assert that getting the (default) string handle creates no ops.\n self.assertLen(ops.get_default_graph().get_operations(), created_ops)\n\n # Specifying an explicit name will create a new op.\n handle_with_name = one_shot_iterator.string_handle(name=\"foo\")\n self.assertEqual(\"foo\", handle_with_name.op.name)\n self.assertIsNot(one_shot_iterator.string_handle(), handle_with_name)\n\n handle_with_same_name = one_shot_iterator.string_handle(name=\"foo\")\n self.assertEqual(\"foo_1\", handle_with_same_name.op.name)\n self.assertIsNot(handle_with_name, handle_with_same_name)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testIteratorStringHandleError(self):\n dataset_int_scalar = (\n dataset_ops.Dataset.from_tensor_slices([1, 2, 3]).repeat())\n dataset_float_vector = (dataset_ops.Dataset.from_tensors([1.0, 2.0, 3.0]))\n\n handle_placeholder = array_ops.placeholder(dtypes.string, shape=[])\n\n feedable_int_scalar = iterator_ops.Iterator.from_string_handle(\n handle_placeholder, dtypes.int32, [])\n feedable_int_vector = iterator_ops.Iterator.from_string_handle(\n handle_placeholder, dtypes.int32, [None])\n feedable_int_any = iterator_ops.Iterator.from_string_handle(\n handle_placeholder, dtypes.int32)\n\n with self.cached_session() as sess:\n handle_int_scalar = sess.run(dataset_ops.make_one_shot_iterator(\n dataset_int_scalar).string_handle())\n handle_float_vector = sess.run(dataset_ops.make_one_shot_iterator(\n dataset_float_vector).string_handle())\n\n self.assertEqual(1,\n sess.run(\n feedable_int_scalar.get_next(),\n feed_dict={handle_placeholder: handle_int_scalar}))\n\n self.assertEqual(2,\n sess.run(\n feedable_int_any.get_next(),\n feed_dict={handle_placeholder: handle_int_scalar}))\n\n with self.assertRaises(errors.InvalidArgumentError):\n print(sess.run(\n feedable_int_vector.get_next(),\n feed_dict={handle_placeholder: handle_int_scalar}))\n\n with self.assertRaises(errors.InvalidArgumentError):\n print(sess.run(\n feedable_int_vector.get_next(),\n feed_dict={handle_placeholder: handle_float_vector}))\n\n @combinations.generate(test_base.graph_only_combinations())\n def testRemoteIteratorUsingRemoteCallOpDirectSession(self):\n worker_config = config_pb2.ConfigProto()\n worker_config.device_count[\"CPU\"] = 3\n\n with ops.device(\"/job:localhost/replica:0/task:0/cpu:1\"):\n dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n iterator_3 = dataset_ops.make_one_shot_iterator(dataset_3)\n iterator_3_handle = iterator_3.string_handle()\n\n @function.Defun(dtypes.string)\n def _remote_fn(h):\n remote_iterator = iterator_ops.Iterator.from_string_handle(\n h, dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_shapes(dataset_3))\n return remote_iterator.get_next()\n\n with ops.device(\"/job:localhost/replica:0/task:0/cpu:0\"):\n target_placeholder = array_ops.placeholder(dtypes.string, shape=[])\n remote_op = functional_ops.remote_call(\n args=[iterator_3_handle],\n Tout=[dtypes.int32],\n f=_remote_fn,\n target=target_placeholder)\n\n with self.session(config=worker_config) as sess:\n elem = sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:1\"\n })\n self.assertEqual(elem, [1])\n # Fails when target is cpu:2 where the resource is not located.\n with self.assertRaises(errors.InvalidArgumentError):\n sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:2\"\n })\n elem = sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:1\"\n })\n self.assertEqual(elem, [2])\n elem = sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:1\"\n })\n self.assertEqual(elem, [3])\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:1\"\n })\n\n @combinations.generate(test_base.graph_only_combinations())\n def testRemoteIteratorUsingRemoteCallOpMultiWorkers(self):\n s1 = server_lib.Server.create_local_server()\n s2 = server_lib.Server.create_local_server()\n s3 = server_lib.Server.create_local_server()\n\n cluster_def = cluster_pb2.ClusterDef()\n workers = cluster_def.job.add()\n workers.name = \"worker\"\n workers.tasks[0] = s1.target[len(\"grpc://\"):]\n workers.tasks[1] = s2.target[len(\"grpc://\"):]\n client = cluster_def.job.add()\n client.name = \"client\"\n client.tasks[0] = s3.target[len(\"grpc://\"):]\n config = config_pb2.ConfigProto(cluster_def=cluster_def)\n\n worker_devices = [\n \"/job:worker/replica:0/task:%d/cpu:0\" % i for i in range(2)\n ]\n itr_handles = []\n for device in worker_devices:\n with ops.device(device):\n src = dataset_ops.Dataset.from_tensor_slices([device])\n itr = dataset_ops.make_one_shot_iterator(src)\n itr_handles.append(itr.string_handle())\n\n targets = dataset_ops.Dataset.from_tensor_slices(worker_devices)\n handles = dataset_ops.Dataset.from_tensor_slices(itr_handles)\n\n @function.Defun(dtypes.string)\n def loading_func(h):\n remote_itr = iterator_ops.Iterator.from_string_handle(\n h, dataset_ops.get_legacy_output_types(itr),\n dataset_ops.get_legacy_output_shapes(itr))\n return remote_itr.get_next()\n\n def map_fn(target, handle):\n return functional_ops.remote_call(\n args=[handle], Tout=[dtypes.string], f=loading_func, target=target)\n\n with ops.device(\"/job:client\"):\n client_dataset = dataset_ops.Dataset.zip((targets, handles)).map(map_fn)\n itr = dataset_ops.make_initializable_iterator(client_dataset)\n n = itr.get_next()\n\n with session.Session(s3.target, config=config) as sess:\n sess.run(itr.initializer)\n expected_values = worker_devices\n for expected in expected_values:\n self.assertEqual((compat.as_bytes(expected),), sess.run(n))\n\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(n)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testRemoteIteratorUsingRemoteCallOpDirectSessionGPUCPU(self):\n if not test_util.is_gpu_available():\n self.skipTest(\"No GPU available\")\n\n with ops.device(\"/job:localhost/replica:0/task:0/cpu:0\"):\n dataset_3 = dataset_ops.Dataset.from_tensor_slices([1, 2, 3])\n iterator_3 = dataset_ops.make_one_shot_iterator(dataset_3)\n iterator_3_handle = iterator_3.string_handle()\n\n def _encode_raw(byte_array):\n return bytes(bytearray(byte_array))\n\n @function.Defun(dtypes.uint8)\n def _remote_fn(h):\n handle = script_ops.py_func(_encode_raw, [h], dtypes.string)\n remote_iterator = iterator_ops.Iterator.from_string_handle(\n handle, dataset_ops.get_legacy_output_types(dataset_3),\n dataset_ops.get_legacy_output_shapes(dataset_3))\n return remote_iterator.get_next()\n\n with ops.device(\"/job:localhost/replica:0/task:0/device:GPU:0\"):\n target_placeholder = array_ops.placeholder(dtypes.string, shape=[])\n iterator_3_handle_uint8 = parsing_ops.decode_raw(\n input_bytes=iterator_3_handle, out_type=dtypes.uint8)\n remote_op = functional_ops.remote_call(\n args=[iterator_3_handle_uint8],\n Tout=[dtypes.int32],\n f=_remote_fn,\n target=target_placeholder)\n\n with self.cached_session() as sess:\n elem = sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:0\"\n })\n self.assertEqual(elem, [1])\n elem = sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:0\"\n })\n self.assertEqual(elem, [2])\n elem = sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:0\"\n })\n self.assertEqual(elem, [3])\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(\n remote_op,\n feed_dict={\n target_placeholder: \"/job:localhost/replica:0/task:0/cpu:0\"\n })\n\n @combinations.generate(test_base.graph_only_combinations())\n def testRepeatedGetNextWarning(self):\n iterator = dataset_ops.make_one_shot_iterator(dataset_ops.Dataset.range(10))\n warnings.simplefilter(\"always\")\n with warnings.catch_warnings(record=True) as w:\n for _ in range(100):\n iterator.get_next()\n self.assertLen(w, 100 - iterator_ops.GET_NEXT_CALL_WARNING_THRESHOLD)\n for warning in w:\n self.assertIn(\n iterator_ops.GET_NEXT_CALL_WARNING_MESSAGE, str(warning.message))\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n expected_element_structure=tensor_spec.TensorSpec([],\n dtypes.float32),\n expected_output_classes=ops.Tensor,\n expected_output_types=dtypes.float32,\n expected_output_shapes=[[]])))\n def testTensorIteratorStructure(self, expected_element_structure,\n expected_output_classes,\n expected_output_types,\n expected_output_shapes):\n tf_value_fn = lambda: constant_op.constant(37.0)\n tf_value = tf_value_fn()\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensors(tf_value))\n\n self.assertTrue(\n structure.are_compatible(\n dataset_ops.get_structure(iterator), expected_element_structure))\n self.assertEqual(expected_output_classes,\n dataset_ops.get_legacy_output_classes(iterator))\n self.assertEqual(expected_output_types,\n dataset_ops.get_legacy_output_types(iterator))\n self.assertEqual(expected_output_shapes,\n dataset_ops.get_legacy_output_shapes(iterator))\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n expected_element_structure=sparse_tensor.SparseTensorSpec(\n [1], dtypes.int32),\n expected_output_classes=sparse_tensor.SparseTensor,\n expected_output_types=dtypes.int32,\n expected_output_shapes=[[1]])))\n def testSparseTensorIteratorStructure(self, expected_element_structure,\n expected_output_classes,\n expected_output_types,\n expected_output_shapes):\n\n def tf_value_fn():\n return sparse_tensor.SparseTensor(\n indices=[[0]],\n values=constant_op.constant([0], dtype=dtypes.int32),\n dense_shape=[1])\n\n tf_value = tf_value_fn()\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensors(tf_value))\n\n self.assertTrue(\n structure.are_compatible(\n dataset_ops.get_structure(iterator), expected_element_structure))\n self.assertEqual(expected_output_classes,\n dataset_ops.get_legacy_output_classes(iterator))\n self.assertEqual(expected_output_types,\n dataset_ops.get_legacy_output_types(iterator))\n self.assertEqual(expected_output_shapes,\n dataset_ops.get_legacy_output_shapes(iterator))\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n expected_element_structure={\n \"a\":\n tensor_spec.TensorSpec([], dtypes.float32),\n \"b\": (tensor_spec.TensorSpec([1], dtypes.string),\n tensor_spec.TensorSpec([], dtypes.string))\n },\n expected_output_classes={\n \"a\": ops.Tensor,\n \"b\": (ops.Tensor, ops.Tensor)\n },\n expected_output_types={\n \"a\": dtypes.float32,\n \"b\": (dtypes.string, dtypes.string)\n },\n expected_output_shapes={\n \"a\": [],\n \"b\": ([1], [])\n })))\n def testNestedTensorIteratorStructure(self, expected_element_structure,\n expected_output_classes,\n expected_output_types,\n expected_output_shapes):\n\n def tf_value_fn():\n return {\n \"a\": constant_op.constant(37.0),\n \"b\": (constant_op.constant([\"Foo\"]), constant_op.constant(\"Bar\"))\n }\n\n tf_value = tf_value_fn()\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensors(tf_value))\n\n self.assertTrue(\n structure.are_compatible(\n dataset_ops.get_structure(iterator), expected_element_structure))\n self.assertEqual(expected_output_classes,\n dataset_ops.get_legacy_output_classes(iterator))\n self.assertEqual(expected_output_types,\n dataset_ops.get_legacy_output_types(iterator))\n self.assertEqual(expected_output_shapes,\n dataset_ops.get_legacy_output_shapes(iterator))\n\n @combinations.generate(test_base.graph_only_combinations())\n def testIteratorGetNextName(self):\n with ops.Graph().as_default():\n iterator = dataset_ops.make_one_shot_iterator(\n dataset_ops.Dataset.from_tensors(37.0))\n next_element = iterator.get_next(name=\"overridden_name\")\n self.assertEqual(\"overridden_name\", next_element.op.name)\n\n @combinations.generate(\n combinations.combine(\n tf_api_version=[1, 2],\n mode=\"eager\",\n execution_mode=[context.ASYNC, context.SYNC]))\n def testIteratorEagerIteration(self, execution_mode):\n with context.eager_mode(), context.execution_mode(execution_mode):\n val = 0\n dataset = dataset_ops.Dataset.range(10)\n iterator = iter(dataset)\n for foo in iterator:\n self.assertEqual(val, foo.numpy())\n val += 1\n\n @combinations.generate(test_base.eager_only_combinations())\n def testOwnedIteratorFunction(self):\n\n queue = data_flow_ops.FIFOQueue(10, dtypes.int64)\n\n @def_function.function\n def fn():\n dataset = dataset_ops.Dataset.range(10)\n iterator = iter(dataset)\n for _ in range(10):\n queue.enqueue(next(iterator))\n\n fn()\n\n for i in range(10):\n self.assertEqual(queue.dequeue().numpy(), i)\n\n @combinations.generate(test_base.eager_only_combinations())\n def testOwnedIteratorFunctionError(self):\n # In this test we verify that a function that raises an error ends up\n # properly deallocating the iterator resource.\n\n queue = data_flow_ops.FIFOQueue(10, dtypes.int64)\n queue.enqueue(0)\n\n def init_fn(n):\n return n\n\n def next_fn(_):\n ds = dataset_ops.Dataset.range(0)\n return next(iter(ds))\n\n def finalize_fn(n):\n queue.enqueue(0)\n return n\n\n @def_function.function\n def fn():\n output_signature = tensor_spec.TensorSpec((), dtypes.int64)\n dataset = dataset_ops._GeneratorDataset(1, init_fn, next_fn, finalize_fn,\n output_signature)\n iterator = iter(dataset)\n next(iterator)\n\n with self.assertRaises(errors.OutOfRangeError):\n fn()\n\n self.assertEqual(queue.size().numpy(), 2)\n\n @combinations.generate(test_base.default_test_combinations())\n def testNoInitializer(self):\n dataset = dataset_ops.Dataset.range(10)\n iterator = iterator_ops.Iterator.from_structure(\n dataset_ops.get_legacy_output_types(dataset), [])\n with self.assertRaisesRegex(\n ValueError, \"The iterator does not have an initializer.\"):\n _ = iterator.initializer\n\n @combinations.generate(test_base.default_test_combinations())\n def testtestMissingInput(self):\n with self.assertRaisesRegex(\n ValueError,\n \"When `dataset` is not provided, both `components` and `element_spec` \"\n \"must be specified.\"):\n iterator_ops.OwnedIterator(dataset=None)\n\n @combinations.generate(test_base.eager_only_combinations())\n def testExtraElementSpecInput(self):\n dataset = dataset_ops.Dataset.range(1000)\n with self.assertRaisesRegex(\n ValueError,\n \"When `dataset` is provided, `element_spec` and `components` must \"\n \"not be specified.\"):\n iterator_ops.OwnedIterator(\n dataset, element_spec=dataset.element_spec)\n\n @combinations.generate(test_base.eager_only_combinations())\n def testLimitedRetracing(self):\n trace_count = [0]\n\n @def_function.function\n def f(iterator):\n trace_count[0] += 1\n counter = np.int64(0)\n for elem in iterator:\n counter += elem\n return counter\n\n dataset = dataset_ops.Dataset.range(5)\n dataset2 = dataset_ops.Dataset.range(10)\n\n for _ in range(10):\n self.assertEqual(self.evaluate(f(iter(dataset))), 10)\n self.assertEqual(self.evaluate(f(iter(dataset2))), 45)\n self.assertEqual(trace_count[0], 1)\n\n @combinations.generate(test_base.eager_only_combinations())\n def testNestedFunctionsIteratorResource(self):\n\n @def_function.function\n def sum_dataset(ds):\n it = iter(ds)\n\n @def_function.function\n def next_element(it):\n return next(it)\n\n total = 0\n for _ in range(10):\n total += next_element(it)\n return total\n\n ds = dataset_ops.Dataset.range(10)\n self.assertEqual(sum_dataset(ds).numpy(), 45)\n self.assertEqual(sum_dataset(ds).numpy(), 45)\n\n @combinations.generate(test_base.default_test_combinations())\n def testNestedAutomaticControlDependencies(self):\n counter_var = variables.Variable(0)\n\n def map_fn(x):\n counter_var.assign_add(1)\n return x\n\n def dataset_fn():\n return dataset_ops.Dataset.range(10).map(map_fn)\n\n @def_function.function\n def fn():\n it = iter(dataset_fn())\n for _ in range(10):\n _ = next(it)\n return counter_var\n\n self.evaluate(counter_var.initializer)\n self.assertEqual(self.evaluate(fn()), 10)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# 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\"\"\"Curses-Based Command-Line Interface of TensorFlow Debugger (tfdbg).\"\"\"\nimport collections\nimport curses\nfrom curses import textpad\nimport os\nimport signal\nimport sys\nimport threading\n\n\nfrom tensorflow.python.debug.cli import base_ui\nfrom tensorflow.python.debug.cli import cli_shared\nfrom tensorflow.python.debug.cli import command_parser\nfrom tensorflow.python.debug.cli import curses_widgets\nfrom tensorflow.python.debug.cli import debugger_cli_common\nfrom tensorflow.python.debug.cli import tensor_format\n\n\n_SCROLL_REFRESH = \"refresh\"\n_SCROLL_UP = \"up\"\n_SCROLL_DOWN = \"down\"\n_SCROLL_UP_A_LINE = \"up_a_line\"\n_SCROLL_DOWN_A_LINE = \"down_a_line\"\n_SCROLL_HOME = \"home\"\n_SCROLL_END = \"end\"\n_SCROLL_TO_LINE_INDEX = \"scroll_to_line_index\"\n\n_COLOR_READY_COLORTERMS = [\"gnome-terminal\", \"xfce4-terminal\"]\n_COLOR_ENABLED_TERM = \"xterm-256color\"\n\n\ndef _get_command_from_line_attr_segs(mouse_x, attr_segs):\n \"\"\"Attempt to extract command from the attribute segments of a line.\n\n Args:\n mouse_x: (int) x coordinate of the mouse event.\n attr_segs: (list) The list of attribute segments of a line from a\n RichTextLines object.\n\n Returns:\n (str or None) If a command exists: the command as a str; otherwise, None.\n \"\"\"\n\n for seg in attr_segs:\n if seg[0] <= mouse_x < seg[1]:\n attributes = seg[2] if isinstance(seg[2], list) else [seg[2]]\n for attr in attributes:\n if isinstance(attr, debugger_cli_common.MenuItem):\n return attr.content\n\n\nclass ScrollBar(object):\n \"\"\"Vertical ScrollBar for Curses-based CLI.\n\n An object of this class has knowledge of the location of the scroll bar\n in the screen coordinates, the current scrolling position, and the total\n number of text lines in the screen text. By using this information, it\n can generate text rendering of the scroll bar, which consists of and UP\n button on the top and a DOWN button on the bottom, in addition to a scroll\n block in between, whose exact location is determined by the scrolling\n position. The object can also calculate the scrolling command (e.g.,\n _SCROLL_UP_A_LINE, _SCROLL_DOWN) from the coordinate of a mouse click\n event in the screen region it occupies.\n \"\"\"\n\n BASE_ATTR = cli_shared.COLOR_BLACK + \"_on_\" + cli_shared.COLOR_WHITE\n\n def __init__(self,\n min_x,\n min_y,\n max_x,\n max_y,\n scroll_position,\n output_num_rows):\n \"\"\"Constructor of ScrollBar.\n\n Args:\n min_x: (int) left index of the scroll bar on the screen (inclusive).\n min_y: (int) top index of the scroll bar on the screen (inclusive).\n max_x: (int) right index of the scroll bar on the screen (inclusive).\n max_y: (int) bottom index of the scroll bar on the screen (inclusive).\n scroll_position: (int) 0-based location of the screen output. For example,\n if the screen output is scrolled to the top, the value of\n scroll_position should be 0. If it is scrolled to the bottom, the value\n should be output_num_rows - 1.\n output_num_rows: (int) Total number of output rows.\n\n Raises:\n ValueError: If the width or height of the scroll bar, as determined\n by min_x, max_x, min_y and max_y, is too small.\n \"\"\"\n\n self._min_x = min_x\n self._min_y = min_y\n self._max_x = max_x\n self._max_y = max_y\n self._scroll_position = scroll_position\n self._output_num_rows = output_num_rows\n self._scroll_bar_height = max_y - min_y + 1\n\n if self._max_x < self._min_x:\n raise ValueError(\"Insufficient width for ScrollBar (%d)\" %\n (self._max_x - self._min_x + 1))\n if self._max_y < self._min_y + 3:\n raise ValueError(\"Insufficient height for ScrollBar (%d)\" %\n (self._max_y - self._min_y + 1))\n\n def _block_y(self, screen_coord_sys=False):\n \"\"\"Get the 0-based y coordinate of the scroll block.\n\n This y coordinate takes into account the presence of the UP and DN buttons\n present at the top and bottom of the ScrollBar. For example, at the home\n location, the return value will be 1; at the bottom location, the return\n value will be self._scroll_bar_height - 2.\n\n Args:\n screen_coord_sys: (`bool`) whether the return value will be in the\n screen coordinate system.\n\n Returns:\n (int) 0-based y coordinate of the scroll block, in the ScrollBar\n coordinate system by default. For example,\n when scroll position is at the top, this return value will be 1 (not 0,\n because of the presence of the UP button). When scroll position is at\n the bottom, this return value will be self._scroll_bar_height - 2\n (not self._scroll_bar_height - 1, because of the presence of the DOWN\n button).\n \"\"\"\n\n rel_block_y = int(\n float(self._scroll_position) / (self._output_num_rows - 1) *\n (self._scroll_bar_height - 3)) + 1\n return rel_block_y + self._min_y if screen_coord_sys else rel_block_y\n\n def layout(self):\n \"\"\"Get the RichTextLines layout of the scroll bar.\n\n Returns:\n (debugger_cli_common.RichTextLines) The text layout of the scroll bar.\n \"\"\"\n width = self._max_x - self._min_x + 1\n empty_line = \" \" * width\n foreground_font_attr_segs = [(0, width, self.BASE_ATTR)]\n\n if self._output_num_rows > 1:\n block_y = self._block_y()\n\n if width == 1:\n up_text = \"U\"\n down_text = \"D\"\n elif width == 2:\n up_text = \"UP\"\n down_text = \"DN\"\n elif width == 3:\n up_text = \"UP \"\n down_text = \"DN \"\n else:\n up_text = \" UP \"\n down_text = \"DOWN\"\n\n layout = debugger_cli_common.RichTextLines(\n [up_text], font_attr_segs={0: [(0, width, self.BASE_ATTR)]})\n for i in range(1, self._scroll_bar_height - 1):\n font_attr_segs = foreground_font_attr_segs if i == block_y else None\n layout.append(empty_line, font_attr_segs=font_attr_segs)\n layout.append(down_text, font_attr_segs=foreground_font_attr_segs)\n else:\n layout = debugger_cli_common.RichTextLines(\n [empty_line] * self._scroll_bar_height)\n\n return layout\n\n def get_click_command(self, mouse_y):\n if self._output_num_rows <= 1:\n return None\n elif mouse_y == self._min_y:\n return _SCROLL_UP_A_LINE\n elif mouse_y == self._max_y:\n return _SCROLL_DOWN_A_LINE\n elif (mouse_y > self._block_y(screen_coord_sys=True) and\n mouse_y < self._max_y):\n return _SCROLL_DOWN\n elif (mouse_y < self._block_y(screen_coord_sys=True) and\n mouse_y > self._min_y):\n return _SCROLL_UP\n else:\n return None\n\n\nclass CursesUI(base_ui.BaseUI):\n \"\"\"Curses-based Command-line UI.\n\n In this class, the methods with the prefix \"_screen_\" are the methods that\n interact with the actual terminal using the curses library.\n \"\"\"\n\n CLI_TERMINATOR_KEY = 7 # Terminator key for input text box.\n CLI_TAB_KEY = ord(\"\\t\")\n BACKSPACE_KEY = ord(\"\\b\")\n REGEX_SEARCH_PREFIX = \"/\"\n TENSOR_INDICES_NAVIGATION_PREFIX = \"@\"\n\n _NAVIGATION_FORWARD_COMMAND = \"next\"\n _NAVIGATION_BACK_COMMAND = \"prev\"\n\n # Limit screen width to work around the limitation of the curses library that\n # it may return invalid x coordinates for large values.\n _SCREEN_WIDTH_LIMIT = 220\n\n # Possible Enter keys. 343 is curses key code for the num-pad Enter key when\n # num lock is off.\n CLI_CR_KEYS = [ord(\"\\n\"), ord(\"\\r\"), 343]\n\n _KEY_MAP = {\n 127: curses.KEY_BACKSPACE, # Backspace\n curses.KEY_DC: 4, # Delete\n }\n\n _FOREGROUND_COLORS = {\n cli_shared.COLOR_WHITE: curses.COLOR_WHITE,\n cli_shared.COLOR_RED: curses.COLOR_RED,\n cli_shared.COLOR_GREEN: curses.COLOR_GREEN,\n cli_shared.COLOR_YELLOW: curses.COLOR_YELLOW,\n cli_shared.COLOR_BLUE: curses.COLOR_BLUE,\n cli_shared.COLOR_CYAN: curses.COLOR_CYAN,\n cli_shared.COLOR_MAGENTA: curses.COLOR_MAGENTA,\n cli_shared.COLOR_BLACK: curses.COLOR_BLACK,\n }\n _BACKGROUND_COLORS = {\n \"transparent\": -1,\n cli_shared.COLOR_WHITE: curses.COLOR_WHITE,\n cli_shared.COLOR_BLACK: curses.COLOR_BLACK,\n }\n\n # Font attribute for search and highlighting.\n _SEARCH_HIGHLIGHT_FONT_ATTR = (\n cli_shared.COLOR_BLACK + \"_on_\" + cli_shared.COLOR_WHITE)\n _ARRAY_INDICES_COLOR_PAIR = (\n cli_shared.COLOR_BLACK + \"_on_\" + cli_shared.COLOR_WHITE)\n _ERROR_TOAST_COLOR_PAIR = (\n cli_shared.COLOR_RED + \"_on_\" + cli_shared.COLOR_WHITE)\n _INFO_TOAST_COLOR_PAIR = (\n cli_shared.COLOR_BLUE + \"_on_\" + cli_shared.COLOR_WHITE)\n _STATUS_BAR_COLOR_PAIR = (\n cli_shared.COLOR_BLACK + \"_on_\" + cli_shared.COLOR_WHITE)\n _UI_WAIT_COLOR_PAIR = (\n cli_shared.COLOR_MAGENTA + \"_on_\" + cli_shared.COLOR_WHITE)\n _NAVIGATION_WARNING_COLOR_PAIR = (\n cli_shared.COLOR_RED + \"_on_\" + cli_shared.COLOR_WHITE)\n\n _UI_WAIT_MESSAGE = \"Processing...\"\n\n # The delay (in ms) between each update of the scroll bar when the mouse\n # button is held down on the scroll bar. Controls how fast the screen scrolls.\n _MOUSE_SCROLL_DELAY_MS = 100\n\n _single_instance_lock = threading.Lock()\n\n def __init__(self, on_ui_exit=None, config=None):\n \"\"\"Constructor of CursesUI.\n\n Args:\n on_ui_exit: (Callable) Callback invoked when the UI exits.\n config: An instance of `cli_config.CLIConfig()` carrying user-facing\n configurations.\n \"\"\"\n\n base_ui.BaseUI.__init__(self, on_ui_exit=on_ui_exit, config=config)\n\n self._screen_init()\n self._screen_refresh_size()\n # TODO(cais): Error out if the size of the screen is too small.\n\n # Initialize some UI component size and locations.\n self._init_layout()\n\n self._command_history_store = debugger_cli_common.CommandHistory()\n\n # Active list of command history, used in history navigation.\n # _command_handler_registry holds all the history commands the CLI has\n # received, up to a size limit. _active_command_history is the history\n # currently being navigated in, e.g., using the Up/Down keys. The latter\n # can be different from the former during prefixed or regex-based history\n # navigation, e.g., when user enter the beginning of a command and hit Up.\n self._active_command_history = []\n\n # Pointer to the current position in the history sequence.\n # 0 means it is a new command being keyed in.\n self._command_pointer = 0\n\n self._command_history_limit = 100\n\n self._pending_command = \"\"\n\n self._nav_history = curses_widgets.CursesNavigationHistory(10)\n\n # State related to screen output.\n self._output_pad = None\n self._output_pad_row = 0\n self._output_array_pointer_indices = None\n self._curr_unwrapped_output = None\n self._curr_wrapped_output = None\n\n try:\n # Register signal handler for SIGINT.\n signal.signal(signal.SIGINT, self._interrupt_handler)\n except ValueError:\n # Running in a child thread, can't catch signals.\n pass\n\n self.register_command_handler(\n \"mouse\",\n self._mouse_mode_command_handler,\n \"Get or set the mouse mode of this CLI: (on|off)\",\n prefix_aliases=[\"m\"])\n\n def _init_layout(self):\n \"\"\"Initialize the layout of UI components.\n\n Initialize the location and size of UI components such as command textbox\n and output region according to the terminal size.\n \"\"\"\n\n # NamedTuple for rectangular locations on screen\n self.rectangle = collections.namedtuple(\"rectangle\",\n \"top left bottom right\")\n\n # Height of command text box\n self._command_textbox_height = 2\n\n self._title_row = 0\n\n # Row index of the Navigation Bar (i.e., the bar that contains forward and\n # backward buttons and displays the current command line).\n self._nav_bar_row = 1\n\n # Top row index of the output pad.\n # A \"pad\" is a curses object that holds lines of text and not limited to\n # screen size. It can be rendered on the screen partially with scroll\n # parameters specified.\n self._output_top_row = 2\n\n # Number of rows that the output pad has.\n self._output_num_rows = (\n self._max_y - self._output_top_row - self._command_textbox_height - 1)\n\n # Row index of scroll information line: Taking into account the zero-based\n # row indexing and the command textbox area under the scroll information\n # row.\n self._output_scroll_row = self._max_y - 1 - self._command_textbox_height\n\n # Tab completion bottom row.\n self._candidates_top_row = self._output_scroll_row - 4\n self._candidates_bottom_row = self._output_scroll_row - 1\n\n # Maximum number of lines the candidates display can have.\n self._candidates_max_lines = int(self._output_num_rows / 2)\n\n self.max_output_lines = 10000\n\n # Regex search state.\n self._curr_search_regex = None\n self._unwrapped_regex_match_lines = []\n\n # Size of view port on screen, which is always smaller or equal to the\n # screen size.\n self._output_pad_screen_height = self._output_num_rows - 1\n self._output_pad_screen_width = self._max_x - 2\n self._output_pad_screen_location = self.rectangle(\n top=self._output_top_row,\n left=0,\n bottom=self._output_top_row + self._output_num_rows,\n right=self._output_pad_screen_width)\n\n def _screen_init(self):\n \"\"\"Screen initialization.\n\n Creates curses stdscr and initialize the color pairs for display.\n \"\"\"\n # If the terminal type is color-ready, enable it.\n if os.getenv(\"COLORTERM\") in _COLOR_READY_COLORTERMS:\n os.environ[\"TERM\"] = _COLOR_ENABLED_TERM\n self._stdscr = curses.initscr()\n self._command_window = None\n self._screen_color_init()\n\n def _screen_color_init(self):\n \"\"\"Initialization of screen colors.\"\"\"\n curses.start_color()\n curses.use_default_colors()\n self._color_pairs = {}\n color_index = 0\n\n # Prepare color pairs.\n for fg_color in self._FOREGROUND_COLORS:\n for bg_color in self._BACKGROUND_COLORS:\n color_index += 1\n curses.init_pair(color_index, self._FOREGROUND_COLORS[fg_color],\n self._BACKGROUND_COLORS[bg_color])\n\n color_name = fg_color\n if bg_color != \"transparent\":\n color_name += \"_on_\" + bg_color\n\n self._color_pairs[color_name] = curses.color_pair(color_index)\n\n # Try getting color(s) available only under 256-color support.\n try:\n color_index += 1\n curses.init_pair(color_index, 245, -1)\n self._color_pairs[cli_shared.COLOR_GRAY] = curses.color_pair(color_index)\n except curses.error:\n # Use fall-back color(s):\n self._color_pairs[cli_shared.COLOR_GRAY] = (\n self._color_pairs[cli_shared.COLOR_GREEN])\n\n # A_BOLD or A_BLINK is not really a \"color\". But place it here for\n # convenience.\n self._color_pairs[\"bold\"] = curses.A_BOLD\n self._color_pairs[\"blink\"] = curses.A_BLINK\n self._color_pairs[\"underline\"] = curses.A_UNDERLINE\n\n # Default color pair to use when a specified color pair does not exist.\n self._default_color_pair = self._color_pairs[cli_shared.COLOR_WHITE]\n\n def _screen_launch(self, enable_mouse_on_start):\n \"\"\"Launch the curses screen.\"\"\"\n\n curses.noecho()\n curses.cbreak()\n self._stdscr.keypad(1)\n\n self._mouse_enabled = self.config.get(\"mouse_mode\")\n self._screen_set_mousemask()\n self.config.set_callback(\n \"mouse_mode\",\n lambda cfg: self._set_mouse_enabled(cfg.get(\"mouse_mode\")))\n\n self._screen_create_command_window()\n\n def _screen_create_command_window(self):\n \"\"\"Create command window according to screen size.\"\"\"\n if self._command_window:\n del self._command_window\n\n self._command_window = curses.newwin(\n self._command_textbox_height, self._max_x - len(self.CLI_PROMPT),\n self._max_y - self._command_textbox_height, len(self.CLI_PROMPT))\n\n def _screen_refresh(self):\n self._stdscr.refresh()\n\n def _screen_terminate(self):\n \"\"\"Terminate the curses screen.\"\"\"\n\n self._stdscr.keypad(0)\n curses.nocbreak()\n curses.echo()\n curses.endwin()\n\n try:\n # Remove SIGINT handler.\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n except ValueError:\n # Can't catch signals unless you're the main thread.\n pass\n\n def run_ui(self,\n init_command=None,\n title=None,\n title_color=None,\n enable_mouse_on_start=True):\n \"\"\"Run the CLI: See the doc of base_ui.BaseUI.run_ui for more details.\"\"\"\n\n # Only one instance of the Curses UI can be running at a time, since\n # otherwise they would try to both read from the same keystrokes, and write\n # to the same screen.\n self._single_instance_lock.acquire()\n\n self._screen_launch(enable_mouse_on_start=enable_mouse_on_start)\n\n # Optional initial command.\n if init_command is not None:\n self._dispatch_command(init_command)\n\n if title is not None:\n self._title(title, title_color=title_color)\n\n # CLI main loop.\n exit_token = self._ui_loop()\n\n if self._on_ui_exit:\n self._on_ui_exit()\n\n self._screen_terminate()\n\n self._single_instance_lock.release()\n\n return exit_token\n\n def get_help(self):\n return self._command_handler_registry.get_help()\n\n def _addstr(self, *args):\n try:\n self._stdscr.addstr(*args)\n except curses.error:\n pass\n\n def _refresh_pad(self, pad, *args):\n try:\n pad.refresh(*args)\n except curses.error:\n pass\n\n def _screen_create_command_textbox(self, existing_command=None):\n \"\"\"Create command textbox on screen.\n\n Args:\n existing_command: (str) A command string to put in the textbox right\n after its creation.\n \"\"\"\n\n # Display the tfdbg prompt.\n self._addstr(self._max_y - self._command_textbox_height, 0,\n self.CLI_PROMPT, curses.A_BOLD)\n self._stdscr.refresh()\n\n self._command_window.clear()\n\n # Command text box.\n self._command_textbox = textpad.Textbox(\n self._command_window, insert_mode=True)\n\n # Enter existing command.\n self._auto_key_in(existing_command)\n\n def _ui_loop(self):\n \"\"\"Command-line UI loop.\n\n Returns:\n An exit token of arbitrary type. The token can be None.\n \"\"\"\n\n while True:\n # Enter history command if pointer is in history (> 0):\n if self._command_pointer > 0:\n existing_command = self._active_command_history[-self._command_pointer]\n else:\n existing_command = self._pending_command\n self._screen_create_command_textbox(existing_command)\n\n try:\n command, terminator, pending_command_changed = self._get_user_command()\n except debugger_cli_common.CommandLineExit as e:\n return e.exit_token\n\n if not command and terminator != self.CLI_TAB_KEY:\n continue\n\n if terminator in self.CLI_CR_KEYS or terminator == curses.KEY_MOUSE:\n exit_token = self._dispatch_command(command)\n if exit_token is not None:\n return exit_token\n elif terminator == self.CLI_TAB_KEY:\n tab_completed = self._tab_complete(command)\n self._pending_command = tab_completed\n self._cmd_ptr = 0\n elif pending_command_changed:\n self._pending_command = command\n\n return\n\n def _get_user_command(self):\n \"\"\"Get user command from UI.\n\n Returns:\n command: (str) The user-entered command.\n terminator: (str) Terminator type for the command.\n If command is a normal command entered with the Enter key, the value\n will be the key itself. If this is a tab completion call (using the\n Tab key), the value will reflect that as well.\n pending_command_changed: (bool) If the pending command has changed.\n Used during command history navigation.\n \"\"\"\n\n # First, reset textbox state variables.\n self._textbox_curr_terminator = None\n self._textbox_pending_command_changed = False\n\n command = self._screen_get_user_command()\n command = self._strip_terminator(command)\n return (command, self._textbox_curr_terminator,\n self._textbox_pending_command_changed)\n\n def _screen_get_user_command(self):\n return self._command_textbox.edit(validate=self._on_textbox_keypress)\n\n def _strip_terminator(self, command):\n if not command:\n return command\n\n for v in self.CLI_CR_KEYS:\n if v < 256:\n command = command.replace(chr(v), \"\")\n\n return command.strip()\n\n def _screen_refresh_size(self):\n self._max_y, self._max_x = self._stdscr.getmaxyx()\n if self._max_x > self._SCREEN_WIDTH_LIMIT:\n self._max_x = self._SCREEN_WIDTH_LIMIT\n\n def _navigate_screen_output(self, command):\n \"\"\"Navigate in screen output history.\n\n Args:\n command: (`str`) the navigation command, from\n {self._NAVIGATION_FORWARD_COMMAND, self._NAVIGATION_BACK_COMMAND}.\n \"\"\"\n if command == self._NAVIGATION_FORWARD_COMMAND:\n if self._nav_history.can_go_forward():\n item = self._nav_history.go_forward()\n scroll_position = item.scroll_position\n else:\n self._toast(\"At the LATEST in navigation history!\",\n color=self._NAVIGATION_WARNING_COLOR_PAIR)\n return\n else:\n if self._nav_history.can_go_back():\n item = self._nav_history.go_back()\n scroll_position = item.scroll_position\n else:\n self._toast(\"At the OLDEST in navigation history!\",\n color=self._NAVIGATION_WARNING_COLOR_PAIR)\n return\n\n self._display_output(item.screen_output)\n if scroll_position != 0:\n self._scroll_output(_SCROLL_TO_LINE_INDEX, line_index=scroll_position)\n\n def _dispatch_command(self, command):\n \"\"\"Dispatch user command.\n\n Args:\n command: (str) Command to dispatch.\n\n Returns:\n An exit token object. None value means that the UI loop should not exit.\n A non-None value means the UI loop should exit.\n \"\"\"\n\n if self._output_pad:\n self._toast(self._UI_WAIT_MESSAGE, color=self._UI_WAIT_COLOR_PAIR)\n\n if command in self.CLI_EXIT_COMMANDS:\n # Explicit user command-triggered exit: EXPLICIT_USER_EXIT as the exit\n # token.\n return debugger_cli_common.EXPLICIT_USER_EXIT\n elif (command == self._NAVIGATION_FORWARD_COMMAND or\n command == self._NAVIGATION_BACK_COMMAND):\n self._navigate_screen_output(command)\n return\n\n if command:\n self._command_history_store.add_command(command)\n\n if (command.startswith(self.REGEX_SEARCH_PREFIX) and\n self._curr_unwrapped_output):\n if len(command) > len(self.REGEX_SEARCH_PREFIX):\n # Command is like \"/regex\". Perform regex search.\n regex = command[len(self.REGEX_SEARCH_PREFIX):]\n\n self._curr_search_regex = regex\n self._display_output(self._curr_unwrapped_output, highlight_regex=regex)\n elif self._unwrapped_regex_match_lines:\n # Command is \"/\". Continue scrolling down matching lines.\n self._display_output(\n self._curr_unwrapped_output,\n is_refresh=True,\n highlight_regex=self._curr_search_regex)\n\n self._command_pointer = 0\n self._pending_command = \"\"\n return\n elif command.startswith(self.TENSOR_INDICES_NAVIGATION_PREFIX):\n indices_str = command[1:].strip()\n if indices_str:\n try:\n indices = command_parser.parse_indices(indices_str)\n omitted, line_index, _, _ = tensor_format.locate_tensor_element(\n self._curr_wrapped_output, indices)\n if not omitted:\n self._scroll_output(\n _SCROLL_TO_LINE_INDEX, line_index=line_index)\n except Exception as e: # pylint: disable=broad-except\n self._error_toast(str(e))\n else:\n self._error_toast(\"Empty indices.\")\n\n return\n\n try:\n prefix, args, output_file_path = self._parse_command(command)\n except SyntaxError as e:\n self._error_toast(str(e))\n return\n\n if not prefix:\n # Empty command: take no action. Should not exit.\n return\n\n # Take into account scroll bar width.\n screen_info = {\"cols\": self._max_x - 2}\n exit_token = None\n if self._command_handler_registry.is_registered(prefix):\n try:\n screen_output = self._command_handler_registry.dispatch_command(\n prefix, args, screen_info=screen_info)\n except debugger_cli_common.CommandLineExit as e:\n exit_token = e.exit_token\n else:\n screen_output = debugger_cli_common.RichTextLines([\n self.ERROR_MESSAGE_PREFIX + \"Invalid command prefix \\\"%s\\\"\" % prefix\n ])\n\n # Clear active command history. Until next up/down history navigation\n # occurs, it will stay empty.\n self._active_command_history = []\n\n if exit_token is not None:\n return exit_token\n\n self._nav_history.add_item(command, screen_output, 0)\n\n self._display_output(screen_output)\n if output_file_path:\n try:\n screen_output.write_to_file(output_file_path)\n self._info_toast(\"Wrote output to %s\" % output_file_path)\n except Exception: # pylint: disable=broad-except\n self._error_toast(\"Failed to write output to %s\" % output_file_path)\n\n self._command_pointer = 0\n self._pending_command = \"\"\n\n def _screen_gather_textbox_str(self):\n \"\"\"Gather the text string in the command text box.\n\n Returns:\n (str) the current text string in the command textbox, excluding any\n return keys.\n \"\"\"\n\n txt = self._command_textbox.gather()\n return txt.strip()\n\n def _on_textbox_keypress(self, x):\n \"\"\"Text box key validator: Callback of key strokes.\n\n Handles a user's keypress in the input text box. Translates certain keys to\n terminator keys for the textbox to allow its edit() method to return.\n Also handles special key-triggered events such as PgUp/PgDown scrolling of\n the screen output.\n\n Args:\n x: (int) Key code.\n\n Returns:\n (int) A translated key code. In most cases, this is identical to the\n input x. However, if x is a Return key, the return value will be\n CLI_TERMINATOR_KEY, so that the text box's edit() method can return.\n\n Raises:\n TypeError: If the input x is not of type int.\n debugger_cli_common.CommandLineExit: If a mouse-triggered command returns\n an exit token when dispatched.\n \"\"\"\n if not isinstance(x, int):\n raise TypeError(\"Key validator expected type int, received type %s\" %\n type(x))\n\n if x in self.CLI_CR_KEYS:\n # Make Enter key the terminator\n self._textbox_curr_terminator = x\n return self.CLI_TERMINATOR_KEY\n elif x == self.CLI_TAB_KEY:\n self._textbox_curr_terminator = self.CLI_TAB_KEY\n return self.CLI_TERMINATOR_KEY\n elif x == curses.KEY_PPAGE:\n self._scroll_output(_SCROLL_UP_A_LINE)\n return x\n elif x == curses.KEY_NPAGE:\n self._scroll_output(_SCROLL_DOWN_A_LINE)\n return x\n elif x == curses.KEY_HOME:\n self._scroll_output(_SCROLL_HOME)\n return x\n elif x == curses.KEY_END:\n self._scroll_output(_SCROLL_END)\n return x\n elif x in [curses.KEY_UP, curses.KEY_DOWN]:\n # Command history navigation.\n if not self._active_command_history:\n hist_prefix = self._screen_gather_textbox_str()\n self._active_command_history = (\n self._command_history_store.lookup_prefix(\n hist_prefix, self._command_history_limit))\n\n if self._active_command_history:\n if x == curses.KEY_UP:\n if self._command_pointer < len(self._active_command_history):\n self._command_pointer += 1\n elif x == curses.KEY_DOWN:\n if self._command_pointer > 0:\n self._command_pointer -= 1\n else:\n self._command_pointer = 0\n\n self._textbox_curr_terminator = x\n\n # Force return from the textbox edit(), so that the textbox can be\n # redrawn with a history command entered.\n return self.CLI_TERMINATOR_KEY\n elif x == curses.KEY_RESIZE:\n # Respond to terminal resize.\n self._screen_refresh_size()\n self._init_layout()\n self._screen_create_command_window()\n self._redraw_output()\n\n # Force return from the textbox edit(), so that the textbox can be\n # redrawn.\n return self.CLI_TERMINATOR_KEY\n elif x == curses.KEY_MOUSE and self._mouse_enabled:\n try:\n _, mouse_x, mouse_y, _, mouse_event_type = self._screen_getmouse()\n except curses.error:\n mouse_event_type = None\n\n if mouse_event_type == curses.BUTTON1_PRESSED:\n # Logic for held mouse-triggered scrolling.\n if mouse_x >= self._max_x - 2:\n # Disable blocking on checking for user input.\n self._command_window.nodelay(True)\n\n # Loop while mouse button is pressed.\n while mouse_event_type == curses.BUTTON1_PRESSED:\n # Sleep for a bit.\n curses.napms(self._MOUSE_SCROLL_DELAY_MS)\n scroll_command = self._scroll_bar.get_click_command(mouse_y)\n if scroll_command in (_SCROLL_UP_A_LINE, _SCROLL_DOWN_A_LINE):\n self._scroll_output(scroll_command)\n\n # Check to see if different mouse event is in queue.\n self._command_window.getch()\n try:\n _, _, _, _, mouse_event_type = self._screen_getmouse()\n except curses.error:\n pass\n\n self._command_window.nodelay(False)\n return x\n elif mouse_event_type == curses.BUTTON1_RELEASED:\n # Logic for mouse-triggered scrolling.\n if mouse_x >= self._max_x - 2:\n scroll_command = self._scroll_bar.get_click_command(mouse_y)\n if scroll_command is not None:\n self._scroll_output(scroll_command)\n return x\n else:\n command = self._fetch_hyperlink_command(mouse_x, mouse_y)\n if command:\n self._screen_create_command_textbox()\n exit_token = self._dispatch_command(command)\n if exit_token is not None:\n raise debugger_cli_common.CommandLineExit(exit_token=exit_token)\n else:\n # Mark the pending command as modified.\n self._textbox_pending_command_changed = True\n # Invalidate active command history.\n self._command_pointer = 0\n self._active_command_history = []\n return self._KEY_MAP.get(x, x)\n\n def _screen_getmouse(self):\n return curses.getmouse()\n\n def _redraw_output(self):\n if self._curr_unwrapped_output is not None:\n self._display_nav_bar()\n self._display_main_menu(self._curr_unwrapped_output)\n self._display_output(self._curr_unwrapped_output, is_refresh=True)\n\n def _fetch_hyperlink_command(self, mouse_x, mouse_y):\n output_top = self._output_top_row\n if self._main_menu_pad:\n output_top += 1\n\n if mouse_y == self._nav_bar_row and self._nav_bar:\n # Click was in the nav bar.\n return _get_command_from_line_attr_segs(mouse_x,\n self._nav_bar.font_attr_segs[0])\n elif mouse_y == self._output_top_row and self._main_menu_pad:\n # Click was in the menu bar.\n return _get_command_from_line_attr_segs(mouse_x,\n self._main_menu.font_attr_segs[0])\n else:\n absolute_mouse_y = mouse_y + self._output_pad_row - output_top\n if absolute_mouse_y in self._curr_wrapped_output.font_attr_segs:\n return _get_command_from_line_attr_segs(\n mouse_x, self._curr_wrapped_output.font_attr_segs[absolute_mouse_y])\n\n def _title(self, title, title_color=None):\n \"\"\"Display title.\n\n Args:\n title: (str) The title to display.\n title_color: (str) Color of the title, e.g., \"yellow\".\n \"\"\"\n\n # Pad input title str with \"-\" and space characters to make it pretty.\n self._title_line = \"--- %s \" % title\n if len(self._title_line) < self._max_x:\n self._title_line += \"-\" * (self._max_x - len(self._title_line))\n\n self._screen_draw_text_line(\n self._title_row, self._title_line, color=title_color)\n\n def _auto_key_in(self, command, erase_existing=False):\n \"\"\"Automatically key in a command to the command Textbox.\n\n Args:\n command: The command, as a string or None.\n erase_existing: (bool) whether existing text (if any) is to be erased\n first.\n \"\"\"\n if erase_existing:\n self._erase_existing_command()\n\n command = command or \"\"\n for c in command:\n self._command_textbox.do_command(ord(c))\n\n def _erase_existing_command(self):\n \"\"\"Erase existing text in command textpad.\"\"\"\n\n existing_len = len(self._command_textbox.gather())\n for _ in range(existing_len):\n self._command_textbox.do_command(self.BACKSPACE_KEY)\n\n def _screen_draw_text_line(self, row, line, attr=curses.A_NORMAL, color=None):\n \"\"\"Render a line of text on the screen.\n\n Args:\n row: (int) Row index.\n line: (str) The line content.\n attr: curses font attribute.\n color: (str) font foreground color name.\n\n Raises:\n TypeError: If row is not of type int.\n \"\"\"\n\n if not isinstance(row, int):\n raise TypeError(\"Invalid type in row\")\n\n if len(line) > self._max_x:\n line = line[:self._max_x]\n\n color_pair = (self._default_color_pair if color is None else\n self._color_pairs[color])\n\n self._addstr(row, 0, line, color_pair | attr)\n self._screen_refresh()\n\n def _screen_new_output_pad(self, rows, cols):\n \"\"\"Generate a new pad on the screen.\n\n Args:\n rows: (int) Number of rows the pad will have: not limited to screen size.\n cols: (int) Number of columns the pad will have: not limited to screen\n size.\n\n Returns:\n A curses textpad object.\n \"\"\"\n\n return curses.newpad(rows, cols)\n\n def _screen_display_output(self, output):\n \"\"\"Actually render text output on the screen.\n\n Wraps the lines according to screen width. Pad lines below according to\n screen height so that the user can scroll the output to a state where\n the last non-empty line is on the top of the screen. Then renders the\n lines on the screen.\n\n Args:\n output: (RichTextLines) text lines to display on the screen. These lines\n may have widths exceeding the screen width. This method will take care\n of the wrapping.\n\n Returns:\n (List of int) A list of line indices, in the wrapped output, where there\n are regex matches.\n \"\"\"\n\n # Wrap the output lines according to screen width.\n self._curr_wrapped_output, wrapped_line_indices = (\n debugger_cli_common.wrap_rich_text_lines(output, self._max_x - 2))\n\n # Append lines to curr_wrapped_output so that the user can scroll to a\n # state where the last text line is on the top of the output area.\n self._curr_wrapped_output.lines.extend([\"\"] * (self._output_num_rows - 1))\n\n # Limit number of lines displayed to avoid curses overflow problems.\n if self._curr_wrapped_output.num_lines() > self.max_output_lines:\n self._curr_wrapped_output = self._curr_wrapped_output.slice(\n 0, self.max_output_lines)\n self._curr_wrapped_output.lines.append(\"Output cut off at %d lines!\" %\n self.max_output_lines)\n self._curr_wrapped_output.font_attr_segs[self.max_output_lines] = [\n (0, len(output.lines[-1]), cli_shared.COLOR_MAGENTA)\n ]\n\n self._display_nav_bar()\n self._display_main_menu(self._curr_wrapped_output)\n\n (self._output_pad, self._output_pad_height,\n self._output_pad_width) = self._display_lines(self._curr_wrapped_output,\n self._output_num_rows)\n\n # The indices of lines with regex matches (if any) need to be mapped to\n # indices of wrapped lines.\n return [\n wrapped_line_indices[line]\n for line in self._unwrapped_regex_match_lines\n ]\n\n def _display_output(self, output, is_refresh=False, highlight_regex=None):\n \"\"\"Display text output in a scrollable text pad.\n\n This method does some preprocessing on the text lines, render them on the\n screen and scroll to the appropriate line. These are done according to regex\n highlighting requests (if any), scroll-to-next-match requests (if any),\n and screen refresh requests (if any).\n\n TODO(cais): Separate these unrelated request to increase clarity and\n maintainability.\n\n Args:\n output: A RichTextLines object that is the screen output text.\n is_refresh: (bool) Is this a refreshing display with existing output.\n highlight_regex: (str) Optional string representing the regex used to\n search and highlight in the current screen output.\n \"\"\"\n\n if not output:\n return\n\n if highlight_regex:\n try:\n output = debugger_cli_common.regex_find(\n output, highlight_regex, font_attr=self._SEARCH_HIGHLIGHT_FONT_ATTR)\n except ValueError as e:\n self._error_toast(str(e))\n return\n\n if not is_refresh:\n # Perform new regex search on the current output.\n self._unwrapped_regex_match_lines = output.annotations[\n debugger_cli_common.REGEX_MATCH_LINES_KEY]\n else:\n # Continue scrolling down.\n self._output_pad_row += 1\n else:\n self._curr_unwrapped_output = output\n self._unwrapped_regex_match_lines = []\n\n # Display output on the screen.\n wrapped_regex_match_lines = self._screen_display_output(output)\n\n # Now that the text lines are displayed on the screen scroll to the\n # appropriate line according to previous scrolling state and regex search\n # and highlighting state.\n\n if highlight_regex:\n next_match_line = -1\n for match_line in wrapped_regex_match_lines:\n if match_line >= self._output_pad_row:\n next_match_line = match_line\n break\n\n if next_match_line >= 0:\n self._scroll_output(\n _SCROLL_TO_LINE_INDEX, line_index=next_match_line)\n else:\n # Regex search found no match >= current line number. Display message\n # stating as such.\n self._toast(\"Pattern not found\", color=self._ERROR_TOAST_COLOR_PAIR)\n elif is_refresh:\n self._scroll_output(_SCROLL_REFRESH)\n elif debugger_cli_common.INIT_SCROLL_POS_KEY in output.annotations:\n line_index = output.annotations[debugger_cli_common.INIT_SCROLL_POS_KEY]\n self._scroll_output(_SCROLL_TO_LINE_INDEX, line_index=line_index)\n else:\n self._output_pad_row = 0\n self._scroll_output(_SCROLL_HOME)\n\n def _display_lines(self, output, min_num_rows):\n \"\"\"Display RichTextLines object on screen.\n\n Args:\n output: A RichTextLines object.\n min_num_rows: (int) Minimum number of output rows.\n\n Returns:\n 1) The text pad object used to display the main text body.\n 2) (int) number of rows of the text pad, which may exceed screen size.\n 3) (int) number of columns of the text pad.\n\n Raises:\n ValueError: If input argument \"output\" is invalid.\n \"\"\"\n\n if not isinstance(output, debugger_cli_common.RichTextLines):\n raise ValueError(\n \"Output is required to be an instance of RichTextLines, but is not.\")\n\n self._screen_refresh()\n\n # Number of rows the output area will have.\n rows = max(min_num_rows, len(output.lines))\n\n # Size of the output pad, which may exceed screen size and require\n # scrolling.\n cols = self._max_x - 2\n\n # Create new output pad.\n pad = self._screen_new_output_pad(rows, cols)\n\n for i in range(len(output.lines)):\n if i in output.font_attr_segs:\n self._screen_add_line_to_output_pad(\n pad, i, output.lines[i], color_segments=output.font_attr_segs[i])\n else:\n self._screen_add_line_to_output_pad(pad, i, output.lines[i])\n\n return pad, rows, cols\n\n def _display_nav_bar(self):\n nav_bar_width = self._max_x - 2\n self._nav_bar_pad = self._screen_new_output_pad(1, nav_bar_width)\n self._nav_bar = self._nav_history.render(\n nav_bar_width,\n self._NAVIGATION_BACK_COMMAND,\n self._NAVIGATION_FORWARD_COMMAND)\n self._screen_add_line_to_output_pad(\n self._nav_bar_pad, 0, self._nav_bar.lines[0][:nav_bar_width - 1],\n color_segments=(self._nav_bar.font_attr_segs[0]\n if 0 in self._nav_bar.font_attr_segs else None))\n\n def _display_main_menu(self, output):\n \"\"\"Display main menu associated with screen output, if the menu exists.\n\n Args:\n output: (debugger_cli_common.RichTextLines) The RichTextLines output from\n the annotations field of which the menu will be extracted and used (if\n the menu exists).\n \"\"\"\n\n if debugger_cli_common.MAIN_MENU_KEY in output.annotations:\n self._main_menu = output.annotations[\n debugger_cli_common.MAIN_MENU_KEY].format_as_single_line(\n prefix=\"| \", divider=\" | \", enabled_item_attrs=[\"underline\"])\n\n self._main_menu_pad = self._screen_new_output_pad(1, self._max_x - 2)\n\n # The unwrapped menu line may exceed screen width, in which case it needs\n # to be cut off.\n wrapped_menu, _ = debugger_cli_common.wrap_rich_text_lines(\n self._main_menu, self._max_x - 3)\n self._screen_add_line_to_output_pad(\n self._main_menu_pad,\n 0,\n wrapped_menu.lines[0],\n color_segments=(wrapped_menu.font_attr_segs[0]\n if 0 in wrapped_menu.font_attr_segs else None))\n else:\n self._main_menu = None\n self._main_menu_pad = None\n\n def _pad_line_end_with_whitespace(self, pad, row, line_end_x):\n \"\"\"Pad the whitespace at the end of a line with the default color pair.\n\n Prevents spurious color pairs from appearing at the end of the lines in\n certain text terminals.\n\n Args:\n pad: The curses pad object to operate on.\n row: (`int`) row index.\n line_end_x: (`int`) column index of the end of the line (beginning of\n the whitespace).\n \"\"\"\n if line_end_x < self._max_x - 2:\n pad.addstr(row, line_end_x, \" \" * (self._max_x - 3 - line_end_x),\n self._default_color_pair)\n\n def _screen_add_line_to_output_pad(self, pad, row, txt, color_segments=None):\n \"\"\"Render a line in a text pad.\n\n Assumes: segments in color_segments are sorted in ascending order of the\n beginning index.\n Note: Gaps between the segments are allowed and will be fixed in with a\n default color.\n\n Args:\n pad: The text pad to render the line in.\n row: Row index, as an int.\n txt: The text to be displayed on the specified row, as a str.\n color_segments: A list of 3-tuples. Each tuple represents the beginning\n and the end of a color segment, in the form of a right-open interval:\n [start, end). The last element of the tuple is a color string, e.g.,\n \"red\".\n\n Raisee:\n TypeError: If color_segments is not of type list.\n \"\"\"\n\n if not color_segments:\n pad.addstr(row, 0, txt, self._default_color_pair)\n self._pad_line_end_with_whitespace(pad, row, len(txt))\n return\n\n if not isinstance(color_segments, list):\n raise TypeError(\"Input color_segments needs to be a list, but is not.\")\n\n all_segments = []\n all_color_pairs = []\n\n # Process the beginning.\n if color_segments[0][0] == 0:\n pass\n else:\n all_segments.append((0, color_segments[0][0]))\n all_color_pairs.append(self._default_color_pair)\n\n for (curr_start, curr_end, curr_attrs), (next_start, _, _) in zip(\n color_segments, color_segments[1:] + [(len(txt), None, None)]):\n all_segments.append((curr_start, curr_end))\n\n if not isinstance(curr_attrs, list):\n curr_attrs = [curr_attrs]\n\n curses_attr = curses.A_NORMAL\n for attr in curr_attrs:\n if (self._mouse_enabled and\n isinstance(attr, debugger_cli_common.MenuItem)):\n curses_attr |= curses.A_UNDERLINE\n else:\n curses_attr |= self._color_pairs.get(attr, self._default_color_pair)\n all_color_pairs.append(curses_attr)\n\n if curr_end < next_start:\n # Fill in the gap with the default color.\n all_segments.append((curr_end, next_start))\n all_color_pairs.append(self._default_color_pair)\n\n # Finally, draw all the segments.\n for segment, color_pair in zip(all_segments, all_color_pairs):\n if segment[1] < self._max_x:\n pad.addstr(row, segment[0], txt[segment[0]:segment[1]], color_pair)\n if all_segments:\n self._pad_line_end_with_whitespace(pad, row, all_segments[-1][1])\n\n def _screen_scroll_output_pad(self, pad, viewport_top, viewport_left,\n screen_location_top, screen_location_left,\n screen_location_bottom, screen_location_right):\n self._refresh_pad(pad, viewport_top, viewport_left, screen_location_top,\n screen_location_left, screen_location_bottom,\n screen_location_right)\n self._scroll_bar = ScrollBar(\n self._max_x - 2,\n 3,\n self._max_x - 1,\n self._output_num_rows + 1,\n self._output_pad_row,\n self._output_pad_height - self._output_pad_screen_height)\n\n (scroll_pad, _, _) = self._display_lines(\n self._scroll_bar.layout(), self._output_num_rows - 1)\n self._refresh_pad(scroll_pad, 0, 0, self._output_top_row + 1,\n self._max_x - 2, self._output_num_rows + 1,\n self._max_x - 1)\n\n def _scroll_output(self, direction, line_index=None):\n \"\"\"Scroll the output pad.\n\n Args:\n direction: _SCROLL_REFRESH, _SCROLL_UP, _SCROLL_DOWN, _SCROLL_UP_A_LINE,\n _SCROLL_DOWN_A_LINE, _SCROLL_HOME, _SCROLL_END, _SCROLL_TO_LINE_INDEX\n line_index: (int) Specifies the zero-based line index to scroll to.\n Applicable only if direction is _SCROLL_TO_LINE_INDEX.\n\n Raises:\n ValueError: On invalid scroll direction.\n TypeError: If line_index is not int and direction is\n _SCROLL_TO_LINE_INDEX.\n \"\"\"\n\n if not self._output_pad:\n # No output pad is present. Do nothing.\n return\n\n if direction == _SCROLL_REFRESH:\n pass\n elif direction == _SCROLL_UP:\n # Scroll up.\n self._output_pad_row -= int(self._output_num_rows / 3)\n if self._output_pad_row < 0:\n self._output_pad_row = 0\n elif direction == _SCROLL_DOWN:\n # Scroll down.\n self._output_pad_row += int(self._output_num_rows / 3)\n if (self._output_pad_row >\n self._output_pad_height - self._output_pad_screen_height - 1):\n self._output_pad_row = (\n self._output_pad_height - self._output_pad_screen_height - 1)\n elif direction == _SCROLL_UP_A_LINE:\n # Scroll up a line\n if self._output_pad_row - 1 >= 0:\n self._output_pad_row -= 1\n elif direction == _SCROLL_DOWN_A_LINE:\n # Scroll down a line\n if self._output_pad_row + 1 < (\n self._output_pad_height - self._output_pad_screen_height):\n self._output_pad_row += 1\n elif direction == _SCROLL_HOME:\n # Scroll to top\n self._output_pad_row = 0\n elif direction == _SCROLL_END:\n # Scroll to bottom\n self._output_pad_row = (\n self._output_pad_height - self._output_pad_screen_height - 1)\n elif direction == _SCROLL_TO_LINE_INDEX:\n if not isinstance(line_index, int):\n raise TypeError(\"Invalid line_index type (%s) under mode %s\" %\n (type(line_index), _SCROLL_TO_LINE_INDEX))\n self._output_pad_row = line_index\n else:\n raise ValueError(\"Unsupported scroll mode: %s\" % direction)\n\n self._nav_history.update_scroll_position(self._output_pad_row)\n\n # Actually scroll the output pad: refresh with new location.\n output_pad_top = self._output_pad_screen_location.top\n if self._main_menu_pad:\n output_pad_top += 1\n self._screen_scroll_output_pad(self._output_pad, self._output_pad_row, 0,\n output_pad_top,\n self._output_pad_screen_location.left,\n self._output_pad_screen_location.bottom,\n self._output_pad_screen_location.right)\n self._screen_render_nav_bar()\n self._screen_render_menu_pad()\n\n self._scroll_info = self._compile_ui_status_summary()\n self._screen_draw_text_line(\n self._output_scroll_row,\n self._scroll_info,\n color=self._STATUS_BAR_COLOR_PAIR)\n\n def _screen_render_nav_bar(self):\n if self._nav_bar_pad:\n self._refresh_pad(self._nav_bar_pad, 0, 0, self._nav_bar_row, 0,\n self._output_pad_screen_location.top, self._max_x)\n\n def _screen_render_menu_pad(self):\n if self._main_menu_pad:\n self._refresh_pad(\n self._main_menu_pad, 0, 0, self._output_pad_screen_location.top, 0,\n self._output_pad_screen_location.top, self._max_x)\n\n def _compile_ui_status_summary(self):\n \"\"\"Compile status summary about this Curses UI instance.\n\n The information includes: scroll status and mouse ON/OFF status.\n\n Returns:\n (str) A single text line summarizing the UI status, adapted to the\n current screen width.\n \"\"\"\n\n info = \"\"\n if self._output_pad_height > self._output_pad_screen_height + 1:\n # Display information about the scrolling of tall screen output.\n scroll_percentage = 100.0 * (min(\n 1.0,\n float(self._output_pad_row) /\n (self._output_pad_height - self._output_pad_screen_height - 1)))\n if self._output_pad_row == 0:\n scroll_directions = \" (PgDn)\"\n elif self._output_pad_row >= (\n self._output_pad_height - self._output_pad_screen_height - 1):\n scroll_directions = \" (PgUp)\"\n else:\n scroll_directions = \" (PgDn/PgUp)\"\n\n info += \"--- Scroll%s: %.2f%% \" % (scroll_directions, scroll_percentage)\n\n self._output_array_pointer_indices = self._show_array_indices()\n\n # Add array indices information to scroll message.\n if self._output_array_pointer_indices:\n if self._output_array_pointer_indices[0]:\n info += self._format_indices(self._output_array_pointer_indices[0])\n info += \"-\"\n if self._output_array_pointer_indices[-1]:\n info += self._format_indices(self._output_array_pointer_indices[-1])\n info += \" \"\n\n # Add mouse mode information.\n mouse_mode_str = \"Mouse: \"\n mouse_mode_str += \"ON\" if self._mouse_enabled else \"OFF\"\n\n if len(info) + len(mouse_mode_str) + 5 < self._max_x:\n info += \"-\" * (self._max_x - len(info) - len(mouse_mode_str) - 4)\n info += \" \"\n info += mouse_mode_str\n info += \" ---\"\n else:\n info += \"-\" * (self._max_x - len(info))\n\n return info\n\n def _format_indices(self, indices):\n # Remove the spaces to make it compact.\n return repr(indices).replace(\" \", \"\")\n\n def _show_array_indices(self):\n \"\"\"Show array indices for the lines at the top and bottom of the output.\n\n For the top line and bottom line of the output display area, show the\n element indices of the array being displayed.\n\n Returns:\n If either the top of the bottom row has any matching array indices,\n a dict from line index (0 being the top of the display area, -1\n being the bottom of the display area) to array element indices. For\n example:\n {0: [0, 0], -1: [10, 0]}\n Otherwise, None.\n \"\"\"\n\n indices_top = self._show_array_index_at_line(0)\n\n output_top = self._output_top_row\n if self._main_menu_pad:\n output_top += 1\n bottom_line_index = (\n self._output_pad_screen_location.bottom - output_top - 1)\n indices_bottom = self._show_array_index_at_line(bottom_line_index)\n\n if indices_top or indices_bottom:\n return {0: indices_top, -1: indices_bottom}\n else:\n return None\n\n def _show_array_index_at_line(self, line_index):\n \"\"\"Show array indices for the specified line in the display area.\n\n Uses the line number to array indices map in the annotations field of the\n RichTextLines object being displayed.\n If the displayed RichTextLines object does not contain such a mapping,\n will do nothing.\n\n Args:\n line_index: (int) 0-based line index from the top of the display area.\n For example,if line_index == 0, this method will display the array\n indices for the line currently at the top of the display area.\n\n Returns:\n (list) The array indices at the specified line, if available. None, if\n not available.\n \"\"\"\n\n # Examine whether the index information is available for the specified line\n # number.\n pointer = self._output_pad_row + line_index\n if (pointer in self._curr_wrapped_output.annotations and\n \"i0\" in self._curr_wrapped_output.annotations[pointer]):\n indices = self._curr_wrapped_output.annotations[pointer][\"i0\"]\n\n array_indices_str = self._format_indices(indices)\n array_indices_info = \"@\" + array_indices_str\n\n # TODO(cais): Determine line_index properly given menu pad status.\n # Test coverage?\n output_top = self._output_top_row\n if self._main_menu_pad:\n output_top += 1\n\n self._toast(\n array_indices_info,\n color=self._ARRAY_INDICES_COLOR_PAIR,\n line_index=output_top + line_index)\n\n return indices\n else:\n return None\n\n def _tab_complete(self, command_str):\n \"\"\"Perform tab completion.\n\n Obtains tab completion candidates.\n If there are no candidates, return command_str and take no other actions.\n If there are candidates, display the candidates on screen and return\n command_str + (common prefix of the candidates).\n\n Args:\n command_str: (str) The str in the command input textbox when Tab key is\n hit.\n\n Returns:\n (str) Completed string. Could be the same as command_str if no completion\n candidate is available. If candidate(s) are available, return command_str\n appended by the common prefix of the candidates.\n \"\"\"\n\n context, prefix, except_last_word = self._analyze_tab_complete_input(\n command_str)\n candidates, common_prefix = self._tab_completion_registry.get_completions(\n context, prefix)\n\n if candidates and len(candidates) > 1:\n self._display_candidates(candidates)\n else:\n # In the case of len(candidates) == 1, the single completion will be\n # entered to the textbox automatically. So there is no need to show any\n # candidates.\n self._display_candidates([])\n\n if common_prefix:\n # Common prefix is not None and non-empty. The completed string will\n # incorporate the common prefix.\n return except_last_word + common_prefix\n else:\n return except_last_word + prefix\n\n def _display_candidates(self, candidates):\n \"\"\"Show candidates (e.g., tab-completion candidates) on multiple lines.\n\n Args:\n candidates: (list of str) candidates.\n \"\"\"\n\n if self._curr_unwrapped_output:\n # Force refresh screen output.\n self._scroll_output(_SCROLL_REFRESH)\n\n if not candidates:\n return\n\n candidates_prefix = \"Candidates: \"\n candidates_line = candidates_prefix + \" \".join(candidates)\n candidates_output = debugger_cli_common.RichTextLines(\n candidates_line,\n font_attr_segs={\n 0: [(len(candidates_prefix), len(candidates_line), \"yellow\")]\n })\n\n candidates_output, _ = debugger_cli_common.wrap_rich_text_lines(\n candidates_output, self._max_x - 3)\n\n # Calculate how many lines the candidate text should occupy. Limit it to\n # a maximum value.\n candidates_num_rows = min(\n len(candidates_output.lines), self._candidates_max_lines)\n self._candidates_top_row = (\n self._candidates_bottom_row - candidates_num_rows + 1)\n\n # Render the candidate text on screen.\n pad, _, _ = self._display_lines(candidates_output, 0)\n self._screen_scroll_output_pad(\n pad, 0, 0, self._candidates_top_row, 0,\n self._candidates_top_row + candidates_num_rows - 1, self._max_x - 2)\n\n def _toast(self, message, color=None, line_index=None):\n \"\"\"Display a one-line message on the screen.\n\n By default, the toast is displayed in the line right above the scroll bar.\n But the line location can be overridden with the line_index arg.\n\n Args:\n message: (str) the message to display.\n color: (str) optional color attribute for the message.\n line_index: (int) line index.\n \"\"\"\n\n pad, _, _ = self._display_lines(\n debugger_cli_common.RichTextLines(\n message,\n font_attr_segs={\n 0: [(0, len(message), color or cli_shared.COLOR_WHITE)]}),\n 0)\n\n right_end = min(len(message), self._max_x - 2)\n\n if line_index is None:\n line_index = self._output_scroll_row - 1\n self._screen_scroll_output_pad(pad, 0, 0, line_index, 0, line_index,\n right_end)\n\n def _error_toast(self, message):\n \"\"\"Display a one-line error message on screen.\n\n Args:\n message: The error message, without the preceding \"ERROR: \" substring.\n \"\"\"\n\n self._toast(\n self.ERROR_MESSAGE_PREFIX + message, color=self._ERROR_TOAST_COLOR_PAIR)\n\n def _info_toast(self, message):\n \"\"\"Display a one-line informational message on screen.\n\n Args:\n message: The informational message.\n \"\"\"\n\n self._toast(\n self.INFO_MESSAGE_PREFIX + message, color=self._INFO_TOAST_COLOR_PAIR)\n\n def _interrupt_handler(self, signal_num, frame):\n del signal_num # Unused.\n del frame # Unused.\n\n if self._on_ui_exit:\n self._on_ui_exit()\n\n self._screen_terminate()\n print(\"\\ntfdbg: caught SIGINT; calling sys.exit(1).\", file=sys.stderr)\n sys.exit(1)\n\n def _mouse_mode_command_handler(self, args, screen_info=None):\n \"\"\"Handler for the command prefix 'mouse'.\n\n Args:\n args: (list of str) Arguments to the command prefix 'mouse'.\n screen_info: (dict) Information about the screen, unused by this handler.\n\n Returns:\n None, as this command handler does not generate any screen outputs other\n than toasts.\n \"\"\"\n\n del screen_info\n\n if not args or len(args) == 1:\n if args:\n if args[0].lower() == \"on\":\n enabled = True\n elif args[0].lower() == \"off\":\n enabled = False\n else:\n self._error_toast(\"Invalid mouse mode: %s\" % args[0])\n return None\n\n self._set_mouse_enabled(enabled)\n\n mode_str = \"on\" if self._mouse_enabled else \"off\"\n self._info_toast(\"Mouse mode: %s\" % mode_str)\n else:\n self._error_toast(\"mouse_mode: syntax error\")\n\n return None\n\n def _set_mouse_enabled(self, enabled):\n if self._mouse_enabled != enabled:\n self._mouse_enabled = enabled\n self._screen_set_mousemask()\n self._redraw_output()\n\n def _screen_set_mousemask(self):\n if self._mouse_enabled:\n curses.mousemask(curses.BUTTON1_RELEASED | curses.BUTTON1_PRESSED)\n else:\n curses.mousemask(0)\n", "# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for flatbuffer_utils.py.\"\"\"\nimport copy\nimport os\nimport subprocess\n\nfrom tensorflow.lite.tools import flatbuffer_utils\nfrom tensorflow.lite.tools import test_utils\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\n\n_SKIPPED_BUFFER_INDEX = 1\n\n\nclass WriteReadModelTest(test_util.TensorFlowTestCase):\n\n def testWriteReadModel(self):\n # 1. SETUP\n # Define the initial model\n initial_model = test_utils.build_mock_model()\n # Define temporary files\n tmp_dir = self.get_temp_dir()\n model_filename = os.path.join(tmp_dir, 'model.tflite')\n\n # 2. INVOKE\n # Invoke the write_model and read_model functions\n flatbuffer_utils.write_model(initial_model, model_filename)\n final_model = flatbuffer_utils.read_model(model_filename)\n\n # 3. VALIDATE\n # Validate that the initial and final models are the same\n # Validate the description\n self.assertEqual(initial_model.description, final_model.description)\n # Validate the main subgraph's name, inputs, outputs, operators and tensors\n initial_subgraph = initial_model.subgraphs[0]\n final_subgraph = final_model.subgraphs[0]\n self.assertEqual(initial_subgraph.name, final_subgraph.name)\n for i in range(len(initial_subgraph.inputs)):\n self.assertEqual(initial_subgraph.inputs[i], final_subgraph.inputs[i])\n for i in range(len(initial_subgraph.outputs)):\n self.assertEqual(initial_subgraph.outputs[i], final_subgraph.outputs[i])\n for i in range(len(initial_subgraph.operators)):\n self.assertEqual(initial_subgraph.operators[i].opcodeIndex,\n final_subgraph.operators[i].opcodeIndex)\n initial_tensors = initial_subgraph.tensors\n final_tensors = final_subgraph.tensors\n for i in range(len(initial_tensors)):\n self.assertEqual(initial_tensors[i].name, final_tensors[i].name)\n self.assertEqual(initial_tensors[i].type, final_tensors[i].type)\n self.assertEqual(initial_tensors[i].buffer, final_tensors[i].buffer)\n for j in range(len(initial_tensors[i].shape)):\n self.assertEqual(initial_tensors[i].shape[j], final_tensors[i].shape[j])\n # Validate the first valid buffer (index 0 is always None)\n initial_buffer = initial_model.buffers[1].data\n final_buffer = final_model.buffers[1].data\n for i in range(initial_buffer.size):\n self.assertEqual(initial_buffer.data[i], final_buffer.data[i])\n\n\nclass StripStringsTest(test_util.TensorFlowTestCase):\n\n def testStripStrings(self):\n # 1. SETUP\n # Define the initial model\n initial_model = test_utils.build_mock_model()\n final_model = copy.deepcopy(initial_model)\n\n # 2. INVOKE\n # Invoke the strip_strings function\n flatbuffer_utils.strip_strings(final_model)\n\n # 3. VALIDATE\n # Validate that the initial and final models are the same except strings\n # Validate the description\n self.assertIsNotNone(initial_model.description)\n self.assertIsNone(final_model.description)\n self.assertIsNotNone(initial_model.signatureDefs)\n self.assertIsNone(final_model.signatureDefs)\n\n # Validate the main subgraph's name, inputs, outputs, operators and tensors\n initial_subgraph = initial_model.subgraphs[0]\n final_subgraph = final_model.subgraphs[0]\n self.assertIsNotNone(initial_model.subgraphs[0].name)\n self.assertIsNone(final_model.subgraphs[0].name)\n for i in range(len(initial_subgraph.inputs)):\n self.assertEqual(initial_subgraph.inputs[i], final_subgraph.inputs[i])\n for i in range(len(initial_subgraph.outputs)):\n self.assertEqual(initial_subgraph.outputs[i], final_subgraph.outputs[i])\n for i in range(len(initial_subgraph.operators)):\n self.assertEqual(initial_subgraph.operators[i].opcodeIndex,\n final_subgraph.operators[i].opcodeIndex)\n initial_tensors = initial_subgraph.tensors\n final_tensors = final_subgraph.tensors\n for i in range(len(initial_tensors)):\n self.assertIsNotNone(initial_tensors[i].name)\n self.assertIsNone(final_tensors[i].name)\n self.assertEqual(initial_tensors[i].type, final_tensors[i].type)\n self.assertEqual(initial_tensors[i].buffer, final_tensors[i].buffer)\n for j in range(len(initial_tensors[i].shape)):\n self.assertEqual(initial_tensors[i].shape[j], final_tensors[i].shape[j])\n # Validate the first valid buffer (index 0 is always None)\n initial_buffer = initial_model.buffers[1].data\n final_buffer = final_model.buffers[1].data\n for i in range(initial_buffer.size):\n self.assertEqual(initial_buffer.data[i], final_buffer.data[i])\n\n\nclass RandomizeWeightsTest(test_util.TensorFlowTestCase):\n\n def testRandomizeWeights(self):\n # 1. SETUP\n # Define the initial model\n initial_model = test_utils.build_mock_model()\n final_model = copy.deepcopy(initial_model)\n\n # 2. INVOKE\n # Invoke the randomize_weights function\n flatbuffer_utils.randomize_weights(final_model)\n\n # 3. VALIDATE\n # Validate that the initial and final models are the same, except that\n # the weights in the model buffer have been modified (i.e, randomized)\n # Validate the description\n self.assertEqual(initial_model.description, final_model.description)\n # Validate the main subgraph's name, inputs, outputs, operators and tensors\n initial_subgraph = initial_model.subgraphs[0]\n final_subgraph = final_model.subgraphs[0]\n self.assertEqual(initial_subgraph.name, final_subgraph.name)\n for i in range(len(initial_subgraph.inputs)):\n self.assertEqual(initial_subgraph.inputs[i], final_subgraph.inputs[i])\n for i in range(len(initial_subgraph.outputs)):\n self.assertEqual(initial_subgraph.outputs[i], final_subgraph.outputs[i])\n for i in range(len(initial_subgraph.operators)):\n self.assertEqual(initial_subgraph.operators[i].opcodeIndex,\n final_subgraph.operators[i].opcodeIndex)\n initial_tensors = initial_subgraph.tensors\n final_tensors = final_subgraph.tensors\n for i in range(len(initial_tensors)):\n self.assertEqual(initial_tensors[i].name, final_tensors[i].name)\n self.assertEqual(initial_tensors[i].type, final_tensors[i].type)\n self.assertEqual(initial_tensors[i].buffer, final_tensors[i].buffer)\n for j in range(len(initial_tensors[i].shape)):\n self.assertEqual(initial_tensors[i].shape[j], final_tensors[i].shape[j])\n # Validate the first valid buffer (index 0 is always None)\n initial_buffer = initial_model.buffers[1].data\n final_buffer = final_model.buffers[1].data\n for j in range(initial_buffer.size):\n self.assertNotEqual(initial_buffer.data[j], final_buffer.data[j])\n\n def testRandomizeSomeWeights(self):\n # 1. SETUP\n # Define the initial model\n initial_model = test_utils.build_mock_model()\n final_model = copy.deepcopy(initial_model)\n\n # 2. INVOKE\n # Invoke the randomize_weights function, but skip the first buffer\n flatbuffer_utils.randomize_weights(\n final_model, buffers_to_skip=[_SKIPPED_BUFFER_INDEX])\n\n # 3. VALIDATE\n # Validate that the initial and final models are the same, except that\n # the weights in the model buffer have been modified (i.e, randomized)\n # Validate the description\n self.assertEqual(initial_model.description, final_model.description)\n # Validate the main subgraph's name, inputs, outputs, operators and tensors\n initial_subgraph = initial_model.subgraphs[0]\n final_subgraph = final_model.subgraphs[0]\n self.assertEqual(initial_subgraph.name, final_subgraph.name)\n for i, _ in enumerate(initial_subgraph.inputs):\n self.assertEqual(initial_subgraph.inputs[i], final_subgraph.inputs[i])\n for i, _ in enumerate(initial_subgraph.outputs):\n self.assertEqual(initial_subgraph.outputs[i], final_subgraph.outputs[i])\n for i, _ in enumerate(initial_subgraph.operators):\n self.assertEqual(initial_subgraph.operators[i].opcodeIndex,\n final_subgraph.operators[i].opcodeIndex)\n initial_tensors = initial_subgraph.tensors\n final_tensors = final_subgraph.tensors\n for i, _ in enumerate(initial_tensors):\n self.assertEqual(initial_tensors[i].name, final_tensors[i].name)\n self.assertEqual(initial_tensors[i].type, final_tensors[i].type)\n self.assertEqual(initial_tensors[i].buffer, final_tensors[i].buffer)\n for j in range(len(initial_tensors[i].shape)):\n self.assertEqual(initial_tensors[i].shape[j], final_tensors[i].shape[j])\n # Validate that the skipped buffer is unchanged.\n initial_buffer = initial_model.buffers[_SKIPPED_BUFFER_INDEX].data\n final_buffer = final_model.buffers[_SKIPPED_BUFFER_INDEX].data\n for j in range(initial_buffer.size):\n self.assertEqual(initial_buffer.data[j], final_buffer.data[j])\n\n\nclass XxdOutputToBytesTest(test_util.TensorFlowTestCase):\n\n def testXxdOutputToBytes(self):\n # 1. SETUP\n # Define the initial model\n initial_model = test_utils.build_mock_model()\n initial_bytes = flatbuffer_utils.convert_object_to_bytearray(initial_model)\n\n # Define temporary files\n tmp_dir = self.get_temp_dir()\n model_filename = os.path.join(tmp_dir, 'model.tflite')\n\n # 2. Write model to temporary file (will be used as input for xxd)\n flatbuffer_utils.write_model(initial_model, model_filename)\n\n # 3. DUMP WITH xxd\n input_cc_file = os.path.join(tmp_dir, 'model.cc')\n\n command = 'xxd -i {} > {}'.format(model_filename, input_cc_file)\n subprocess.call(command, shell=True)\n\n # 4. VALIDATE\n final_bytes = flatbuffer_utils.xxd_output_to_bytes(input_cc_file)\n\n # Validate that the initial and final bytearray are the same\n self.assertEqual(initial_bytes, final_bytes)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.kernels.sparse_op.\"\"\"\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import test\n\n\n@test_util.with_eager_op_as_function\nclass SparseToDenseTest(test.TestCase):\n\n def testInt(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], 1, 0)\n np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testFloat(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], 1.0, 0.0)\n np_ans = np.array([0, 1, 0, 1, 0]).astype(np.float32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testEmptyNonZeros(self):\n indices = array_ops.constant([], dtype=dtypes.int32)\n values = array_ops.constant([], dtype=dtypes.float32)\n tf_ans = sparse_ops.sparse_to_dense(indices, [5], values, 0.0)\n np_ans = np.array([0, 0, 0, 0, 0]).astype(np.float32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testString(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], \"a\", \"b\")\n np_ans = np.array([\"b\", \"a\", \"b\", \"a\", \"b\"]).astype(np.string_)\n self.assertAllEqual(np_ans, tf_ans)\n\n def testSetValue(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], [1, 2], -1)\n np_ans = np.array([-1, 1, -1, 2, -1]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testSetSingleValue(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], 1, -1)\n np_ans = np.array([-1, 1, -1, 1, -1]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def test2d(self):\n tf_ans = sparse_ops.sparse_to_dense([[1, 3], [2, 0]], [3, 4], 1, -1)\n np_ans = np.array([[-1, -1, -1, -1],\n [-1, -1, -1, 1],\n [1, -1, -1, -1]]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testZeroDefault(self):\n x = sparse_ops.sparse_to_dense(2, [4], 7)\n self.assertAllEqual(x, [0, 0, 7, 0])\n\n def test3d(self):\n tf_ans = sparse_ops.sparse_to_dense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1,\n -1)\n np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1\n np_ans[1, 3, 0] = 1\n np_ans[2, 0, 1] = 1\n self.assertAllClose(np_ans, tf_ans)\n\n def testBadShape(self):\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"must be rank 1\"):\n sparse_ops.sparse_to_dense([1, 3], [[5], [3]], 1, -1)\n\n def testBadValue(self):\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n r\"sparse_values has incorrect shape \\[2,1\\], \"\n r\"should be \\[\\] or \\[2\\]\"):\n self.evaluate(sparse_ops.sparse_to_dense([1, 3], [5], [[5], [3]], -1))\n\n def testBadNumValues(self):\n with self.assertRaisesRegex(\n (ValueError, errors.InvalidArgumentError),\n r\"sparse_values has incorrect shape \\[3\\], should be \\[\\] or \\[2\\]\"):\n self.evaluate(sparse_ops.sparse_to_dense([1, 3], [5], [1, 2, 3], -1))\n\n def testBadDefault(self):\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"default_value should be a scalar\"):\n self.evaluate(sparse_ops.sparse_to_dense([1, 3], [5], [1, 2], [0]))\n\n @test_util.disable_xla(\"XLA does not check validity for SparseToDense\")\n def testOutOfBoundsIndicesWithWithoutValidation(self):\n # The GPU implementation doesn't print the contents of the invalid inputs,\n # since the overhead of memory copy between device to host is large.\n # Therefore, the following three tests on invalid inputs will distinguish\n # the reference error messages between GPUs and CPUs.\n error_msg = (r\"out of bounds\" if test_util.is_gpu_available() else\n r\"indices\\[1\\] = \\[10\\] is out of bounds: need 0 <= \"\n \"index < \\[5\\]\")\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n error_msg):\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [10]], [5], [1.0, 1.0], 0.0))\n # When validate_indices=False, the GPU kernel won't check out-of-bound\n # access. Therefore, we skip the following test.\n if not test_util.is_gpu_available():\n # Disable checks, the allocation should still fail.\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"out of bounds\"):\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [10]], [5], [-1.0, 1.0],\n 0.0,\n validate_indices=False))\n\n @test_util.disable_xla(\"XLA does not check validity for SparseToDense\")\n def testRepeatingIndicesWithWithoutValidation(self):\n error_msg = (r\"indices\\[1\\] is repeated\" if test_util.is_gpu_available()\n else r\"indices\\[1\\] = \\[1\\] is repeated\")\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n error_msg):\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [1]], [5], [-1.0, 1.0], 0.0))\n # Disable checks\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [1]], [5], [-1.0, 1.0],\n 0.0,\n validate_indices=False))\n\n @test_util.disable_xla(\"XLA does not check validity for SparseToDense\")\n def testUnsortedIndicesWithWithoutValidation(self):\n error_msg = (r\"indices\\[1\\] is out of order\"\n if test_util.is_gpu_available() else\n r\"indices\\[1\\] = \\[1\\] is out of order\")\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n error_msg):\n self.evaluate(\n sparse_ops.sparse_to_dense([[2], [1]], [5], [-1.0, 1.0], 0.0))\n # Disable checks\n self.evaluate(\n sparse_ops.sparse_to_dense([[2], [1]], [5], [-1.0, 1.0],\n 0.0,\n validate_indices=False))\n\n def testShapeInferenceKnownShape(self):\n with ops.Graph().as_default():\n indices = array_ops.placeholder(dtypes.int64)\n\n shape = [4, 5, 6]\n output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)\n self.assertEqual(output.get_shape(), [4, 5, 6])\n\n shape = array_ops.placeholder(dtypes.int64, shape=(3,))\n output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)\n self.assertEqual(output.get_shape().as_list(), [None, None, None])\n\n def testShapeInferenceUnknownShape(self):\n with ops.Graph().as_default():\n indices = array_ops.placeholder(dtypes.int64)\n shape = array_ops.placeholder(dtypes.int64)\n output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)\n self.assertIsNone(output.get_shape().ndims)\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "tensorflow.python.platform.tf_logging.warning", "numpy.meshgrid", "numpy.asarray", "numpy.arange", "tensorflow.python.tpu.topology.Topology", "tensorflow.python.util.tf_export.tf_export", "numpy.full", "numpy.concatenate", "numpy.prod", "numpy.array" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.init_ops_v2.Constant" ], [ "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.util.tf_export.tf_export" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.data.kernel_tests.test_base.default_test_combinations", "tensorflow.python.data.ops.options.Options", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.framework.combinations.NamedObject", "tensorflow.python.data.kernel_tests.test_base.graph_only_combinations", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.data.experimental.ops.grouping.Reducer", "tensorflow.python.platform.test.main", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.data.experimental.ops.grouping.group_by_window", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.data.ops.dataset_ops.make_initializable_iterator", "tensorflow.python.data.experimental.ops.testing.assert_next", "tensorflow.python.data.experimental.ops.batching.map_and_batch", "numpy.array", "tensorflow.python.data.experimental.ops.grouping.group_by_reducer", "tensorflow.python.framework.combinations.combine", "tensorflow.python.data.experimental.ops.scan_ops.scan", "tensorflow.python.ops.variable_scope.get_variable", "numpy.ones", "tensorflow.python.ops.random_ops.random_uniform" ], [ "tensorflow.lite.testing.zip_test_utils.make_zip_of_tests", "tensorflow.lite.testing.zip_test_utils.ExtraConvertOptions", "tensorflow.lite.testing.zip_test_utils.create_tensor_data", "tensorflow.compat.v1.compat.v1.placeholder", "tensorflow.lite.testing.zip_test_utils.register_make_test_function" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.ops.parsing_ops.decode_raw", "tensorflow.python.data.kernel_tests.test_base.default_test_combinations", "tensorflow.python.ops.functional_ops.remote_call", "tensorflow.python.data.ops.dataset_ops._GeneratorDataset", "tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.variables.Variable", "tensorflow.python.data.kernel_tests.test_base.graph_only_combinations", "tensorflow.python.data.ops.iterator_ops.OwnedIterator", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.framework.ops.device", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "tensorflow.python.ops.gradients_impl.gradients", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_types", "tensorflow.python.framework.test_util.is_gpu_available", "tensorflow.python.framework.ops.container", "numpy.arange", "tensorflow.python.framework.function.Defun", "tensorflow.python.eager.context.execution_mode", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_classes", "tensorflow.python.platform.test.main", "tensorflow.python.data.kernel_tests.test_base.eager_only_combinations", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.data.ops.dataset_ops.make_initializable_iterator", "tensorflow.python.ops.math_ops.square", "tensorflow.python.framework.sparse_tensor.SparseTensorSpec", "tensorflow.python.ops.script_ops.py_func", "numpy.int64", "tensorflow.python.training.server_lib.Server.create_local_server", "tensorflow.python.client.session.Session", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.framework.ops.convert_to_tensor", "numpy.array", "tensorflow.python.ops.data_flow_ops.FIFOQueue", "tensorflow.python.framework.combinations.combine", "tensorflow.python.data.ops.iterator_ops.Iterator.from_string_handle", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.framework.ops.Graph", "tensorflow.python.data.ops.dataset_ops.get_structure", "tensorflow.python.data.ops.dataset_ops.Dataset.from_generator", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.data.ops.dataset_ops.Dataset.zip", "tensorflow.core.protobuf.cluster_pb2.ClusterDef", "tensorflow.python.data.ops.iterator_ops.Iterator.from_structure", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.debug.cli.command_parser.parse_indices", "tensorflow.python.debug.cli.debugger_cli_common.regex_find", "tensorflow.python.debug.cli.debugger_cli_common.RichTextLines", "tensorflow.python.debug.cli.debugger_cli_common.CommandLineExit", "tensorflow.python.debug.cli.base_ui.BaseUI.__init__", "tensorflow.python.debug.cli.debugger_cli_common.CommandHistory", "tensorflow.python.debug.cli.debugger_cli_common.wrap_rich_text_lines", "tensorflow.python.debug.cli.tensor_format.locate_tensor_element", "tensorflow.python.debug.cli.curses_widgets.CursesNavigationHistory" ], [ "tensorflow.lite.tools.flatbuffer_utils.randomize_weights", "tensorflow.lite.tools.flatbuffer_utils.convert_object_to_bytearray", "tensorflow.lite.tools.test_utils.build_mock_model", "tensorflow.lite.tools.flatbuffer_utils.xxd_output_to_bytes", "tensorflow.lite.tools.flatbuffer_utils.read_model", "tensorflow.python.platform.test.main", "tensorflow.lite.tools.flatbuffer_utils.write_model", "tensorflow.lite.tools.flatbuffer_utils.strip_strings" ], [ "tensorflow.python.framework.test_util.disable_xla", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.framework.ops.Graph", "numpy.ones", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.test.main", "tensorflow.python.ops.sparse_ops.sparse_to_dense", "numpy.array", "tensorflow.python.framework.test_util.is_gpu_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.9", "2.8", "2.7", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] } ]
OverFitted/ai-academy-2022
[ "e58a68a13d81f203027cc367f5f335c2b22f0962" ]
[ "modules/feature_extraction.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nclass VGG_FeatureExtractor(nn.Module):\n def __init__(self, input_channel, output_channel=512):\n super(VGG_FeatureExtractor, self).__init__()\n self.output_channel = [int(output_channel / 8), int(output_channel / 4),\n int(output_channel / 2), output_channel] # [64, 128, 256, 512]\n self.ConvNet = nn.Sequential(\n nn.Conv2d(input_channel, self.output_channel[0], 3, 1, 1), nn.ReLU(True),\n nn.MaxPool2d(2, 2), # 64x16x50\n nn.Conv2d(self.output_channel[0], self.output_channel[1], 3, 1, 1), nn.ReLU(True),\n nn.MaxPool2d(2, 2), # 128x8x25\n nn.Conv2d(self.output_channel[1], self.output_channel[2], 3, 1, 1), nn.ReLU(True), # 256x8x25\n nn.Conv2d(self.output_channel[2], self.output_channel[2], 3, 1, 1), nn.ReLU(True),\n nn.MaxPool2d((2, 1), (2, 1)), # 256x4x25\n nn.Conv2d(self.output_channel[2], self.output_channel[3], 3, 1, 1, bias=False),\n nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True), # 512x4x25\n nn.Conv2d(self.output_channel[3], self.output_channel[3], 3, 1, 1, bias=False),\n nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True),\n nn.MaxPool2d((2, 1), (2, 1)), # 512x2x25\n nn.Conv2d(self.output_channel[3], self.output_channel[3], 2, 1, 0), nn.ReLU(True)) # 512x1x24\n\n def forward(self, input):\n return self.ConvNet(input)\n\n\nclass RCNN_FeatureExtractor(nn.Module):\n def __init__(self, input_channel, output_channel=512):\n super(RCNN_FeatureExtractor, self).__init__()\n self.output_channel = [int(output_channel / 8), int(output_channel / 4),\n int(output_channel / 2), output_channel] # [64, 128, 256, 512]\n self.ConvNet = nn.Sequential(\n nn.Conv2d(input_channel, self.output_channel[0], 3, 1, 1), nn.ReLU(True),\n nn.MaxPool2d(2, 2), # 64 x 16 x 50\n GRCL(self.output_channel[0], self.output_channel[0], num_iteration=5, kernel_size=3, pad=1),\n nn.MaxPool2d(2, 2), # 64 x 8 x 25\n GRCL(self.output_channel[0], self.output_channel[1], num_iteration=5, kernel_size=3, pad=1),\n nn.MaxPool2d(2, (2, 1), (0, 1)), # 128 x 4 x 26\n GRCL(self.output_channel[1], self.output_channel[2], num_iteration=5, kernel_size=3, pad=1),\n nn.MaxPool2d(2, (2, 1), (0, 1)), # 256 x 2 x 27\n nn.Conv2d(self.output_channel[2], self.output_channel[3], 2, 1, 0, bias=False),\n nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True)) # 512 x 1 x 26\n\n def forward(self, input):\n return self.ConvNet(input)\n\n\nclass ResNet_FeatureExtractor(nn.Module):\n def __init__(self, input_channel, output_channel=512):\n super(ResNet_FeatureExtractor, self).__init__()\n self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [1, 2, 5, 3])\n\n def forward(self, input):\n return self.ConvNet(input)\n\n\nclass GRCL(nn.Module):\n\n def __init__(self, input_channel, output_channel, num_iteration, kernel_size, pad):\n super(GRCL, self).__init__()\n self.wgf_u = nn.Conv2d(input_channel, output_channel, 1, 1, 0, bias=False)\n self.wgr_x = nn.Conv2d(output_channel, output_channel, 1, 1, 0, bias=False)\n self.wf_u = nn.Conv2d(input_channel, output_channel, kernel_size, 1, pad, bias=False)\n self.wr_x = nn.Conv2d(output_channel, output_channel, kernel_size, 1, pad, bias=False)\n\n self.BN_x_init = nn.BatchNorm2d(output_channel)\n\n self.num_iteration = num_iteration\n self.GRCL = [GRCL_unit(output_channel) for _ in range(num_iteration)]\n self.GRCL = nn.Sequential(*self.GRCL)\n\n def forward(self, input):\n \"\"\" The input of GRCL is consistant over time t, which is denoted by u(0)\n thus wgf_u / wf_u is also consistant over time t.\n \"\"\"\n wgf_u = self.wgf_u(input)\n wf_u = self.wf_u(input)\n x = F.relu(self.BN_x_init(wf_u))\n\n for i in range(self.num_iteration):\n x = self.GRCL[i](wgf_u, self.wgr_x(x), wf_u, self.wr_x(x))\n\n return x\n\n\nclass GRCL_unit(nn.Module):\n\n def __init__(self, output_channel):\n super(GRCL_unit, self).__init__()\n self.BN_gfu = nn.BatchNorm2d(output_channel)\n self.BN_grx = nn.BatchNorm2d(output_channel)\n self.BN_fu = nn.BatchNorm2d(output_channel)\n self.BN_rx = nn.BatchNorm2d(output_channel)\n self.BN_Gx = nn.BatchNorm2d(output_channel)\n\n def forward(self, wgf_u, wgr_x, wf_u, wr_x):\n G_first_term = self.BN_gfu(wgf_u)\n G_second_term = self.BN_grx(wgr_x)\n G = F.sigmoid(G_first_term + G_second_term)\n\n x_first_term = self.BN_fu(wf_u)\n x_second_term = self.BN_Gx(self.BN_rx(wr_x) * G)\n x = F.relu(x_first_term + x_second_term)\n\n return x\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = self._conv3x3(inplanes, planes)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = self._conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def _conv3x3(self, in_planes, out_planes, stride=1):\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, input_channel, output_channel, block, layers):\n super(ResNet, self).__init__()\n\n self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]\n\n self.inplanes = int(output_channel / 8)\n self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 16),\n kernel_size=3, stride=1, padding=1, bias=False)\n self.bn0_1 = nn.BatchNorm2d(int(output_channel / 16))\n self.conv0_2 = nn.Conv2d(int(output_channel / 16), self.inplanes,\n kernel_size=3, stride=1, padding=1, bias=False)\n self.bn0_2 = nn.BatchNorm2d(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n\n self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.layer1 = self._make_layer(block, self.output_channel_block[0], layers[0])\n self.conv1 = nn.Conv2d(self.output_channel_block[0], self.output_channel_block[\n 0], kernel_size=3, stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(self.output_channel_block[0])\n\n self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.layer2 = self._make_layer(block, self.output_channel_block[1], layers[1], stride=1)\n self.conv2 = nn.Conv2d(self.output_channel_block[1], self.output_channel_block[\n 1], kernel_size=3, stride=1, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(self.output_channel_block[1])\n\n self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=(2, 1), padding=(0, 1))\n self.layer3 = self._make_layer(block, self.output_channel_block[2], layers[2], stride=1)\n self.conv3 = nn.Conv2d(self.output_channel_block[2], self.output_channel_block[\n 2], kernel_size=3, stride=1, padding=1, bias=False)\n self.bn3 = nn.BatchNorm2d(self.output_channel_block[2])\n\n self.layer4 = self._make_layer(block, self.output_channel_block[3], layers[3], stride=1)\n self.conv4_1 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[\n 3], kernel_size=2, stride=(2, 1), padding=(0, 1), bias=False)\n self.bn4_1 = nn.BatchNorm2d(self.output_channel_block[3])\n self.conv4_2 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[\n 3], kernel_size=2, stride=1, padding=0, bias=False)\n self.bn4_2 = nn.BatchNorm2d(self.output_channel_block[3])\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv0_1(x)\n x = self.bn0_1(x)\n x = self.relu(x)\n x = self.conv0_2(x)\n x = self.bn0_2(x)\n x = self.relu(x)\n\n x = self.maxpool1(x)\n x = self.layer1(x)\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.maxpool2(x)\n x = self.layer2(x)\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n\n x = self.maxpool3(x)\n x = self.layer3(x)\n x = self.conv3(x)\n x = self.bn3(x)\n x = self.relu(x)\n\n x = self.layer4(x)\n x = self.conv4_1(x)\n x = self.bn4_1(x)\n x = self.relu(x)\n x = self.conv4_2(x)\n x = self.bn4_2(x)\n x = self.relu(x)\n\n return x\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Conv2d", "torch.nn.functional.sigmoid", "torch.nn.MaxPool2d", "torch.nn.functional.relu", "torch.cuda.is_available", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
StatMixedML/GPBoost
[ "786d8be61c5c28da0690e167af636a6d777bf9e1" ]
[ "examples/python-guide/Gaussian_process_mixed_effects_models_example.py" ]
[ "# coding: utf-8\n# pylint: disable = invalid-name, C0111\nimport gpboost as gpb\nimport numpy as np\n# import pandas as pd\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\n\n# --------------------Grouped random effects model: single-level random effect----------------\n# Simulate data\nn = 100 # number of samples\nm = 25 # number of categories / levels for grouping variable\ngroup = np.arange(n) # grouping variable\nfor i in range(m):\n group[int(i * n / m):int((i + 1) * n / m)] = i\n# incidence matrix relating grouped random effects to samples\nZ1 = np.zeros((n, m))\nfor i in range(m):\n Z1[np.where(group == i), i] = 1\nsigma2_1 = 1 ** 2 # random effect variance\nsigma2 = 0.5 ** 2 # error variance\nnp.random.seed(1)\nb1 = np.sqrt(sigma2_1) * np.random.normal(size=m) # simulate random effects\neps = Z1.dot(b1)\nxi = np.sqrt(sigma2) * np.random.normal(size=n) # simulate error term\ny = eps + xi # observed data\n\n# Define and fit model\ngp_model = gpb.GPModel(group_data=group)\ngp_model.fit(y=y, std_dev=True)\ngp_model.summary()\n\n# Make predictions\ngroup_test = np.arange(m)\npred = gp_model.predict(group_data_pred=group_test)\n# Compare true and predicted random effects\nplt.scatter(b1, pred['mu'])\nplt.title(\"Comparison of true and predicted random effects\")\nplt.xlabel(\"truth\")\nplt.ylabel(\"predicted\")\nplt.show()\n\n# Other optimization specifications (gradient descent with Nesterov acceleration)\ngp_model = gpb.GPModel(group_data=group)\ngp_model.fit(y=y, std_dev=True, params={\"optimizer_cov\": \"gradient_descent\", \"lr_cov\": 0.1,\n \"use_nesterov_acc\": True})\ngp_model.summary()\n\n# --------------------Two crossed random effects and a random slope----------------\n# NOTE: run the above example first to create the first random effect\n# Simulate data\nnp.random.seed(1)\nx = np.random.uniform(size=n) # covariate data for random slope\nn_obs_gr = int(n / m) # number of sampels per group\ngroup2 = np.arange(n) # grouping variable for second random effect\nfor i in range(m):\n group2[(n_obs_gr * i):(n_obs_gr * (i + 1))] = np.arange(n_obs_gr)\n# incidence matrix relating grouped random effects to samples\nZ2 = np.zeros((n, n_obs_gr))\nfor i in range(n_obs_gr):\n Z2[np.where(group2 == i), i] = 1\nZ3 = np.diag(x).dot(Z1)\nsigma2_2 = 0.5 ** 2 # variance of second random effect\nsigma2_3 = 0.75 ** 2 # variance of random slope for first random effect\nb2 = np.sqrt(sigma2_2) * np.random.normal(size=n_obs_gr) # simulate random effects\nb3 = np.sqrt(sigma2_3) * np.random.normal(size=m)\neps2 = Z1.dot(b1) + Z2.dot(b2) + Z3.dot(b3)\ny = eps2 + xi # observed data\n# Define and fit model\ngroup_data = np.column_stack((group, group2))\ngp_model = gpb.GPModel(group_data=group_data, group_rand_coef_data=x, ind_effect_group_rand_coef=[1])\ngp_model.fit(y=y, std_dev=True)\ngp_model.summary()\n\n# --------------------Mixed effects model: random effects and linear fixed effects----------------\n# NOTE: run the above example first to create the random effects part\n# Simulate data\nnp.random.seed(1)\nX = np.column_stack(\n (np.random.uniform(size=n), np.random.uniform(size=n))) # desing matrix / covariate data for fixed effect\nbeta = np.array([3, 3]) # regression coefficents\ny = eps2 + xi + X.dot(beta) # add fixed effect to observed data\n# Define and fit model\ngp_model = gpb.GPModel(group_data=group_data, group_rand_coef_data=x, ind_effect_group_rand_coef=[1])\ngp_model.fit(y=y, X=X, std_dev=True)\ngp_model.summary()\n\n# --------------------Gaussian process model----------------\n# Simulate data\nn = 200 # number of samples\nnp.random.seed(2)\ncoords = np.column_stack(\n (np.random.uniform(size=n), np.random.uniform(size=n))) # locations (=features) for Gaussian process\nsigma2_1 = 1 ** 2 # marginal variance of GP\nrho = 0.1 # range parameter\nsigma2 = 0.5 ** 2 # error variance\nD = np.zeros((n, n)) # distance matrix\nfor i in range(0, n):\n for j in range(i + 1, n):\n D[i, j] = np.linalg.norm(coords[i, :] - coords[j, :])\n D[j, i] = D[i, j]\nSigma = sigma2_1 * np.exp(-D / rho) + np.diag(np.zeros(n) + 1e-20)\nC = np.linalg.cholesky(Sigma)\nb1 = np.random.normal(size=n) # simulate random effects\neps = C.dot(b1)\nxi = np.sqrt(sigma2) * np.random.normal(size=n) # simulate error term\ny = eps + xi\n\n# Define and fit model\ngp_model = gpb.GPModel(gp_coords=coords, cov_function=\"exponential\")\n## Other covariance functions:\n# gp_model = gpb.GPModel(gp_coords=coords, cov_function=\"gaussian\")\n# gp_model = gpb.GPModel(gp_coords=coords, cov_function=\"matern\", cov_fct_shape=1.5)\n# gp_model = gpb.GPModel(gp_coords=coords, cov_function=\"powered_exponential\", cov_fct_shape=1.1)\ngp_model.fit(y=y, std_dev=True, params={\"optimizer_cov\": \"gradient_descent\",\n \"lr_cov\": 0.1})\ngp_model.summary()\n\n# Make predictions\nnp.random.seed(1)\nntest = 5\n# prediction locations (=features) for Gaussian process\ncoords_test = np.column_stack(\n (np.random.uniform(size=ntest), np.random.uniform(size=ntest))) / 10.\npred = gp_model.predict(gp_coords_pred=coords_test, predict_cov_mat=True)\nprint(\"Predicted (posterior/conditional) mean of GP\")\npred['mu']\nprint(\"Predicted (posterior/conditional) covariance matrix of GP\")\npred['cov']\n\n# --------------------Gaussian process model with Vecchia approximation----------------\ngp_model = gpb.GPModel(gp_coords=coords, cov_function=\"exponential\",\n vecchia_approx=True, num_neighbors=30)\ngp_model.fit(y=y, params={\"optimizer_cov\": \"gradient_descent\",\n \"lr_cov\": 0.1})\ngp_model.summary()\n\n# --------------------Gaussian process model with random coefficents----------------\n# Simulate data\nn = 500 # number of samples\nnp.random.seed(1)\ncoords = np.column_stack(\n (np.random.uniform(size=n), np.random.uniform(size=n))) # locations (=features) for Gaussian process\nsigma2_1 = 1 ** 2 # marginal variance of GP (for simplicity, all GPs have the same parameters)\nrho = 0.1 # range parameter\nsigma2 = 0.5 ** 2 # error variance\nD = np.zeros((n, n)) # distance matrix\nfor i in range(0, n):\n for j in range(i + 1, n):\n D[i, j] = np.linalg.norm(coords[i, :] - coords[j, :])\n D[j, i] = D[i, j]\nSigma = sigma2_1 * np.exp(-D / rho) + np.diag(np.zeros(n) + 1e-20)\nC = np.linalg.cholesky(Sigma)\nX_SVC = np.column_stack(\n (np.random.uniform(size=n), np.random.uniform(size=n))) # covariate data for random coeffients\nb1 = np.random.normal(size=n) # simulate random effect\nb2 = np.random.normal(size=n)\nb3 = np.random.normal(size=n)\neps = C.dot(b1) + X_SVC[:, 0] * C.dot(b2) + X_SVC[:, 1] * C.dot(b3)\nxi = np.sqrt(sigma2) * np.random.normal(size=n) # simulate error term\ny = eps + xi\n# Define and fit model (takes a few seconds)\ngp_model = gpb.GPModel(gp_coords=coords, cov_function=\"exponential\", gp_rand_coef_data=X_SVC)\ngp_model.fit(y=y, std_dev=True, params={\"optimizer_cov\": \"gradient_descent\",\n \"lr_cov\": 0.05,\n \"use_nesterov_acc\": True,\n \"acc_rate_cov\": 0.5})\ngp_model.summary()\n\n# --------------------Combine Gaussian process with grouped random effects----------------\nn = 200 # number of samples\nm = 25 # number of categories / levels for grouping variable\ngroup = np.arange(n) # grouping variable\nfor i in range(m):\n group[int(i * n / m):int((i + 1) * n / m)] = i\n# incidence matrix relating grouped random effects to samples\nZ1 = np.zeros((n, m))\nfor i in range(m):\n Z1[np.where(group == i), i] = 1\nnp.random.seed(1)\ncoords = np.column_stack(\n (np.random.uniform(size=n), np.random.uniform(size=n))) # locations (=features) for Gaussian process\nsigma2_1 = 1 ** 2 # random effect variance\nsigma2_2 = 1 ** 2 # marginal variance of GP\nrho = 0.1 # range parameter\nsigma2 = 0.5 ** 2 # error variance\nD = np.zeros((n, n)) # distance matrix\nfor i in range(0, n):\n for j in range(i + 1, n):\n D[i, j] = np.linalg.norm(coords[i, :] - coords[j, :])\n D[j, i] = D[i, j]\nSigma = sigma2_2 * np.exp(-D / rho) + np.diag(np.zeros(n) + 1e-20)\nC = np.linalg.cholesky(Sigma)\nb1 = np.random.normal(size=m) # simulate random effect\nb2 = np.random.normal(size=n)\neps = Z1.dot(b1) + C.dot(b2)\nxi = np.sqrt(sigma2) * np.random.normal(size=n) # simulate error term\ny = eps + xi\n\n# Create Gaussian process model\ngp_model = gpb.GPModel(group_data=group, gp_coords=coords, cov_function=\"exponential\")\ngp_model.fit(y=y, std_dev=True, params={\"optimizer_cov\": \"gradient_descent\",\n \"lr_cov\": 0.05,\n \"use_nesterov_acc\": True,\n \"acc_rate_cov\": 0.5})\ngp_model.summary()\n" ]
[ [ "numpy.diag", "numpy.sqrt", "numpy.exp", "numpy.where", "numpy.arange", "numpy.column_stack", "numpy.zeros", "matplotlib.pyplot.style.use", "matplotlib.pyplot.title", "matplotlib.pyplot.xlabel", "numpy.linalg.cholesky", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.scatter", "numpy.random.seed", "numpy.linalg.norm", "numpy.random.normal", "numpy.random.uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TangJiahui/cs107_system_devlopment
[ "c46d7769683d9be0c31973e3b0666e3fe2a4099b" ]
[ "homework/HW4/HW4-final/P1.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Part A: Numerical Differentiation Closure\ndef numerical_diff(f,h):\n def inner(x):\n return (f(x+h) - f(x))/h\n return inner\n\n# Part B:\nf = np.log\nx = np.linspace(0.2, 0.4, 500)\nh = [1e-1, 1e-7, 1e-15]\ny_analytical = 1/x\nresult = {}\n\n\nfor i in h:\n y = numerical_diff(f,i)(x)\n result[i] = y\n\n# Plotting\nplt.figure(figsize = (8,5))\nplt.plot(x, y_analytical, 'x-', label='Analytical Derivative')\nfor i in h:\n plt.plot(x, result[i], label='Estimated derivative h = '+str(i))\nplt.xlabel(\"X value\")\nplt.ylabel(\"Derivative Value at X\")\nplt.title(\"Differentiation Value at X on various h value\")\nplt.legend()\n\n\n# Part C:\nprint(\"Answer to Q-a: When h value is 1e-7, it most closely approximates the true derivative. \\n\",\n \"When h value is too small: The approximation is jumping around stepwise and not displaying a smooth curve approximation, it amplifies floating point errors in numerical operation such as rounding and division\\n\",\n \"When h value is too large: The approximation is lower than the true value, it doesn't provide a good approximation to the derivative\\n\")\nprint(\"Answer to Q-b: Automatic differentiation avoids the problem of not choosing a good h value. \\n\"\n \"The finite difference approach is quick and easy but suffers from accuracy and stability problems.\\n\"\n \"Symbolic derivatives can be evaluated to machine precision, but can be costly to evaluate.\\n\"\n \"Automatic differentiation (AD) overcomes both of these deficiencies. It is less costly than symbolic differentiation while evaluating derivatives to machine precision.\\n\"\n \"AD uses forward or backward modes to differentiate, via Computational Graph, chain rule and evaluation trace.\")\n\n# Show plot\nplt.show()\n# plt.savefig('P1_fig.png')\n\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linspace", "matplotlib.pyplot.title", "matplotlib.pyplot.figure", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
UnacceptableBehaviour/pytorch_tut_00
[ "ca74b9bde8485f651bda9314b8f4a7ed277db787" ]
[ "scripts/07_tensor_linear_regresssion.py" ]
[ "#! /usr/bin/env python\n\n# PyTorch Tutorial 07 - Linear Regression\n# https://www.youtube.com/watch?v=YAJ5XBwlN4o&list=PLqnslRFeH2UrcDBWF5mfPGpqQDSta6VK4&index=7\n\n#from __future__ import print_function\nimport torch\nprint(\"\\n\" * 20)\nprint(\"-\" * 80)\nprint(\"-\" * 80)\nprint(\"\\n\" * 2)\n\n#### Steps in Torch ML pipeline\n# 1) Design Model (input, output size, forward pass)\n# 2) Construct the loss & optimiser\n# 3) Training Loop\n# - forward pass: compute prediction\n# - backward pass: gradients\n# - update weights\n\n# 0m - review Steps in Torch ML pipeline\n# 1m - library imports\n# 2m - coding starts - prepare data\n# 4m30 - 1) Design Model (input, output size, forward pass)\n# 5m40 - 2) Construct the loss & optimiser\n# 7m - 3) Training Loop\n# 10m - plot\n\nimport torch\n\nimport torch.nn as nn # PyTorch nn module has high-level APIs to build a neural network.\n # Torch. nn module uses Tensors and Automatic differentiation modules for training and building layers such as input,\n # hidden, and output layers - DOCS: https://pytorch.org/docs/stable/nn.html\n\nimport numpy as np # NumPy is a library for the Python programming language, adding support for large,\n # multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate\n # on these arrays - DOCS: https://numpy.org/doc/stable/user/whatisnumpy.html\n\nfrom sklearn import datasets # to generate a regression dataset\n # Scikit-learn is a library in Python that provides many unsupervised and supervised\n # learning algorithms. It contains a lot of efficient tools for machine learning and statistical modeling including\n # classification, regression, clustering and dimensionality reduction. Built upon some of the technology you might\n # already be familiar with, like NumPy, pandas, and Matplotlib!\n # DOCS: https://scikit-learn.org/stable/\n\nimport matplotlib.pyplot as plt # Matplotlib is a plotting library for the Python programming language. It provides an\n # object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter,\n # wxPython, Qt, or GTK - DOCS:\n # cheatsheets: https://github.com/matplotlib/cheatsheets#cheatsheets\n # How to plot & save graph hello world: https://github.com/UnacceptableBehaviour/latex_maths#python---matplotlib-numpy\n\n\n# 0) prepare data - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nx_numpy, y_numpy = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=1)\n# returned from ^\n# change data type from double to float32 - avoid erros later\nX = torch.from_numpy(x_numpy.astype(np.float32)) # create torch tensor from numpy array\nY = torch.from_numpy(y_numpy.astype(np.float32))\nprint(f\"\\n Y = torch.from_numpy(y_numpy.astype(np.float32)) \\n{ Y }\")\n# Y = torch.from_numpy(y_numpy.astype(np.float32)) # tensor w a single row - see square brackets\n# tensor([-5.5539e+01, -1.0662e+01, 2.2757e+01, 1.0110e+02, 1.4434e+02,\n# 3.3289e+01, 3.3015e+01, -2.5887e+01, -9.9639e+01, 2.3803e+01,\n# -4.5589e+01, -8.3388e+00, -9.5315e+01, 3.6407e+01, -8.7293e+01,\n# 6.7669e+01, -1.3687e+01, -5.5441e+01, -6.5340e+01, -5.4450e+01,\n# -2.8835e+01, 1.7884e+02, 6.5084e+01, 2.6668e+01, -1.8546e+01,\n# -4.1499e+01, 8.5583e-01, 4.4562e+01, 1.1598e+02, -6.4620e+01,\n# -2.5931e+01, -6.0882e+01, 1.8720e+01, 7.5070e+01, 1.1720e+02,\n# -2.2698e+01, -5.6363e+01, 1.8084e+02, -1.9257e+02, 6.8503e+01,\n# 1.6552e+02, 1.0500e+02, -7.0434e+01, -5.8769e+01, -4.1576e+01,\n# 7.3247e+01, 4.0966e+01, 8.0462e+01, -2.8794e+01, 3.4234e+01,\n# -4.1715e+01, 1.4355e+01, 7.9336e+01, 2.7129e+01, -3.9487e+01,\n# 6.6805e+01, 9.5531e+01, 3.5610e+00, 1.0857e-01, 5.6495e+01,\n# 5.1575e+01, -2.0974e+00, -2.6656e+01, 3.9742e+01, 3.6101e+01,\n# -7.5602e+01, 1.9713e+01, -7.1601e+01, -1.9904e+01, -7.6708e+01,\n# -1.1834e+02, -2.9825e+01, 1.5108e+02, 5.2923e+01, -5.9552e+01,\n# 3.0721e+01, -2.9355e+01, -4.4786e+01, 1.0006e+02, 1.5058e+02,\n# 1.2200e+02, -1.8186e+02, 3.4739e+00, -2.2980e+01, 4.5184e+01,\n# 9.8606e+01, -9.2779e+00, -5.2478e+01, 3.8593e+01, -1.9997e+02,\n# -9.5201e+00, -3.4724e+00, -3.5312e+01, 7.5406e+01, 1.7570e+01,\n# -2.3960e+01, 1.3209e+02, 2.0608e+01, 5.1111e+01, -2.6306e+01])\n\nprint(f\"\\n Y.shape[0] \\n{ Y.shape[0] }\") # 100\ny = Y.view(Y.shape[0], 1) # reshape to a column tensor Y.view(ROW, COL) Y.view(100, 1)\nprint(f\"\\n y = Y.view(y.shape[0], 1) \\n{ y }\")\n\n# tensor([[-5.5539e+01],\n# [-1.0662e+01],\n# [ 2.2757e+01],\n# [ 1.0110e+02],\n# .\n# 100 in total\n# .\n# [ 1.3209e+02],\n# [ 2.0608e+01],\n# [ 5.1111e+01],\n# [-2.6306e+01]])\n\nprint(f\"\\n y.shape \\n{ y.shape }\") # new little y shape = torch.Size([100, 1]) ROWS, COLS\nprint(f\"\\n X.shape \\n{ X.shape }\")\nn_samples, n_features = X.shape\n\n\n\n\n#print(f\"\\n \\n{ }\")\n\n# 1) model - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# in LINEAR REGRESSION case this is ONE layer\ninput_size = n_features\noutput_size = 1\nmodel = nn.Linear(input_size, output_size) # built in Linear model\n\n# 2) loss optimizer - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nlearning_rate = 0.01\n\ncriterion = nn.MSELoss() # for LINEAR REGRESSION - BUILT IN Loss function Mean Squared Error Loss\n # nn.MSELoss() creates a criterion - https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html\n\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) # SGD - Stocastic Gradient Descent\n # https://pytorch.org/docs/stable/optim.html?highlight=torch%20optim%20sgd#torch.optim.SGD\n # w/ optional Nesterov momentum :o\n\n# 3) training loop - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nnum_epochs = 100\n\nfor epoch in range(num_epochs):\n # - forward pass: compute prediction\n y_predicted = model(X) # call model passing in data X\n loss = criterion(y_predicted, y) # actual labels & predicted - output = criterion(input, target)\n\n # - backward pass: gradients\n loss.backward()\n\n # - update weights\n optimizer.step()\n optimizer.zero_grad()\n\n if (epoch+1) % 10 == 0:\n print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')\n\n# plot\npredicted = model(X).detach().numpy() # prevent gradient tracking?\nlabel_data = plt.plot(x_numpy, y_numpy, 'ro')\nlabel_model = plt.plot(x_numpy, predicted, 'b')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.legend(['data','model'])\nplt.show()\nprint('plt.show')\nprint(f\"\\n x_numpy \\n{ x_numpy }\")\nprint(f\"\\n y_numpy \\n{ y_numpy }\")\nprint(f\"\\n predicted \\n{ predicted }\")\n\n\n\n#print(f\"\\n \\n{ }\")\n\n#print(f\"\\n \\n{ }\")\nprint('\\n')\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "torch.nn.Linear", "sklearn.datasets.make_regression", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "torch.nn.MSELoss", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sergioalberto/rpi-deep-learning
[ "94024c2b2c225dc607954874bdcd345b805b1561" ]
[ "examples/image_classification/classify.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# from tflite_runtime.interpreter import Interpreter\nfrom tensorflow.lite.python.interpreter import Interpreter \nimport numpy as np\nimport argparse\nfrom PIL import Image\n\nparser = argparse.ArgumentParser(description='Image Classification')\nparser.add_argument('--filename', type=str, help='Specify the filename', required=True)\nparser.add_argument('--model_path', type=str, help='Specify the model path', required=True)\nparser.add_argument('--label_path', type=str, help='Specify the label map', required=True)\nparser.add_argument('--top_k', type=int, help='How many top results', default=3)\n\nargs = parser.parse_args()\n\nfilename = args.filename\nmodel_path = args.model_path \nlabel_path = args.label_path \ntop_k_results = args.top_k\n\nwith open(label_path, 'r') as f:\n labels = list(map(str.strip, f.readlines()))\n\n# Load TFLite model and allocate tensors\ninterpreter = Interpreter(model_path=model_path)\ninterpreter.allocate_tensors()\n\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\n# Read image\nimg = Image.open(filename).convert('RGB')\n\n# Get input size\ninput_shape = input_details[0]['shape']\nsize = input_shape[:2] if len(input_shape) == 3 else input_shape[1:3]\n\n# Preprocess image\nimg = img.resize(size)\nimg = np.array(img)\n\n# Add a batch dimension\ninput_data = np.expand_dims(img, axis=0)\n\n# Point the data to be used for testing and run the interpreter\ninterpreter.set_tensor(input_details[0]['index'], input_data)\ninterpreter.invoke()\n\n# Obtain results and map them to the classes\npredictions = interpreter.get_tensor(output_details[0]['index'])[0]\n\n# Get indices of the top k results\ntop_k_indices = np.argsort(predictions)[::-1][:top_k_results]\n\nfor i in range(top_k_results):\n print(labels[top_k_indices[i]], predictions[top_k_indices[i]] / 255.0)\n" ]
[ [ "numpy.argsort", "numpy.array", "numpy.expand_dims", "tensorflow.lite.python.interpreter.Interpreter" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] } ]
mrhuytran/bnb-api-wrapper
[ "569e6eddc9c44f50a918b046cdb248bee60ac0e1" ]
[ "binance.py" ]
[ "import requests\nimport json\nfrom datetime import datetime\nimport time\nimport pandas as pd\nfrom pandas import DataFrame as df\nimport hmac\nimport hashlib\nfrom interval_enum import Interval\nfrom order_enum import Order\n\nclass BinanceClient:\n\n def __init__(self, api_key, api_secret):\n self.key = api_key\n self.secret = api_secret\n self.base = 'https://api.binance.com'\n self.endpoint = {\n 'klines': '/api/v1/klines',\n 'price_ticker': '/api/v3/ticker/price',\n '24hr_ticker': '/api/v3/ticker/24hr',\n 'historical_trade': '/api/v3/historicalTrades', # recent trades on the market\n 'order': '/api/v3/order',\n 'test_order': '/api/v3/order/test',\n 'open_order': '/api/v3/openOrders', # all open orders\n 'all_order': '/api/v3/allOrders', # all orders: active, cancelled, filler\n 'my_trade': '/api/v3/myTrades' # all trades for a specific symbol on the account\n }\n\n\n '''\n ***********************************************************\n GET METHODS\n ***********************************************************\n '''\n\n\n '''\n return klines for a specified symbol\n @param\n required - symbol: str, interval: Interval\n '''\n def get_klines(self, symbol, interval):\n\n # specifying parameters for request body\n params = {\n 'symbol': symbol,\n 'interval': interval.value\n }\n # specifying url enpoint\n url = self.base + self.endpoint['klines']\n\n # get api response\n response = requests.get(url, params=params)\n # convert json to dict\n data = json.loads(response.text)\n\n # convert dict to data frame\n klines_df = df(data)\n\n # get open time and close time from klines_df\n o_timestamp_df = klines_df[0] # open timestamp\n c_timestamp_df = klines_df[6] # close timestamp\n\n # create empty arrays for formatted datetime\n o_time = [] # open time\n c_time = [] # close time\n \n # convert timestamps to datetime format\n for (o_timestamp, c_timestamp) in zip(o_timestamp_df, c_timestamp_df):\n o_time.append(datetime.fromtimestamp(int(o_timestamp/1000)))\n c_time.append(datetime.fromtimestamp(int(c_timestamp/1000)))\n\n # convert datetime to string datetime format for df\n o_timestamp_df = df(o_time)\n c_timestamp_df = df(c_time)\n\n # replacing the original timestamp with formatted datetime string\n klines_df[0] = o_timestamp_df\n klines_df[6] = c_timestamp_df\n\n # modifying dataframe\n klines_df.pop(11)\n klines_df.columns = ['openTime', 'open', 'high', 'low', 'close',\n 'volume', 'closeTime', 'quoteAssetVol',\n 'no. of trades', 'taker_buy_baseAssetVol',\n 'taker_buy_quoteAssetVol']\n return klines_df\n\n\n '''\n return current price\n 1. for a symbol if symbol is specified\n 2. for all symbols\n @param\n optional - symbol: str\n '''\n def get_price(self, symbol=None):\n \n # specifying parameters for request body\n params = {\n 'symbol': symbol\n }\n\n # specifying url endpoint\n url = self.base + self.endpoint['price_ticker']\n \n # get api response\n response = requests.get(url, params=params)\n # convert json to dict\n data = json.loads(response.text)\n\n # convert dict to dataframe\n if isinstance(data, list):\n price_df = df(data)\n else:\n price_df = df([data])\n\n return price_df\n\n\n '''\n return 24 hour ticker\n 1. for a symbol if symbol is specified\n 2. for all symbols\n @param\n optional - symbol: str\n ''' \n def get_24hr_ticker(self, symbol=None):\n\n # specify parameters for request body\n params = {\n 'symbol': symbol\n }\n # specifying url endpoint\n url = self.base + self.endpoint['24hr_ticker']\n\n # request api response\n response = requests.get(url, params=params)\n # convert json to dict\n data = json.loads(response.text)\n \n # convert dict to dataframe\n if isinstance(data, list):\n ticker_df = df(data)\n else:\n ticker_df = df([data])\n\n # get openTime and closeTime from ticker_df\n open_time_df = ticker_df['openTime']\n close_time_df = ticker_df['closeTime']\n\n # create new empty arrays for openTime and closeTime\n open_time = []\n close_time = []\n\n # convert timestamps to datetime format\n for (o, c) in zip(open_time_df, close_time_df):\n open_time.append(datetime.fromtimestamp(int(o/1000)))\n close_time.append(datetime.fromtimestamp(int(c/1000)))\n\n # convert timestamps to string format\n open_time_df = df(open_time)\n close_time_df = df(close_time)\n\n # replace timestamps in ticker_df with formatted timestamps\n ticker_df['openTime'] = open_time_df\n ticker_df['closeTime'] = close_time_df\n\n return ticker_df\n\n\n '''\n return list of historical trades\n 1. start from a specific trade if tradeId is specified upto\n the specified amount of trade records\n 2. most recent trades if tradeId is not specified\n a. most recent 500 trades if limit is not specified\n b. the amount of trades specified by limit\n @param\n required - symbol: str\n optional - limit: int, tradeId: long\n '''\n def get_historical_trade(self, symbol, limit=None, tradeId=None):\n\n # specifying parameter for request body\n params = {\n 'symbol': symbol,\n 'limit': limit,\n 'fromId': tradeId\n }\n # specifying url endpoint\n url = self.base + self.endpoint['historical_trade']\n\n # request api response\n response = requests.get(url, params=params, headers={'X-MBX-APIKEY': self.key})\n data = json.loads(response.text)\n\n # when exception occurs\n if not isinstance(data, list):\n return data\n\n # convert dict to dataframe\n trade_df = df(data)\n\n if not trade_df.empty:\n # get time from trade_df\n time_df = trade_df['time']\n \n # make new empty array for time\n _time = []\n\n # convert timestamp to datetime format\n for t in time_df:\n _time.append(datetime.fromtimestamp(int(t/1000)))\n \n # convert timestamp to string format\n time_df = df(_time)\n\n # replace timestamp in trade_df with formatted timestamp\n trade_df['time'] = time_df \n\n return trade_df\n\n\n '''\n get the status of an order\n @param \n required - symbol: str, orderId: long\n '''\n def get_query_order(self, symbol, orderId):\n \n # specify parameters for request body\n params = {\n 'symbol': symbol,\n 'orderId': orderId,\n 'timestamp': int(round(time.time()*1000))\n }\n # specify url endpoint\n url = self.base + self.endpoint['order']\n \n # sign request\n self.sign_request(params)\n\n # request api response\n response = requests.get(url, params=params, headers={'X-MBX-APIKEY': self.key})\n data = json.loads(response.text)\n\n return data\n\n\n '''\n return list of open orders\n 1. of a symbol if symbol is specified\n 2. of all symbols if symbol is not specified\n @param \n optional - symbol: str\n '''\n def get_open_order(self, symbol=None):\n\n # specify general paramenters for request body\n params = {\n 'timestamp': int(round(time.time()*1000))\n\n }\n # specify optional parameters for request body\n if symbol != None:\n params['symbol'] = symbol\n # specify url endpoint\n url = self.base + self.endpoint['open_order']\n\n # sign request\n self.sign_request(params)\n\n # request api response\n response = requests.get(url, params=params, headers={'X-MBX-APIKEY': self.key})\n # convert json to dict\n data = json.loads(response.text)\n \n # when exception occurs\n if not isinstance(data, list):\n return data\n\n # convert dict to dataframe\n open_order_df = df(data)\n\n # if dataframe is not empty\n if not open_order_df.empty:\n # get time and updateTime form open_order_df\n time_df = open_order_df['time'] # time\n updateTime_df = open_order_df['updateTime'] # updateTime\n\n # create new empty arrays for time and updateTime\n _time = []\n _updateTime = []\n\n # convert time and updateTime to datetime format\n for (t, u) in zip(time_df, updateTime_df):\n _time.append(datetime.fromtimestamp(int(t/1000)))\n _updateTime.append(datetime.fromtimestamp(int(u/1000)))\n\n # convert time and updateTime to df\n time_df = df(_time)\n updateTime_df = df(_updateTime)\n\n # replace original timestamps with formatted timestamps in open_order_df\n open_order_df['time'] = time_df\n open_order_df['updateTime'] = updateTime_df\n\n return open_order_df\n\n\n '''\n return all orders of the specified symbol: active, canceled, filled\n 1. if orderId is specified, return orders with id >= orderId\n 2. else, return most recent orders for this symbol \n @param \n required - symbol: str\n optional - orderId: long, limit: int\n '''\n def get_all_order(self, symbol, orderId=None, limit=None):\n\n # specify the general parameters for request body\n params = {\n 'symbol': symbol,\n 'timestamp': int(round(time.time()*1000))\n\n }\n # specify optional parameters for request body\n if limit != None:\n if orderId != None:\n params['orderId'] = orderId\n params['limit'] = limit\n else:\n params['limit'] = limit \n else:\n if orderId != None:\n params['orderId'] = orderId\n # specify url endpoint\n url = self.base + self.endpoint['all_order']\n\n # sign request\n self.sign_request(params)\n\n # request api response\n response = requests.get(url, params=params, headers={'X-MBX-APIKEY': self.key})\n # convert json to dict\n data = json.loads(response.text)\n\n # when exception occurs \n if not isinstance(data, list):\n return data\n\n # convert data to dataframe\n all_order_df = df(data)\n\n # time and updateTime from all_order_df\n time_df = all_order_df['time'] # time\n updateTime_df = all_order_df['updateTime'] # updateTime\n\n # create new empty arrays for time and updateTime\n _time = []\n _updateTime = []\n\n # convert time and updateTime to datetime format\n for (t, u) in zip(time_df, updateTime_df):\n _time.append(datetime.fromtimestamp(int(t/1000)))\n _updateTime.append(datetime.fromtimestamp(int(u/1000)))\n\n # convert time and updateTime to df\n time_df = df(_time)\n updateTime_df = df(_updateTime)\n\n # replace original timestamps with formatted timestamps in all_order_df\n all_order_df['time'] = time_df\n all_order_df['updateTime'] = updateTime_df\n\n return all_order_df\n\n \n '''\n ***********************************************************\n POST METHODS\n ***********************************************************\n '''\n\n\n '''\n make a new order\n 1. set test=True if want to test order\n 2. set test=False if want to place order and the order is relected on the account\n @private\n @params \n required - symbol: str, side: enum, orderType: enum\n '''\n def __new_order(self, symbol, side, orderType, test=True, timeInForce=None, quantity=None,\n quoteOrderQty=None, price=None, stopPrice=None, icebergQty=None):\n \n # specify the general parameters for request body\n params = {\n 'symbol': symbol,\n 'side': side.value,\n 'type': orderType.value,\n 'newOrderRespType': 'RESULT',\n 'timestamp': int(round(time.time()*1000))\n }\n # specify option parameters for request body\n if orderType == Order.LIMIT:\n params['timeInForce'] = timeInForce\n params['quantity'] = quantity\n params['price'] = price\n if icebergQty != None:\n params['icebergQty'] = icebergQty\n elif orderType == Order.MARKET:\n params['quantity'] = quantity\n elif orderType == Order.STOP_LOSS:\n params['quantity'] = quantity\n params['stopPrice'] = stopPrice \n elif orderType == Order.STOP_LOSS_LIMIT:\n params['timeInForce'] = timeInForce\n params['quantity'] = quantity\n params['price'] = price\n params['stopPrice'] = stopPrice\n if icebergQty != None:\n params['icebergQty'] = icebergQty\n elif orderType == Order.TAKE_PROFIT:\n params['quantity'] = quantity\n params['stopPrice'] = stopPrice\n elif orderType == Order.TAKE_PROFIT_LIMIT:\n params['timeInForce'] = timeInForce\n params['quantity'] = quantity\n params['price'] = price\n params['stopPrice'] = stopPrice\n if icebergQty != None:\n params['icebergQty'] = icebergQty\n elif orderType == Order.LIMIT_MAKER:\n params['quantity'] = quantity\n params['price'] = price\n else:\n raise Exception('Invalid order type.')\n # specify url endpoint\n if test == True:\n url = self.base + self.endpoint['test_order']\n else:\n url = self.base + self.endpoint['order']\n\n # sign request\n self.sign_request(params)\n\n # initialize new order, request api response\n response = requests.post(url, params=params, headers={'X-MBX-APIKEY': self.key})\n data = json.loads(response.text)\n\n return data\n\n '''\n make a new buy order \n 1. set test=True if want to test buy order\n 2. set test=False if want to place buy order and the buy order is relected on the account\n @params \n required - symbol: str, orderType: enum\n '''\n def buy(self, symbol, orderType, test=True, timeInForce=None, quantity=None,\n quoteOrderQty=None, price=None, stopPrice=None, icebergQty=None):\n\n return self.__new_order(symbol, Order.BUY, orderType, test=test, timeInForce=timeInForce, quantity=quantity,\n quoteOrderQty=quoteOrderQty, price=price, stopPrice=stopPrice, icebergQty=icebergQty)\n \n\n '''\n make a new sell order\n 1. set test=True if want to test sell order\n 2. set test=False if want to place sell order and the sell order is relected on the account\n @params \n required - symbol: str, orderType: enum\n '''\n def sell(self, symbol, orderType, test=True, timeInForce=None, quantity=None,\n quoteOrderQty=None, price=None, stopPrice=None, icebergQty=None):\n \n return self.__new_order(symbol, Order.SELL, orderType, test=test, timeInForce=timeInForce, quantity=quantity,\n quoteOrderQty=quoteOrderQty, price=price, stopPrice=stopPrice, icebergQty=icebergQty)\n\n \n '''\n ***********************************************************\n DELETE METHODS\n ***********************************************************\n '''\n\n\n '''\n cancel an open order\n @param\n @require symbol: str, orderId: long\n '''\n def cancel_order(self, symbol, orderId):\n\n # specify parameters for request body\n params = {\n 'symbol': symbol,\n 'orderId': orderId,\n 'timestamp': int(round(time.time()*1000))\n }\n # specify url endpoint\n url = self.base + self.endpoint['order']\n\n # sign request\n self.sign_request(params)\n\n # initialize cancel order, request api response\n response = requests.delete(url, params=params, headers={'X-MBX-APIKEY': self.key})\n data = json.loads(response.text)\n \n return data\n\n\n '''\n sign your request to Binance API\n '''\n def sign_request(self, params: dict):\n \n #make a query string\n query_string = '&'.join([\"{}={}\".format(d,params[d]) for d in params])\n \n #hashing secret\n signature = hmac.new(self.secret.encode('utf-8'), \n query_string.encode('utf-8'),\n hashlib.sha256)\n \n # add your signature to the request body\n params['signature'] = signature.hexdigest()\n\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Kushalshingote/Hands-On-Generative-Adversarial-Networks-with-Keras
[ "fccada4810ba1fe8b79c5a74420a590c95623b52", "fccada4810ba1fe8b79c5a74420a590c95623b52" ]
[ "Chapter05/utils.py", "Chapter06/utils.py" ]
[ "import matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pylab as plt\nfrom math import ceil\nimport numpy as np\nimport argparse\nfrom functools import partial\nimport os\nfrom keras.models import Model, Sequential\nfrom keras.layers import Input, Dense, Reshape, Flatten\nfrom keras.layers.merge import _Merge\nfrom keras.layers.convolutional import Convolution2D, Conv2DTranspose\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.optimizers import Adam, RMSprop\nfrom keras.datasets import mnist\nfrom keras import backend as K\n\nfrom keras.datasets import cifar10\n\n\ndef get_data():\n # load cifar10 data\n (X_train, y_train), (X_test, y_test) = cifar10.load_data()\n\n # convert train and test data to float32\n X_train = X_train.astype(np.float32)\n X_test = X_test.astype(np.float32)\n\n # scale train and test data to [-1, 1]\n X_train = (X_train / 255) * 2 - 1\n X_test = (X_train / 255) * 2 - 1\n\n return X_train, X_test\n\ndef plot_images(images, filename):\n # scale images to [0.0, 1.0]\n images = (images + 1) / 2\n h, w, c = images.shape[1:]\n grid_size = ceil(np.sqrt(images.shape[0]))\n images = (images.reshape(grid_size, grid_size, h, w, c)\n .transpose(0, 2, 1, 3, 4)\n .reshape(grid_size*h, grid_size*w, c))\n plt.figure(figsize=(16, 16))\n plt.imsave(filename, images)\n plt.close('all')\n\n\ndef plot_losses(losses_d, losses_g, filename):\n losses_d = np.array(losses_d)\n fig, axes = plt.subplots(2, 2, figsize=(8, 8))\n axes = axes.flatten()\n axes[0].plot(losses_d[:, 0])\n axes[1].plot(losses_d[:, 1])\n axes[2].plot(losses_d[:, 2])\n axes[3].plot(losses_g)\n axes[0].set_title(\"losses_d\")\n axes[1].set_title(\"losses_d_real\")\n axes[2].set_title(\"losses_d_fake\")\n axes[3].set_title(\"losses_g\")\n plt.tight_layout()\n plt.savefig(filename)\n plt.close()", "import io\nfrom PIL import Image\nimport numpy as np\nimport h5py\nfrom keras.models import model_from_json\nfrom glob import glob\n\n\ndef load_model(folder_path):\n # load json and create model\n json_file = open(\"{}/model.json\".format(folder_path), 'r')\n model_json = json_file.read()\n json_file.close()\n model = model_from_json(model_json)\n # load weights into new model\n model.load_weights(\"{}/model.h5\".format(folder_path))\n print(\"Loaded model from disk\")\n return model\n\n\ndef save_model(model, folder_path):\n # serialize model to JSON\n model_json = model.to_json()\n with open(\"{}/model.json\".format(folder_path), \"w\") as json_file:\n json_file.write(model_json)\n # serialize weights to HDF5\n model.save_weights(\"{}/model.h5\".format(folder_path))\n print(\"Saved model to disk\")\n\n\ndef load_image(filepath, scale=True):\n images = np.array(Image.open(filepath), dtype=int)\n if scale:\n images = 2 * (images / 255.0) - 1\n images = images.astype(float)\n return images\n\n\ndef iterate_minibatches(glob_str, batch_size=128, img_size=256):\n filepaths = glob(glob_str)\n n_files = len(filepaths)\n cur_batch = 0\n while True:\n # drop last if it does not fit\n if (n_files - cur_batch*batch_size) < batch_size or cur_batch == 0:\n ids = np.random.randint(0, n_files, n_files)\n np.random.shuffle(ids)\n cur_batch = 0\n\n train_data = []\n for i in range(batch_size):\n image_ab = load_image(filepaths[ids[cur_batch*batch_size+i]])\n train_data.append([image_ab[:, :img_size], image_ab[:, img_size:]])\n\n cur_batch = (cur_batch + 1) % int(len(filepaths)/batch_size)\n\n train_data = np.array(train_data)\n yield train_data, cur_batch\n\n\ndef get_edges(t):\n edge = np.zeros(t.shape, dtype=bool)\n edge[:,1:] = edge[:,1:] | (t[:,1:] != t[:,:-1])\n edge[:,:-1] = edge[:,:-1] | (t[:,1:] != t[:,:-1])\n edge[1:,:] = edge[1:,:] | (t[1:,:] != t[:-1,:])\n edge[:-1,:] = edge[:-1,:] | (t[1:,:] != t[:-1,:])\n return edge.astype(float)\n\n\ndef iterate_minibatches_cityscapes(folder_path, prefix='train', use_edges=True,\n batch_size=3):\n filepaths_img = sorted(\n glob(\"{}/{}_img/*.png\".format(folder_path, prefix)))\n filepaths_label = sorted(\n glob(\"{}/{}_label/*.png\".format(folder_path, prefix)))\n if use_edges:\n filepaths_inst = sorted(\n glob(\"{}/{}_inst/*.png\".format(folder_path, prefix)))\n\n n_files = len(filepaths_img)\n cur_batch = 0\n while True:\n # drop last if it does not fit\n if (n_files - cur_batch*batch_size) < batch_size or cur_batch == 0:\n ids = np.random.choice(range(n_files), n_files, replace=False)\n np.random.shuffle(ids)\n cur_batch = 0\n train_data = []\n for i in range(batch_size):\n img = load_image(filepaths_img[ids[cur_batch*batch_size+i]])\n lbl = load_image(filepaths_label[ids[cur_batch*batch_size+i]])\n lbl = lbl[:, :, None]\n if use_edges:\n inst = load_image(filepaths_inst[ids[cur_batch*batch_size+i]])\n edges = get_edges(inst)[..., None]\n train_data.append(np.dstack((img, lbl, edges)))\n else:\n train_data.append(np.dstack((img, lbl)))\n\n cur_batch = (cur_batch + 1) % int(len(filepaths_img)/batch_size)\n\n yield np.array(train_data), cur_batch\n\n\ndef log_images(images, name, i, logger, h=256, w=256, shape=4):\n images = (images.reshape(shape, shape, h, w, images.shape[-1])\n .transpose(0, 2, 1, 3, 4)\n .reshape(shape*h, shape*w, images.shape[-1]))\n images = ((images + 1) * 0.5)\n logger.add_image('{}'.format(name, i), images, i, dataformats='HWC')\n\n\ndef log_losses(loss_d, loss_g, iteration, logger):\n logger.add_scalar(\"loss_d\", loss_d[0], iteration)\n logger.add_scalar(\"loss_d_real\", loss_d[1], iteration)\n logger.add_scalar(\"loss_d_fake\", loss_d[2], iteration)\n logger.add_scalar(\"loss_g\", loss_g[0], iteration)\n logger.add_scalar(\"loss_g_fake\", loss_g[1], iteration)\n logger.add_scalar(\"loss_g_reconstruction\", loss_g[2], iteration)\n\n\ndef log_losses_pix2pixhd(loss_d, loss_g, iteration, logger):\n for i in range(len(loss_d)):\n logger.add_scalar(\"loss_d{}\".format(i), loss_d[i][0], iteration)\n logger.add_scalar(\"loss_d{}_real\".format(i), loss_d[i][1], iteration)\n logger.add_scalar(\"loss_d{}_fake\".format(i), loss_d[i][2], iteration)\n logger.add_scalar(\"loss_g\", loss_g[0], iteration)\n logger.add_scalar(\"loss_g_fake\", loss_g[1], iteration)\n logger.add_scalar(\"loss_g_reconstruction\", loss_g[2], iteration)\n" ]
[ [ "matplotlib.pylab.tight_layout", "numpy.sqrt", "matplotlib.use", "matplotlib.pylab.imsave", "matplotlib.pylab.figure", "matplotlib.pylab.subplots", "matplotlib.pylab.savefig", "numpy.array", "matplotlib.pylab.close" ], [ "numpy.dstack", "numpy.random.shuffle", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aPere3/MVAProject-RecVis16
[ "83b581c37cb486ec855e4a40652860df4e56b363" ]
[ "data/mnist.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module contains a method to load mnist data. Based on David Larson work at:\nhttp://g.sweyla.com/blog/2012/mnist-numpy/a\n\"\"\"\n\nimport numpy\nimport os, struct\nfrom array import array as pyarray\n\n\ndef load_mnist(dataset=\"training\", digits=numpy.arange(10), path=\"mnist\"):\n \"\"\"\n The Mnist loading methods from David Larson. Can be checked out at: http://g.sweyla.com/blog/2012/mnist-numpy/a\n\n :param dataset: 'training' or 'testing' depending on the files to load.\n :param digits: digits to load\n :param path: path to the mnist directory\n :return: X, y: data and labels\n \"\"\"\n\n if dataset == \"training\":\n fname_img = os.path.join(path, 'train-images.idx3-ubyte')\n fname_lbl = os.path.join(path, 'train-labels.idx1-ubyte')\n elif dataset == \"testing\":\n fname_img = os.path.join(path, 't10k-images.idx3-ubyte')\n fname_lbl = os.path.join(path, 't10k-labels.idx1-ubyte')\n else:\n raise ValueError(\"dataset must be 'testing' or 'training'\")\n\n flbl = open(fname_lbl, 'rb')\n magic_nr, size = struct.unpack(\">II\", flbl.read(8))\n lbl = pyarray(\"b\", flbl.read())\n flbl.close()\n\n fimg = open(fname_img, 'rb')\n magic_nr, size, rows, cols = struct.unpack(\">IIII\", fimg.read(16))\n img = pyarray(\"B\", fimg.read())\n fimg.close()\n\n ind = [ k for k in range(size) if lbl[k] in digits ]\n N = len(ind)\n\n images = numpy.zeros((N, rows, cols), dtype=numpy.uint8)\n labels = numpy.zeros((N, 1), dtype=numpy.int8)\n for i in range(len(ind)):\n images[i] = numpy.array(img[ ind[i]*rows*cols : (ind[i]+1)*rows*cols ]).reshape((rows, cols))\n labels[i] = lbl[ind[i]]\n\n return images, labels\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jnothman/sphinx-gallery
[ "b930662613a32fe05f16b39f86fafdb4c8d6f424" ]
[ "tutorials/plot_notebook.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n========================\nNotebook styled examples\n========================\n\nThe gallery is capable of transforming python files into reStructuredText files\nwith a notebook structure. For this to be used you need to respect some syntax\nrules.\n\nIt makes a lot of sense to contrast this output rst file with the\n:download:`original python script <plot_notebook.py>` to get better feeling of\nthe necessary file structure.\n\nAnything before the python script docstring is ignored by sphinx-gallery and\nwill not appear in the rst file, nor will it be executed.\nThis python docstring requires an reStructuredText title to name the file and\ncorrectly build the reference links.\n\nOnce you close the docstring you would be writing python code. This code gets\nexecuted by sphinx gallery shows the plots and attaches the generating code.\nNevertheless you can break your code into blocks and give the rendered file\na notebook style. In this case you have to include a code comment breaker\na line of at least 20 hashes and then every comment start with the a new hash.\n\nAs in this example we start by first writing this module\nstyle docstring, then for the first code block we write the example file author\nand script license continued by the import modules instructions.\n\"\"\"\n\n# Code source: Óscar Nájera\n# License: BSD 3 clause\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n##############################################################################\n# This code block is executed, although it produces no output. Lines starting\n# with a simple hash are code comment and get treated as part of the code\n# block. To include this new comment string we started the new block with a\n# long line of hashes.\n#\n# The sphinx-gallery parser will assume everything after this splitter and that\n# continues to start with a **comment hash and space** (respecting code style)\n# is text that has to be rendered in\n# html format. Keep in mind to always keep your comments always together by\n# comment hashes. That means to break a paragraph you still need to commend\n# that line break.\n#\n# In this example the next block of code produces some plotable data. Code is\n# executed, figure is saved and then code is presented next, followed by the\n# inlined figure.\n\nx = np.linspace(-np.pi, np.pi, 300)\nxx, yy = np.meshgrid(x, x)\nz = np.cos(xx) + np.cos(yy)\n\nplt.figure()\nplt.imshow(z)\nplt.colorbar()\nplt.xlabel('$x$')\nplt.ylabel('$y$')\n\n###########################################################################\n# Again it is possble to continue the discussion with a new python string. This\n# time to introduce the next code block generates 2 separate figures.\n\nplt.figure()\nplt.imshow(z, cmap=plt.cm.get_cmap('hot'))\nplt.figure()\nplt.imshow(z, cmap=plt.cm.get_cmap('Spectral'), interpolation='none')\n\n##########################################################################\n# There's some subtle differences between rendered html rendered comment\n# strings and code comment strings which I'll demonstrate below. (Some of this\n# only makes sense if you look at the\n# :download:`raw python script <plot_notebook.py>`)\n#\n# Comments in comment blocks remain nested in the text.\n\n\ndef dummy():\n \"\"\"Dummy function to make sure docstrings don't get rendered as text\"\"\"\n pass\n\n# Code comments not preceded by the hash splitter are left in code blocks.\n\nstring = \"\"\"\nTriple-quoted string which tries to break parser but doesn't.\n\"\"\"\n\n############################################################################\n# Finally, I'll call ``show`` at the end just so someone running the python\n# code directly will see the plots; this is not necessary for creating the docs\n\nplt.show()\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.linspace", "matplotlib.pyplot.cm.get_cmap", "numpy.cos", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gatapia/py_ml_utils
[ "844d8b62a7c5cc0a80f4f62c0bfda092aac57ade" ]
[ "pml/engineer_tests.py" ]
[ "from __future__ import print_function, absolute_import\r\n\r\nimport unittest, math\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom . import *\r\n\r\nclass T(base_pandas_extensions_tester.BasePandasExtensionsTester):\r\n def test_concat(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2': ['d', 'e', 'f']}) \r\n df.engineer('concat(c_1, c_2)')\r\n self.assertTrue(np.array_equal(df['c_concat(c_1,c_2)'].values, \r\n np.array(['ad', 'be', 'cf'], 'object')))\r\n\r\n def test_concat_3_cols(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2': ['d', 'e', 'f'], 'c_3': ['h', 'i', 'j']}) \r\n df.engineer('concat(c_3, c_1, c_2)')\r\n self.assertTrue(np.array_equal(df['c_concat(c_3,c_1,c_2)'].values, \r\n np.array(['had', 'ibe', 'jcf'], 'object')))\r\n\r\n def test_concat_with_numerical_col(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3]}) \r\n df.engineer('concat(c_1,n_2)')\r\n self.assertTrue(np.array_equal(df['c_concat(c_1,n_2)'].values, \r\n np.array(['a1', 'b2', 'c3'], 'object')))\r\n\r\n def test_concat_with_numerical_col_3_cols(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6]}) \r\n df.engineer('concat(n_3,c_1,n_2)')\r\n self.assertTrue(np.array_equal(df['c_concat(n_3,c_1,n_2)'].values, \r\n np.array(['4a1', '5b2', '6c3'], 'object')))\r\n\r\n def test_multiplication(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('mult(n_2, n_3)')\r\n self.assertTrue(np.array_equal(df['n_mult(n_2,n_3)'].values, \r\n np.array([4, 10, 18], long)))\r\n\r\n def test_multiplication_3_cols(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('mult(n_2, n_3, n_4)')\r\n self.assertTrue(np.array_equal(df['n_mult(n_2,n_3,n_4)'].values, \r\n np.array([4*7, 80, 18*9], long)))\r\n\r\n def test_square_on_whole_data_frame(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('pow(2)')\r\n np.testing.assert_array_equal(df.values, \r\n np.array([\r\n ['a', 1, 4, 7, 1*1, 4*4, 7*7],\r\n ['b', 2, 5, 8, 2*2, 5*5, 8*8],\r\n ['c', 3, 6, 9, 3*3, 6*6, 9*9],\r\n ], 'object'))\r\n\r\n def test_square_on_cols(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('pow(n_3, 2)')\r\n np.testing.assert_array_equal(df.values, \r\n np.array([\r\n ['a', 1, 4, 7, 4*4],\r\n ['b', 2, 5, 8, 5*5],\r\n ['c', 3, 6, 9, 6*6],\r\n ], 'object'))\r\n\r\n def test_log_on_whole_data_frame(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('lg()')\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 1, 4, 7, math.log(1), math.log(4), math.log(7)],\r\n ['b', 2, 5, 8, math.log(2), math.log(5), math.log(8)],\r\n ['c', 3, 6, 9, math.log(3), math.log(6), math.log(9)],\r\n ], 'object')))\r\n\r\n def test_log_on_cols(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('lg(n_3)')\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 1, 4, 7, math.log(4)],\r\n ['b', 2, 5, 8, math.log(5)],\r\n ['c', 3, 6, 9, math.log(6)],\r\n ], 'object')))\r\n\r\n def test_sqrt_on_whole_data_frame(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('sqrt()')\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 1, 4, 7, math.sqrt(1), math.sqrt(4), math.sqrt(7)],\r\n ['b', 2, 5, 8, math.sqrt(2), math.sqrt(5), math.sqrt(8)],\r\n ['c', 3, 6, 9, math.sqrt(3), math.sqrt(6), math.sqrt(9)],\r\n ], 'object')))\r\n\r\n def test_sqrt_on_cols(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('sqrt(n_3)')\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 1, 4, 7, math.sqrt(4)],\r\n ['b', 2, 5, 8, math.sqrt(5)],\r\n ['c', 3, 6, 9, math.sqrt(6)],\r\n ], 'object')))\r\n\r\n def test_rolling_sum_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_sum(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 35, 40, 30, 29, 48], df['n_' + col])\r\n\r\n def test_rolling_mean_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_mean(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_allclose([np.nan, np.nan, 11.66, 13.33, 10, 9.66, 16], df['n_' + col], rtol=1e-3)\r\n\r\n def test_rolling_median_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_median(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 12, 13, 13, 12, 12], df['n_' + col])\r\n\r\n def test_rolling_min_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_min(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 10, 12, 2, 2, 2], df['n_' + col])\r\n\r\n def test_rolling_max_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_max(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 13, 15, 15, 15, 34], df['n_' + col])\r\n\r\n def test_rolling_std_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_std(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_allclose([np.nan, np.nan, 1.528, 1.528, 7, 6.807, 16.371], df['n_' + col], rtol=1e-3)\r\n\r\n def test_rolling_var_on_single_col(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34]})\r\n col = 'rolling_var(n_1,3)'\r\n df.engineer(col)\r\n np.testing.assert_allclose([np.nan, np.nan, 2.333, 2.333, 49, 46.333, 268], df['n_' + col], rtol=1e-3)\r\n\r\n # Multiple Columns\r\n\r\n def test_rolling_sum_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_sum(3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 35, 40, 30, 29, 48], df['n_rolling_sum(n_1,3)'])\r\n np.testing.assert_array_equal([np.nan, np.nan, 6, 10, 10, 9, 8], df['n_rolling_sum(n_2,3)'])\r\n\r\n def test_rolling_mean_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_mean(3)'\r\n df.engineer(col)\r\n np.testing.assert_allclose([np.nan, np.nan, 11.66, 13.33, 10, 9.66, 16], df['n_rolling_mean(n_1,3)'], rtol=1e-3)\r\n np.testing.assert_allclose([np.nan, np.nan, 2, 3.333, 3.333, 3, 2.666], df['n_rolling_mean(n_2,3)'], rtol=1e-3)\r\n\r\n def test_rolling_median_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_median(3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 12, 13, 13, 12, 12], df['n_rolling_median(n_1,3)'])\r\n np.testing.assert_array_equal([np.nan, np.nan, 2, 3, 3, 2, 2], df['n_rolling_median(n_2,3)'])\r\n\r\n def test_rolling_min_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_min(3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 10, 12, 2, 2, 2], df['n_rolling_min(n_1,3)'])\r\n np.testing.assert_array_equal([np.nan, np.nan, 1, 2, 2, 2, 2], df['n_rolling_min(n_2,3)'])\r\n\r\n def test_rolling_max_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_max(3)'\r\n df.engineer(col)\r\n np.testing.assert_array_equal([np.nan, np.nan, 13, 15, 15, 15, 34], df['n_rolling_max(n_1,3)'])\r\n np.testing.assert_array_equal([np.nan, np.nan, 3, 5, 5, 5, 4], df['n_rolling_max(n_2,3)'])\r\n\r\n def test_rolling_std_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_std(3)'\r\n df.engineer(col)\r\n np.testing.assert_allclose([np.nan, np.nan, 1.528, 1.528, 7, 6.807, 16.371], df['n_rolling_std(n_1,3)'], rtol=1e-3)\r\n np.testing.assert_allclose([np.nan, np.nan, 1, 1.528, 1.528, 1.732, 1.1547], df['n_rolling_std(n_2,3)'], rtol=1e-3)\r\n\r\n def test_rolling_var_on_multi_cols(self):\r\n df = pd.DataFrame({'n_1': [10, 12, 13, 15, 2, 12, 34], 'n_2': [1, 2, 3, 5, 2, 2, 4]})\r\n col = 'rolling_var(3)'\r\n df.engineer(col)\r\n np.testing.assert_allclose([np.nan, np.nan, 2.333, 2.333, 49, 46.333, 268], df['n_rolling_var(n_1,3)'], rtol=1e-3)\r\n np.testing.assert_allclose([np.nan, np.nan, 1, 2.333, 2.333, 3, 1.333], df['n_rolling_var(n_2,3)'], rtol=1e-3)\r\n\r\n def test_method_chaining(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2':['d', 'e', 'f'], \r\n 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.\\\r\n engineer('concat(c_1, c_2)').\\\r\n engineer('concat(c_1, n_2)').\\\r\n engineer('mult(n_2, n_3)').\\\r\n engineer('lg(n_2)').\\\r\n engineer('pow(n_3, 2)')\r\n\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 'd', 1, 4, 7, 'ad', 'a1', 4, math.log(1), 4*4],\r\n ['b', 'e', 2, 5, 8, 'be', 'b2', 10, math.log(2), 5*5],\r\n ['c', 'f', 3, 6, 9, 'cf', 'c3', 18, math.log(3), 6*6]\r\n ], 'object')))\r\n\r\n def test_chaining_single_call_semi_col_sep(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2':['d', 'e', 'f'], \r\n 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('concat(c_1, c_2);concat(c_1, n_2);mult(n_2, n_3);lg(n_2);pow(n_3, 2)')\r\n\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 'd', 1, 4, 7, 'ad', 'a1', 4, math.log(1), 4*4],\r\n ['b', 'e', 2, 5, 8, 'be', 'b2', 10, math.log(2), 5*5],\r\n ['c', 'f', 3, 6, 9, 'cf', 'c3', 18, math.log(3), 6*6]\r\n ], 'object')))\r\n\r\n def test_chaining_single_with_arr_arg(self):\r\n df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2':['d', 'e', 'f'], \r\n 'n_2': [1, 2, 3], 'n_3': [4, 5, 6], 'n_4': [7, 8, 9]}) \r\n df.engineer('concat(c_1, c_2);concat(c_1, n_2);mult(n_2, n_3);lg(n_2);pow(n_3, 2)'.split(';'))\r\n\r\n self.assertTrue(np.array_equal(df.values, \r\n np.array([\r\n ['a', 'd', 1, 4, 7, 'ad', 'a1', 4, math.log(1), 4*4],\r\n ['b', 'e', 2, 5, 8, 'be', 'b2', 10, math.log(2), 5*5],\r\n ['c', 'f', 3, 6, 9, 'cf', 'c3', 18, math.log(3), 6*6]\r\n ], 'object')))\r\n\r\n def test_long_method_chains(self):\r\n df1 = pd.DataFrame({'n_1': [1, 2, 3], 'n_2': [4, 5, 6]}) \r\n df2 = pd.DataFrame({'n_1': [1, 2, 3], 'n_2': [4, 5, 6]}) \r\n df1.engineer('mult(lg(mult(n_1, n_2)), lg(pow(n_1, 3)))')\r\n df2.engineer('mult(n_1,n_2);pow(n_1,3)')\r\n df2.engineer('lg(pow(n_1,3));lg(mult(n_1, n_2))')\r\n df2.engineer('mult(lg(mult(n_1,n_2)),lg(pow(n_1, 3)))')\r\n\r\n np.testing.assert_array_equal(df1.columns.values.sort(), df2.columns.values.sort());\r\n np.testing.assert_array_equal(df1['n_mult(n_1,n_2)'].values, df2['n_mult(n_1,n_2)'].values);\r\n np.testing.assert_array_equal(df1['n_pow(n_1,3)'], df2['n_pow(n_1,3)']);\r\n np.testing.assert_array_equal(df1['n_lg(pow(n_1,3))'], df2['n_lg(pow(n_1,3))']);\r\n np.testing.assert_array_equal(df1['n_lg(mult(n_1,n_2))'], df2['n_lg(mult(n_1,n_2))']);\r\n np.testing.assert_array_equal(df1['n_mult(lg(mult(n_1,n_2)),lg(pow(n_1,3)))'], df2['n_mult(lg(mult(n_1,n_2)),lg(pow(n_1,3)))']);\r\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array", "pandas.DataFrame", "numpy.testing.assert_allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
bonesbb/HASPR
[ "856af4a480f4ff135591bbbcc1267898d88cbf0d" ]
[ "Analysis Scripts/co2_offset.py" ]
[ "# HASPR - High-Altitude Solar Power Research\r\n# Script to calculate CO2-equivalent offset given generation profiles\r\n# Version 0.1\r\n# Author: neyring\r\n\r\nfrom os import walk\r\nimport haspr\r\nfrom haspr import Result\r\nfrom haspr import Dataset\r\nimport numpy as np\r\nfrom numpy import genfromtxt\r\n\r\n# PARAMETERS #\r\n# path to .csv file of grid CI data (Wh, UTC, 1h res, no leap days):\r\nciPath = \"D:\\\\00_Results\\\\04_CO2 Offset\\\\1_Swiss Grid CI - 1h - UTC.csv\"\r\n# directory containing generation profiles (1h res, Wh) to run our analyses on (without leap days):\r\ninputDirectory = \"D:\\\\00_Results\\\\Out\"\r\n# directory to write output to:\r\nhaspr.outputDirectory = \"D:\\\\00_Results\\\\04_CO2 Offset\\\\Case 5 - 30 to 65 deg winter opt\"\r\n# OS path delimiter (\"\\\\\" for windows, \"/\" for unix)\"\r\nhaspr.osPathDelimiter = \"\\\\\"\r\n\r\n# extract carbon intensity data:\r\nci = Dataset(\"ci\")\r\nhaspr.get_csv_data(ciPath, ci)\r\ntimestamps = []\r\nci_values = []\r\nfor p in ci.payload:\r\n timestamps.append(str(p[0]))\r\n ci_values.append(float(p[1]))\r\n\r\nci_values = np.array(ci_values) # use numpy for efficient element-wise calculations\r\n\r\n# get all file names in inputDirectory:\r\nfile_names = []\r\nfor (dirpath, dirnames, filenames) in walk(inputDirectory):\r\n file_names.extend(filenames)\r\n\r\n# cycle through files and build result objects:\r\nresults = []\r\nfor f in file_names:\r\n file_path = inputDirectory + haspr.osPathDelimiter + f\r\n\r\n # get generation profile:\r\n extracted_array = genfromtxt(file_path, delimiter=',', skip_header=1)\r\n gen_values = extracted_array[:, 1] # we only want generation values\r\n\r\n # get carbon offset for current generation profile:\r\n carbon_offset = np.multiply(ci_values, gen_values)\r\n\r\n # build current result object:\r\n result_title = f[0:len(f) - 4] + \" - CO2-eq offset\"\r\n current_result = Result(result_title)\r\n current_result.payload.append(\"Time [UTC], CO2-eq offset [g]\")\r\n for i in range(8760):\r\n str_to_append = str(timestamps[i]) + \", \" + str(carbon_offset[i])\r\n current_result.payload.append(str_to_append)\r\n\r\n results.append(current_result)\r\n\r\n# dump all results:\r\nfor r in results:\r\n r.dump()\r\n" ]
[ [ "numpy.array", "numpy.multiply", "numpy.genfromtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jedbrown/PetIBM
[ "8584d824e0ffbbe2ea413dcf081e79a72b39bf5f", "8584d824e0ffbbe2ea413dcf081e79a72b39bf5f" ]
[ "examples/decoupledibpm/flatplate3dRe100_GPU/scripts/plotForceCoefficients.py", "examples/decoupledibpm/flatplate3dRe100_GPU/AoA90/scripts/createBody.py" ]
[ "\"\"\"\nPlots the steady-state force coefficients of an inclined flat-plate with\naspect-ratio 2 at Reynolds number 100 for angles of attack between 0 and 90\ndegrees.\nCompares with experimental results reported in Taira et al. (2007).\n_References:_\n* Taira, K., Dickson, W. B., Colonius,\n T., Dickinson, M. H., & Rowley, C. W. (2007).\n Unsteadiness in flow over a flat plate at angle-of-attack at low Reynolds\n numbers.\n AIAA Paper, 710, 2007.\n\"\"\"\n\nimport os\nimport numpy\nfrom matplotlib import pyplot\n\n\nif not os.environ.get('PETIBM_EXAMPLES'):\n raise KeyError('Environment variable PETIBM_EXAMPLES is not set; '\n 'Set PETIBM_EXAMPLES as the root directory of the examples.')\n\nscript_dir = os.path.dirname(os.path.realpath(__file__))\nroot_dir = os.sep.join(script_dir.split(os.sep)[:-1])\n\n# Read forces and computes mean values for each angle of inclination.\ntime_limits = (15.0, 20.0)\nangles = numpy.arange(0, 90 + 1, 10, dtype=numpy.int32)\ncd = numpy.zeros_like(angles, dtype=numpy.float64)\ncl = numpy.zeros_like(angles, dtype=numpy.float64)\nfor i, angle in enumerate(angles):\n filepath = os.path.join(root_dir, 'AoA{}'.format(angle), 'forces.txt')\n with open(filepath, 'r') as infile:\n data = numpy.loadtxt(infile, dtype=numpy.float64, unpack=True)\n mask = numpy.where(numpy.logical_and(data[0] >= time_limits[0],\n data[0] <= time_limits[1]))[0]\n cd[i], cl[i] = data[1][mask].mean(), data[2][mask].mean()\n\n# Read experimental data from Taira et al. (2007).\ndirectory = os.path.join(os.environ['PETIBM_EXAMPLES'], 'data')\ntaira = {'cd': {'aoa': None, 'values': None,\n 'filename': 'taira_et_al_2007_flatPlateRe100AR2_CdvsAoA.dat'},\n 'cl': {'aoa': None, 'values': None,\n 'filename': 'taira_et_al_2007_flatPlateRe100AR2_ClvsAoA.dat'}}\nfor key in taira.keys():\n filepath = os.path.join(directory, taira[key]['filename'])\n with open(filepath, 'r') as infile:\n data = numpy.loadtxt(infile, dtype=numpy.float64, unpack=True)\n taira[key]['aoa'], taira[key]['values'] = data[0], data[1]\n\n# Plots the force coefficients versus the angle-of-attack and compares with\n# experimental results reported in Taira et al. (2007).\npyplot.style.use('seaborn-dark')\nfig, ax = pyplot.subplots(2, figsize=(6.0, 6.0), sharex=True)\nax[0].grid(zorder=0)\nax[0].set_ylabel('$C_D$', fontname='DejaVu Serif', fontsize=16)\nax[0].scatter(angles, cd,\n label='PetIBM',\n marker='x', s=40,\n facecolors='black', edgecolors='none',\n zorder=4)\nax[0].scatter(taira['cd']['aoa'], taira['cd']['values'],\n label='Taira et al. (2007)',\n marker='o', s=40,\n facecolors='none', edgecolors='#1B9E77',\n zorder=3)\nax[0].set_ylim(0.0, 2.0)\nax[1].grid(zorder=0)\nax[1].set_xlabel('angle of attack (deg)',\n fontname='DejaVu Serif', fontsize=16)\nax[1].set_ylabel('$C_L$', fontname='DejaVu Serif', fontsize=16)\nax[1].scatter(angles, cl,\n label='PetIBM',\n marker='x', s=40,\n facecolors='black', edgecolors='none',\n zorder=4)\nax[1].scatter(taira['cl']['aoa'], taira['cl']['values'],\n label='Taira et al. (2007)',\n marker='o', s=40,\n facecolors='none', edgecolors='#1B9E77',\n zorder=3)\nax[1].set_xlim(0.0, 90.0)\nax[1].set_ylim(0.0, 2.0)\nfor a in ax:\n for method in ['get_xticklabels', 'get_yticklabels']:\n for label in getattr(a, method)():\n label.set_fontname('DejaVu Serif')\n label.set_fontsize(14)\nhandles, labels = ax[0].get_legend_handles_labels()\nfig.legend(handles, labels,\n ncol=2, loc='center', prop={'family': 'serif', 'size': 14},\n frameon=False, bbox_to_anchor=(0.54, 0.53))\nfig.tight_layout()\n\n# Save the figure.\nfigures_dir = os.path.join(root_dir, 'figures')\nif not os.path.isdir(figures_dir):\n os.makedirs(figures_dir)\nfilepath = os.path.join(figures_dir, 'forceCoefficients.png')\nfig.savefig(filepath)\n\npyplot.show()\n", "\"\"\"\nCreate a flat plate of length 1.0 with aspect ratio 2.0 and a 90-degree\ninclination.\nThe plate is discretized with spacing 0.04 in the x-y plane and with spacing\n0.04 along the z-direction.\n\"\"\"\n\nimport os\nimport numpy\n\n\n# Flat-plate's parameters.\nL = 1.0 # chord length\nAR = 2.0 # aspect ratio\nxc, yc, zc = 0.0, 0.0, 0.0 # center's coordinates\naoa = 90 # angle of inclination in degrees\nds = 0.04 # mesh spacing\n\nscript_dir = os.path.dirname(os.path.realpath(__file__))\nsimu_dir = os.sep.join(script_dir.split(os.sep)[:-1])\n\n# Generate coordinates of the flat plate.\nn = int(L / ds)\nsection = numpy.linspace(xc - L / 2, xc + L / 2, n)\n\nx = xc + numpy.cos(numpy.radians(-aoa)) * section\ny = yc + numpy.sin(numpy.radians(-aoa)) * section\n\nnz = int(L * AR / ds)\nz = numpy.linspace(zc - L * AR / 2, zc + L * AR / 2, nz)\n\n# Write coordinates into file.\nfilepath = os.path.join(simu_dir, 'flatplateAoA{}.body'.format(aoa))\nwith open(filepath, 'w') as outfile:\n outfile.write('{}\\n'.format(n * nz))\nfor zi in z:\n with open(filepath, 'ab') as outfile:\n numpy.savetxt(outfile, numpy.c_[x, y, zi * numpy.ones(n)])\n" ]
[ [ "numpy.logical_and", "numpy.arange", "matplotlib.pyplot.subplots", "numpy.zeros_like", "matplotlib.pyplot.show", "matplotlib.pyplot.style.use", "numpy.loadtxt" ], [ "numpy.radians", "numpy.linspace", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
deciding/tf-kaldi-speaker
[ "ceaed721e502a71434d910fd73b202940ea2ce60" ]
[ "egs/voxceleb/v1/nnet/lib/extract.py" ]
[ "import argparse\nimport numpy as np\nimport os\nimport sys\nimport numpy, scipy, sklearn\nfrom model.trainer import Trainer\nfrom misc.utils import Params\nfrom dataset.kaldi_io import FeatureReader, open_or_fd, read_mat_ark, write_vec_flt\nfrom six.moves import range\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-g\", \"--gpu\", type=int, default=-1, help=\"The GPU id. GPU disabled if -1.\")\nparser.add_argument(\"-m\", \"--min-chunk-size\", type=int, default=25, help=\"The minimum length of the segments. Any segment shorted than this value will be ignored.\")\nparser.add_argument(\"-s\", \"--chunk-size\", type=int, default=10000, help=\"The length of the segments used to extract the embeddings. \"\n \"Segments longer than this value will be splited before extraction. \"\n \"Then the splited embeddings will be averaged to get the final embedding. \"\n \"L2 normalizaion will be applied before the averaging if specified.\")\nparser.add_argument(\"-n\", \"--normalize\", action=\"store_true\", help=\"Normalize the embedding before averaging and output.\")\nparser.add_argument(\"--node\", type=str, default=\"\", help=\"The node to output the embeddings.\")\nparser.add_argument(\"model_dir\", type=str, help=\"The model directory.\")\nparser.add_argument(\"rspecifier\", type=str, help=\"Kaldi feature rspecifier (or ark file).\")\nparser.add_argument(\"wspecifier\", type=str, help=\"Kaldi output wspecifier (or ark file).\")\n\nargs = parser.parse_args()\n\nif args.gpu == -1:\n # Disable GPU\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n# In the GPU situation, it is difficult to know how to specify the GPU id.\n# If the program is launched locally, you can set CUDA_VISIBLE_DEVICES to the id.\n# However, if SGE is used, we cannot simply set CUDA_VISIBLE_DEVICES.\n# So it is better to specify the GPU id outside the program.\n# Give an arbitrary number (except for -1) to --gpu can enable it. Leave it blank if you want to disable gpu.\n\nimport tensorflow as tf\n\nif __name__ == '__main__':\n tf.reset_default_graph()\n tf.logging.set_verbosity(tf.logging.INFO)\n\n nnet_dir = os.path.join(args.model_dir, \"nnet\")\n\n config_json = os.path.join(args.model_dir, \"nnet/config.json\")\n if not os.path.isfile(config_json):\n sys.exit(\"Cannot find params.json in %s\" % config_json)\n params = Params(config_json)\n\n # Change the output node if necessary\n if len(args.node) != 0:\n params.embedding_node = args.node\n tf.logging.info(\"Extract embedding from %s\" % params.embedding_node)\n\n with open(os.path.join(nnet_dir, \"feature_dim\"), \"r\") as f:\n dim = int(f.readline().strip())\n #trainer = Trainer(params, args.model_dir, dim, single_cpu=True)\n trainer = Trainer(params, args.model_dir, dim)\n trainer.build(\"predict\")\n\n if args.rspecifier.rsplit(\".\", 1)[1] == \"scp\":\n # The rspecifier cannot be scp\n sys.exit(\"The rspecifier must be ark or input pipe\")\n\n fp_out = open_or_fd(args.wspecifier, \"wb\")\n # import pdb;pdb.set_trace()\n # args.rspecifier=args.rspecifier.replace('JOB', '1')\n for index, (key, feature) in enumerate(read_mat_ark(args.rspecifier)):\n if feature.shape[0] < args.min_chunk_size:\n tf.logging.info(\"[INFO] Key %s length too short, %d < %d, skip.\" % (key, feature.shape[0], args.min_chunk_size))\n continue\n if feature.shape[0] > args.chunk_size:\n feature_array = []\n feature_length = []\n num_chunks = int(np.ceil(float(feature.shape[0] - args.chunk_size) / (args.chunk_size / 2))) + 1\n tf.logging.info(\"[INFO] Key %s length %d > %d, split to %d segments.\" % (key, feature.shape[0], args.chunk_size, num_chunks))\n for i in range(num_chunks):\n start = int(i * (args.chunk_size / 2))\n this_chunk_size = args.chunk_size if feature.shape[0] - start > args.chunk_size else feature.shape[0] - start\n feature_length.append(this_chunk_size)\n feature_array.append(feature[start:start+this_chunk_size])\n\n feature_length = np.expand_dims(np.array(feature_length), axis=1)\n # Except for the last feature, the length of other features should be the same (=chunk_size)\n embeddings = trainer.predict(np.array(feature_array[:-1], dtype=np.float32))\n embedding_last = trainer.predict(feature_array[-1])\n embeddings = np.concatenate([embeddings, np.expand_dims(embedding_last, axis=0)], axis=0)\n if args.normalize:\n embeddings /= np.sqrt(np.sum(np.square(embeddings), axis=1, keepdims=True))\n embedding = np.sum(embeddings * feature_length, axis=0) / np.sum(feature_length)\n else:\n tf.logging.info(\"[INFO] Key %s length %d.\" % (key, feature.shape[0]))\n embedding = trainer.predict(feature)\n tf.logging.info(\"[INFO] Key %s finished predicting\" % (key))\n\n if args.normalize:\n embedding /= np.sqrt(np.sum(np.square(embedding)))\n write_vec_flt(fp_out, embedding, key=key)\n tf.logging.info(\"[INFO] Key %s finished writing\" % (key))\n fp_out.close()\n trainer.close()\n" ]
[ [ "numpy.square", "numpy.expand_dims", "tensorflow.reset_default_graph", "tensorflow.logging.info", "tensorflow.logging.set_verbosity", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
uio-bmi/graph_peak_caller
[ "89deeabf3cd0b23fba49b1304f1c81222fb534d7", "89deeabf3cd0b23fba49b1304f1c81222fb534d7" ]
[ "graph_peak_caller/analysis/diploratio_v_motifrate.py", "tests/test_sparseholescleaning.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plot(base_name):\n def get_hist(s):\n return s[\"summary\"][0]*s[\"diplo_hist\"]\n motif = np.load(base_name + \"/limited_summits_alignments_motif_summary.npz\")\n nonmotif = np.load(base_name + \"/limited_summits_alignments_nonmotif_summary.npz\")\n motif_hist = get_hist(motif)\n nonmotif_hist = get_hist(nonmotif)\n cum_motif = np.cumsum(motif_hist)\n cum_nonmotif = np.cumsum(nonmotif_hist)\n cum_total = cum_motif + cum_nonmotif\n ratio = np.where(cum_total == 0, 0, cum_motif/cum_total)\n plt.plot(np.linspace(0, 1, 100), ratio, label=base_name)\n\nif __name__ == \"__main__\":\n import sys\n paths = sys.argv[1].split(\",\")\n for path in paths:\n plot(path)\n plt.xlabel(\"Ratio of reads covered by diplotypes threshold\")\n plt.ylabel(\"Motif match percentage\")\n plt.legend()\n\n plt.show()\n", "import numpy as np\nimport offsetbasedgraph as obg\nfrom graph_peak_caller.postprocess.holecleaner import HolesCleaner\nfrom graph_peak_caller.sparsediffs import SparseValues\nimport pytest\n\n\[email protected]\ndef complicated_graph():\n nodes = {i: obg.Block(2) for i in range(1, 11)}\n edges = {1: [2, 3],\n 2: [4],\n 3: [4],\n 4: [5, 6],\n 5: [7],\n 6: [7],\n 7: [8, 9],\n 9: [10]}\n return obg.GraphWithReversals(nodes, edges)\n\n\[email protected]\ndef complicated_offset():\n nodes = {i: obg.Block(2) for i in range(101, 111)}\n edges = {101: [102, 103],\n 102: [104],\n 103: [104],\n 104: [105, 106],\n 105: [107],\n 106: [107],\n 107: [108, 109],\n 109: [110]}\n return obg.GraphWithReversals(nodes, edges)\n\n\[email protected]\ndef small_graph():\n nodes = {i: obg.Block(10) for i in range(101, 107)}\n edges = {101: [102],\n 102: [103, 104],\n 103: [105],\n 104: [105],\n 105: [106]}\n return obg.GraphWithReversals(nodes, edges)\n\n\ndef test_holes_cleaner():\n indices = np.array([80, 100,\n 180, 220,\n 240, 250,\n 300, 400,\n 500, 520,\n 610, 810])\n values = np.array([(i % 2) for i, _ in enumerate(indices)])\n pileup = SparseValues(indices, values)\n graph = obg.GraphWithReversals({i+1: obg.Block(100) for i in range(10)},\n {i: [i+1] for i in range(1, 10)})\n # graph.node_indexes = np.arange(0, 1001, 100)\n holes = HolesCleaner(graph, pileup, 10).run()\n print(holes)\n\n\ndef test_end_hole():\n pileup = SparseValues([0, 5, 10],\n [False, True, False])\n graph = obg.GraphWithReversals(\n {1: obg.Block(12)}, {1: []})\n holes = HolesCleaner(graph, pileup, 4).run()\n assert holes == pileup\n\n\ndef test_long_hole():\n pileup = SparseValues([0, 5, 95],\n [True, False, True])\n graph = obg.GraphWithReversals(\n {i: obg.Block(1) for i in range(1, 101)},\n {i: [i+1] for i in range(1, 100)})\n holes = HolesCleaner(graph, pileup, 56).run()\n assert holes == pileup\n\n\ndef test_complicated(complicated_graph):\n # graph = complicated_graph()\n # \n pileup = SparseValues(\n # 1 1 2--3 4 5---6 7 8\n np.array([0, 1, 2, 4, 6, 8, 10, 12, 14], dtype=\"int\"),\n np.array([1, 0, 1, 0, 1, 0, 1, 0, 1], dtype=\"bool\"))\n holes = HolesCleaner(complicated_graph, pileup, 3).run()\n true = SparseValues([0, 8, 10], [1, 0, 1])\n assert holes == true\n\n\ndef test_offset(complicated_offset):\n pileup = SparseValues(\n # 1 1 2--3 4 5---6 7 8\n np.array([0, 1, 2, 4, 6, 8, 10, 12, 14], dtype=\"int\"),\n np.array([1, 0, 1, 0, 1, 0, 1, 0, 1], dtype=\"bool\"))\n holes = HolesCleaner(complicated_offset, pileup, 3).run()\n true = SparseValues([0, 8, 10], [1, 0, 1])\n assert holes == true\n\n\ndef test_internals():\n graph = obg.GraphWithReversals({101: obg.Block(100)},\n {101: []})\n\n pileup = SparseValues(\n [0, 10, 19, 30, 41, 50],\n [1, 0, 1, 0, 1, 0])\n cleaned = HolesCleaner(graph, pileup, 10).run()\n true = SparseValues(\n [0, 30, 41, 50],\n [1, 0, 1, 0])\n\n assert cleaned == true\n\n\ndef test_touched_edge(small_graph):\n touched_nodes = set([101, 103, 106])\n pileup = SparseValues([0, 4, 22, 28, 56],\n [1, 0, 1, 0, 1])\n cleaned = HolesCleaner(small_graph, pileup, 4, touched_nodes).run()\n assert cleaned == pileup\n\n\n# @pytest.mark.skip\ndef test_non_touched_mid(small_graph):\n touched_nodes = set([101, 102, 103, 104, 105, 106])\n pileup = SparseValues([0, 4, 22, 28, 56],\n [1, 0, 1, 0, 1])\n cleaned = HolesCleaner(small_graph, pileup, 20, touched_nodes).run()\n true = SparseValues([0, 30, 40], [1, 0, 1])\n assert cleaned == true\n\n\nif __name__ == \"__main__\":\n # test_holes_cleaner()\n # test_end_hole()\n test_internals()\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linspace", "numpy.cumsum", "matplotlib.pyplot.xlabel", "numpy.load", "matplotlib.pyplot.show", "numpy.where", "matplotlib.pyplot.ylabel" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
UBCDingXin/cGAN-KD
[ "c32a4b014fe024222101ff11d63de518448f7f8d", "c32a4b014fe024222101ff11d63de518448f7f8d", "c32a4b014fe024222101ff11d63de518448f7f8d", "c32a4b014fe024222101ff11d63de518448f7f8d", "c32a4b014fe024222101ff11d63de518448f7f8d" ]
[ "Tiny-ImageNet/SSKD/cifar.py", "Tiny-ImageNet/cGAN-based_KD/models/shufflenetv2.py", "CIFAR/CIFAR_10K/Distiller/models/cifar10/shufflenetv2.py", "CIFAR/CIFAR_10K/cGAN-based_KD/models/densenet.py", "Tiny-ImageNet/cGAN-based_KD/models/efficientnet.py" ]
[ "from __future__ import print_function\nfrom PIL import Image\nimport os\nimport os.path\nimport numpy as np\nimport sys\n\nimport pickle\nimport torch\nimport torch.utils.data as data\n\nfrom itertools import permutations\n\nclass VisionDataset(data.Dataset):\n _repr_indent = 4\n\n def __init__(self, root, transforms=None, transform=None, target_transform=None):\n if isinstance(root, torch._six.string_classes):\n root = os.path.expanduser(root)\n self.root = root\n\n has_transforms = transforms is not None\n has_separate_transform = transform is not None or target_transform is not None\n if has_transforms and has_separate_transform:\n raise ValueError(\"Only transforms or transform/target_transform can \"\n \"be passed as argument\")\n\n # for backwards-compatibility\n self.transform = transform\n self.target_transform = target_transform\n\n if has_separate_transform:\n transforms = StandardTransform(transform, target_transform)\n self.transforms = transforms\n\n def __getitem__(self, index):\n raise NotImplementedError\n\n def __len__(self):\n raise NotImplementedError\n\n def __repr__(self):\n head = \"Dataset \" + self.__class__.__name__\n body = [\"Number of datapoints: {}\".format(self.__len__())]\n if self.root is not None:\n body.append(\"Root location: {}\".format(self.root))\n body += self.extra_repr().splitlines()\n if self.transforms is not None:\n body += [repr(self.transforms)]\n lines = [head] + [\" \" * self._repr_indent + line for line in body]\n return '\\n'.join(lines)\n\n def _format_transform_repr(self, transform, head):\n lines = transform.__repr__().splitlines()\n return ([\"{}{}\".format(head, lines[0])] +\n [\"{}{}\".format(\" \" * len(head), line) for line in lines[1:]])\n\n def extra_repr(self):\n return \"\"\n\nclass CIFAR10(VisionDataset):\n base_folder = 'cifar-10-batches-py'\n url = \"https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\"\n filename = \"cifar-10-python.tar.gz\"\n tgz_md5 = 'c58f30108f718f92721af3b95e74349a'\n train_list = [\n ['data_batch_1', 'c99cafc152244af753f735de768cd75f'],\n ['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],\n ['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'],\n ['data_batch_4', '634d18415352ddfa80567beed471001a'],\n ['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],\n ]\n\n test_list = [\n ['test_batch', '40351d587109b95175f43aff81a1287e'],\n ]\n meta = {\n 'filename': 'batches.meta',\n 'key': 'label_names',\n 'md5': '5ff9c542aee3614f3951f8cda6e48888',\n }\n\n def __init__(self, root, train=True,\n transform=None, download=False):\n\n super(CIFAR10, self).__init__(root)\n self.transform = transform\n\n self.train = train # training set or test set\n\n if download:\n raise ValueError('cannot download.')\n exit()\n #self.download()\n\n #if not self._check_integrity():\n # raise RuntimeError('Dataset not found or corrupted.' +\n # ' You can use download=True to download it')\n\n if self.train:\n downloaded_list = self.train_list\n else:\n downloaded_list = self.test_list\n\n self.data = []\n self.targets = []\n\n # now load the picked numpy arrays\n for file_name, checksum in downloaded_list:\n file_path = os.path.join(self.root, self.base_folder, file_name)\n with open(file_path, 'rb') as f:\n if sys.version_info[0] == 2:\n entry = pickle.load(f)\n else:\n entry = pickle.load(f, encoding='latin1')\n self.data.append(entry['data'])\n if 'labels' in entry:\n self.targets.extend(entry['labels'])\n else:\n self.targets.extend(entry['fine_labels'])\n\n self.data = np.vstack(self.data).reshape(-1, 3, 32, 32)\n self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC\n\n self._load_meta()\n\n def _load_meta(self):\n path = os.path.join(self.root, self.base_folder, self.meta['filename'])\n #if not check_integrity(path, self.meta['md5']):\n # raise RuntimeError('Dataset metadata file not found or corrupted.' +\n # ' You can use download=True to download it')\n with open(path, 'rb') as infile:\n if sys.version_info[0] == 2:\n data = pickle.load(infile)\n else:\n data = pickle.load(infile, encoding='latin1')\n self.classes = data[self.meta['key']]\n self.class_to_idx = {_class: i for i, _class in enumerate(self.classes)}\n\n def __getitem__(self, index):\n\n img, target = self.data[index], self.targets[index]\n if self.train:\n if np.random.rand() < 0.5:\n img = img[:,::-1,:]\n\n img0 = np.rot90(img, 0).copy()\n img0 = Image.fromarray(img0)\n img0 = self.transform(img0)\n\n img1 = np.rot90(img, 1).copy()\n img1 = Image.fromarray(img1)\n img1 = self.transform(img1)\n\n img2 = np.rot90(img, 2).copy()\n img2 = Image.fromarray(img2)\n img2 = self.transform(img2)\n\n img3 = np.rot90(img, 3).copy()\n img3 = Image.fromarray(img3)\n img3 = self.transform(img3)\n\n img = torch.stack([img0,img1,img2,img3])\n\n return img, target\n\n\n def __len__(self):\n return len(self.data)\n\n def _check_integrity(self):\n root = self.root\n for fentry in (self.train_list + self.test_list):\n filename, md5 = fentry[0], fentry[1]\n fpath = os.path.join(root, self.base_folder, filename)\n if not check_integrity(fpath, md5):\n return False\n return True\n\n def download(self):\n import tarfile\n\n if self._check_integrity():\n print('Files already downloaded and verified')\n return\n\n download_url(self.url, self.root, self.filename, self.tgz_md5)\n\n # extract file\n with tarfile.open(os.path.join(self.root, self.filename), \"r:gz\") as tar:\n tar.extractall(path=self.root)\n\n def extra_repr(self):\n return \"Split: {}\".format(\"Train\" if self.train is True else \"Test\")\n\n\nclass CIFAR100(CIFAR10):\n \"\"\"`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.\n\n This is a subclass of the `CIFAR10` Dataset.\n \"\"\"\n base_folder = 'cifar-100-python'\n url = \"https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz\"\n filename = \"cifar-100-python.tar.gz\"\n tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'\n train_list = [\n ['train', '16019d7e3df5f24257cddd939b257f8d'],\n ]\n\n test_list = [\n ['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],\n ]\n meta = {\n 'filename': 'meta',\n 'key': 'fine_label_names',\n 'md5': '7973b15100ade9c7d40fb424638fde48',\n }\n", "'''ShuffleNetV2 in PyTorch.\nSee the paper \"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design\" for more details.\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ShuffleBlock(nn.Module):\n def __init__(self, groups=2):\n super(ShuffleBlock, self).__init__()\n self.groups = groups\n\n def forward(self, x):\n '''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'''\n N, C, H, W = x.size()\n g = self.groups\n return x.view(N, g, C//g, H, W).permute(0, 2, 1, 3, 4).reshape(N, C, H, W)\n\n\nclass SplitBlock(nn.Module):\n def __init__(self, ratio):\n super(SplitBlock, self).__init__()\n self.ratio = ratio\n\n def forward(self, x):\n c = int(x.size(1) * self.ratio)\n return x[:, :c, :, :], x[:, c:, :, :]\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, in_channels, split_ratio=0.5):\n super(BasicBlock, self).__init__()\n self.split = SplitBlock(split_ratio)\n in_channels = int(in_channels * split_ratio)\n self.conv1 = nn.Conv2d(in_channels, in_channels,\n kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv2 = nn.Conv2d(in_channels, in_channels,\n kernel_size=3, stride=1, padding=1, groups=in_channels, bias=False)\n self.bn2 = nn.BatchNorm2d(in_channels)\n self.conv3 = nn.Conv2d(in_channels, in_channels,\n kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(in_channels)\n self.shuffle = ShuffleBlock()\n\n def forward(self, x):\n x1, x2 = self.split(x)\n out = F.relu(self.bn1(self.conv1(x2)))\n out = self.bn2(self.conv2(out))\n out = F.relu(self.bn3(self.conv3(out)))\n out = torch.cat([x1, out], 1)\n out = self.shuffle(out)\n return out\n\n\nclass DownBlock(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(DownBlock, self).__init__()\n mid_channels = out_channels // 2\n # left\n self.conv1 = nn.Conv2d(in_channels, in_channels,\n kernel_size=3, stride=2, padding=1, groups=in_channels, bias=False)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv2 = nn.Conv2d(in_channels, mid_channels,\n kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(mid_channels)\n # right\n self.conv3 = nn.Conv2d(in_channels, mid_channels,\n kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(mid_channels)\n self.conv4 = nn.Conv2d(mid_channels, mid_channels,\n kernel_size=3, stride=2, padding=1, groups=mid_channels, bias=False)\n self.bn4 = nn.BatchNorm2d(mid_channels)\n self.conv5 = nn.Conv2d(mid_channels, mid_channels,\n kernel_size=1, bias=False)\n self.bn5 = nn.BatchNorm2d(mid_channels)\n\n self.shuffle = ShuffleBlock()\n\n def forward(self, x):\n # left\n out1 = self.bn1(self.conv1(x))\n out1 = F.relu(self.bn2(self.conv2(out1)))\n # right\n out2 = F.relu(self.bn3(self.conv3(x)))\n out2 = self.bn4(self.conv4(out2))\n out2 = F.relu(self.bn5(self.conv5(out2)))\n # concat\n out = torch.cat([out1, out2], 1)\n out = self.shuffle(out)\n return out\n\n\nclass ShuffleNetV2(nn.Module):\n def __init__(self, net_size, num_classes=200):\n super(ShuffleNetV2, self).__init__()\n out_channels = configs[net_size]['out_channels']\n num_blocks = configs[net_size]['num_blocks']\n\n self.conv1 = nn.Conv2d(3, 24, kernel_size=3,\n stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(24)\n self.in_channels = 24\n self.layer1 = self._make_layer(out_channels[0], num_blocks[0])\n self.layer2 = self._make_layer(out_channels[1], num_blocks[1])\n self.layer3 = self._make_layer(out_channels[2], num_blocks[2])\n self.conv2 = nn.Conv2d(out_channels[2], out_channels[3],\n kernel_size=1, stride=1, padding=0, bias=False)\n self.bn2 = nn.BatchNorm2d(out_channels[3])\n self.linear = nn.Linear(out_channels[3], num_classes)\n\n def _make_layer(self, out_channels, num_blocks):\n layers = [DownBlock(self.in_channels, out_channels)]\n for i in range(num_blocks):\n layers.append(BasicBlock(out_channels))\n self.in_channels = out_channels\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = F.max_pool2d(out, 3, stride=2, padding=1) ##add for 64x64 images\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = F.relu(self.bn2(self.conv2(out)))\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\nconfigs = {\n 0.5: {\n 'out_channels': (48, 96, 192, 1024),\n 'num_blocks': (3, 7, 3)\n },\n\n 1: {\n 'out_channels': (116, 232, 464, 1024),\n 'num_blocks': (3, 7, 3)\n },\n 1.5: {\n 'out_channels': (176, 352, 704, 1024),\n 'num_blocks': (3, 7, 3)\n },\n 2: {\n 'out_channels': (224, 488, 976, 2048),\n 'num_blocks': (3, 7, 3)\n }\n}\n\n\ndef shufflenet_v2_x0_5(num_classes=10):\n return ShuffleNetV2(net_size=0.5,num_classes=num_classes)\n\ndef shufflenet_v2_x1_0(num_classes=10):\n return ShuffleNetV2(net_size=1.0,num_classes=num_classes)\n\ndef shufflenet_v2_x1_5(num_classes=10):\n return ShuffleNetV2(net_size=1.5,num_classes=num_classes)\n\ndef shufflenet_v2_x2_0(num_classes=10):\n return ShuffleNetV2(net_size=2.0,num_classes=num_classes)\n\n\nif __name__ == \"__main__\":\n net = shufflenet_v2_x1_0(num_classes=200)\n x = torch.randn(10, 3, 64, 64)\n y = net(x)\n print(y.shape)\n", "'''ShuffleNetV2 in PyTorch.\n\nSee the paper \"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design\" for more details.\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ShuffleBlock(nn.Module):\n def __init__(self, groups=2):\n super(ShuffleBlock, self).__init__()\n self.groups = groups\n\n def forward(self, x):\n '''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'''\n N, C, H, W = x.size()\n g = self.groups\n return x.view(N, g, C//g, H, W).permute(0, 2, 1, 3, 4).reshape(N, C, H, W)\n\n\nclass SplitBlock(nn.Module):\n def __init__(self, ratio):\n super(SplitBlock, self).__init__()\n self.ratio = ratio\n\n def forward(self, x):\n c = int(x.size(1) * self.ratio)\n return x[:, :c, :, :], x[:, c:, :, :]\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, in_channels, split_ratio=0.5):\n super(BasicBlock, self).__init__()\n self.split = SplitBlock(split_ratio)\n in_channels = int(in_channels * split_ratio)\n self.conv1 = nn.Conv2d(in_channels, in_channels,\n kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv2 = nn.Conv2d(in_channels, in_channels,\n kernel_size=3, stride=1, padding=1, groups=in_channels, bias=False)\n self.bn2 = nn.BatchNorm2d(in_channels)\n self.conv3 = nn.Conv2d(in_channels, in_channels,\n kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(in_channels)\n self.shuffle = ShuffleBlock()\n\n def forward(self, x):\n x1, x2 = self.split(x)\n out = F.relu(self.bn1(self.conv1(x2)))\n out = self.bn2(self.conv2(out))\n out = F.relu(self.bn3(self.conv3(out)))\n out = torch.cat([x1, out], 1)\n out = self.shuffle(out)\n return out\n\n\nclass DownBlock(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(DownBlock, self).__init__()\n mid_channels = out_channels // 2\n # left\n self.conv1 = nn.Conv2d(in_channels, in_channels,\n kernel_size=3, stride=2, padding=1, groups=in_channels, bias=False)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv2 = nn.Conv2d(in_channels, mid_channels,\n kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(mid_channels)\n # right\n self.conv3 = nn.Conv2d(in_channels, mid_channels,\n kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(mid_channels)\n self.conv4 = nn.Conv2d(mid_channels, mid_channels,\n kernel_size=3, stride=2, padding=1, groups=mid_channels, bias=False)\n self.bn4 = nn.BatchNorm2d(mid_channels)\n self.conv5 = nn.Conv2d(mid_channels, mid_channels,\n kernel_size=1, bias=False)\n self.bn5 = nn.BatchNorm2d(mid_channels)\n\n self.shuffle = ShuffleBlock()\n\n def forward(self, x):\n # left\n out1 = self.bn1(self.conv1(x))\n out1 = F.relu(self.bn2(self.conv2(out1)))\n # right\n out2 = F.relu(self.bn3(self.conv3(x)))\n out2 = self.bn4(self.conv4(out2))\n out2 = F.relu(self.bn5(self.conv5(out2)))\n # concat\n out = torch.cat([out1, out2], 1)\n out = self.shuffle(out)\n return out\n\n\nclass ShuffleNetV2(nn.Module):\n def __init__(self, net_size=1.0, num_classes=10):\n super(ShuffleNetV2, self).__init__()\n out_channels = configs[net_size]['out_channels']\n num_blocks = configs[net_size]['num_blocks']\n\n self.conv1 = nn.Conv2d(3, 24, kernel_size=3,\n stride=1, padding=1, bias=False)\n self.bn1 = nn.BatchNorm2d(24)\n self.in_channels = 24\n self.layer1 = self._make_layer(out_channels[0], num_blocks[0])\n self.layer2 = self._make_layer(out_channels[1], num_blocks[1])\n self.layer3 = self._make_layer(out_channels[2], num_blocks[2])\n self.conv2 = nn.Conv2d(out_channels[2], out_channels[3],\n kernel_size=1, stride=1, padding=0, bias=False)\n self.bn2 = nn.BatchNorm2d(out_channels[3])\n self.linear = nn.Linear(out_channels[3], num_classes)\n\n def _make_layer(self, out_channels, num_blocks):\n layers = [DownBlock(self.in_channels, out_channels)]\n for i in range(num_blocks):\n layers.append(BasicBlock(out_channels))\n self.in_channels = out_channels\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n # out = F.max_pool2d(out, 3, stride=2, padding=1)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = F.relu(self.bn2(self.conv2(out)))\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\nconfigs = {\n 0.5: {\n 'out_channels': (48, 96, 192, 1024),\n 'num_blocks': (3, 7, 3)\n },\n\n 1: {\n 'out_channels': (116, 232, 464, 1024),\n 'num_blocks': (3, 7, 3)\n },\n 1.5: {\n 'out_channels': (176, 352, 704, 1024),\n 'num_blocks': (3, 7, 3)\n },\n 2: {\n 'out_channels': (224, 488, 976, 2048),\n 'num_blocks': (3, 7, 3)\n }\n}\n\n\ndef test():\n net = ShuffleNetV2(net_size=0.5, num_classes=10)\n x = torch.randn(3, 3, 32, 32)\n y = net(x)\n print(y.shape)\n\n\n# test()\n", "'''DenseNet in PyTorch.'''\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.autograd import Variable\n\nNC=3\nresize = (32,32)\n\n\n\nclass Bottleneck(nn.Module):\n def __init__(self, in_planes, growth_rate):\n super(Bottleneck, self).__init__()\n self.bn1 = nn.BatchNorm2d(in_planes)\n self.conv1 = nn.Conv2d(in_planes, 4*growth_rate, kernel_size=1, bias=False)\n self.bn2 = nn.BatchNorm2d(4*growth_rate)\n self.conv2 = nn.Conv2d(4*growth_rate, growth_rate, kernel_size=3, padding=1, bias=False)\n\n def forward(self, x):\n out = self.conv1(F.relu(self.bn1(x)))\n out = self.conv2(F.relu(self.bn2(out)))\n out = torch.cat([out,x], 1)\n return out\n\n\nclass Transition(nn.Module):\n def __init__(self, in_planes, out_planes):\n super(Transition, self).__init__()\n self.bn = nn.BatchNorm2d(in_planes)\n self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False)\n\n def forward(self, x):\n out = self.conv(F.relu(self.bn(x)))\n out = F.avg_pool2d(out, 2)\n return out\n\n\nclass DenseNet(nn.Module):\n def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10):\n super(DenseNet, self).__init__()\n self.growth_rate = growth_rate\n\n num_planes = 2*growth_rate\n self.conv1 = nn.Conv2d(NC, num_planes, kernel_size=3, padding=1, bias=False)\n\n self.dense1 = self._make_dense_layers(block, num_planes, nblocks[0])\n num_planes += nblocks[0]*growth_rate\n out_planes = int(math.floor(num_planes*reduction))\n self.trans1 = Transition(num_planes, out_planes)\n num_planes = out_planes\n\n self.dense2 = self._make_dense_layers(block, num_planes, nblocks[1])\n num_planes += nblocks[1]*growth_rate\n out_planes = int(math.floor(num_planes*reduction))\n self.trans2 = Transition(num_planes, out_planes)\n num_planes = out_planes\n\n self.dense3 = self._make_dense_layers(block, num_planes, nblocks[2])\n num_planes += nblocks[2]*growth_rate\n out_planes = int(math.floor(num_planes*reduction))\n self.trans3 = Transition(num_planes, out_planes)\n num_planes = out_planes\n\n self.dense4 = self._make_dense_layers(block, num_planes, nblocks[3])\n num_planes += nblocks[3]*growth_rate\n\n self.bn = nn.BatchNorm2d(num_planes)\n self.linear = nn.Linear(num_planes, num_classes)\n\n def _make_dense_layers(self, block, in_planes, nblock):\n layers = []\n for i in range(nblock):\n layers.append(block(in_planes, self.growth_rate))\n in_planes += self.growth_rate\n return nn.Sequential(*layers)\n\n def forward(self, x):\n # x = nn.functional.interpolate(x,size=resize,mode='bilinear',align_corners=True)\n out = self.conv1(x)\n out = self.trans1(self.dense1(out))\n out = self.trans2(self.dense2(out))\n out = self.trans3(self.dense3(out))\n out = self.dense4(out)\n out = F.avg_pool2d(F.relu(self.bn(out)), 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\ndef DenseNet121(num_classes=10):\n return DenseNet(Bottleneck, [6,12,24,16], growth_rate=32, num_classes=num_classes)\n\ndef DenseNet169(num_classes=10):\n return DenseNet(Bottleneck, [6,12,32,32], growth_rate=32, num_classes=num_classes)\n\ndef DenseNet201(num_classes=10):\n return DenseNet(Bottleneck, [6,12,48,32], growth_rate=32, num_classes=num_classes)\n\ndef DenseNet161(num_classes=10):\n return DenseNet(Bottleneck, [6,12,36,24], growth_rate=48, num_classes=num_classes)\n\n\ndef test_densenet():\n net = DenseNet121(num_classes=10)\n x = torch.randn(2,3,32,32)\n y = net(Variable(x))\n print(y.shape)\n\n\nif __name__ == \"__main__\":\n test_densenet()\n", "'''EfficientNet in PyTorch.\nPaper: \"EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks\".\nReference: https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef swish(x):\n return x * x.sigmoid()\n\n\ndef drop_connect(x, drop_ratio):\n keep_ratio = 1.0 - drop_ratio\n mask = torch.empty([x.shape[0], 1, 1, 1], dtype=x.dtype, device=x.device)\n mask.bernoulli_(keep_ratio)\n x.div_(keep_ratio)\n x.mul_(mask)\n return x\n\n\nclass SE(nn.Module):\n '''Squeeze-and-Excitation block with Swish.'''\n\n def __init__(self, in_channels, se_channels):\n super(SE, self).__init__()\n self.se1 = nn.Conv2d(in_channels, se_channels,\n kernel_size=1, bias=True)\n self.se2 = nn.Conv2d(se_channels, in_channels,\n kernel_size=1, bias=True)\n\n def forward(self, x):\n out = F.adaptive_avg_pool2d(x, (1, 1))\n out = swish(self.se1(out))\n out = self.se2(out).sigmoid()\n out = x * out\n return out\n\n\nclass Block(nn.Module):\n '''expansion + depthwise + pointwise + squeeze-excitation'''\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride,\n expand_ratio=1,\n se_ratio=0.,\n drop_rate=0.):\n super(Block, self).__init__()\n self.stride = stride\n self.drop_rate = drop_rate\n self.expand_ratio = expand_ratio\n\n # Expansion\n channels = expand_ratio * in_channels\n self.conv1 = nn.Conv2d(in_channels,\n channels,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False)\n self.bn1 = nn.BatchNorm2d(channels)\n\n # Depthwise conv\n self.conv2 = nn.Conv2d(channels,\n channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=(1 if kernel_size == 3 else 2),\n groups=channels,\n bias=False)\n self.bn2 = nn.BatchNorm2d(channels)\n\n # SE layers\n se_channels = int(in_channels * se_ratio)\n self.se = SE(channels, se_channels)\n\n # Output\n self.conv3 = nn.Conv2d(channels,\n out_channels,\n kernel_size=1,\n stride=1,\n padding=0,\n bias=False)\n self.bn3 = nn.BatchNorm2d(out_channels)\n\n # Skip connection if in and out shapes are the same (MV-V2 style)\n self.has_skip = (stride == 1) and (in_channels == out_channels)\n\n def forward(self, x):\n out = x if self.expand_ratio == 1 else swish(self.bn1(self.conv1(x)))\n out = swish(self.bn2(self.conv2(out)))\n out = self.se(out)\n out = self.bn3(self.conv3(out))\n if self.has_skip:\n if self.training and self.drop_rate > 0:\n out = drop_connect(out, self.drop_rate)\n out = out + x\n return out\n\n\nclass EfficientNet(nn.Module):\n def __init__(self, cfg, num_classes=200):\n super(EfficientNet, self).__init__()\n self.cfg = cfg\n self.conv1 = nn.Conv2d(3,\n 32,\n kernel_size=3,\n stride=1,\n padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(32)\n self.layers = self._make_layers(in_channels=32)\n self.linear = nn.Linear(cfg['out_channels'][-1], num_classes)\n\n def _make_layers(self, in_channels):\n layers = []\n cfg = [self.cfg[k] for k in ['expansion', 'out_channels', 'num_blocks', 'kernel_size',\n 'stride']]\n b = 0\n blocks = sum(self.cfg['num_blocks'])\n for expansion, out_channels, num_blocks, kernel_size, stride in zip(*cfg):\n strides = [stride] + [1] * (num_blocks - 1)\n for stride in strides:\n drop_rate = self.cfg['drop_connect_rate'] * b / blocks\n layers.append(\n Block(in_channels,\n out_channels,\n kernel_size,\n stride,\n expansion,\n se_ratio=0.25,\n drop_rate=drop_rate))\n in_channels = out_channels\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = swish(self.bn1(self.conv1(x)))\n out = self.layers(out)\n out = F.adaptive_avg_pool2d(out, 1)\n out = out.view(out.size(0), -1)\n dropout_rate = self.cfg['dropout_rate']\n if self.training and dropout_rate > 0:\n out = F.dropout(out, p=dropout_rate)\n out = self.linear(out)\n return out\n\n\ndef EfficientNetB0(num_classes=200):\n cfg = {\n 'num_blocks': [1, 2, 2, 3, 3, 4, 1],\n 'expansion': [1, 6, 6, 6, 6, 6, 6],\n 'out_channels': [16, 24, 40, 80, 112, 192, 320],\n 'kernel_size': [3, 3, 5, 3, 5, 5, 3],\n 'stride': [1, 2, 2, 2, 1, 2, 1],\n 'dropout_rate': 0.2,\n 'drop_connect_rate': 0.2,\n }\n return EfficientNet(cfg, num_classes=num_classes)\n\n\ndef test():\n net = EfficientNetB0()\n x = torch.randn(2, 3, 64, 64)\n y = net(x)\n print(y.shape)\n\n\nif __name__ == '__main__':\n test()" ]
[ [ "torch.stack", "numpy.rot90", "numpy.random.rand", "numpy.vstack" ], [ "torch.nn.Sequential", "torch.cat", "torch.randn", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.BatchNorm2d", "torch.nn.functional.max_pool2d" ], [ "torch.nn.Sequential", "torch.cat", "torch.randn", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.BatchNorm2d" ], [ "torch.nn.Sequential", "torch.cat", "torch.randn", "torch.nn.functional.avg_pool2d", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.BatchNorm2d", "torch.autograd.Variable" ], [ "torch.nn.Sequential", "torch.empty", "torch.nn.functional.dropout", "torch.randn", "torch.nn.Conv2d", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.Linear", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
egaebel/diffwave
[ "c5d7d8d90b662f208ecdfba616782559146dc116" ]
[ "src/diffwave/inference.py" ]
[ "# Copyright 2020 LMNT, Inc. 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\nimport numpy as np\nimport os\nimport torch\nimport torchaudio\n\nfrom argparse import ArgumentParser\n\nfrom diffwave.params import AttrDict, params as base_params\nfrom diffwave.model import DiffWave\n\n\nmodels = {}\n\n\ndef load_model(model_dir, device):\n global models\n if os.path.exists(f\"{model_dir}/weights.pt\"):\n checkpoint = torch.load(f\"{model_dir}/weights.pt\", map_location=device)\n else:\n checkpoint = torch.load(model_dir, map_location=device)\n model = DiffWave(AttrDict(base_params)).to(device)\n model.load_state_dict(checkpoint[\"model\"])\n model.eval()\n models[model_dir] = model\n\n\ndef predict(spectrogram, model_dir=None, params=None, device=torch.device(\"cuda\")):\n global models\n # Lazy load model.\n if not model_dir in models:\n load_model(model_dir, device)\n\n model = models[model_dir]\n model.params.override(params)\n with torch.no_grad():\n beta = np.array(model.params.noise_schedule)\n alpha = 1 - beta\n alpha_cum = np.cumprod(alpha)\n\n # Expand rank 2 tensors by adding a batch dimension.\n if len(spectrogram.shape) == 2:\n spectrogram = spectrogram.unsqueeze(0)\n spectrogram = spectrogram.to(device)\n\n audio = torch.randn(\n spectrogram.shape[0],\n model.params.hop_samples * spectrogram.shape[-1],\n device=device,\n )\n noise_scale = torch.from_numpy(alpha_cum ** 0.5).float().unsqueeze(1).to(device)\n\n for n in range(len(alpha) - 1, -1, -1):\n c1 = 1 / alpha[n] ** 0.5\n c2 = beta[n] / (1 - alpha_cum[n]) ** 0.5\n audio = c1 * (\n audio\n - c2\n * model(\n audio, spectrogram, torch.tensor([n], device=audio.device)\n ).squeeze(1)\n )\n if n > 0:\n noise = torch.randn_like(audio)\n sigma = (\n (1.0 - alpha_cum[n - 1]) / (1.0 - alpha_cum[n]) * beta[n]\n ) ** 0.5\n audio += sigma * noise\n audio = torch.clamp(audio, -1.0, 1.0)\n return audio, model.params.sample_rate\n\n\ndef main(args):\n spectrogram = torch.from_numpy(np.load(args.spectrogram_path))\n audio, sr = predict(spectrogram, model_dir=args.model_dir)\n torchaudio.save(args.output, audio.cpu(), sample_rate=sr)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(\n description=\"runs inference on a spectrogram file generated by diffwave.preprocess\"\n )\n parser.add_argument(\n \"model_dir\",\n help=\"directory containing a trained model (or full path to weights.pt file)\",\n )\n parser.add_argument(\n \"spectrogram_path\",\n help=\"path to a spectrogram file generated by diffwave.preprocess\",\n )\n parser.add_argument(\"--output\", \"-o\", default=\"output.wav\", help=\"output file name\")\n main(parser.parse_args())\n" ]
[ [ "torch.randn_like", "torch.load", "torch.randn", "torch.from_numpy", "torch.tensor", "numpy.cumprod", "torch.no_grad", "torch.device", "numpy.load", "torch.clamp", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wietsedv/transformers
[ "5e289f69bc564c94132f77c89a34e5f1dd69a592" ]
[ "transformers/modeling_tf_transfo_xl_utilities.py" ]
[ "# coding=utf-8\n# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. 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\"\"\" A TF 2.0 Adaptive Softmax for Transformer XL model.\n\"\"\"\n\nfrom collections import defaultdict\n\nimport numpy as np\n\nimport tensorflow as tf\n\nfrom .modeling_tf_utils import shape_list\n\nclass TFAdaptiveSoftmaxMask(tf.keras.layers.Layer):\n def __init__(self, vocab_size, d_embed, d_proj, cutoffs, div_val=1,\n keep_order=False, **kwargs):\n super(TFAdaptiveSoftmaxMask, self).__init__(**kwargs)\n\n self.vocab_size = vocab_size\n self.d_embed = d_embed\n self.d_proj = d_proj\n\n self.cutoffs = cutoffs + [vocab_size]\n self.cutoff_ends = [0] + self.cutoffs\n self.div_val = div_val\n\n self.shortlist_size = self.cutoffs[0]\n self.n_clusters = len(self.cutoffs) - 1\n self.head_size = self.shortlist_size + self.n_clusters\n self.keep_order = keep_order\n\n self.out_layers = []\n self.out_projs = []\n\n def build(self, input_shape):\n if self.n_clusters > 0:\n self.cluster_weight = self.add_weight(shape=(self.n_clusters, self.d_embed),\n initializer='zeros',\n trainable=True,\n name='cluster_weight')\n self.cluster_bias = self.add_weight(shape=(self.n_clusters,),\n initializer='zeros',\n trainable=True,\n name='cluster_bias')\n\n if self.div_val == 1:\n for i in range(len(self.cutoffs)):\n if self.d_proj != self.d_embed:\n weight = self.add_weight(shape=(self.d_embed, self.d_proj),\n initializer='zeros',\n trainable=True,\n name='out_projs_._{}'.format(i))\n self.out_projs.append(weight)\n else:\n self.out_projs.append(None)\n weight = self.add_weight(shape=(self.vocab_size, self.d_embed,),\n initializer='zeros',\n trainable=True,\n name='out_layers_._{}_._weight'.format(i))\n bias = self.add_weight(shape=(self.vocab_size,),\n initializer='zeros',\n trainable=True,\n name='out_layers_._{}_._bias'.format(i))\n self.out_layers.append((weight, bias))\n else:\n for i in range(len(self.cutoffs)):\n l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i+1]\n d_emb_i = self.d_embed // (self.div_val ** i)\n\n weight = self.add_weight(shape=(d_emb_i, self.d_proj),\n initializer='zeros',\n trainable=True,\n name='out_projs_._{}'.format(i))\n self.out_projs.append(weight)\n weight = self.add_weight(shape=(r_idx-l_idx, d_emb_i,),\n initializer='zeros',\n trainable=True,\n name='out_layers_._{}_._weight'.format(i))\n bias = self.add_weight(shape=(r_idx-l_idx,),\n initializer='zeros',\n trainable=True,\n name='out_layers_._{}_._bias'.format(i))\n self.out_layers.append((weight, bias))\n super(TFAdaptiveSoftmaxMask, self).build(input_shape)\n\n @staticmethod\n def _logit(x, W, b, proj=None):\n y = x\n if proj is not None:\n y = tf.einsum('ibd,ed->ibe', y, proj)\n return tf.einsum('ibd,nd->ibn', y, W) + b\n\n @staticmethod\n def _gather_logprob(logprob, target):\n lp_size = shape_list(logprob)\n r = tf.range(lp_size[0])\n idx = tf.stack([r, target], 1)\n return tf.gather_nd(logprob, idx)\n\n def call(self, inputs, return_mean=True, training=False):\n hidden, target = inputs\n head_logprob = 0\n if self.n_clusters == 0:\n softmax_b = tf.get_variable('bias', [self.config.vocab_size], initializer=tf.zeros_initializer())\n output = self._logit(hidden, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0])\n if target is not None:\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output)\n out = tf.nn.log_softmax(output, axis=-1)\n else:\n hidden_sizes = shape_list(hidden)\n out = []\n loss = tf.zeros(hidden_sizes[:2], dtype=tf.float32)\n for i in range(len(self.cutoffs)):\n l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]\n if target is not None:\n mask = (target >= l_idx) & (target < r_idx)\n mask_idx = tf.where(mask)\n cur_target = tf.boolean_mask(target, mask) - l_idx\n\n if self.div_val == 1:\n cur_W = self.out_layers[0][0][l_idx:r_idx]\n cur_b = self.out_layers[0][1][l_idx:r_idx]\n else:\n cur_W = self.out_layers[i][0]\n cur_b = self.out_layers[i][1]\n\n if i == 0:\n cur_W = tf.concat([cur_W, self.cluster_weight], 0)\n cur_b = tf.concat([cur_b, self.cluster_bias], 0)\n\n head_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[0])\n head_logprob = tf.nn.log_softmax(head_logit)\n out.append(head_logprob[..., :self.cutoffs[0]])\n if target is not None:\n cur_head_logprob = tf.boolean_mask(head_logprob, mask)\n cur_logprob = self._gather_logprob(cur_head_logprob, cur_target)\n else:\n tail_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[i])\n tail_logprob = tf.nn.log_softmax(tail_logit)\n cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster\n logprob_i = head_logprob[..., cluster_prob_idx, None] + tail_logprob\n out.append(logprob_i)\n if target is not None:\n cur_head_logprob = tf.boolean_mask(head_logprob, mask)\n cur_tail_logprob = tf.boolean_mask(tail_logprob, mask)\n cur_logprob = self._gather_logprob(cur_tail_logprob, cur_target)\n cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]\n if target is not None:\n loss += tf.scatter_nd(mask_idx, -cur_logprob, tf.cast(shape_list(loss), dtype=tf.int64))\n out = tf.concat(out, axis=-1)\n\n if target is not None:\n if return_mean:\n loss = tf.reduce_mean(loss)\n # Add the training-time loss value to the layer using `self.add_loss()`.\n self.add_loss(loss)\n\n # Log the loss as a metric (we could log arbitrary metrics,\n # including different metrics for training and inference.\n self.add_metric(loss, name=self.name, aggregation='mean' if return_mean else '')\n\n return out\n" ]
[ [ "tensorflow.boolean_mask", "tensorflow.concat", "tensorflow.nn.log_softmax", "tensorflow.gather_nd", "tensorflow.range", "tensorflow.zeros", "tensorflow.stack", "tensorflow.reduce_mean", "tensorflow.zeros_initializer", "tensorflow.einsum", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
wentaozhu/deep-mil-for-whole-mammogram-classification
[ "8c046bbd77d268499849319cf57254015778549c", "8c046bbd77d268499849319cf57254015778549c" ]
[ "inbreast.py", "roc_auc.py" ]
[ "#import dicom # some machines not install pydicom\r\nimport scipy.misc\r\nimport numpy as np \r\nfrom sklearn.model_selection import StratifiedKFold\r\nimport cPickle\r\n#import matplotlib\r\n#import matplotlib.pyplot as plt \r\nfrom skimage.filters import threshold_otsu\r\nimport os\r\nfrom os.path import join as join\r\nimport csv\r\nimport scipy.ndimage\r\nimport dicom\r\n#import cv2\r\npath = '../AllDICOMs/'\r\npreprocesspath = '../preprocesspath/'\r\nlabelfile = './label.txt'\r\n\r\ndef readlabel():\r\n '''read the label as a dict from labelfile'''\r\n mydict = {}\r\n with open(labelfile, 'r') as f:\r\n flines = f.readlines()\r\n for line in flines:\r\n data = line.split()\r\n if int(data[1]) == 0:\r\n mydict[data[0]] = int(data[1])\r\n else:\r\n assert(int(data[1])==2 or int(data[1])==1)\r\n mydict[data[0]] = int(data[1])-1\r\n return mydict\r\n\r\ndef readdicom(mydict):\r\n '''read the dicom image, rename it consistently with the name in labels, crop and resize, and save as pickle.\r\n mydict is the returned value of readlabel'''\r\n img_ext = '.dcm'\r\n img_fnames = [x for x in os.listdir(path) if x.endswith(img_ext)]\r\n for f in img_fnames:\r\n names = f.split('_')\r\n if names[0] not in mydict:\r\n print(names[0]+'occur error')\r\n dicom_content = dicom.read_file(join(path,f))\r\n img = dicom_content.pixel_array\r\n '''fig = plt.figure()\r\n ax1 = plt.subplot(3,3,1)\r\n ax2 = plt.subplot(3,3,2)\r\n ax3 = plt.subplot(3,3,3)\r\n ax4 = plt.subplot(3,3,4)\r\n ax5 = plt.subplot(3,3,5)\r\n ax6 = plt.subplot(3,3,6)\r\n ax7 = plt.subplot(3,3,7)\r\n ax8 = plt.subplot(3,3,8)\r\n ax9 = plt.subplot(3,3,9)\r\n ax1.imshow(img, cmap='Greys_r')\r\n ax1.set_title('Original')\r\n ax1.axis('off')'''\r\n \r\n thresh = threshold_otsu(img)\r\n binary = img > thresh\r\n #ax2.imshow(binary, cmap='Greys_r')\r\n #ax2.set_title('mask')\r\n #ax2.axis('off')\r\n \r\n minx, miny = 0, 0\r\n maxx, maxy = img.shape[0], img.shape[1]\r\n for xx in xrange(img.shape[1]):\r\n if sum(binary[xx, :]==0) < binary.shape[1]-60:\r\n minx = xx\r\n break\r\n for xx in xrange(img.shape[0]-1,0,-1):\r\n if sum(binary[xx, :]==0) < binary.shape[1]-60:\r\n maxx = xx\r\n break\r\n if names[3] == 'R':\r\n maxy = img.shape[1]\r\n for yy in xrange(int(img.shape[1]*3.0/4), -1, -1):\r\n if sum(binary[:,yy]==0) > binary.shape[0]-10: \r\n miny = yy\r\n break\r\n else:\r\n miny = 0\r\n for yy in xrange(int(img.shape[1]/4.0), img.shape[1], 1):\r\n if sum(binary[:,yy]==0) > binary.shape[0]-10: \r\n maxy = yy\r\n break\r\n print(minx, maxx, miny, maxy)\r\n #ax3.set_title('Foreground')\r\n #ax3.imshow(img[minx:maxx+1, miny:maxy+1], cmap='Greys_r')\r\n #ax3.axis('off')\r\n \r\n img = img.astype(np.float32)\r\n img1 = scipy.misc.imresize(img[minx:maxx+1, miny:maxy+1], (227, 227), interp='cubic')\r\n with open(join(preprocesspath, names[0])+'227.pickle', 'wb') as outfile:\r\n cPickle.dump(img1, outfile) \r\n img1 = scipy.misc.imresize(img[minx:maxx+1, miny:maxy+1], (299, 299), interp='cubic')\r\n with open(join(preprocesspath, names[0])+'299.pickle', 'wb') as outfile:\r\n cPickle.dump(img1, outfile) \r\n '''ax4.set_title('Resize')\r\n ax4.imshow(img, cmap='Greys_r')\r\n ax4.axis('off')\r\n\r\n img = img.astype(np.float32)\r\n img -= np.mean(img)\r\n img /= np.std(img)\r\n ax5.set_title('Norm')\r\n ax5.imshow(img, cmap='Greys_r')\r\n ax5.axis('off')\r\n with open(join(preprocesspath, names[0])+'norm.pickle', 'wb') as outfile:\r\n cPickle.dump(img, outfile)\r\n #imgshape = img.shape\r\n \r\n img = np.fliplr(img)\r\n ax6.set_title('Flip')\r\n ax6.imshow(img, cmap='Greys_r')\r\n ax6.axis('off')\r\n \r\n num_rot = np.random.choice(4) #rotate 90 randomly\r\n img = np.rot90(img, num_rot)\r\n ax7.set_title('Rotation')\r\n ax7.imshow(img, cmap='Greys_r')\r\n ax7.axis('off')\r\n fig.savefig(join(preprocesspath, names[0])+'.jpg')\r\n plt.close(fig)'''\r\n\r\ndef cvsplit(fold, totalfold, mydict):\r\n '''get the split of train and test\r\n fold is the returned fold th data, from 0 to totalfold-1\r\n total fold is for the cross validation\r\n mydict is the return dict from readlabel'''\r\n skf = StratifiedKFold(n_splits=totalfold) # default shuffle is false, okay!\r\n #readdicom(mydict)\r\n y = mydict.values()\r\n x = mydict.keys()\r\n count = 0\r\n for train, test in skf.split(x,y):\r\n print(len(train), len(test))\r\n if count == fold:\r\n #print test\r\n return train, test\r\n count += 1\r\n\r\ndef cvsplitenhance(fold, totalfold, mydict, valfold=-1):\r\n '''get the split of train and test\r\n fold is the returned fold th data, from 0 to totalfold-1\r\n total fold is for the cross validation\r\n mydict is the return dict from readlabel\r\n sperate the data into train, validation, test'''\r\n skf = StratifiedKFold(n_splits=totalfold) # default shuffle is false, okay!\r\n #readdicom(mydict)\r\n y = mydict.values()\r\n x = mydict.keys()\r\n count = 0\r\n if valfold == -1: \r\n valfold = (fold+1) % totalfold\r\n print('valfold'+str(valfold))\r\n trainls, valls, testls = [], [], []\r\n for train, test in skf.split(x,y):\r\n print(len(train), len(test))\r\n if count == fold:\r\n #print test[:]\r\n testls = test[:]\r\n elif count == valfold:\r\n valls = test[:]\r\n else:\r\n for i in test:\r\n trainls.append(i)\r\n count += 1\r\n return trainls, valls, testls\r\n\r\ndef loadim(fname, preprocesspath=preprocesspath):\r\n ''' from preprocess path load fname\r\n fname file name in preprocesspath\r\n aug is true, we augment im fliplr, rot 4'''\r\n ims = []\r\n with open(join(preprocesspath, fname), 'rb') as inputfile:\r\n im = cPickle.load(inputfile)\r\n #up_bound = np.random.choice(174) #zero out square\r\n #right_bound = np.random.choice(174)\r\n img = im\r\n #img[up_bound:(up_bound+50), right_bound:(right_bound+50)] = 0.0\r\n ims.append(img)\r\n inputfile.close()\r\n return ims\r\n\r\ndef loaddata(fold, totalfold, usedream=True, aug=True):\r\n '''get the fold th train and test data from inbreast\r\n fold is the returned fold th data, from 0 to totalfold-1\r\n total fold is for the cross validation'''\r\n mydict = readlabel()\r\n mydictkey = mydict.keys()\r\n mydictvalue = mydict.values()\r\n trainindex, testindex = cvsplit(fold, totalfold, mydict)\r\n if aug == True:\r\n traindata, trainlabel = np.zeros((6*len(trainindex),227,227)), np.zeros((6*len(trainindex),))\r\n else:\r\n traindata, trainlabel = np.zeros((len(trainindex),227,227)), np.zeros((len(trainindex),))\r\n testdata, testlabel = np.zeros((len(testindex),227,227)), np.zeros((len(testindex),))\r\n traincount = 0\r\n for i in xrange(len(trainindex)):\r\n ims = loadim(mydictkey[trainindex[i]]+'.pickle', aug=aug)\r\n for im in ims:\r\n traindata[traincount, :, :] = im\r\n trainlabel[traincount] = mydictvalue[trainindex[i]]\r\n traincount += 1\r\n assert(traincount==traindata.shape[0])\r\n testcount = 0\r\n for i in xrange(len(testindex)):\r\n ims = loadim(mydictkey[testindex[i]]+'.pickle', aug=aug)\r\n testdata[testcount,:,:] = ims[0]\r\n testlabel[testcount] = mydictvalue[testindex[i]]\r\n testcount += 1\r\n assert(testcount==testdata.shape[0])\r\n if usedream:\r\n outx, outy = extractdreamdata()\r\n traindata = np.concatenate((traindata,outx), axis=0)\r\n trainlabel = np.concatenate((trainlabel,outy), axis=0)\r\n return traindata, trainlabel, testdata, testlabel\r\n\r\ndef loaddataenhance(fold, totalfold, valfold=-1, valnum=60):\r\n '''get the fold th train and test data from inbreast\r\n fold is the returned fold th data, from 0 to totalfold-1\r\n total fold is for the cross validation'''\r\n mydict = readlabel()\r\n mydictkey = mydict.keys()\r\n mydictvalue = mydict.values()\r\n trainindex, valindex, testindex = cvsplitenhance(fold, totalfold, mydict, valfold=valfold)\r\n traindata, trainlabel = np.zeros((len(trainindex),227,227)), np.zeros((len(trainindex),))\r\n valdata, vallabel = np.zeros((len(valindex),227,227)), np.zeros((len(valindex),))\r\n testdata, testlabel = np.zeros((len(testindex),227,227)), np.zeros((len(testindex),))\r\n traincount = 0\r\n for i in xrange(len(trainindex)):\r\n ims = loadim(mydictkey[trainindex[i]]+'227.pickle')\r\n for im in ims:\r\n traindata[traincount, :, :] = im\r\n trainlabel[traincount] = int(mydictvalue[trainindex[i]])\r\n traincount += 1\r\n assert(traincount==traindata.shape[0])\r\n valcount = 0\r\n for i in xrange(len(valindex)):\r\n ims = loadim(mydictkey[valindex[i]]+'227.pickle')\r\n valdata[valcount,:,:] = ims[0]\r\n vallabel[valcount] = int(mydictvalue[valindex[i]])\r\n valcount += 1\r\n assert(valcount==valdata.shape[0])\r\n testcount = 0\r\n for i in xrange(len(testindex)):\r\n #print mydictkey[testindex[i]]\r\n ims = loadim(mydictkey[testindex[i]]+'227.pickle')\r\n testdata[testcount,:,:] = ims[0]\r\n testlabel[testcount] = int(mydictvalue[testindex[i]])\r\n testcount += 1\r\n assert(testcount==testdata.shape[0])\r\n #print(valdata.shape)\r\n randindex = np.random.permutation(valdata.shape[0])\r\n valdata = valdata[randindex,:,:]\r\n vallabel = vallabel[randindex]\r\n #print(valdata.shape)\r\n traindata = np.concatenate((traindata, valdata[valnum:,:,:]), axis=0)\r\n trainlabel = np.concatenate((trainlabel, vallabel[valnum:]), axis=0)\r\n valdata = valdata[:valnum,:,:]\r\n vallabel = vallabel[:valnum]\r\n maxvalue = (traindata.max()*1.0)\r\n print('inbreast max %f', maxvalue)\r\n traindata = traindata / maxvalue\r\n valdata = valdata / maxvalue\r\n testdata = testdata / maxvalue\r\n print('train data feature')\r\n #meanx = traindata.mean()\r\n #stdx = traindata.std()\r\n #traindata -= meanx\r\n #traindata /= stdx\r\n #valdata -= meanx\r\n #valdata /= stdx\r\n #testdata -= meanx\r\n #testdata /= stdx\r\n print(traindata.mean(), traindata.std(), traindata.max(), traindata.min())\r\n print('val data feature')\r\n print(valdata.mean(), valdata.std(), valdata.max(), valdata.min())\r\n print('test data feature')\r\n print(testdata.mean(), testdata.std(), testdata.max(), testdata.min())\r\n #meandata = traindata.mean()\r\n #stddata = traindata.std()\r\n #traindata = traindata - meandata\r\n #traindata = traindata / stddata\r\n #valdata = valdata - meandata\r\n #valdata = valdata / stddata\r\n #testdata = testdata - meandata\r\n #testdata = testdata / stddata\r\n return traindata, trainlabel, valdata, vallabel, testdata, testlabel\r\n\r\nif __name__ == '__main__':\r\n traindata, trainlabel, testdata, testlabel = loaddata(0, 5)\r\n print(sum(trainlabel), sum(testlabel))\r\n\r\n traindata, trainlabel, valdata, vallabel, testdata, testlabel = loaddataenhance(0, 5)\r\n print(sum(trainlabel), sum(vallabel), sum(testlabel))\r\n", "\"\"\"\r\nTrainExtension subclass for calculating ROC AUC scores on monitoring\r\ndataset(s), reported via monitor channels.\r\n\"\"\"\r\n\r\n__author__ = \"Steven Kearnes\"\r\n__copyright__ = \"Copyright 2014, Stanford University\"\r\n__license__ = \"3-clause BSD\"\r\n\r\nimport numpy as np\r\ntry:\r\n from sklearn.metrics import roc_auc_score, roc_curve\r\nexcept ImportError:\r\n roc_auc_score = None\r\nimport logging\r\nimport theano\r\nfrom theano import gof, config\r\nfrom theano import tensor as T\r\nfrom keras.callbacks import Callback\r\nimport os\r\n#from pylearn2.train_extensions import TrainExtension\r\n\r\nclass AUCEpoch(Callback):\r\n def __init__(self, filepath, validation_data=(), interval=1, mymil=False):\r\n super(Callback, self).__init__()\r\n self.interval = interval\r\n self.auc = 0\r\n self.X_val, self.y_val = validation_data\r\n self.filepath = filepath\r\n self.mymil = mymil\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.interval == 0:\r\n y_pred = self.model.predict(self.X_val, verbose=0)\r\n #print(np.sum(y_pred[:,1]))\r\n #y_true = np.argmax(self.y_val, axis=1)\r\n #y_pred = np.argmax(y_pred, axis=1)\r\n #print(y_true.shape, y_pred.shape)\r\n if self.mymil:\r\n score = roc_auc_score(self.y_val.max(axis=1), y_pred.max(axis=1)) \r\n else: score = roc_auc_score(self.y_val[:,1], y_pred[:,1])\r\n print(\"interval evaluation - epoch: {:d} - auc: {:.2f}\".format(epoch, score))\r\n if score > self.auc:\r\n self.auc = score\r\n for f in os.listdir('./'):\r\n if f.startswith(self.filepath+'auc'):\r\n os.remove(f)\r\n self.model.save(self.filepath+'auc'+str(score)+'ep'+str(epoch)+'.hdf5')\r\n\r\nclass RocAucScoreOp(gof.Op):\r\n \"\"\"\r\n Theano Op wrapping sklearn.metrics.roc_auc_score.\r\n\r\n Parameters\r\n ----------\r\n name : str, optional (default 'roc_auc')\r\n Name of this Op.\r\n use_c_code : WRITEME\r\n \"\"\"\r\n def __init__(self, name='roc_auc', use_c_code=theano.config.cxx):\r\n super(RocAucScoreOp, self).__init__(use_c_code)\r\n self.name = name\r\n\r\n def make_node(self, y_true, y_score):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n y_true : tensor_like\r\n Target class labels.\r\n y_score : tensor_like\r\n Predicted class labels or probabilities for positive class.\r\n \"\"\"\r\n y_true = T.as_tensor_variable(y_true)\r\n y_score = T.as_tensor_variable(y_score)\r\n output = [T.vector(name=self.name, dtype=config.floatX)]\r\n return gof.Apply(self, [y_true, y_score], output)\r\n\r\n def perform(self, node, inputs, output_storage):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n node : Apply instance\r\n Symbolic inputs and outputs.\r\n inputs : list\r\n Sequence of inputs.\r\n output_storage : list\r\n List of mutable 1-element lists.\r\n \"\"\"\r\n if roc_auc_score is None:\r\n raise RuntimeError(\"Could not import from sklearn.\")\r\n y_true, y_score = inputs\r\n try:\r\n roc_auc = roc_auc_score(y_true, y_score)\r\n except ValueError:\r\n roc_auc = np.nan\r\n #rvalue = np.array((roc_auc, prec, reca, f1))\r\n #[0][0]\r\n output_storage[0][0] = theano._asarray(roc_auc, dtype=config.floatX)\r\n\r\nclass PrecisionEpoch(Callback):\r\n def __init__(self, filepath, validation_data=(), interval=1, mymil=False):\r\n super(Callback, self).__init__()\r\n self.interval = interval\r\n self.prec = 0\r\n self.X_val, self.y_val = validation_data\r\n self.filepath = filepath\r\n self.mymil = mymil\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.interval == 0:\r\n y_pred = self.model.predict(self.X_val, verbose=0)\r\n if self.mymil:\r\n y_true = self.y_val.max(axis=1)\r\n y_score = y_pred.max(axis=1)>0.5\r\n else:\r\n y_true = np.argmax(self.y_val, axis=1)\r\n y_score = np.argmax(y_pred, axis=1)\r\n #print(type(y_true), y_true.shape, type(y_score), y_score.shape)\r\n #print(y_score, y_true)\r\n TP = np.sum(y_true[y_score==1]==1)*1. #/ sum(y_true)\r\n FP = np.sum(y_true[y_score==1]==0)*1. #/ (y_true.shape[0]-sum(y_true))\r\n prec = TP / (TP+FP+1e-6)\r\n print(\"interval evaluation - epoch: {:d} - prec: {:.2f}\".format(epoch, prec))\r\n if prec > self.prec:\r\n self.prec = prec\r\n for f in os.listdir('./'):\r\n if f.startswith(self.filepath+'prec'):\r\n os.remove(f)\r\n self.model.save(self.filepath+'prec'+str(prec)+'ep'+str(epoch)+'.hdf5')\r\n\r\nclass PrecisionOp(gof.Op):\r\n \"\"\"\r\n Theano Op wrapping sklearn.metrics.roc_auc_score.\r\n\r\n Parameters\r\n ----------\r\n name : str, optional (default 'roc_auc')\r\n Name of this Op.\r\n use_c_code : WRITEME\r\n \"\"\"\r\n def __init__(self, name='precision', use_c_code=theano.config.cxx):\r\n super(PrecisionOp, self).__init__(use_c_code)\r\n self.name = name\r\n\r\n def make_node(self, y_true, y_score):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n y_true : tensor_like\r\n Target class labels.\r\n y_score : tensor_like\r\n Predicted class labels or probabilities for positive class.\r\n \"\"\"\r\n y_true = T.as_tensor_variable(y_true)\r\n y_score = T.as_tensor_variable(y_score)\r\n output = [T.vector(name=self.name, dtype=config.floatX)]\r\n return gof.Apply(self, [y_true, y_score], output)\r\n\r\n def perform(self, node, inputs, output_storage):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n node : Apply instance\r\n Symbolic inputs and outputs.\r\n inputs : list\r\n Sequence of inputs.\r\n output_storage : list\r\n List of mutable 1-element lists.\r\n \"\"\"\r\n if roc_auc_score is None:\r\n raise RuntimeError(\"Could not import from sklearn.\")\r\n y_true, y_score = inputs\r\n print(y_true.shape)\r\n y_true = np.argmax(y_true, axis=1)\r\n y_score = np.argmax(y_score, axis=1)\r\n #print(type(y_true), y_true.shape, type(y_score), y_score.shape)\r\n try:\r\n TP = np.sum(y_true[y_score==1]==1)*1. #/ sum(y_true)\r\n FP = np.sum(y_true[y_score==1]==0)*1. #/ (y_true.shape[0]-sum(y_true))\r\n prec = TP / (TP+FP+1e-6)\r\n except ValueError:\r\n prec = np.nan\r\n #rvalue = np.array((roc_auc, prec, reca, f1))\r\n #[0][0]\r\n output_storage[0][0] = theano._asarray(prec, dtype=config.floatX)\r\n\r\nclass RecallEpoch(Callback):\r\n def __init__(self, filepath, validation_data=(), interval=1, mymil=False):\r\n super(Callback, self).__init__()\r\n self.interval = interval\r\n self.filepath = filepath\r\n self.reca = 0\r\n self.X_val, self.y_val = validation_data\r\n self.mymil = mymil\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.interval == 0:\r\n y_pred = self.model.predict(self.X_val, verbose=0)\r\n if self.mymil:\r\n y_true = self.y_val.max(axis=1)\r\n y_score = y_pred.max(axis=1)>0.5\r\n else:\r\n y_true = np.argmax(self.y_val, axis=1)\r\n y_score = np.argmax(y_pred, axis=1)\r\n #print(type(y_true), y_true.shape, type(y_score), y_score.shape)\r\n TP = np.sum(y_true[y_score==1]==1)*1. #/ sum(y_true)\r\n FN = np.sum(y_true[y_score==0]==1)*1. #/ sum(y_true)\r\n reca = TP / (TP+FN+1e-6)\r\n print(\"interval evaluation - epoch: {:d} - reca: {:.2f}\".format(epoch, reca))\r\n if reca > self.reca:\r\n self.reca = reca\r\n for f in os.listdir('./'):\r\n if f.startswith(self.filepath+'reca'):\r\n os.remove(f)\r\n self.model.save(self.filepath+'reca'+str(reca)+'ep'+str(epoch)+'.hdf5')\r\n\r\nclass RecallOp(gof.Op):\r\n \"\"\"\r\n Theano Op wrapping sklearn.metrics.roc_auc_score.\r\n\r\n Parameters\r\n ----------\r\n name : str, optional (default 'roc_auc')\r\n Name of this Op.\r\n use_c_code : WRITEME\r\n \"\"\"\r\n def __init__(self, name='recall', use_c_code=theano.config.cxx):\r\n super(RecallOp, self).__init__(use_c_code)\r\n self.name = name\r\n\r\n def make_node(self, y_true, y_score):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n y_true : tensor_like\r\n Target class labels.\r\n y_score : tensor_like\r\n Predicted class labels or probabilities for positive class.\r\n \"\"\"\r\n y_true = T.as_tensor_variable(y_true)\r\n y_score = T.as_tensor_variable(y_score)\r\n output = [T.vector(name=self.name, dtype=config.floatX)]\r\n return gof.Apply(self, [y_true, y_score], output)\r\n\r\n def perform(self, node, inputs, output_storage):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n node : Apply instance\r\n Symbolic inputs and outputs.\r\n inputs : list\r\n Sequence of inputs.\r\n output_storage : list\r\n List of mutable 1-element lists.\r\n \"\"\"\r\n if roc_auc_score is None:\r\n raise RuntimeError(\"Could not import from sklearn.\")\r\n y_true, y_score = inputs\r\n y_true = np.argmax(y_true, axis=1)\r\n y_score = np.argmax(y_score, axis=1)\r\n try:\r\n TP = np.sum(y_true[y_score==1]==1)*1. #/ sum(y_true)\r\n FN = np.sum(y_true[y_score==0]==1)*1. #/ sum(y_true)\r\n reca = TP / (TP+FN+1e-6)\r\n except ValueError:\r\n reca = np.nan\r\n #rvalue = np.array((roc_auc, prec, reca, f1))\r\n #[0][0]\r\n output_storage[0][0] = theano._asarray(reca, dtype=config.floatX)\r\n\r\nclass F1Epoch(Callback):\r\n def __init__(self, filepath, validation_data=(), interval=1, mymil=False):\r\n super(Callback, self).__init__()\r\n self.interval = interval\r\n self.filepath = filepath\r\n self.f1 = 0\r\n self.X_val, self.y_val = validation_data\r\n self.mymil = mymil\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.interval == 0:\r\n y_pred = self.model.predict(self.X_val, verbose=0)\r\n #print(y_pred.shape)\r\n if self.mymil:\r\n y_true = self.y_val.max(axis=1)\r\n y_score = y_pred.max(axis=1)>0.5\r\n else:\r\n y_true = np.argmax(self.y_val, axis=1)\r\n y_score = np.argmax(y_pred, axis=1)\r\n #print(type(y_true), y_true.shape, type(y_score), y_score.shape)\r\n TP = np.sum(y_true[y_score==1]==1)*1. #/ sum(y_true)\r\n FP = np.sum(y_true[y_score==1]==0)*1. #/ (y_true.shape[0]-sum(y_true))\r\n #TN = np.sum(truey[predy==0]==0)*1. / (truey.shape[0]-sum(truey))\r\n FN = np.sum(y_true[y_score==0]==1)*1. #/ sum(y_true)\r\n #prec = TP / (TP+FP+1e-6)\r\n #reca = TP / (TP+FN+1e-6)\r\n #f1 = 2*prec*reca / (prec+reca+1e-6)\r\n f1 = 2*TP / (2*TP + FP + FN+1e-6)\r\n print(\"interval evaluation - epoch: {:d} - f1: {:.2f}\".format(epoch, f1))\r\n if f1 > self.f1:\r\n self.f1 = f1\r\n for f in os.listdir('./'):\r\n if f.startswith(self.filepath+'f1'):\r\n os.remove(f)\r\n self.model.save(self.filepath+'f1'+str(f1)+'ep'+str(epoch)+'.hdf5')\r\n\r\nclass ACCEpoch(Callback):\r\n def __init__(self, filepath, validation_data=(), interval=1, mymil=False):\r\n super(Callback, self).__init__()\r\n self.interval = interval\r\n self.filepath = filepath\r\n self.acc = 0\r\n self.X_val, self.y_val = validation_data\r\n self.mymil = mymil\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.interval == 0:\r\n y_pred = self.model.predict(self.X_val, verbose=0)\r\n #print(y_pred.shape)\r\n if self.mymil:\r\n y_true = self.y_val.max(axis=1)\r\n y_score = y_pred.max(axis=1)#>0.5\r\n else:\r\n y_true = self.y_val[:,1] #np.argmax(self.y_val, axis=1)\r\n y_score = y_pred[:,1] #np.argmax(y_pred, axis=1)\r\n sortindex = np.argsort(y_score)\r\n y_score = y_score[sortindex]\r\n y_true = y_true[sortindex]\r\n bestacc, bestthresh = np.mean(y_true == np.ones_like(y_true)), y_score[0]-0.001\r\n for thresh in y_score:\r\n acc = np.mean(y_true == (y_score>thresh))\r\n if acc > bestacc:\r\n bestacc, bestthresh = acc, thresh\r\n y_score = y_score>bestthresh\r\n #y_score = y_score >0.5\r\n acc = np.mean(y_true == y_score)\r\n assert(acc == bestacc)\r\n print(\"interval evaluation - epoch: {:d} - acc: {:.2f}\".format(epoch, acc))\r\n if acc > self.acc:\r\n self.acc = acc\r\n for f in os.listdir('./'):\r\n if f.startswith(self.filepath+'acc'):\r\n os.remove(f)\r\n self.model.save(self.filepath+'acc'+str(acc)+'ep'+str(epoch)+'.hdf5')\r\n\r\nclass LossEpoch(Callback):\r\n def __init__(self, filepath, validation_data=(), interval=1, mymil=False):\r\n super(Callback, self).__init__()\r\n self.interval = interval\r\n self.filepath = filepath\r\n self.loss = 1e6\r\n self.X_val, self.y_val = validation_data\r\n self.mymil = mymil\r\n def on_epoch_end(self, epoch, logs={}):\r\n if epoch % self.interval == 0:\r\n y_pred = self.model.predict(self.X_val, verbose=0)\r\n #print(y_pred.shape)\r\n if self.mymil:\r\n y_true = self.y_val.max(axis=1)\r\n y_score = y_pred.max(axis=1)>0.5\r\n else:\r\n y_true = np.argmax(self.y_val, axis=1)\r\n y_score = y_pred[np.arange(len(y_true)), y_true] #y_pred[:, y_true] #np.argmax(y_pred, axis=1)\r\n loss = -np.mean(np.log(y_score+1e-6)) #-np.mean(y_true*np.log(y_score+1e-6) + (1-y_true)*np.log(1-y_score+1e-6))\r\n print('')\r\n print(\"interval evaluation - epoch: {:d} - loss: {:.2f}\".format(epoch, loss))\r\n if loss < self.loss:\r\n self.loss = loss\r\n for f in os.listdir('./'):\r\n if f.startswith(self.filepath+'loss'):\r\n os.remove(f)\r\n self.model.save(self.filepath+'loss'+str(loss)+'ep'+str(epoch)+'.hdf5')\r\n\r\nclass F1Op(gof.Op):\r\n \"\"\"\r\n Theano Op wrapping sklearn.metrics.roc_auc_score.\r\n\r\n Parameters\r\n ----------\r\n name : str, optional (default 'roc_auc')\r\n Name of this Op.\r\n use_c_code : WRITEME\r\n \"\"\"\r\n def __init__(self, name='f1', use_c_code=theano.config.cxx):\r\n super(F1Op, self).__init__(use_c_code)\r\n self.name = name\r\n\r\n def make_node(self, y_true, y_score):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n y_true : tensor_like\r\n Target class labels.\r\n y_score : tensor_like\r\n Predicted class labels or probabilities for positive class.\r\n \"\"\"\r\n y_true = T.as_tensor_variable(y_true)\r\n y_score = T.as_tensor_variable(y_score)\r\n output = [T.vector(name=self.name, dtype=config.floatX)]\r\n return gof.Apply(self, [y_true, y_score], output)\r\n\r\n def perform(self, node, inputs, output_storage):\r\n \"\"\"\r\n Calculate ROC AUC score.\r\n\r\n Parameters\r\n ----------\r\n node : Apply instance\r\n Symbolic inputs and outputs.\r\n inputs : list\r\n Sequence of inputs.\r\n output_storage : list\r\n List of mutable 1-element lists.\r\n \"\"\"\r\n if roc_auc_score is None:\r\n raise RuntimeError(\"Could not import from sklearn.\")\r\n y_true, y_score = inputs\r\n y_true = np.argmax(y_true, axis=1)\r\n y_score = np.argmax(y_score, axis=1)\r\n try:\r\n TP = np.sum(y_true[y_score==1]==1)*1. #/ sum(y_true)\r\n FP = np.sum(y_true[y_score==1]==0)*1. #/ (y_true.shape[0]-sum(y_true))\r\n #TN = np.sum(truey[predy==0]==0)*1. / (truey.shape[0]-sum(truey))\r\n FN = np.sum(y_true[y_score==0]==1)*1. #/ sum(y_true)\r\n #prec = TP / (TP+FP+1e-6)\r\n #reca = TP / (TP+FN+1e-6)\r\n #f1 = 2*prec*reca / (prec+reca+1e-6)\r\n f1 = 2*TP / (2*TP +FP +FN)\r\n except ValueError:\r\n f1 = np.nan\r\n #rvalue = np.array((roc_auc, prec, reca, f1))\r\n #[0][0]\r\n output_storage[0][0] = theano._asarray(f1, dtype=config.floatX)\r\n'''class RocAucChannel(TrainExtension):\r\n \"\"\"\r\n Adds a ROC AUC channel to the monitor for each monitoring dataset.\r\n\r\n This monitor will return nan unless both classes are represented in\r\n y_true. For this reason, it is recommended to set monitoring_batches\r\n to 1, especially when using unbalanced datasets.\r\n\r\n Parameters\r\n ----------\r\n channel_name_suffix : str, optional (default 'roc_auc')\r\n Channel name suffix.\r\n positive_class_index : int, optional (default 1)\r\n Index of positive class in predicted values.\r\n negative_class_index : int or None, optional (default None)\r\n Index of negative class in predicted values for calculation of\r\n one vs. one performance. If None, uses all examples not in the\r\n positive class (one vs. the rest).\r\n \"\"\"\r\n def __init__(self, channel_name_suffix='roc_auc', positive_class_index=1,\r\n negative_class_index=None):\r\n self.channel_name_suffix = channel_name_suffix\r\n self.positive_class_index = positive_class_index\r\n self.negative_class_index = negative_class_index\r\n\r\n def setup(self, model, dataset, algorithm):\r\n \"\"\"\r\n Add ROC AUC channels for monitoring dataset(s) to model.monitor.\r\n\r\n Parameters\r\n ----------\r\n model : object\r\n The model being trained.\r\n dataset : object\r\n Training dataset.\r\n algorithm : object\r\n Training algorithm.\r\n \"\"\"\r\n m_space, m_source = model.get_monitoring_data_specs()\r\n state, target = m_space.make_theano_batch()\r\n\r\n y = T.argmax(target, axis=1)\r\n y_hat = model.fprop(state)[:, self.positive_class_index]\r\n\r\n # one vs. the rest\r\n if self.negative_class_index is None:\r\n y = T.eq(y, self.positive_class_index)\r\n\r\n # one vs. one\r\n else:\r\n pos = T.eq(y, self.positive_class_index)\r\n neg = T.eq(y, self.negative_class_index)\r\n keep = T.add(pos, neg).nonzero()\r\n y = T.eq(y[keep], self.positive_class_index)\r\n y_hat = y_hat[keep]\r\n\r\n roc_auc = RocAucScoreOp(self.channel_name_suffix)(y, y_hat)\r\n roc_auc = T.cast(roc_auc, config.floatX)\r\n for dataset_name, dataset in algorithm.monitoring_dataset.items():\r\n if dataset_name:\r\n channel_name = '{0}_{1}'.format(dataset_name,\r\n self.channel_name_suffix)\r\n else:\r\n channel_name = self.channel_name_suffix\r\n model.monitor.add_channel(name=channel_name,\r\n ipt=(state, target),\r\n val=roc_auc,\r\n data_specs=(m_space, m_source),\r\n dataset=dataset)'''" ]
[ [ "numpy.concatenate", "numpy.random.permutation", "sklearn.model_selection.StratifiedKFold" ], [ "sklearn.metrics.roc_auc_score", "numpy.log", "numpy.ones_like", "numpy.argmax", "numpy.mean", "numpy.argsort", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mv1388/AIToolbox
[ "1060435e6cbdfd19abcb726c4080b663536b7467", "1060435e6cbdfd19abcb726c4080b663536b7467", "1060435e6cbdfd19abcb726c4080b663536b7467" ]
[ "tests_gpu/test_multi_gpu/test_core_pytorch_compare/test_ddp/test_mnist_cnn.py", "aitoolbox/experiment/local_load/local_model_load.py", "aitoolbox/nlp/experiment_evaluation/NLP_metrics.py" ]
[ "import unittest\n\nimport os\nimport shutil\nimport random\nimport pickle\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\n\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.utils.data.distributed import DistributedSampler\n\nfrom aitoolbox import TrainLoop, TTModel\nfrom tests_gpu.test_multi_gpu.ddp_prediction_saver import DDPPredictionSave\n\nTHIS_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nclass CNNNet(TTModel):\n def __init__(self):\n super(CNNNet, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n def get_loss(self, batch_data, criterion, device):\n data, target = batch_data\n data, target = data.to(device), target.to(device)\n\n output = self(data)\n loss = criterion(output, target)\n\n return loss\n\n def get_predictions(self, batch_data, device):\n data, y_test = batch_data\n data = data.to(device)\n\n output = self(data)\n y_pred = output.argmax(dim=1, keepdim=False)\n\n return y_pred.cpu(), y_test, {}\n\n\nclass TestMNISTCNN(unittest.TestCase):\n def test_trainloop_core_pytorch_compare(self):\n os.mkdir(f'{THIS_DIR}/ddp_cnn_save')\n\n val_loss_tl, y_pred_tl, y_true_tl = self.train_eval_trainloop(num_epochs=5, use_real_train_data=True)\n val_loss_pt, y_pred_pt, y_true_pt = self.train_eval_core_pytorch(num_epochs=5, use_real_train_data=True)\n\n self.assertAlmostEqual(val_loss_tl, val_loss_pt, places=8)\n self.assertEqual(y_pred_tl, y_pred_pt)\n self.assertEqual(y_true_tl, y_true_pt)\n\n project_path = os.path.join(THIS_DIR, 'ddp_cnn_save')\n if os.path.exists(project_path):\n shutil.rmtree(project_path)\n project_path = os.path.join(THIS_DIR, 'data')\n if os.path.exists(project_path):\n shutil.rmtree(project_path)\n\n def train_eval_trainloop(self, num_epochs, use_real_train_data=False):\n self.set_seeds()\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(THIS_DIR, 'data'), train=use_real_train_data, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=100, shuffle=True)\n val_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(THIS_DIR, 'data'), train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=100)\n\n model = CNNNet()\n optimizer = optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999))\n criterion = nn.NLLLoss()\n\n print('Starting train loop')\n tl = TrainLoop(\n model,\n train_loader, val_loader, None,\n optimizer, criterion,\n gpu_mode='ddp'\n )\n self.assertEqual(tl.device.type, \"cuda\")\n\n tl.fit(num_epochs=num_epochs,\n callbacks=[DDPPredictionSave(dir_path=f'{THIS_DIR}/ddp_cnn_save',\n file_name='tl_ddp_predictions.p')])\n\n with open(f'{THIS_DIR}/ddp_cnn_save/tl_ddp_predictions.p', 'rb') as f:\n val_loss, y_pred, y_true = pickle.load(f)\n\n return val_loss, y_pred, y_true\n\n def train_eval_core_pytorch(self, num_epochs, use_real_train_data=False):\n self.set_seeds()\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(THIS_DIR, 'data'), train=use_real_train_data, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=100)\n val_loader = torch.utils.data.DataLoader(\n datasets.MNIST(os.path.join(THIS_DIR, 'data'), train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=100)\n\n model_pt = CNNNet()\n optimizer_pt = optim.Adam(model_pt.parameters(), lr=0.001, betas=(0.9, 0.999))\n criterion_pt = nn.NLLLoss()\n\n os.environ['MASTER_ADDR'] = 'localhost'\n os.environ['MASTER_PORT'] = '8888'\n\n print('Starting the manual DDP training')\n\n mp.spawn(\n self.manual_ddp_training,\n args=(num_epochs, model_pt, optimizer_pt, criterion_pt, train_loader, val_loader),\n nprocs=torch.cuda.device_count()\n )\n\n val_loss, y_pred, y_true = [], [], []\n for idx in range(torch.cuda.device_count()):\n with open(f'{THIS_DIR}/ddp_cnn_save/pt_ddp_predictions_{idx}.p', 'rb') as f:\n val_loss_f, y_pred_f, y_true_f = pickle.load(f)\n val_loss += val_loss_f\n y_pred += y_pred_f\n y_true += y_true_f\n\n val_loss = np.mean(val_loss)\n return val_loss, y_pred, y_true\n\n @staticmethod\n def manual_ddp_training(gpu, num_epochs, model_pt, optimizer_pt, criterion_pt, train_loader, val_loader):\n rank = gpu\n dist.init_process_group(backend='nccl', init_method='env://', world_size=torch.cuda.device_count(), rank=rank)\n torch.manual_seed(0)\n torch.cuda.set_device(gpu)\n device = torch.device(f\"cuda:{gpu}\")\n\n train_sampler = DistributedSampler(dataset=train_loader.dataset, shuffle=True,\n num_replicas=torch.cuda.device_count(), rank=rank)\n val_sampler = DistributedSampler(dataset=val_loader.dataset, shuffle=False,\n num_replicas=torch.cuda.device_count(), rank=rank)\n train_loader_ddp = DataLoader(train_loader.dataset, batch_size=100, sampler=train_sampler)\n val_loader_ddp = DataLoader(val_loader.dataset, batch_size=100, sampler=val_sampler)\n\n model_pt = model_pt.to(device)\n criterion_pt = criterion_pt.to(device)\n\n model_pt = DistributedDataParallel(model_pt, device_ids=[gpu])\n\n model_pt.train()\n for epoch in range(num_epochs):\n print(f'Epoch: {epoch}')\n train_sampler.set_epoch(epoch)\n\n for i, (input_data, target) in enumerate(train_loader_ddp):\n input_data = input_data.to(device)\n target = target.to(device)\n\n predicted = model_pt(input_data)\n loss = criterion_pt(predicted, target)\n loss.backward()\n optimizer_pt.step()\n optimizer_pt.zero_grad()\n\n # Imitate what happens in auto_execute_end_of_epoch() in TrainLoop\n for _ in train_loader:\n pass\n for _ in val_loader:\n pass\n\n print('Evaluating')\n val_loss, val_pred, val_true = [], [], []\n model_pt.eval()\n with torch.no_grad():\n for input_data, target in val_loader_ddp:\n input_data = input_data.to(device)\n target = target.to(device)\n\n predicted = model_pt(input_data)\n loss_batch = criterion_pt(predicted, target).cpu().item()\n val_pred += predicted.argmax(dim=1, keepdim=False).cpu().tolist()\n val_true += target.cpu().tolist()\n val_loss.append(loss_batch)\n\n with open(f'{THIS_DIR}/ddp_cnn_save/pt_ddp_predictions_{gpu}.p', 'wb') as f:\n pickle.dump([val_loss, val_pred, val_true], f)\n\n @staticmethod\n def set_seeds():\n manual_seed = 0\n torch.backends.cudnn.enabled = False\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n np.random.seed(manual_seed)\n random.seed(manual_seed)\n torch.manual_seed(manual_seed)\n # if you are suing GPU\n torch.cuda.manual_seed(manual_seed)\n torch.cuda.manual_seed_all(manual_seed)\n", "from abc import ABC, abstractmethod\nimport os\nfrom collections import OrderedDict\nimport torch\n\nfrom aitoolbox.experiment.local_save.folder_create import ExperimentFolder\nfrom aitoolbox.torchtrain.schedulers.basic import AbstractScheduler\n\n\nclass AbstractLocalModelLoader(ABC):\n @abstractmethod\n def load_model(self, project_name, experiment_name, experiment_timestamp, model_save_dir, epoch_num=None, **kwargs):\n \"\"\"Model loading method all the model loaders need to implement\n\n Args:\n project_name (str): root name of the project\n experiment_name (str): name of the particular experiment\n experiment_timestamp (str): time stamp at the start of training\n model_save_dir (str): name of the folder inside experiment folder where the model is saved\n epoch_num (int or None): epoch number of the model checkpoint or none if loading final model\n **kwargs: additional parameters for specific framework model loader\n\n Returns:\n model\n \"\"\"\n pass\n\n\nclass PyTorchLocalModelLoader(AbstractLocalModelLoader):\n def __init__(self, local_model_result_folder_path):\n \"\"\"PyTorch saved model loader and initializer\n\n Args:\n local_model_result_folder_path (str): root local path where project folder will be created\n \"\"\"\n self.local_model_result_folder_path = os.path.expanduser(local_model_result_folder_path)\n self.model_representation = None\n\n def load_model(self, project_name, experiment_name, experiment_timestamp, model_save_dir='checkpoint_model',\n epoch_num=None, map_location=None):\n \"\"\"Model loading interface compatible with the experiment folder structure maintained by the AIToolbox TrainLoop\n\n Args:\n project_name (str): root name of the project\n experiment_name (str): name of the particular experiment\n experiment_timestamp (str): time stamp at the start of training\n model_save_dir (str): name of the folder inside experiment folder where the model is saved\n epoch_num (int or None): epoch number of the model checkpoint or none if loading final model\n map_location (str or None):\n\n Returns:\n model\n \"\"\"\n _, experiment_dir_path = ExperimentFolder.get_base_folder_paths(project_name, experiment_name,\n experiment_timestamp,\n self.local_model_result_folder_path)\n if epoch_num is None:\n model_name = f'model_{experiment_name}_{experiment_timestamp}.pth'\n else:\n model_name = f'model_{experiment_name}_{experiment_timestamp}_E{epoch_num}.pth'\n\n model_path = os.path.join(experiment_dir_path, model_save_dir, model_name)\n\n self.model_representation = torch.load(model_path, map_location=map_location)\n\n # Fix for back-compatibility\n if 'schedulers_state_dict' not in self.model_representation:\n self.model_representation['schedulers_state_dict'] = []\n\n return self.model_representation\n\n def load_model_from_path(self, model_path, map_location=None):\n \"\"\"General model loading when the AIToolbox TrainLoop experiment folder structure is not used\n\n Args:\n model_path (str): full path to the model\n map_location (str or None): a function, :class:`torch.device`, string or a dict specifying how to remap\n storage locations\n\n Returns:\n model\n \"\"\"\n self.model_representation = torch.load(model_path, map_location=map_location)\n return self.model_representation\n\n def check_if_model_loaded(self):\n if self.model_representation is None:\n raise ValueError('Model has not yet been loaded. Please call load_model() first.')\n\n def init_model(self, model, used_data_parallel=False):\n \"\"\"Initialize provided PyTorch model with the loaded model weights\n\n For this function to work, load_model() must be first called to read the model representation into memory.\n\n Args:\n model (TTModel or nn.Module): PyTorch model\n used_data_parallel (bool): if the saved model was nn.DataParallel or normal model\n\n Returns:\n PyTorch model\n \"\"\"\n self.check_if_model_loaded()\n\n state_dict = self.model_representation['model_state_dict']\n\n if used_data_parallel:\n state_dict = OrderedDict()\n for k, v in self.model_representation['model_state_dict'].items():\n name = k[7:] # remove `module.`\n state_dict[name] = v\n\n model.load_state_dict(state_dict)\n return model\n\n def init_optimizer(self, optimizer, device='cuda'):\n \"\"\"Initialize the optimizer based on saved model/optimizer checkpoint\n\n Args:\n optimizer: PyTorch optimizer\n device (str): device id\n\n Returns:\n PyTorch optimizer\n \"\"\"\n self.check_if_model_loaded()\n\n optimizer.load_state_dict(self.model_representation['optimizer_state_dict'])\n\n # for state in optimizer.state.values():\n # for k, v in state.items():\n # if isinstance(v, torch.Tensor):\n # state[k] = v.to(device)\n\n return optimizer\n\n def init_scheduler(self, scheduler_callbacks_list, ignore_saved=False, ignore_missing_saved=False):\n \"\"\"Initialize the list of schedulers based on saved model/optimizer/scheduler checkpoint\n\n Args:\n scheduler_callbacks_list (list): list of scheduler (callbacks)\n ignore_saved (bool): if exception should be raised in the case there are found scheduler snapshots\n in the checkpoint, but not schedulers are provided to this method\n ignore_missing_saved (bool): if exception should be raised in the case schedulers are provided to\n this method but no saved scheduler snapshots can be found in the checkpoint\n\n Returns:\n list: list of initialized scheduler (callbacks)\n \"\"\"\n self.check_if_model_loaded()\n loaded_schedulers = self.model_representation['schedulers_state_dict']\n\n if len(loaded_schedulers) == 0 and len(scheduler_callbacks_list) > 0:\n if not ignore_missing_saved:\n raise KeyError('Schedulers_state_dict not found in the loaded model representation but you provided '\n 'schedulers to TrainLoop.')\n return scheduler_callbacks_list\n\n if len(loaded_schedulers) > 0 and len(scheduler_callbacks_list) == 0:\n if not ignore_saved:\n raise ValueError('No schedulers were provided to the TrainLoop, however scheduler state_dicts were'\n 'found saved in the loaded model representation.')\n return scheduler_callbacks_list\n\n if len(scheduler_callbacks_list) != len(loaded_schedulers):\n raise ValueError('Number of provided schedulers does not match the number of loaded scheduler state_dicts. '\n f'Number of given schedulers: {len(scheduler_callbacks_list)} and number of loaded'\n f\"scheduler state_dicts: {len(loaded_schedulers)}\")\n\n # Initialize the scheduler callbacks with the saved scheduler states\n for sch_cb, sch_state_dict in zip(scheduler_callbacks_list, loaded_schedulers):\n if not isinstance(sch_cb, AbstractScheduler):\n raise TypeError('Provided scheduler is not inherited from AbstractScheduler')\n\n sch_cb.load_state_dict(sch_state_dict)\n\n return scheduler_callbacks_list\n\n def init_amp(self, amp_scaler):\n \"\"\"Initialize AMP GradScaler\n\n Args:\n amp_scaler (torch.cuda.amp.GradScaler): AMP GradScaler\n\n Returns:\n torch.cuda.amp.GradScaler: initialized AMP GradScaler\n \"\"\"\n amp_scaler.load_state_dict(self.model_representation['amp'])\n return amp_scaler\n", "import os\nimport re\nimport shutil\nimport string\nfrom collections import Counter\nimport numpy as np\nfrom pyrouge import Rouge155\nfrom rouge import Rouge\nfrom nltk.translate.bleu_score import sentence_bleu, corpus_bleu\nfrom torchnlp.metrics import bleu\nfrom transformers import glue_compute_metrics, xnli_compute_metrics\n\nfrom aitoolbox.experiment.core_metrics.abstract_metric import AbstractBaseMetric\n\n\nclass ROUGEMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted,\n target_actual_text=False, output_text_dir=None,\n output_text_cleaning_regex=(r'<.*?>', r'[^a-zA-Z0-9.?! ]+')):\n \"\"\"ROGUE score calculation\n\n From this package:\n https://github.com/pltrdy/rouge\n\n\n Args:\n y_true (numpy.array or list):\n y_predicted (numpy.array or list):\n target_actual_text (bool):\n output_text_dir (str):\n output_text_cleaning_regex (list):\n\n \"\"\"\n self.output_text_cleaning_regex = output_text_cleaning_regex\n self.target_actual_text = target_actual_text\n self.output_text_dir = output_text_dir\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='ROGUE', np_array=False)\n\n def calculate_metric(self):\n if self.output_text_dir is not None:\n # Not affecting the metric calculation. Just for record keeping it drops the texts to disk so they can be\n # reviewed\n self.dump_answer_text_to_disk(self.y_true, self.y_predicted,\n self.output_text_dir, self.output_text_cleaning_regex,\n self.target_actual_text)\n\n self.prepare_text()\n\n rouge_calc = Rouge()\n hypothesis = self.y_predicted\n reference = self.y_true\n\n # TODO: remove try-except... just for testing\n try:\n return rouge_calc.get_scores(hypothesis, reference, avg=True)\n except:\n print('hypothesis')\n print(hypothesis)\n print('reference')\n print(reference)\n exit()\n\n def prepare_text(self):\n if not self.target_actual_text:\n self.y_true = [' '.join(sent) for sent in self.y_true]\n self.y_predicted = [' '.join(sent) if len(sent) > 0 else ' ' for sent in self.y_predicted]\n\n @staticmethod\n def dump_answer_text_to_disk(true_text, pred_text, output_text_dir, output_text_cleaning_regex, target_actual_text):\n \"\"\"\n\n Problems:\n Defined regex text cleaning to deal with Illegal division by zero\n https://ireneli.eu/2018/01/11/working-with-rouge-1-5-5-evaluation-metric-in-python/\n\n Args:\n true_text (list):\n pred_text (list):\n output_text_dir (str):\n output_text_cleaning_regex (list):\n target_actual_text (bool):\n\n Returns:\n\n \"\"\"\n if os.path.exists(output_text_dir):\n shutil.rmtree(output_text_dir)\n\n os.mkdir(output_text_dir)\n\n for i, (pred_answ, true_answ) in enumerate(zip(pred_text, true_text)):\n with open(os.path.join(output_text_dir, f'answer_pred_true_{i}.txt'), 'w', encoding='utf-8') as f:\n # Default regex cleaners: (r'<.*?>', r'[^a-zA-Z0-9.?! ]+')\n pred_answ_clean = ROUGEPerlMetric.regex_clean_text(pred_answ, output_text_cleaning_regex)\n pred_answ_clean = ' '.join(pred_answ_clean) if len(pred_answ_clean) > 0 else ' '\n\n if target_actual_text:\n true_answ_clean = [true_answ]\n else:\n true_answ_clean = ROUGEPerlMetric.regex_clean_text(true_answ, output_text_cleaning_regex)\n true_answ_clean = ' '.join(true_answ_clean)\n\n f.write(f'Answer to question {i}:\\n')\n f.write(f'Predicted:\\t{pred_answ_clean}\\n')\n f.write(f'True:\\t{true_answ_clean}\\n')\n\n\nclass ROUGEPerlMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted,\n output_text_dir, output_text_cleaning_regex=(r'<.*?>', r'[^a-zA-Z0-9.?! ]+'),\n target_actual_text=False):\n \"\"\"ROGUE score calculation using the Perl implementation\n\n Use this package:\n https://pypi.org/project/pyrouge/\n https://github.com/bheinzerling/pyrouge\n\n\n Problems:\n Defined regex text cleaning to deal with Illegal division by zero\n https://ireneli.eu/2018/01/11/working-with-rouge-1-5-5-evaluation-metric-in-python/\n\n\n Args:\n y_true (numpy.array or list): gold standard summaries are ‘model’ summaries\n y_predicted (numpy.array or list): your summaries are ‘system’ summaries\n output_text_dir (str):\n output_text_cleaning_regex (list):\n target_actual_text (bool):\n\n \"\"\"\n self.output_text_dir = output_text_dir\n self.output_text_cleaning_regex = output_text_cleaning_regex\n self.target_actual_text = target_actual_text\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='ROGUE_Perl', np_array=False)\n\n def calculate_metric(self):\n self.dump_answer_text_to_disk(self.y_true, self.y_predicted,\n self.output_text_dir, self.output_text_cleaning_regex,\n self.target_actual_text)\n\n rouge = Rouge155()\n # In ROUGE, your summaries are ‘system’ summaries and the gold standard summaries are ‘model’ summaries.\n rouge.system_dir = os.path.join(self.output_text_dir, 'pred_answer')\n rouge.model_dir = os.path.join(self.output_text_dir, 'true_answer')\n rouge.system_filename_pattern = 'pred_answer_text.(\\d+).txt'\n rouge.model_filename_pattern = 'true_answer_text.#ID#.txt'\n\n rouge_output = rouge.convert_and_evaluate()\n output_dict = rouge.output_to_dict(rouge_output)\n \n return output_dict\n\n @staticmethod\n def dump_answer_text_to_disk(true_text, pred_text, output_text_dir, output_text_cleaning_regex, target_actual_text):\n \"\"\"\n\n Problems:\n Defined regex text cleaning to deal with Illegal division by zero\n https://ireneli.eu/2018/01/11/working-with-rouge-1-5-5-evaluation-metric-in-python/\n\n Args:\n true_text (list):\n pred_text (list):\n output_text_dir (str):\n output_text_cleaning_regex (list):\n target_actual_text (bool):\n\n Returns:\n\n \"\"\"\n if os.path.exists(output_text_dir):\n shutil.rmtree(output_text_dir)\n\n os.mkdir(output_text_dir)\n os.mkdir(os.path.join(output_text_dir, 'true_answer'))\n os.mkdir(os.path.join(output_text_dir, 'pred_answer'))\n\n for i, text in enumerate(true_text):\n # TODO: Encoding setting not tested yet\n with open(os.path.join(output_text_dir, f'true_answer/true_answer_text.{i}.txt'), 'w', encoding='utf-8') as f:\n # Default regex cleaners: (r'<.*?>', r'[^a-zA-Z0-9.?! ]+')\n if target_actual_text:\n text_clean = [text]\n else:\n text_clean = ROUGEPerlMetric.regex_clean_text(text, output_text_cleaning_regex)\n f.write(' '.join(text_clean))\n\n for i, text in enumerate(pred_text):\n # TODO: Encoding setting not tested yet\n with open(os.path.join(output_text_dir, f'pred_answer/pred_answer_text.{i}.txt'), 'w', encoding='utf-8') as f:\n # Default regex cleaners: (r'<.*?>', r'[^a-zA-Z0-9.?! ]+')\n text_clean = ROUGEPerlMetric.regex_clean_text(text, output_text_cleaning_regex)\n f.write(' '.join(text_clean) if len(text_clean) > 0 else ' ')\n\n @staticmethod\n def regex_clean_text(text, cleaning_regex_list):\n \"\"\"\n\n Args:\n text (list):\n cleaning_regex_list (list):\n\n Returns:\n list:\n\n \"\"\"\n # The default is: (r'<.*?>', r'[^a-zA-Z0-9.?! ]+')\n for cleaning_regex in cleaning_regex_list:\n re_pattern = re.compile(cleaning_regex)\n text = [re_pattern.sub('', t) for t in text if len(re_pattern.sub('', t)) > 0]\n return text\n\n\nclass ExactMatchTextMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted,\n target_actual_text=False, output_text_dir=None):\n \"\"\"Calculate exact match of answered strings\n\n Args:\n y_true (numpy.array or list):\n y_predicted (numpy.array or list):\n target_actual_text (bool):\n output_text_dir (str):\n \"\"\"\n if len(y_true) != len(y_predicted):\n raise ValueError(f'len(y_true) != len(y_predicted). Got {len(y_true)} != {len(y_predicted)}')\n\n self.target_actual_text = target_actual_text\n self.output_text_dir = output_text_dir\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='EM', np_array=False)\n\n def calculate_metric(self):\n if self.output_text_dir is not None:\n # Not affecting the metric calculation. Just for record keeping it drops the texts to disk so they can be\n # reviewed\n ROUGEMetric.dump_answer_text_to_disk(self.y_true, self.y_predicted,\n self.output_text_dir, [], self.target_actual_text)\n\n if not self.target_actual_text:\n self.y_true = [' '.join(sent) for sent in self.y_true]\n self.y_predicted = [' '.join(sent) for sent in self.y_predicted]\n\n em = 0\n for pred_answ, true_answ in zip(self.y_predicted, self.y_true):\n em += int(self.normalize_answer(pred_answ) == self.normalize_answer(true_answ))\n\n return 100. * em / len(self.y_true)\n\n @staticmethod\n def normalize_answer(text_str):\n \"\"\"Convert to lowercase and remove punctuation, articles and extra whitespace.\n\n All methods below this line are from the official SQuAD 2.0 eval script\n https://worksheets.codalab.org/rest/bundles/0x6b567e1cf2e041ec80d7098f031c5c9e/contents/blob/\n\n Args:\n text_str (str):\n\n Returns:\n str\n \"\"\"\n def remove_articles(text):\n regex = re.compile(r'\\b(a|an|the)\\b', re.UNICODE)\n return re.sub(regex, ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(text_str))))\n\n\nclass F1TextMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted,\n target_actual_text=False, output_text_dir=None):\n \"\"\"Calculate F1 score of answered strings\n\n Args:\n y_true (numpy.array or list):\n y_predicted (numpy.array or list):\n target_actual_text (bool):\n output_text_dir (str):\n \"\"\"\n if len(y_true) != len(y_predicted):\n raise ValueError(f'len(y_true) != len(y_predicted). Got {len(y_true)} != {len(y_predicted)}')\n\n self.target_actual_text = target_actual_text\n self.output_text_dir = output_text_dir\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='F1', np_array=False)\n\n def calculate_metric(self):\n if self.output_text_dir is not None:\n # Not affecting the metric calculation. Just for record keeping it drops the texts to disk so they can be\n # reviewed\n ROUGEMetric.dump_answer_text_to_disk(self.y_true, self.y_predicted,\n self.output_text_dir, [], self.target_actual_text)\n\n if not self.target_actual_text:\n self.y_true = [' '.join(sent) for sent in self.y_true]\n self.y_predicted = [' '.join(sent) for sent in self.y_predicted]\n\n f1 = 0\n for pred_answ, true_answ in zip(self.y_predicted, self.y_true):\n f1 += self.compute_f1(true_answ, pred_answ)\n\n return 100. * f1 / len(self.y_true)\n\n @staticmethod\n def compute_f1(a_gold, a_pred):\n gold_toks = F1TextMetric.get_tokens(a_gold)\n pred_toks = F1TextMetric.get_tokens(a_pred)\n common = Counter(gold_toks) & Counter(pred_toks)\n num_same = sum(common.values())\n if len(gold_toks) == 0 or len(pred_toks) == 0:\n # If either is no-answer, then F1 is 1 if they agree, 0 otherwise\n return int(gold_toks == pred_toks)\n if num_same == 0:\n return 0\n precision = 1.0 * num_same / len(pred_toks)\n recall = 1.0 * num_same / len(gold_toks)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\n @staticmethod\n def get_tokens(s):\n if not s:\n return []\n return ExactMatchTextMetric.normalize_answer(s).split()\n\n\nclass BLEUSentenceScoreMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted, source_sents=None, output_text_dir=None):\n \"\"\"BLEU score calculation\n\n NLTK provides the sentence_bleu() function for evaluating a candidate sentence\n against one or more reference sentences.\n\n https://machinelearningmastery.com/calculate-bleu-score-for-text-python/\n\n The reference sentences must be provided as a list of sentences where each reference is a list of tokens.\n The candidate sentence is provided as a list of tokens. For example:\n\n reference = [['this', 'is', 'a', 'test'], ['this', 'is' 'test']]\n candidate = ['this', 'is', 'a', 'test']\n score = sentence_bleu(reference, candidate)\n\n Args:\n y_true (list):\n y_predicted (list):\n source_sents (list or None):\n output_text_dir (str or None):\n\n \"\"\"\n if output_text_dir is not None and source_sents is None:\n raise ValueError('output_text_dir is not None and source_sents is None; '\n 'if output_text_dir you must give the source_sents')\n\n self.output_text_dir = output_text_dir\n self.source_sents = source_sents\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='BLEU_sentence_score', np_array=False)\n\n def calculate_metric(self):\n self.check_transl_sent_num_match([self.y_true, self.y_predicted])\n\n sentence_bleu_results = [sentence_bleu([true_t], pred_t) for true_t, pred_t in zip(self.y_true, self.y_predicted)]\n\n if self.output_text_dir is not None:\n self.dump_translation_text_to_disk(self.source_sents,\n [' '.join(sent) for sent in self.y_predicted],\n [' '.join(sent) for sent in self.y_true],\n sentence_bleu_results, self.output_text_dir)\n\n return np.mean(sentence_bleu_results)\n\n @staticmethod\n def dump_translation_text_to_disk(source_sents, pred_translations, true_translations, sentence_bleu_results,\n output_text_dir):\n \"\"\"\n\n Args:\n source_sents (list):\n pred_translations (list):\n true_translations (list):\n sentence_bleu_results (list):\n output_text_dir (str):\n\n Returns:\n\n \"\"\"\n BLEUSentenceScoreMetric.check_transl_sent_num_match([pred_translations, true_translations,\n source_sents, sentence_bleu_results])\n\n if os.path.exists(output_text_dir):\n shutil.rmtree(output_text_dir)\n\n os.mkdir(output_text_dir)\n\n for i, (source, pred_transl, true_transl, bleu_result) in enumerate(zip(source_sents, pred_translations,\n true_translations, sentence_bleu_results)):\n with open(os.path.join(output_text_dir, f'transl_{i}.txt'), 'w', encoding='utf-8') as f:\n f.write(f'Source:\\t{source}\\n')\n f.write(f'Predicted:\\t{pred_transl}\\n')\n f.write(f'True:\\t{true_transl}\\n')\n f.write(f'BLEU: {bleu_result}\\n')\n\n @staticmethod\n def check_transl_sent_num_match(sent_types):\n \"\"\"\n\n Args:\n sent_types (list): list of lists\n \n Raises:\n ValueError\n\n \"\"\"\n num_sents = len(sent_types[0])\n for sent_t in sent_types:\n if len(sent_t) != num_sents:\n raise ValueError(f\"The length of list elements across different text types does not match \"\n f\"The featured lengths are: {', '.join([str(len(el)) for el in sent_types])}\")\n\n\nclass BLEUCorpusScoreMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted, source_sents=None, output_text_dir=None):\n \"\"\"BLEU corpus score calculation\n\n Function called corpus_bleu() for calculating the BLEU score for multiple sentences such as a paragraph or\n a document.\n\n https://machinelearningmastery.com/calculate-bleu-score-for-text-python/\n\n The references must be specified as a list of documents where each document is a list of references and each\n alternative reference is a list of tokens, e.g. a list of lists of lists of tokens. The candidate documents must\n be specified as a list where each document is a list of tokens, e.g. a list of lists of tokens.\n\n references = [[['this', 'is', 'a', 'test'], ['this', 'is' 'test']]]\n candidates = [['this', 'is', 'a', 'test']]\n score = corpus_bleu(references, candidates)\n\n Args:\n y_true (list):\n y_predicted (list):\n source_sents (list or None):\n output_text_dir (str or None):\n\n \"\"\"\n self.output_text_dir = output_text_dir\n self.source_sents = source_sents\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='BLEU_corpus_score', np_array=False)\n\n def calculate_metric(self):\n BLEUSentenceScoreMetric.check_transl_sent_num_match([self.y_true, self.y_predicted])\n\n if self.output_text_dir is not None:\n BLEUSentenceScoreMetric.dump_translation_text_to_disk(self.source_sents,\n [' '.join(sent) for sent in self.y_predicted],\n [' '.join(sent) for sent in self.y_true],\n ['na'] * len(self.y_predicted), self.output_text_dir)\n\n return corpus_bleu([[sent] for sent in self.y_true], self.y_predicted)\n\n\nclass BLEUScoreStrTorchNLPMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted, lowercase=False, source_sents=None, output_text_dir=None):\n \"\"\"BLEU score calculation using the TorchNLP implementation\n\n Example:\n hypotheses = [\n \"The brown fox jumps over the dog 笑\",\n \"The brown fox jumps over the dog 2 笑\"\n ]\n references = [\n \"The quick brown fox jumps over the lazy dog 笑\",\n \"The quick brown fox jumps over the lazy dog 笑\"\n ]\n\n get_moses_multi_bleu(hypotheses, references, lowercase=True)\n 46.51\n\n Args:\n y_true (list):\n y_predicted (list):\n lowercase (bool):\n source_sents (list or None):\n output_text_dir (str or None):\n\n \"\"\"\n self.output_text_dir = output_text_dir\n self.source_sents = source_sents\n self.lowercase = lowercase\n AbstractBaseMetric.__init__(self, y_true, y_predicted, metric_name='BLEU_str_torchNLP_score', np_array=False)\n\n def calculate_metric(self):\n BLEUSentenceScoreMetric.check_transl_sent_num_match([self.y_true, self.y_predicted])\n\n sentence_bleu_results = [\n bleu.get_moses_multi_bleu([' '.join(true_t)], [' '.join(pred_t)], lowercase=self.lowercase)\n for true_t, pred_t in zip(self.y_true, self.y_predicted)\n ]\n \n if self.output_text_dir is not None:\n BLEUSentenceScoreMetric.dump_translation_text_to_disk(self.source_sents,\n [' '.join(sent) for sent in self.y_predicted],\n [' '.join(sent) for sent in self.y_true],\n sentence_bleu_results, self.output_text_dir)\n\n return float(np.mean(sentence_bleu_results))\n\n\nclass PerplexityMetric(AbstractBaseMetric):\n def __init__(self, batch_losses):\n \"\"\"Perplexity metric used in MT\n\n Args:\n batch_losses (numpy.array or list):\n \"\"\"\n AbstractBaseMetric.__init__(self, None, batch_losses, metric_name='Perplexity', np_array=False)\n\n def calculate_metric(self):\n return np.exp(np.mean(self.y_predicted))\n\n\nclass GLUEMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted, task_name):\n \"\"\"GLUE evaluation metrics\n\n Wrapper around HF Transformers ``glue_compute_metrics()``\n\n Args:\n y_true:\n y_predicted:\n task_name (str): name of the GLUE task\n \"\"\"\n self.task_name = task_name\n super().__init__(y_true, y_predicted, metric_name=f'GLUE_{task_name}')\n\n def calculate_metric(self):\n metric_dict = glue_compute_metrics(task_name=self.task_name, preds=self.y_predicted, labels=self.y_true)\n metric_dict = {k.replace('/', '_'): v for k, v in metric_dict.items()}\n return metric_dict\n\n\nclass XNLIMetric(AbstractBaseMetric):\n def __init__(self, y_true, y_predicted):\n \"\"\"XNLI evaluation metrics\n\n Wrapper around HF Transformers ``xnli_compute_metrics()``\n\n Args:\n y_true:\n y_predicted:\n \"\"\"\n super().__init__(y_true, y_predicted, metric_name='xnli_accuracy')\n\n def calculate_metric(self):\n metric_dict = xnli_compute_metrics(task_name='xnli', preds=self.y_predicted, labels=self.y_true)\n metric_dict = {k.replace('/', '_'): v for k, v in metric_dict.items()}\n return metric_dict\n" ]
[ [ "torch.nn.Dropout2d", "torch.utils.data.DataLoader", "numpy.mean", "torch.no_grad", "torch.cuda.manual_seed_all", "torch.flatten", "torch.device", "torch.nn.functional.relu", "torch.nn.functional.max_pool2d", "torch.nn.NLLLoss", "torch.nn.Conv2d", "torch.nn.Linear", "torch.cuda.device_count", "torch.nn.parallel.DistributedDataParallel", "torch.nn.functional.log_softmax", "torch.cuda.set_device", "numpy.random.seed", "torch.manual_seed", "torch.cuda.manual_seed" ], [ "torch.load" ], [ "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sankalpdayal5/numpy
[ "9713e86cc65ebed96464f4d81bb2637857b84f44" ]
[ "benchmarks/benchmarks/bench_function_base.py" ]
[ "from __future__ import absolute_import, division, print_function\n\nfrom .common import Benchmark\n\nimport numpy as np\n\n\nclass Histogram1D(Benchmark):\n def setup(self):\n self.d = np.linspace(0, 100, 100000)\n\n def time_full_coverage(self):\n np.histogram(self.d, 200, (0, 100))\n\n def time_small_coverage(self):\n np.histogram(self.d, 200, (50, 51))\n\n def time_fine_binning(self):\n np.histogram(self.d, 10000, (0, 100))\n\n\nclass Histogram2D(Benchmark):\n def setup(self):\n self.d = np.linspace(0, 100, 200000).reshape((-1,2))\n\n def time_full_coverage(self):\n np.histogramdd(self.d, (200, 200), ((0, 100), (0, 100)))\n\n def time_small_coverage(self):\n np.histogramdd(self.d, (200, 200), ((50, 51), (50, 51)))\n\n def time_fine_binning(self):\n np.histogramdd(self.d, (10000, 10000), ((0, 100), (0, 100)))\n\n\nclass Bincount(Benchmark):\n def setup(self):\n self.d = np.arange(80000, dtype=np.intp)\n self.e = self.d.astype(np.float64)\n\n def time_bincount(self):\n np.bincount(self.d)\n\n def time_weights(self):\n np.bincount(self.d, weights=self.e)\n\n\nclass Median(Benchmark):\n def setup(self):\n self.e = np.arange(10000, dtype=np.float32)\n self.o = np.arange(10001, dtype=np.float32)\n\n def time_even(self):\n np.median(self.e)\n\n def time_odd(self):\n np.median(self.o)\n\n def time_even_inplace(self):\n np.median(self.e, overwrite_input=True)\n\n def time_odd_inplace(self):\n np.median(self.o, overwrite_input=True)\n\n def time_even_small(self):\n np.median(self.e[:500], overwrite_input=True)\n\n def time_odd_small(self):\n np.median(self.o[:500], overwrite_input=True)\n\n\nclass Percentile(Benchmark):\n def setup(self):\n self.e = np.arange(10000, dtype=np.float32)\n self.o = np.arange(10001, dtype=np.float32)\n\n def time_quartile(self):\n np.percentile(self.e, [25, 75])\n\n def time_percentile(self):\n np.percentile(self.e, [25, 35, 55, 65, 75])\n\n\nclass Select(Benchmark):\n def setup(self):\n self.d = np.arange(20000)\n self.e = self.d.copy()\n self.cond = [(self.d > 4), (self.d < 2)]\n self.cond_large = [(self.d > 4), (self.d < 2)] * 10\n\n def time_select(self):\n np.select(self.cond, [self.d, self.e])\n\n def time_select_larger(self):\n np.select(self.cond_large, ([self.d, self.e] * 10))\n\n\ndef memoize(f):\n _memoized = {}\n def wrapped(*args):\n if args not in _memoized:\n _memoized[args] = f(*args)\n \n return _memoized[args].copy()\n\n return f\n\n\nclass SortGenerator(object):\n # The size of the unsorted area in the \"random unsorted area\"\n # benchmarks\n AREA_SIZE = 100\n # The size of the \"partially ordered\" sub-arrays\n BUBBLE_SIZE = 100\n\n @staticmethod\n @memoize\n def random(size, dtype):\n \"\"\"\n Returns a randomly-shuffled array.\n \"\"\"\n arr = np.arange(size, dtype=dtype)\n np.random.shuffle(arr)\n return arr\n \n @staticmethod\n @memoize\n def ordered(size, dtype):\n \"\"\"\n Returns an ordered array.\n \"\"\"\n return np.arange(size, dtype=dtype)\n\n @staticmethod\n @memoize\n def reversed(size, dtype):\n \"\"\"\n Returns an array that's in descending order.\n \"\"\"\n return np.arange(size-1, -1, -1, dtype=dtype)\n\n @staticmethod\n @memoize\n def uniform(size, dtype):\n \"\"\"\n Returns an array that has the same value everywhere.\n \"\"\"\n return np.ones(size, dtype=dtype)\n\n @staticmethod\n @memoize\n def swapped_pair(size, dtype, swap_frac):\n \"\"\"\n Returns an ordered array, but one that has ``swap_frac * size``\n pairs swapped.\n \"\"\"\n a = np.arange(size, dtype=dtype)\n for _ in range(int(size * swap_frac)):\n x, y = np.random.randint(0, size, 2)\n a[x], a[y] = a[y], a[x]\n return a\n\n @staticmethod\n @memoize\n def sorted_block(size, dtype, block_size):\n \"\"\"\n Returns an array with blocks that are all sorted.\n \"\"\"\n a = np.arange(size, dtype=dtype)\n b = []\n if size < block_size:\n return a\n block_num = size // block_size\n for i in range(block_num):\n b.extend(a[i::block_num])\n return np.array(b)\n\n @classmethod\n @memoize\n def random_unsorted_area(cls, size, dtype, frac, area_size=None):\n \"\"\"\n This type of array has random unsorted areas such that they\n compose the fraction ``frac`` of the original array.\n \"\"\"\n if area_size is None:\n area_size = cls.AREA_SIZE\n\n area_num = int(size * frac / area_size)\n a = np.arange(size, dtype=dtype)\n for _ in range(area_num):\n start = np.random.randint(size-area_size)\n end = start + area_size\n np.random.shuffle(a[start:end])\n return a\n\n @classmethod\n @memoize\n def random_bubble(cls, size, dtype, bubble_num, bubble_size=None):\n \"\"\"\n This type of array has ``bubble_num`` random unsorted areas.\n \"\"\"\n if bubble_size is None:\n bubble_size = cls.BUBBLE_SIZE\n frac = bubble_size * bubble_num / size\n\n return cls.random_unsorted_area(size, dtype, frac, bubble_size)\n\n\nclass Sort(Benchmark):\n \"\"\"\n This benchmark tests sorting performance with several\n different types of arrays that are likely to appear in\n real-world applications.\n \"\"\"\n params = [\n # In NumPy 1.17 and newer, 'merge' can be one of several\n # stable sorts, it isn't necessarily merge sort.\n ['quick', 'merge', 'heap'],\n ['float64', 'int64', 'int16'],\n [\n ('random',),\n ('ordered',),\n ('reversed',),\n ('uniform',),\n ('sorted_block', 10),\n ('sorted_block', 100),\n ('sorted_block', 1000),\n # ('swapped_pair', 0.01),\n # ('swapped_pair', 0.1),\n # ('swapped_pair', 0.5),\n # ('random_unsorted_area', 0.5),\n # ('random_unsorted_area', 0.1),\n # ('random_unsorted_area', 0.01),\n # ('random_bubble', 1),\n # ('random_bubble', 5),\n # ('random_bubble', 10),\n ],\n ]\n param_names = ['kind', 'dtype', 'array_type']\n\n # The size of the benchmarked arrays.\n ARRAY_SIZE = 10000\n\n def setup(self, kind, dtype, array_type):\n np.random.seed(1234)\n array_class = array_type[0]\n self.arr = getattr(SortGenerator, array_class)(self.ARRAY_SIZE, dtype, *array_type[1:])\n\n def time_sort(self, kind, dtype, array_type):\n # Using np.sort(...) instead of arr.sort(...) because it makes a copy.\n # This is important because the data is prepared once per benchmark, but\n # used across multiple runs.\n np.sort(self.arr, kind=kind)\n\n def time_argsort(self, kind, dtype, array_type):\n np.argsort(self.arr, kind=kind)\n\n\nclass SortWorst(Benchmark):\n def setup(self):\n # quicksort median of 3 worst case\n self.worst = np.arange(1000000)\n x = self.worst\n while x.size > 3:\n mid = x.size // 2\n x[mid], x[-2] = x[-2], x[mid]\n x = x[:-2]\n\n def time_sort_worst(self):\n np.sort(self.worst)\n\n # Retain old benchmark name for backward compatability\n time_sort_worst.benchmark_name = \"bench_function_base.Sort.time_sort_worst\"\n\n\nclass Where(Benchmark):\n def setup(self):\n self.d = np.arange(20000)\n self.e = self.d.copy()\n self.cond = (self.d > 5000)\n\n def time_1(self):\n np.where(self.cond)\n\n def time_2(self):\n np.where(self.cond, self.d, self.e)\n\n def time_2_broadcast(self):\n np.where(self.cond, self.d, 0)\n" ]
[ [ "numpy.linspace", "numpy.random.seed", "numpy.arange", "numpy.median", "numpy.histogramdd", "numpy.percentile", "numpy.random.shuffle", "numpy.ones", "numpy.sort", "numpy.bincount", "numpy.select", "numpy.argsort", "numpy.array", "numpy.histogram", "numpy.where", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mohamedelbeih/Hairloss-Areas-Semantic-Segmentation
[ "49d8a07d600c538e3b706a531af4029823b70236" ]
[ "mrcnn/utils.py" ]
[ "\"\"\"\r\nMask R-CNN\r\nCommon utility functions and classes.\r\nCopyright (c) 2017 Matterport, Inc.\r\nLicensed under the MIT License (see LICENSE for details)\r\nWritten by Waleed Abdulla\r\n\"\"\"\r\n\r\nimport sys\r\nimport os\r\nimport logging\r\nimport math\r\nimport random\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport scipy\r\nimport skimage.color\r\nimport skimage.io\r\nimport skimage.transform\r\nimport urllib.request\r\nimport shutil\r\nimport warnings\r\nfrom distutils.version import LooseVersion\r\n\r\n# URL from which to download the latest COCO trained weights\r\nCOCO_MODEL_URL = \"https://github.com/matterport/Mask_RCNN/releases/download/v2.0/mask_rcnn_coco.h5\"\r\n\r\n\r\n############################################################\r\n# Bounding Boxes\r\n############################################################\r\n\r\ndef extract_bboxes(mask):\r\n \"\"\"Compute bounding boxes from masks.\r\n mask: [height, width, num_instances]. Mask pixels are either 1 or 0.\r\n Returns: bbox array [num_instances, (y1, x1, y2, x2)].\r\n \"\"\"\r\n boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)\r\n for i in range(mask.shape[-1]):\r\n m = mask[:, :, i]\r\n # Bounding box.\r\n horizontal_indicies = np.where(np.any(m, axis=0))[0]\r\n vertical_indicies = np.where(np.any(m, axis=1))[0]\r\n if horizontal_indicies.shape[0]:\r\n x1, x2 = horizontal_indicies[[0, -1]]\r\n y1, y2 = vertical_indicies[[0, -1]]\r\n # x2 and y2 should not be part of the box. Increment by 1.\r\n x2 += 1\r\n y2 += 1\r\n else:\r\n # No mask for this instance. Might happen due to\r\n # resizing or cropping. Set bbox to zeros\r\n x1, x2, y1, y2 = 0, 0, 0, 0\r\n boxes[i] = np.array([y1, x1, y2, x2])\r\n return boxes.astype(np.int32)\r\n\r\n\r\ndef compute_iou(box, boxes, box_area, boxes_area):\r\n \"\"\"Calculates IoU of the given box with the array of the given boxes.\r\n box: 1D vector [y1, x1, y2, x2]\r\n boxes: [boxes_count, (y1, x1, y2, x2)]\r\n box_area: float. the area of 'box'\r\n boxes_area: array of length boxes_count.\r\n Note: the areas are passed in rather than calculated here for\r\n efficiency. Calculate once in the caller to avoid duplicate work.\r\n \"\"\"\r\n # Calculate intersection areas\r\n y1 = np.maximum(box[0], boxes[:, 0])\r\n y2 = np.minimum(box[2], boxes[:, 2])\r\n x1 = np.maximum(box[1], boxes[:, 1])\r\n x2 = np.minimum(box[3], boxes[:, 3])\r\n intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)\r\n union = box_area + boxes_area[:] - intersection[:]\r\n iou = intersection / union\r\n return iou\r\n\r\n\r\ndef compute_overlaps(boxes1, boxes2):\r\n \"\"\"Computes IoU overlaps between two sets of boxes.\r\n boxes1, boxes2: [N, (y1, x1, y2, x2)].\r\n For better performance, pass the largest set first and the smaller second.\r\n \"\"\"\r\n # Areas of anchors and GT boxes\r\n area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])\r\n area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])\r\n\r\n # Compute overlaps to generate matrix [boxes1 count, boxes2 count]\r\n # Each cell contains the IoU value.\r\n overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0]))\r\n for i in range(overlaps.shape[1]):\r\n box2 = boxes2[i]\r\n overlaps[:, i] = compute_iou(box2, boxes1, area2[i], area1)\r\n return overlaps\r\n\r\n\r\ndef compute_overlaps_masks(masks1, masks2):\r\n \"\"\"Computes IoU overlaps between two sets of masks.\r\n masks1, masks2: [Height, Width, instances]\r\n \"\"\"\r\n \r\n # If either set of masks is empty return empty result\r\n if masks1.shape[-1] == 0 or masks2.shape[-1] == 0:\r\n return np.zeros((masks1.shape[-1], masks2.shape[-1]))\r\n # flatten masks and compute their areas\r\n masks1 = np.reshape(masks1 > .5, (-1, masks1.shape[-1])).astype(np.float32)\r\n masks2 = np.reshape(masks2 > .5, (-1, masks2.shape[-1])).astype(np.float32)\r\n area1 = np.sum(masks1, axis=0)\r\n area2 = np.sum(masks2, axis=0)\r\n\r\n # intersections and union\r\n intersections = np.dot(masks1.T, masks2)\r\n union = area1[:, None] + area2[None, :] - intersections\r\n overlaps = intersections / union\r\n\r\n return overlaps\r\n\r\n\r\ndef non_max_suppression(boxes, scores, threshold):\r\n \"\"\"Performs non-maximum suppression and returns indices of kept boxes.\r\n boxes: [N, (y1, x1, y2, x2)]. Notice that (y2, x2) lays outside the box.\r\n scores: 1-D array of box scores.\r\n threshold: Float. IoU threshold to use for filtering.\r\n \"\"\"\r\n assert boxes.shape[0] > 0\r\n if boxes.dtype.kind != \"f\":\r\n boxes = boxes.astype(np.float32)\r\n\r\n # Compute box areas\r\n y1 = boxes[:, 0]\r\n x1 = boxes[:, 1]\r\n y2 = boxes[:, 2]\r\n x2 = boxes[:, 3]\r\n area = (y2 - y1) * (x2 - x1)\r\n\r\n # Get indicies of boxes sorted by scores (highest first)\r\n ixs = scores.argsort()[::-1]\r\n\r\n pick = []\r\n while len(ixs) > 0:\r\n # Pick top box and add its index to the list\r\n i = ixs[0]\r\n pick.append(i)\r\n # Compute IoU of the picked box with the rest\r\n iou = compute_iou(boxes[i], boxes[ixs[1:]], area[i], area[ixs[1:]])\r\n # Identify boxes with IoU over the threshold. This\r\n # returns indices into ixs[1:], so add 1 to get\r\n # indices into ixs.\r\n remove_ixs = np.where(iou > threshold)[0] + 1\r\n # Remove indices of the picked and overlapped boxes.\r\n ixs = np.delete(ixs, remove_ixs)\r\n ixs = np.delete(ixs, 0)\r\n return np.array(pick, dtype=np.int32)\r\n\r\n\r\ndef apply_box_deltas(boxes, deltas):\r\n \"\"\"Applies the given deltas to the given boxes.\r\n boxes: [N, (y1, x1, y2, x2)]. Note that (y2, x2) is outside the box.\r\n deltas: [N, (dy, dx, log(dh), log(dw))]\r\n \"\"\"\r\n boxes = boxes.astype(np.float32)\r\n # Convert to y, x, h, w\r\n height = boxes[:, 2] - boxes[:, 0]\r\n width = boxes[:, 3] - boxes[:, 1]\r\n center_y = boxes[:, 0] + 0.5 * height\r\n center_x = boxes[:, 1] + 0.5 * width\r\n # Apply deltas\r\n center_y += deltas[:, 0] * height\r\n center_x += deltas[:, 1] * width\r\n height *= np.exp(deltas[:, 2])\r\n width *= np.exp(deltas[:, 3])\r\n # Convert back to y1, x1, y2, x2\r\n y1 = center_y - 0.5 * height\r\n x1 = center_x - 0.5 * width\r\n y2 = y1 + height\r\n x2 = x1 + width\r\n return np.stack([y1, x1, y2, x2], axis=1)\r\n\r\n\r\ndef box_refinement_graph(box, gt_box):\r\n \"\"\"Compute refinement needed to transform box to gt_box.\r\n box and gt_box are [N, (y1, x1, y2, x2)]\r\n \"\"\"\r\n box = tf.cast(box, tf.float32)\r\n gt_box = tf.cast(gt_box, tf.float32)\r\n\r\n height = box[:, 2] - box[:, 0]\r\n width = box[:, 3] - box[:, 1]\r\n center_y = box[:, 0] + 0.5 * height\r\n center_x = box[:, 1] + 0.5 * width\r\n\r\n gt_height = gt_box[:, 2] - gt_box[:, 0]\r\n gt_width = gt_box[:, 3] - gt_box[:, 1]\r\n gt_center_y = gt_box[:, 0] + 0.5 * gt_height\r\n gt_center_x = gt_box[:, 1] + 0.5 * gt_width\r\n\r\n dy = (gt_center_y - center_y) / height\r\n dx = (gt_center_x - center_x) / width\r\n dh = tf.math.log(gt_height / height)\r\n dw = tf.math.log(gt_width / width)\r\n\r\n result = tf.stack([dy, dx, dh, dw], axis=1)\r\n return result\r\n\r\n\r\ndef box_refinement(box, gt_box):\r\n \"\"\"Compute refinement needed to transform box to gt_box.\r\n box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is\r\n assumed to be outside the box.\r\n \"\"\"\r\n box = box.astype(np.float32)\r\n gt_box = gt_box.astype(np.float32)\r\n\r\n height = box[:, 2] - box[:, 0]\r\n width = box[:, 3] - box[:, 1]\r\n center_y = box[:, 0] + 0.5 * height\r\n center_x = box[:, 1] + 0.5 * width\r\n\r\n gt_height = gt_box[:, 2] - gt_box[:, 0]\r\n gt_width = gt_box[:, 3] - gt_box[:, 1]\r\n gt_center_y = gt_box[:, 0] + 0.5 * gt_height\r\n gt_center_x = gt_box[:, 1] + 0.5 * gt_width\r\n\r\n dy = (gt_center_y - center_y) / height\r\n dx = (gt_center_x - center_x) / width\r\n dh = np.log(gt_height / height)\r\n dw = np.log(gt_width / width)\r\n\r\n return np.stack([dy, dx, dh, dw], axis=1)\r\n\r\n\r\n############################################################\r\n# Dataset\r\n############################################################\r\n\r\nclass Dataset(object):\r\n \"\"\"The base class for dataset classes.\r\n To use it, create a new class that adds functions specific to the dataset\r\n you want to use. For example:\r\n class CatsAndDogsDataset(Dataset):\r\n def load_cats_and_dogs(self):\r\n ...\r\n def load_mask(self, image_id):\r\n ...\r\n def image_reference(self, image_id):\r\n ...\r\n See COCODataset and ShapesDataset as examples.\r\n \"\"\"\r\n\r\n def __init__(self, class_map=None):\r\n self._image_ids = []\r\n self.image_info = []\r\n # Background is always the first class\r\n self.class_info = [{\"source\": \"\", \"id\": 0, \"name\": \"BG\"}]\r\n self.source_class_ids = {}\r\n\r\n def add_class(self, source, class_id, class_name):\r\n assert \".\" not in source, \"Source name cannot contain a dot\"\r\n # Does the class exist already?\r\n for info in self.class_info:\r\n if info['source'] == source and info[\"id\"] == class_id:\r\n # source.class_id combination already available, skip\r\n return\r\n # Add the class\r\n self.class_info.append({\r\n \"source\": source,\r\n \"id\": class_id,\r\n \"name\": class_name,\r\n })\r\n\r\n def add_image(self, source, image_id, path, **kwargs):\r\n image_info = {\r\n \"id\": image_id,\r\n \"source\": source,\r\n \"path\": path,\r\n }\r\n image_info.update(kwargs)\r\n self.image_info.append(image_info)\r\n\r\n def image_reference(self, image_id):\r\n \"\"\"Return a link to the image in its source Website or details about\r\n the image that help looking it up or debugging it.\r\n Override for your dataset, but pass to this function\r\n if you encounter images not in your dataset.\r\n \"\"\"\r\n return \"\"\r\n\r\n def prepare(self, class_map=None):\r\n \"\"\"Prepares the Dataset class for use.\r\n TODO: class map is not supported yet. When done, it should handle mapping\r\n classes from different datasets to the same class ID.\r\n \"\"\"\r\n\r\n def clean_name(name):\r\n \"\"\"Returns a shorter version of object names for cleaner display.\"\"\"\r\n return \",\".join(name.split(\",\")[:1])\r\n\r\n # Build (or rebuild) everything else from the info dicts.\r\n self.num_classes = len(self.class_info)\r\n self.class_ids = np.arange(self.num_classes)\r\n self.class_names = [clean_name(c[\"name\"]) for c in self.class_info]\r\n self.num_images = len(self.image_info)\r\n self._image_ids = np.arange(self.num_images)\r\n\r\n # Mapping from source class and image IDs to internal IDs\r\n self.class_from_source_map = {\"{}.{}\".format(info['source'], info['id']): id\r\n for info, id in zip(self.class_info, self.class_ids)}\r\n self.image_from_source_map = {\"{}.{}\".format(info['source'], info['id']): id\r\n for info, id in zip(self.image_info, self.image_ids)}\r\n\r\n # Map sources to class_ids they support\r\n self.sources = list(set([i['source'] for i in self.class_info]))\r\n self.source_class_ids = {}\r\n # Loop over datasets\r\n for source in self.sources:\r\n self.source_class_ids[source] = []\r\n # Find classes that belong to this dataset\r\n for i, info in enumerate(self.class_info):\r\n # Include BG class in all datasets\r\n if i == 0 or source == info['source']:\r\n self.source_class_ids[source].append(i)\r\n\r\n def map_source_class_id(self, source_class_id):\r\n \"\"\"Takes a source class ID and returns the int class ID assigned to it.\r\n For example:\r\n dataset.map_source_class_id(\"coco.12\") -> 23\r\n \"\"\"\r\n return self.class_from_source_map[source_class_id]\r\n\r\n def get_source_class_id(self, class_id, source):\r\n \"\"\"Map an internal class ID to the corresponding class ID in the source dataset.\"\"\"\r\n info = self.class_info[class_id]\r\n assert info['source'] == source\r\n return info['id']\r\n\r\n @property\r\n def image_ids(self):\r\n return self._image_ids\r\n\r\n def source_image_link(self, image_id):\r\n \"\"\"Returns the path or URL to the image.\r\n Override this to return a URL to the image if it's available online for easy\r\n debugging.\r\n \"\"\"\r\n return self.image_info[image_id][\"path\"]\r\n\r\n def load_image(self, image_id):\r\n \"\"\"Load the specified image and return a [H,W,3] Numpy array.\r\n \"\"\"\r\n # Load image\r\n image = skimage.io.imread(self.image_info[image_id]['path'])\r\n # If grayscale. Convert to RGB for consistency.\r\n if image.ndim != 3:\r\n image = skimage.color.gray2rgb(image)\r\n # If has an alpha channel, remove it for consistency\r\n if image.shape[-1] == 4:\r\n image = image[..., :3]\r\n return image\r\n\r\n def load_mask(self, image_id):\r\n \"\"\"Load instance masks for the given image.\r\n Different datasets use different ways to store masks. Override this\r\n method to load instance masks and return them in the form of am\r\n array of binary masks of shape [height, width, instances].\r\n Returns:\r\n masks: A bool array of shape [height, width, instance count] with\r\n a binary mask per instance.\r\n class_ids: a 1D array of class IDs of the instance masks.\r\n \"\"\"\r\n # Override this function to load a mask from your dataset.\r\n # Otherwise, it returns an empty mask.\r\n logging.warning(\"You are using the default load_mask(), maybe you need to define your own one.\")\r\n mask = np.empty([0, 0, 0])\r\n class_ids = np.empty([0], np.int32)\r\n return mask, class_ids\r\n\r\n\r\ndef resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode=\"square\"):\r\n \"\"\"Resizes an image keeping the aspect ratio unchanged.\r\n min_dim: if provided, resizes the image such that it's smaller\r\n dimension == min_dim\r\n max_dim: if provided, ensures that the image longest side doesn't\r\n exceed this value.\r\n min_scale: if provided, ensure that the image is scaled up by at least\r\n this percent even if min_dim doesn't require it.\r\n mode: Resizing mode.\r\n none: No resizing. Return the image unchanged.\r\n square: Resize and pad with zeros to get a square image\r\n of size [max_dim, max_dim].\r\n pad64: Pads width and height with zeros to make them multiples of 64.\r\n If min_dim or min_scale are provided, it scales the image up\r\n before padding. max_dim is ignored in this mode.\r\n The multiple of 64 is needed to ensure smooth scaling of feature\r\n maps up and down the 6 levels of the FPN pyramid (2**6=64).\r\n crop: Picks random crops from the image. First, scales the image based\r\n on min_dim and min_scale, then picks a random crop of\r\n size min_dim x min_dim. Can be used in training only.\r\n max_dim is not used in this mode.\r\n Returns:\r\n image: the resized image\r\n window: (y1, x1, y2, x2). If max_dim is provided, padding might\r\n be inserted in the returned image. If so, this window is the\r\n coordinates of the image part of the full image (excluding\r\n the padding). The x2, y2 pixels are not included.\r\n scale: The scale factor used to resize the image\r\n padding: Padding added to the image [(top, bottom), (left, right), (0, 0)]\r\n \"\"\"\r\n # Keep track of image dtype and return results in the same dtype\r\n image_dtype = image.dtype\r\n # Default window (y1, x1, y2, x2) and default scale == 1.\r\n h, w = image.shape[:2]\r\n window = (0, 0, h, w)\r\n scale = 1\r\n padding = [(0, 0), (0, 0), (0, 0)]\r\n crop = None\r\n\r\n if mode == \"none\":\r\n return image, window, scale, padding, crop\r\n\r\n # Scale?\r\n if min_dim:\r\n # Scale up but not down\r\n scale = max(1, min_dim / min(h, w))\r\n if min_scale and scale < min_scale:\r\n scale = min_scale\r\n\r\n # Does it exceed max dim?\r\n if max_dim and mode == \"square\":\r\n image_max = max(h, w)\r\n if round(image_max * scale) > max_dim:\r\n scale = max_dim / image_max\r\n\r\n # Resize image using bilinear interpolation\r\n if scale != 1:\r\n image = resize(image, (round(h * scale), round(w * scale)),\r\n preserve_range=True)\r\n\r\n # Need padding or cropping?\r\n if mode == \"square\":\r\n # Get new height and width\r\n h, w = image.shape[:2]\r\n top_pad = (max_dim - h) // 2\r\n bottom_pad = max_dim - h - top_pad\r\n left_pad = (max_dim - w) // 2\r\n right_pad = max_dim - w - left_pad\r\n padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]\r\n image = np.pad(image, padding, mode='constant', constant_values=0)\r\n window = (top_pad, left_pad, h + top_pad, w + left_pad)\r\n elif mode == \"pad64\":\r\n h, w = image.shape[:2]\r\n # Both sides must be divisible by 64\r\n assert min_dim % 64 == 0, \"Minimum dimension must be a multiple of 64\"\r\n # Height\r\n if h % 64 > 0:\r\n max_h = h - (h % 64) + 64\r\n top_pad = (max_h - h) // 2\r\n bottom_pad = max_h - h - top_pad\r\n else:\r\n top_pad = bottom_pad = 0\r\n # Width\r\n if w % 64 > 0:\r\n max_w = w - (w % 64) + 64\r\n left_pad = (max_w - w) // 2\r\n right_pad = max_w - w - left_pad\r\n else:\r\n left_pad = right_pad = 0\r\n padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]\r\n image = np.pad(image, padding, mode='constant', constant_values=0)\r\n window = (top_pad, left_pad, h + top_pad, w + left_pad)\r\n elif mode == \"crop\":\r\n # Pick a random crop\r\n h, w = image.shape[:2]\r\n y = random.randint(0, (h - min_dim))\r\n x = random.randint(0, (w - min_dim))\r\n crop = (y, x, min_dim, min_dim)\r\n image = image[y:y + min_dim, x:x + min_dim]\r\n window = (0, 0, min_dim, min_dim)\r\n else:\r\n raise Exception(\"Mode {} not supported\".format(mode))\r\n return image.astype(image_dtype), window, scale, padding, crop\r\n\r\n\r\ndef resize_mask(mask, scale, padding, crop=None):\r\n \"\"\"Resizes a mask using the given scale and padding.\r\n Typically, you get the scale and padding from resize_image() to\r\n ensure both, the image and the mask, are resized consistently.\r\n scale: mask scaling factor\r\n padding: Padding to add to the mask in the form\r\n [(top, bottom), (left, right), (0, 0)]\r\n \"\"\"\r\n # Suppress warning from scipy 0.13.0, the output shape of zoom() is\r\n # calculated with round() instead of int()\r\n with warnings.catch_warnings():\r\n warnings.simplefilter(\"ignore\")\r\n mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0)\r\n if crop is not None:\r\n y, x, h, w = crop\r\n mask = mask[y:y + h, x:x + w]\r\n else:\r\n mask = np.pad(mask, padding, mode='constant', constant_values=0)\r\n return mask\r\n\r\n\r\ndef minimize_mask(bbox, mask, mini_shape):\r\n \"\"\"Resize masks to a smaller version to reduce memory load.\r\n Mini-masks can be resized back to image scale using expand_masks()\r\n See inspect_data.ipynb notebook for more details.\r\n \"\"\"\r\n mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)\r\n for i in range(mask.shape[-1]):\r\n # Pick slice and cast to bool in case load_mask() returned wrong dtype\r\n m = mask[:, :, i].astype(bool)\r\n y1, x1, y2, x2 = bbox[i][:4]\r\n m = m[y1:y2, x1:x2]\r\n if m.size == 0:\r\n raise Exception(\"Invalid bounding box with area of zero\")\r\n # Resize with bilinear interpolation\r\n m = resize(m, mini_shape)\r\n mini_mask[:, :, i] = np.around(m).astype(np.bool)\r\n return mini_mask\r\n\r\n\r\ndef expand_mask(bbox, mini_mask, image_shape):\r\n \"\"\"Resizes mini masks back to image size. Reverses the change\r\n of minimize_mask().\r\n See inspect_data.ipynb notebook for more details.\r\n \"\"\"\r\n mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)\r\n for i in range(mask.shape[-1]):\r\n m = mini_mask[:, :, i]\r\n y1, x1, y2, x2 = bbox[i][:4]\r\n h = y2 - y1\r\n w = x2 - x1\r\n # Resize with bilinear interpolation\r\n m = resize(m, (h, w))\r\n mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)\r\n return mask\r\n\r\n\r\n# TODO: Build and use this function to reduce code duplication\r\ndef mold_mask(mask, config):\r\n pass\r\n\r\n\r\ndef unmold_mask(mask, bbox, image_shape):\r\n \"\"\"Converts a mask generated by the neural network to a format similar\r\n to its original shape.\r\n mask: [height, width] of type float. A small, typically 28x28 mask.\r\n bbox: [y1, x1, y2, x2]. The box to fit the mask in.\r\n Returns a binary mask with the same size as the original image.\r\n \"\"\"\r\n threshold = 0.5\r\n y1, x1, y2, x2 = bbox\r\n mask = resize(mask, (y2 - y1, x2 - x1))\r\n mask = np.where(mask >= threshold, 1, 0).astype(np.bool)\r\n\r\n # Put the mask in the right location.\r\n full_mask = np.zeros(image_shape[:2], dtype=np.bool)\r\n full_mask[y1:y2, x1:x2] = mask\r\n return full_mask\r\n\r\n\r\n############################################################\r\n# Anchors\r\n############################################################\r\n\r\ndef generate_anchors(scales, ratios, shape, feature_stride, anchor_stride):\r\n \"\"\"\r\n scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128]\r\n ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2]\r\n shape: [height, width] spatial shape of the feature map over which\r\n to generate anchors.\r\n feature_stride: Stride of the feature map relative to the image in pixels.\r\n anchor_stride: Stride of anchors on the feature map. For example, if the\r\n value is 2 then generate anchors for every other feature map pixel.\r\n \"\"\"\r\n # Get all combinations of scales and ratios\r\n scales, ratios = np.meshgrid(np.array(scales), np.array(ratios))\r\n scales = scales.flatten()\r\n ratios = ratios.flatten()\r\n\r\n # Enumerate heights and widths from scales and ratios\r\n heights = scales / np.sqrt(ratios)\r\n widths = scales * np.sqrt(ratios)\r\n\r\n # Enumerate shifts in feature space\r\n shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride\r\n shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride\r\n shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y)\r\n\r\n # Enumerate combinations of shifts, widths, and heights\r\n box_widths, box_centers_x = np.meshgrid(widths, shifts_x)\r\n box_heights, box_centers_y = np.meshgrid(heights, shifts_y)\r\n\r\n # Reshape to get a list of (y, x) and a list of (h, w)\r\n box_centers = np.stack(\r\n [box_centers_y, box_centers_x], axis=2).reshape([-1, 2])\r\n box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2])\r\n\r\n # Convert to corner coordinates (y1, x1, y2, x2)\r\n boxes = np.concatenate([box_centers - 0.5 * box_sizes,\r\n box_centers + 0.5 * box_sizes], axis=1)\r\n return boxes\r\n\r\n\r\ndef generate_pyramid_anchors(scales, ratios, feature_shapes, feature_strides,\r\n anchor_stride):\r\n \"\"\"Generate anchors at different levels of a feature pyramid. Each scale\r\n is associated with a level of the pyramid, but each ratio is used in\r\n all levels of the pyramid.\r\n Returns:\r\n anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted\r\n with the same order of the given scales. So, anchors of scale[0] come\r\n first, then anchors of scale[1], and so on.\r\n \"\"\"\r\n # Anchors\r\n # [anchor_count, (y1, x1, y2, x2)]\r\n anchors = []\r\n for i in range(len(scales)):\r\n anchors.append(generate_anchors(scales[i], ratios, feature_shapes[i],\r\n feature_strides[i], anchor_stride))\r\n return np.concatenate(anchors, axis=0)\r\n\r\n\r\n############################################################\r\n# Miscellaneous\r\n############################################################\r\n\r\ndef trim_zeros(x):\r\n \"\"\"It's common to have tensors larger than the available data and\r\n pad with zeros. This function removes rows that are all zeros.\r\n x: [rows, columns].\r\n \"\"\"\r\n assert len(x.shape) == 2\r\n return x[~np.all(x == 0, axis=1)]\r\n\r\n\r\ndef compute_matches(gt_boxes, gt_class_ids, gt_masks,\r\n pred_boxes, pred_class_ids, pred_scores, pred_masks,\r\n iou_threshold=0.5, score_threshold=0.0):\r\n \"\"\"Finds matches between prediction and ground truth instances.\r\n Returns:\r\n gt_match: 1-D array. For each GT box it has the index of the matched\r\n predicted box.\r\n pred_match: 1-D array. For each predicted box, it has the index of\r\n the matched ground truth box.\r\n overlaps: [pred_boxes, gt_boxes] IoU overlaps.\r\n \"\"\"\r\n # Trim zero padding\r\n # TODO: cleaner to do zero unpadding upstream\r\n gt_boxes = trim_zeros(gt_boxes)\r\n gt_masks = gt_masks[..., :gt_boxes.shape[0]]\r\n pred_boxes = trim_zeros(pred_boxes)\r\n pred_scores = pred_scores[:pred_boxes.shape[0]]\r\n # Sort predictions by score from high to low\r\n indices = np.argsort(pred_scores)[::-1]\r\n pred_boxes = pred_boxes[indices]\r\n pred_class_ids = pred_class_ids[indices]\r\n pred_scores = pred_scores[indices]\r\n pred_masks = pred_masks[..., indices]\r\n\r\n # Compute IoU overlaps [pred_masks, gt_masks]\r\n overlaps = compute_overlaps_masks(pred_masks, gt_masks)\r\n\r\n # Loop through predictions and find matching ground truth boxes\r\n match_count = 0\r\n pred_match = -1 * np.ones([pred_boxes.shape[0]])\r\n gt_match = -1 * np.ones([gt_boxes.shape[0]])\r\n for i in range(len(pred_boxes)):\r\n # Find best matching ground truth box\r\n # 1. Sort matches by score\r\n sorted_ixs = np.argsort(overlaps[i])[::-1]\r\n # 2. Remove low scores\r\n low_score_idx = np.where(overlaps[i, sorted_ixs] < score_threshold)[0]\r\n if low_score_idx.size > 0:\r\n sorted_ixs = sorted_ixs[:low_score_idx[0]]\r\n # 3. Find the match\r\n for j in sorted_ixs:\r\n # If ground truth box is already matched, go to next one\r\n if gt_match[j] > -1:\r\n continue\r\n # If we reach IoU smaller than the threshold, end the loop\r\n iou = overlaps[i, j]\r\n if iou < iou_threshold:\r\n break\r\n # Do we have a match?\r\n if pred_class_ids[i] == gt_class_ids[j]:\r\n match_count += 1\r\n gt_match[j] = i\r\n pred_match[i] = j\r\n break\r\n\r\n return gt_match, pred_match, overlaps\r\n\r\n\r\ndef compute_ap(gt_boxes, gt_class_ids, gt_masks,\r\n pred_boxes, pred_class_ids, pred_scores, pred_masks,\r\n iou_threshold=0.5):\r\n \"\"\"Compute Average Precision at a set IoU threshold (default 0.5).\r\n Returns:\r\n mAP: Mean Average Precision\r\n precisions: List of precisions at different class score thresholds.\r\n recalls: List of recall values at different class score thresholds.\r\n overlaps: [pred_boxes, gt_boxes] IoU overlaps.\r\n \"\"\"\r\n # Get matches and overlaps\r\n gt_match, pred_match, overlaps = compute_matches(\r\n gt_boxes, gt_class_ids, gt_masks,\r\n pred_boxes, pred_class_ids, pred_scores, pred_masks,\r\n iou_threshold)\r\n\r\n # Compute precision and recall at each prediction box step\r\n precisions = np.cumsum(pred_match > -1) / (np.arange(len(pred_match)) + 1)\r\n recalls = np.cumsum(pred_match > -1).astype(np.float32) / len(gt_match)\r\n\r\n # Pad with start and end values to simplify the math\r\n precisions = np.concatenate([[0], precisions, [0]])\r\n recalls = np.concatenate([[0], recalls, [1]])\r\n\r\n # Ensure precision values decrease but don't increase. This way, the\r\n # precision value at each recall threshold is the maximum it can be\r\n # for all following recall thresholds, as specified by the VOC paper.\r\n for i in range(len(precisions) - 2, -1, -1):\r\n precisions[i] = np.maximum(precisions[i], precisions[i + 1])\r\n\r\n # Compute mean AP over recall range\r\n indices = np.where(recalls[:-1] != recalls[1:])[0] + 1\r\n mAP = np.sum((recalls[indices] - recalls[indices - 1]) *\r\n precisions[indices])\r\n\r\n return mAP, precisions, recalls, overlaps\r\n\r\n\r\ndef compute_ap_range(gt_box, gt_class_id, gt_mask,\r\n pred_box, pred_class_id, pred_score, pred_mask,\r\n iou_thresholds=None, verbose=1):\r\n \"\"\"Compute AP over a range or IoU thresholds. Default range is 0.5-0.95.\"\"\"\r\n # Default is 0.5 to 0.95 with increments of 0.05\r\n iou_thresholds = iou_thresholds or np.arange(0.5, 1.0, 0.05)\r\n \r\n # Compute AP over range of IoU thresholds\r\n AP = []\r\n for iou_threshold in iou_thresholds:\r\n ap, precisions, recalls, overlaps =\\\r\n compute_ap(gt_box, gt_class_id, gt_mask,\r\n pred_box, pred_class_id, pred_score, pred_mask,\r\n iou_threshold=iou_threshold)\r\n if verbose:\r\n print(\"AP @{:.2f}:\\t {:.3f}\".format(iou_threshold, ap))\r\n AP.append(ap)\r\n AP = np.array(AP).mean()\r\n if verbose:\r\n print(\"AP @{:.2f}-{:.2f}:\\t {:.3f}\".format(\r\n iou_thresholds[0], iou_thresholds[-1], AP))\r\n return AP\r\n\r\n\r\ndef compute_recall(pred_boxes, gt_boxes, iou):\r\n \"\"\"Compute the recall at the given IoU threshold. It's an indication\r\n of how many GT boxes were found by the given prediction boxes.\r\n pred_boxes: [N, (y1, x1, y2, x2)] in image coordinates\r\n gt_boxes: [N, (y1, x1, y2, x2)] in image coordinates\r\n \"\"\"\r\n # Measure overlaps\r\n overlaps = compute_overlaps(pred_boxes, gt_boxes)\r\n iou_max = np.max(overlaps, axis=1)\r\n iou_argmax = np.argmax(overlaps, axis=1)\r\n positive_ids = np.where(iou_max >= iou)[0]\r\n matched_gt_boxes = iou_argmax[positive_ids]\r\n\r\n recall = len(set(matched_gt_boxes)) / gt_boxes.shape[0]\r\n return recall, positive_ids\r\n\r\n\r\n# ## Batch Slicing\r\n# Some custom layers support a batch size of 1 only, and require a lot of work\r\n# to support batches greater than 1. This function slices an input tensor\r\n# across the batch dimension and feeds batches of size 1. Effectively,\r\n# an easy way to support batches > 1 quickly with little code modification.\r\n# In the long run, it's more efficient to modify the code to support large\r\n# batches and getting rid of this function. Consider this a temporary solution\r\ndef batch_slice(inputs, graph_fn, batch_size, names=None):\r\n \"\"\"Splits inputs into slices and feeds each slice to a copy of the given\r\n computation graph and then combines the results. It allows you to run a\r\n graph on a batch of inputs even if the graph is written to support one\r\n instance only.\r\n inputs: list of tensors. All must have the same first dimension length\r\n graph_fn: A function that returns a TF tensor that's part of a graph.\r\n batch_size: number of slices to divide the data into.\r\n names: If provided, assigns names to the resulting tensors.\r\n \"\"\"\r\n if not isinstance(inputs, list):\r\n inputs = [inputs]\r\n\r\n outputs = []\r\n for i in range(batch_size):\r\n inputs_slice = [x[i] for x in inputs]\r\n output_slice = graph_fn(*inputs_slice)\r\n if not isinstance(output_slice, (tuple, list)):\r\n output_slice = [output_slice]\r\n outputs.append(output_slice)\r\n # Change outputs from a list of slices where each is\r\n # a list of outputs to a list of outputs and each has\r\n # a list of slices\r\n outputs = list(zip(*outputs))\r\n\r\n if names is None:\r\n names = [None] * len(outputs)\r\n\r\n result = [tf.stack(o, axis=0, name=n)\r\n for o, n in zip(outputs, names)]\r\n if len(result) == 1:\r\n result = result[0]\r\n\r\n return result\r\n\r\n\r\ndef download_trained_weights(coco_model_path, verbose=1):\r\n \"\"\"Download COCO trained weights from Releases.\r\n coco_model_path: local path of COCO trained weights\r\n \"\"\"\r\n if verbose > 0:\r\n print(\"Downloading pretrained model to \" + coco_model_path + \" ...\")\r\n with urllib.request.urlopen(COCO_MODEL_URL) as resp, open(coco_model_path, 'wb') as out:\r\n shutil.copyfileobj(resp, out)\r\n if verbose > 0:\r\n print(\"... done downloading pretrained model!\")\r\n\r\n\r\ndef norm_boxes(boxes, shape):\r\n \"\"\"Converts boxes from pixel coordinates to normalized coordinates.\r\n boxes: [N, (y1, x1, y2, x2)] in pixel coordinates\r\n shape: [..., (height, width)] in pixels\r\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\r\n coordinates it's inside the box.\r\n Returns:\r\n [N, (y1, x1, y2, x2)] in normalized coordinates\r\n \"\"\"\r\n h, w = shape\r\n scale = np.array([h - 1, w - 1, h - 1, w - 1])\r\n shift = np.array([0, 0, 1, 1])\r\n return np.divide((boxes - shift), scale).astype(np.float32)\r\n\r\n\r\ndef denorm_boxes(boxes, shape):\r\n \"\"\"Converts boxes from normalized coordinates to pixel coordinates.\r\n boxes: [N, (y1, x1, y2, x2)] in normalized coordinates\r\n shape: [..., (height, width)] in pixels\r\n Note: In pixel coordinates (y2, x2) is outside the box. But in normalized\r\n coordinates it's inside the box.\r\n Returns:\r\n [N, (y1, x1, y2, x2)] in pixel coordinates\r\n \"\"\"\r\n h, w = shape\r\n scale = np.array([h - 1, w - 1, h - 1, w - 1])\r\n shift = np.array([0, 0, 1, 1])\r\n return np.around(np.multiply(boxes, scale) + shift).astype(np.int32)\r\n\r\n\r\ndef resize(image, output_shape, order=1, mode='constant', cval=0, clip=True,\r\n preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None):\r\n \"\"\"A wrapper for Scikit-Image resize().\r\n Scikit-Image generates warnings on every call to resize() if it doesn't\r\n receive the right parameters. The right parameters depend on the version\r\n of skimage. This solves the problem by using different parameters per\r\n version. And it provides a central place to control resizing defaults.\r\n \"\"\"\r\n if LooseVersion(skimage.__version__) >= LooseVersion(\"0.14\"):\r\n # New in 0.14: anti_aliasing. Default it to False for backward\r\n # compatibility with skimage 0.13.\r\n return skimage.transform.resize(\r\n image, output_shape,\r\n order=order, mode=mode, cval=cval, clip=clip,\r\n preserve_range=preserve_range, anti_aliasing=anti_aliasing,\r\n anti_aliasing_sigma=anti_aliasing_sigma)\r\n else:\r\n return skimage.transform.resize(\r\n image, output_shape,\r\n order=order, mode=mode, cval=cval, clip=clip,\r\n preserve_range=preserve_range)" ]
[ [ "numpy.dot", "numpy.minimum", "numpy.sqrt", "tensorflow.stack", "numpy.around", "tensorflow.cast", "numpy.cumsum", "numpy.concatenate", "numpy.max", "numpy.all", "numpy.any", "numpy.exp", "numpy.where", "numpy.divide", "numpy.pad", "numpy.reshape", "numpy.arange", "scipy.ndimage.zoom", "numpy.stack", "numpy.argmax", "numpy.zeros", "numpy.log", "numpy.multiply", "numpy.delete", "numpy.argsort", "numpy.meshgrid", "numpy.array", "numpy.sum", "numpy.maximum", "tensorflow.math.log", "numpy.ones", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [ "1.10" ] } ]
tobiasaditya/datascience_beginner
[ "fa6868073951259e0a5f8a702de0bcc17c13d295" ]
[ "mlearning2.py" ]
[ "import seaborn as sb\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\n\nperson = {'finances':[1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,7,4,1,8,5,2,9,6,3,9,8,7,6,5,4,3,2,1,1,9,7,3,8,2,7],\n 'management':[1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,7,4,1,8,5,2,9,6,3,9,8,7,6,5,4,3,2,1,1,9,7,3,8,2,7],\n 'logistic':[1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,7,4,1,8,5,2,9,6,3,9,8,7,6,5,4,3,2,1,1,9,7,3,8,2,7],\n 'get_work':[0,0,1,0,0,1,0,0,1,1,1,1,1,1,1,0,0,0,1,0,0,1,0,0,1,1,0,1,0,0,0,0,1,1,1,0,1,0,0,1]\n }\n\ndatabase = pd.DataFrame(person, columns=['finances','management','logistic','get_work'])\n\nprint(database[['finances','management','logistic']])\n\nx = database[['finances','management','logistic']]\ny = database['get_work']\n\n#30% buat tes, 70 buat training\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=0)\n\nlr=LogisticRegression()\nlr.fit(x_train,y_train)\n\ny_predict=lr.predict(x_test)\n\nconfusion_mat = pd.crosstab(y_test,y_predict,rownames=[\"true\"],colnames=[\"prediction\"])\n\nsb.heatmap(confusion_mat,annot=True)\n\nprint(\"Accuracy = \", metrics.accuracy_score(y_test,y_predict))\nprint(confusion_mat)\nplt.show()\n\n" ]
[ [ "pandas.crosstab", "sklearn.linear_model.LogisticRegression", "sklearn.model_selection.train_test_split", "pandas.DataFrame", "matplotlib.pyplot.show", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
dapatil211/deep_architect
[ "feadfb545d166216e27532ea47e8efa178e0d142", "feadfb545d166216e27532ea47e8efa178e0d142", "feadfb545d166216e27532ea47e8efa178e0d142" ]
[ "dev/enas/search_space/enas_search_space.py", "deep_architect/helpers/tensorflow_eager_support.py", "dev/examples/full_benchmarks/arch_search.py" ]
[ "\"\"\"\nSearch space from Efficient Neural Architecture Search (Pham'17)\n\"\"\"\nfrom __future__ import print_function\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nfrom collections import OrderedDict\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom deep_architect.helpers import tensorflow_eager_support as htfe\nfrom deep_architect.hyperparameters import D\nfrom dev.enas.search_space.common_ops import (conv2D, conv2D_depth_separable,\n global_pool, dropout, fc_layer,\n wrap_batch_norm_relu, avg_pool,\n max_pool,\n keras_batch_normalization)\nimport deep_architect.modules as mo\n\nTFEM = htfe.TensorflowEagerModule\n\n\nclass WeightSharer(object):\n\n def __init__(self, isSharing):\n self.name_to_weight = {}\n self.name_to_np_fn = {}\n self.weight_dict = {}\n self.isSharing = isSharing\n\n def get(self, name, construct_fn, np_fn):\n if self.isSharing:\n if name not in self.name_to_weight:\n with tf.device('/gpu:0'):\n self.name_to_weight[name] = construct_fn()\n self.name_to_np_fn[name] = np_fn\n print(name)\n\n # self.weights_used.add(name)\n # self.name_to_weight[name].gpu()\n return self.name_to_weight[name]\n return construct_fn()\n\n def load_weights(self, name):\n if name in self.weight_dict:\n return self.weight_dict[name]\n else:\n return None\n\n def save(self, filename):\n weight_dict = self.weight_dict\n for name in self.name_to_weight:\n weight_dict[name] = self.name_to_np_fn[name](\n self.name_to_weight[name])\n np.save(filename, weight_dict)\n\n def load(self, filename):\n self.weight_dict = np.load(filename).item()\n\n\n# Take in array of boolean hyperparams, concatenate layers corresponding to true\n# to form skip connections\ndef concatenate_skip_layers(h_connects, weight_sharer):\n\n def compile_fn(di, dh):\n\n def fn(di, is_training=True):\n inputs = [\n di['in' + str(i)]\n for i in range(len(dh))\n if dh['select_' + str(i)]\n ]\n inputs.append(di['in' + str(len(dh))])\n with tf.device('/gpu:0'):\n out = tf.add_n(inputs)\n return {'out': tf.add_n(inputs)}\n\n return fn\n\n return TFEM(\n 'SkipConcat',\n {'select_' + str(i): h_connects[i] for i in range(len(h_connects))},\n compile_fn, ['in' + str(i) for i in range(len(h_connects) + 1)],\n ['out']).get_io()\n\n\ndef enas_conv(out_filters, filter_size, separable, weight_sharer, name):\n io_pair = (conv2D_depth_separable(filter_size, name, weight_sharer)\n if separable else conv2D(filter_size, name, weight_sharer))\n return mo.siso_sequential([\n wrap_batch_norm_relu(conv2D(1,\n name,\n weight_sharer,\n out_filters=out_filters),\n weight_sharer=weight_sharer,\n name=name + '_conv_1'),\n wrap_batch_norm_relu(io_pair,\n weight_sharer=weight_sharer,\n name='_'.join(\n [name, str(filter_size),\n str(separable)]))\n ])\n\n\ndef enas_op(h_op_name, out_filters, name, weight_sharer):\n return mo.siso_or(\n {\n 'conv3':\n lambda: enas_conv(out_filters, 3, False, weight_sharer, name),\n 'conv5':\n lambda: enas_conv(out_filters, 5, False, weight_sharer, name),\n 'dsep_conv3':\n lambda: enas_conv(out_filters, 3, True, weight_sharer, name),\n 'dsep_conv5':\n lambda: enas_conv(out_filters, 5, True, weight_sharer, name),\n 'avg_pool':\n lambda: avg_pool(D([3]), D([1])),\n 'max_pool':\n lambda: max_pool(D([3]), D([1]))\n }, h_op_name)\n\n\ndef enas_repeat_fn(inputs, outputs, layer_id, out_filters, weight_sharer):\n h_enas_op = D(\n ['conv3', 'conv5', 'dsep_conv3', 'dsep_conv5', 'avg_pool', 'max_pool'],\n name='op_' + str(layer_id))\n #h_enas_op = D(['max_pool'], name='op_' + str(layer_id))\n op_inputs, op_outputs = enas_op(h_enas_op, out_filters,\n 'op_' + str(layer_id), weight_sharer)\n outputs[list(outputs.keys())[-1]].connect(op_inputs['in'])\n\n #Skip connections\n h_connects = [\n D([True, False], name='skip_' + str(idx) + '_' + str(layer_id))\n for idx in range(layer_id - 1)\n ]\n skip_inputs, skip_outputs = concatenate_skip_layers(h_connects,\n weight_sharer)\n for i in range(len(h_connects)):\n outputs[list(outputs.keys())[i]].connect(skip_inputs['in' + str(i)])\n op_outputs['out'].connect(skip_inputs['in' + str(len(h_connects))])\n\n # Batch norm after skip\n bn_inputs, bn_outputs = keras_batch_normalization(\n name='skip_bn_' + str(len(h_connects)), weight_sharer=weight_sharer)\n skip_outputs['out'].connect(bn_inputs['in'])\n outputs['out' + str(len(outputs))] = bn_outputs['out']\n return inputs, outputs\n\n\ndef enas_space(h_num_layers,\n out_filters,\n fn_first,\n fn_repeats,\n input_names,\n output_names,\n weight_sharer,\n scope=None):\n\n def substitution_fn(dh):\n assert dh[\"num_layers\"] > 0\n inputs, outputs = fn_first()\n temp_outputs = OrderedDict(outputs)\n for i in range(1, dh[\"num_layers\"] + 1):\n inputs, temp_outputs = fn_repeats(inputs, temp_outputs, i,\n out_filters, weight_sharer)\n return inputs, OrderedDict(\n {'out': temp_outputs['out' + str(len(temp_outputs) - 1)]})\n\n return mo.substitution_module('ENASModule', substitution_fn,\n {'num_layers': h_num_layers}, input_names,\n output_names, scope)\n\n\ndef get_enas_search_space(num_classes, num_layers, out_filters, weight_sharer):\n h_N = D([num_layers], name='num_layers')\n return mo.siso_sequential([\n enas_space(\n h_N,\n out_filters,\n #mo.empty,\n lambda: wrap_batch_norm_relu(conv2D(\n 3, 'stem', weight_sharer, out_filters=out_filters),\n add_relu=False,\n weight_sharer=weight_sharer,\n name='stem'),\n enas_repeat_fn,\n ['in'],\n ['out'],\n weight_sharer),\n global_pool(),\n dropout(keep_prob=.9),\n fc_layer(num_classes, 'softmax', weight_sharer),\n ])\n\n\nclass SSFEnasnet(mo.SearchSpaceFactory):\n\n def __init__(self, num_classes, num_layers, out_filters, isSharing=True):\n mo.SearchSpaceFactory.__init__(self, self._get_search_space)\n self.num_classes = num_classes\n self.weight_sharer = WeightSharer(isSharing)\n self.num_layers = num_layers\n self.out_filters = out_filters\n\n def _get_search_space(self):\n inputs, outputs = get_enas_search_space(self.num_classes,\n self.num_layers,\n self.out_filters,\n self.weight_sharer)\n return inputs, outputs, {}\n", "import numpy as np\nimport tensorflow as tf\n\nimport deep_architect.core as co\nfrom deep_architect.hyperparameters import D\n\n\nclass TensorflowEagerModule(co.Module):\n \"\"\"Class for taking Tensorflow eager code and wrapping it in a DeepArchitect module.\n\n This class subclasses :class:`deep_architect.core.Module` as therefore inherits all\n the information associated to it (e.g., inputs, outputs, and hyperparameters).\n It also enables to do the compile and forward operations for these types of\n modules once a module is fully specified, i.e., once all the hyperparameters\n have been chosen.\n\n The compile operation in this case instantiates any Tensorflow eager variables necessary\n for the computation associated to this module.\n The forward operation takes the variables that were created in the compile\n operation and constructs the actual computational graph fragment associated\n to this module.\n\n See :class:`deep_architect.helpers.tensorflow_support.TensorflowModule` for a similar class for\n Tensorflow. One of the main differences is that Tensorflow deals with\n static computational graphs, so the forward functionality is usually only\n called once per creation for the graph creation. Tensorflow eager requires calling\n forward for each tensor of data that is fed through the network.\n\n .. note::\n This module is abstract, meaning that it does not actually implement\n any particular Tensorflow eager computation. It simply wraps Tensorflow eager\n functionality in a DeepArchitect module. This functionality makes extensive use\n of closures.\n\n The keys of the dictionaries that are passed to the compile function\n match the names of the inputs and hyperparameters, respectively.\n The keys of the dictionary that are passed to the forward function match\n the names of the inputs. The keys of dictionary returned by the forward\n function match the names of the outputs.\n\n Args:\n name (str): Name of the module\n compile_fn ((dict[str,object], dict[str,object]) -> ((dict[str,object]) -> (dict[str,object], list[torch.nn.Modules]))):\n The first function takes two dictionaries with\n keys corresponding to `input_names` and `output_names` and returns\n a function that takes a dictionary with keys corresponding to\n `input_names` and returns a dictionary with keys corresponding\n to `output_names` and a list of Pytorch modules involved in the\n computation of the DeepArchitect module.\n name_to_hyperp (dict[str,deep_architect.core.Hyperparameter]): Dictionary of\n hyperparameters that the model depends on. The keys are the local\n names of the hyperparameters.\n input_names (list[str]): List of names for the inputs.\n output_names (list[str]): List of names for the outputs.\n scope (deep_architect.core.Scope, optional): Scope where the module will be\n registered.\n \"\"\"\n\n def __init__(self,\n name,\n compile_fn,\n name_to_hyperp,\n input_names,\n output_names,\n scope=None):\n co.Module.__init__(self, scope, name)\n hyperparam_dict = {}\n for h in name_to_hyperp:\n if not isinstance(name_to_hyperp[h], co.Hyperparameter):\n hyperparam_dict[h] = D([name_to_hyperp[h]])\n else:\n hyperparam_dict[h] = name_to_hyperp[h]\n\n self._register(input_names, output_names, hyperparam_dict)\n self._compile_fn = compile_fn\n self.is_training = True\n\n def _compile(self):\n input_name_to_val = self._get_input_values()\n hyperp_name_to_val = self._get_hyperp_values()\n self._fn = self._compile_fn(input_name_to_val, hyperp_name_to_val)\n\n def _forward(self):\n input_name_to_val = self._get_input_values()\n output_name_to_val = self._fn(input_name_to_val,\n is_training=self.is_training)\n self._set_output_values(output_name_to_val)\n\n def _update(self):\n pass\n\n\ndef set_is_training(outputs, is_training):\n\n def fn(mx):\n if hasattr(mx, 'is_training'):\n mx.is_training = is_training\n\n co.traverse_backward(outputs, fn)\n\n\ndef siso_tensorflow_eager_module(name, compile_fn, name_to_hyperp, scope=None):\n return TensorflowEagerModule(name, compile_fn, name_to_hyperp, ['in'],\n ['out'], scope).get_io()\n\n\ndef siso_tensorflow_eager_module_from_tensorflow_op_fn(layer_fn,\n name_to_hyperp,\n scope=None,\n name=None):\n\n def compile_fn(di, dh):\n m = layer_fn(**dh)\n\n def forward_fn(di, is_training=False):\n return {\"out\": m(di[\"in\"])}\n\n return forward_fn\n\n if name is None:\n name = layer_fn.__name__\n\n return siso_tensorflow_eager_module(name, compile_fn, name_to_hyperp, scope)\n\n\ndef get_num_trainable_parameters():\n return np.sum(\n [np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])", "import argparse\nimport deep_architect.utils as ut\n\nfrom deep_architect.contrib.misc.datasets.loaders import (load_cifar10,\n load_mnist)\nfrom deep_architect.contrib.misc.datasets.dataset import InMemoryDataset\n\nfrom deep_architect.searchers import common as se\nfrom deep_architect.contrib.misc import gpu_utils\nfrom deep_architect import search_logging as sl\n\nfrom search_space_factory import name_to_search_space_factory_fn\nfrom searcher import name_to_searcher_fn\n\nfrom deep_architect.contrib.misc.evaluators.tensorflow.classification import SimpleClassifierEvaluator\n\nfrom deep_architect.contrib.communicators.communicator import get_communicator\n\n\ndef start_searcher(comm,\n searcher,\n resume_if_exists,\n folderpath,\n search_name,\n searcher_load_path,\n num_samples=-1,\n num_epochs=-1,\n save_every=1):\n assert num_samples != -1 or num_epochs != -1\n\n print('SEARCHER')\n\n sl.create_search_folderpath(folderpath, search_name)\n search_data_folder = sl.get_search_data_folderpath(folderpath, search_name)\n save_filepath = ut.join_paths((search_data_folder, searcher_load_path))\n\n models_sampled = 0\n epochs = 0\n finished = 0\n killed = 0\n best_accuracy = 0.\n\n # Load previous searcher\n if resume_if_exists:\n searcher.load(search_data_folder)\n state = ut.read_jsonfile(save_filepath)\n epochs = state['epochs']\n killed = state['killed']\n models_sampled = state['models_finished']\n finished = state['models_finished']\n\n while (finished < models_sampled or killed < comm.num_workers):\n # Search end conditions\n cont = num_samples == -1 or models_sampled < num_samples\n cont = cont and (num_epochs == -1 or epochs < num_epochs)\n if cont:\n # See whether workers are ready to consume architectures\n if comm.is_ready_to_publish_architecture():\n eval_logger = sl.EvaluationLogger(folderpath, search_name,\n models_sampled)\n _, _, vs, searcher_eval_token = searcher.sample()\n\n eval_logger.log_config(vs, searcher_eval_token)\n comm.publish_architecture_to_worker(vs, models_sampled,\n searcher_eval_token)\n\n models_sampled += 1\n else:\n if comm.is_ready_to_publish_architecture():\n comm.kill_worker()\n killed += 1\n\n # See which workers have finished evaluation\n for worker in range(comm.num_workers):\n msg = comm.receive_results_in_master(worker)\n if msg is not None:\n results, model_id, searcher_eval_token = msg\n eval_logger = sl.EvaluationLogger(folderpath, search_name,\n model_id)\n eval_logger.log_results(results)\n\n if 'epoch' in results:\n epochs = max(epochs, results['epoch'])\n\n searcher.update(results['validation_accuracy'],\n searcher_eval_token)\n best_accuracy = max(best_accuracy,\n results['validation_accuracy'])\n finished += 1\n if finished % save_every == 0:\n print('Models sampled: %d Best Accuracy: %f' %\n (finished, best_accuracy))\n best_accuracy = 0.\n\n searcher.save_state(search_data_folder)\n state = {\n 'models_finished': finished,\n 'epochs': epochs,\n 'killed': killed\n }\n ut.write_jsonfile(state, save_filepath)\n\n\ndef start_worker(comm,\n evaluator,\n search_space_factory,\n folderpath,\n search_name,\n resume=True,\n save_every=1):\n # set the available gpu for process\n print('WORKER %d' % comm.get_rank())\n step = 0\n\n sl.create_search_folderpath(folderpath, search_name)\n search_data_folder = sl.get_search_data_folderpath(folderpath, search_name)\n save_filepath = ut.join_paths(\n (search_data_folder, 'worker' + str(comm.get_rank()) + '.json'))\n\n if resume:\n evaluator.load_state(search_data_folder)\n state = ut.read_jsonfile(save_filepath)\n step = state['step']\n\n while (True):\n arch = comm.receive_architecture_in_worker()\n\n # if a kill signal is received\n if arch is None:\n break\n\n vs, evaluation_id, searcher_eval_token = arch\n\n inputs, outputs = search_space_factory.get_search_space()\n se.specify(outputs, vs)\n results = evaluator.eval(inputs, outputs)\n step += 1\n if step % save_every == 0:\n evaluator.save_state(search_data_folder)\n state = {'step': step}\n ut.write_jsonfile(state, save_filepath)\n comm.publish_results_to_master(results, evaluation_id,\n searcher_eval_token)\n\n\ndef main():\n configs = ut.read_jsonfile(\n \"./examples/tensorflow/full_benchmarks/experiment_config.json\")\n\n parser = argparse.ArgumentParser(\"MPI Job for architecture search\")\n parser.add_argument('--config',\n '-c',\n action='store',\n dest='config_name',\n default='normal')\n\n # Other arguments\n parser.add_argument('--display-output',\n '-o',\n action='store_true',\n dest='display_output',\n default=False)\n parser.add_argument('--resume',\n '-r',\n action='store_true',\n dest='resume',\n default=False)\n\n options = parser.parse_args()\n config = configs[options.config_name]\n\n num_procs = config['num_procs'] if 'num_procs' in config else 0\n comm = get_communicator(config['communicator'], num_procs)\n if len(gpu_utils.get_gpu_information()) != 0:\n #https://github.com/tensorflow/tensorflow/issues/1888\n gpu_utils.set_visible_gpus(\n [comm.get_rank() % gpu_utils.get_total_num_gpus()])\n\n if 'eager' in config and config['eager']:\n import tensorflow as tf\n tf.logging.set_verbosity(tf.logging.ERROR)\n tf.enable_eager_execution()\n datasets = {\n 'cifar10': lambda: (load_cifar10('data/cifar10/', one_hot=False), 10),\n 'mnist': lambda: (load_mnist('data/mnist/'), 10),\n }\n\n (Xtrain, ytrain, Xval, yval, Xtest,\n ytest), num_classes = datasets[config['dataset']]()\n search_space_factory = name_to_search_space_factory_fn[\n config['search_space']](num_classes)\n\n save_every = 1 if 'save_every' not in config else config['save_every']\n if comm.get_rank() == 0:\n searcher = name_to_searcher_fn[config['searcher']](\n search_space_factory.get_search_space)\n num_samples = -1 if 'samples' not in config else config['samples']\n num_epochs = -1 if 'epochs' not in config else config['epochs']\n start_searcher(comm,\n searcher,\n options.resume,\n config['search_folder'],\n config['search_name'],\n config['searcher_file_name'],\n num_samples=num_samples,\n num_epochs=num_epochs,\n save_every=save_every)\n else:\n train_d_advataset = InMemoryDataset(Xtrain, ytrain, True)\n val_dataset = InMemoryDataset(Xval, yval, False)\n test_dataset = InMemoryDataset(Xtest, ytest, False)\n\n search_path = sl.get_search_folderpath(config['search_folder'],\n config['search_name'])\n ut.create_folder(ut.join_paths([search_path, 'scratch_data']),\n create_parent_folders=True)\n scratch_folder = ut.join_paths(\n [search_path, 'scratch_data', 'eval_' + str(comm.get_rank())])\n ut.create_folder(scratch_folder)\n\n evaluators = {\n 'simple_classification':\n lambda: SimpleClassifierEvaluator(\n train_dataset,\n val_dataset,\n num_classes,\n './temp' + str(comm.get_rank()),\n max_num_training_epochs=config['eval_epochs'],\n log_output_to_terminal=options.display_output,\n test_dataset=test_dataset),\n }\n\n assert not config['evaluator'].startswith('enas') or hasattr(\n search_space_factory, 'weight_sharer')\n evaluator = evaluators[config['evaluator']]()\n\n start_worker(comm,\n evaluator,\n search_space_factory,\n config['search_folder'],\n config['search_name'],\n resume=options.resume,\n save_every=save_every)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.load", "tensorflow.device", "tensorflow.add_n", "numpy.save" ], [ "tensorflow.trainable_variables" ], [ "tensorflow.enable_eager_execution", "tensorflow.logging.set_verbosity" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
elainevoice/backend
[ "9b5fef59001fd6c2040affc80cd5cb9690c73795" ]
[ "api/models/taco_models/fatchord_version.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom api.models.utils.distribution import sample_from_discretized_mix_logistic\nfrom api.models.utils.display import *\nfrom api.models.utils.dsp import *\nimport os\nimport numpy as np\nfrom pathlib import Path\nfrom typing import Union\n\n\nclass ResBlock(nn.Module):\n def __init__(self, dims):\n super().__init__()\n self.conv1 = nn.Conv1d(dims, dims, kernel_size=1, bias=False)\n self.conv2 = nn.Conv1d(dims, dims, kernel_size=1, bias=False)\n self.batch_norm1 = nn.BatchNorm1d(dims)\n self.batch_norm2 = nn.BatchNorm1d(dims)\n\n def forward(self, x):\n residual = x\n x = self.conv1(x)\n x = self.batch_norm1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = self.batch_norm2(x)\n return x + residual\n\n\nclass MelResNet(nn.Module):\n def __init__(self, res_blocks, in_dims, compute_dims, res_out_dims, pad):\n super().__init__()\n k_size = pad * 2 + 1\n self.conv_in = nn.Conv1d(in_dims, compute_dims, kernel_size=k_size, bias=False)\n self.batch_norm = nn.BatchNorm1d(compute_dims)\n self.layers = nn.ModuleList()\n for i in range(res_blocks):\n self.layers.append(ResBlock(compute_dims))\n self.conv_out = nn.Conv1d(compute_dims, res_out_dims, kernel_size=1)\n\n def forward(self, x):\n x = self.conv_in(x)\n x = self.batch_norm(x)\n x = F.relu(x)\n for f in self.layers: x = f(x)\n x = self.conv_out(x)\n return x\n\n\nclass Stretch2d(nn.Module):\n def __init__(self, x_scale, y_scale):\n super().__init__()\n self.x_scale = x_scale\n self.y_scale = y_scale\n\n def forward(self, x):\n b, c, h, w = x.size()\n x = x.unsqueeze(-1).unsqueeze(3)\n x = x.repeat(1, 1, 1, self.y_scale, 1, self.x_scale)\n return x.view(b, c, h * self.y_scale, w * self.x_scale)\n\n\nclass UpsampleNetwork(nn.Module):\n def __init__(self, feat_dims, upsample_scales, compute_dims,\n res_blocks, res_out_dims, pad):\n super().__init__()\n total_scale = np.cumproduct(upsample_scales)[-1]\n self.indent = pad * total_scale\n self.resnet = MelResNet(res_blocks, feat_dims, compute_dims, res_out_dims, pad)\n self.resnet_stretch = Stretch2d(total_scale, 1)\n self.up_layers = nn.ModuleList()\n for scale in upsample_scales:\n k_size = (1, scale * 2 + 1)\n padding = (0, scale)\n stretch = Stretch2d(scale, 1)\n conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False)\n conv.weight.data.fill_(1. / k_size[1])\n self.up_layers.append(stretch)\n self.up_layers.append(conv)\n\n def forward(self, m):\n aux = self.resnet(m).unsqueeze(1)\n aux = self.resnet_stretch(aux)\n aux = aux.squeeze(1)\n m = m.unsqueeze(1)\n for f in self.up_layers: m = f(m)\n m = m.squeeze(1)[:, :, self.indent:-self.indent]\n return m.transpose(1, 2), aux.transpose(1, 2)\n\n\nclass WaveRNN(nn.Module):\n def __init__(self, rnn_dims, fc_dims, bits, pad, upsample_factors,\n feat_dims, compute_dims, res_out_dims, res_blocks,\n hop_length, sample_rate, mode='RAW'):\n super().__init__()\n self.mode = mode\n self.pad = pad\n if self.mode == 'RAW':\n self.n_classes = 2 ** bits\n elif self.mode == 'MOL':\n self.n_classes = 30\n else:\n RuntimeError(\"Unknown model mode value - \", self.mode)\n\n # List of rnns to call `flatten_parameters()` on\n self._to_flatten = []\n\n self.rnn_dims = rnn_dims\n self.aux_dims = res_out_dims // 4\n self.hop_length = hop_length\n self.sample_rate = sample_rate\n\n self.upsample = UpsampleNetwork(feat_dims, upsample_factors, compute_dims, res_blocks, res_out_dims, pad)\n self.I = nn.Linear(feat_dims + self.aux_dims + 1, rnn_dims)\n\n self.rnn1 = nn.GRU(rnn_dims, rnn_dims, batch_first=True)\n self.rnn2 = nn.GRU(rnn_dims + self.aux_dims, rnn_dims, batch_first=True)\n self._to_flatten += [self.rnn1, self.rnn2]\n\n self.fc1 = nn.Linear(rnn_dims + self.aux_dims, fc_dims)\n self.fc2 = nn.Linear(fc_dims + self.aux_dims, fc_dims)\n self.fc3 = nn.Linear(fc_dims, self.n_classes)\n\n self.register_buffer('step', torch.zeros(1, dtype=torch.long))\n self.num_params()\n\n # Avoid fragmentation of RNN parameters and associated warning\n self._flatten_parameters()\n\n def forward(self, x, mels):\n device = next(self.parameters()).device # use same device as parameters\n\n # Although we `_flatten_parameters()` on init, when using DataParallel\n # the model gets replicated, making it no longer guaranteed that the\n # weights are contiguous in GPU memory. Hence, we must call it again\n self._flatten_parameters()\n\n if self.training:\n self.step += 1\n bsize = x.size(0)\n h1 = torch.zeros(1, bsize, self.rnn_dims, device=device)\n h2 = torch.zeros(1, bsize, self.rnn_dims, device=device)\n mels, aux = self.upsample(mels)\n\n aux_idx = [self.aux_dims * i for i in range(5)]\n a1 = aux[:, :, aux_idx[0]:aux_idx[1]]\n a2 = aux[:, :, aux_idx[1]:aux_idx[2]]\n a3 = aux[:, :, aux_idx[2]:aux_idx[3]]\n a4 = aux[:, :, aux_idx[3]:aux_idx[4]]\n\n x = torch.cat([x.unsqueeze(-1), mels, a1], dim=2)\n x = self.I(x)\n res = x\n x, _ = self.rnn1(x, h1)\n\n x = x + res\n res = x\n x = torch.cat([x, a2], dim=2)\n x, _ = self.rnn2(x, h2)\n\n x = x + res\n x = torch.cat([x, a3], dim=2)\n x = F.relu(self.fc1(x))\n\n x = torch.cat([x, a4], dim=2)\n x = F.relu(self.fc2(x))\n return self.fc3(x)\n\n def generate(self, mels, save_path: Union[str, Path, None], batched, target, overlap, mu_law, silent=False):\n self.eval()\n\n device = next(self.parameters()).device # use same device as parameters\n\n mu_law = mu_law if self.mode == 'RAW' else False\n\n output = []\n start = time.time()\n rnn1 = self.get_gru_cell(self.rnn1)\n rnn2 = self.get_gru_cell(self.rnn2)\n\n with torch.no_grad():\n\n mels = torch.as_tensor(mels, device=device)\n wave_len = (mels.size(-1) - 1) * self.hop_length\n mels = self.pad_tensor(mels.transpose(1, 2), pad=self.pad, side='both')\n mels, aux = self.upsample(mels.transpose(1, 2))\n\n if batched:\n mels = self.fold_with_overlap(mels, target, overlap)\n aux = self.fold_with_overlap(aux, target, overlap)\n\n b_size, seq_len, _ = mels.size()\n\n h1 = torch.zeros(b_size, self.rnn_dims, device=device)\n h2 = torch.zeros(b_size, self.rnn_dims, device=device)\n x = torch.zeros(b_size, 1, device=device)\n\n d = self.aux_dims\n aux_split = [aux[:, :, d * i:d * (i + 1)] for i in range(4)]\n\n for i in range(seq_len):\n\n m_t = mels[:, i, :]\n\n a1_t, a2_t, a3_t, a4_t = \\\n (a[:, i, :] for a in aux_split)\n\n x = torch.cat([x, m_t, a1_t], dim=1)\n x = self.I(x)\n h1 = rnn1(x, h1)\n\n x = x + h1\n inp = torch.cat([x, a2_t], dim=1)\n h2 = rnn2(inp, h2)\n\n x = x + h2\n x = torch.cat([x, a3_t], dim=1)\n x = F.relu(self.fc1(x))\n\n x = torch.cat([x, a4_t], dim=1)\n x = F.relu(self.fc2(x))\n\n logits = self.fc3(x)\n\n if self.mode == 'MOL':\n sample = sample_from_discretized_mix_logistic(logits.unsqueeze(0).transpose(1, 2))\n output.append(sample.view(-1))\n # x = torch.FloatTensor([[sample]]).cuda()\n x = sample.transpose(0, 1)\n\n elif self.mode == 'RAW':\n posterior = F.softmax(logits, dim=1)\n distrib = torch.distributions.Categorical(posterior)\n\n sample = 2 * distrib.sample().float() / (self.n_classes - 1.) - 1.\n output.append(sample)\n x = sample.unsqueeze(-1)\n else:\n raise RuntimeError(\"Unknown model mode value - \", self.mode)\n\n if not silent and i % 100 == 0:\n self.gen_display(i, seq_len, b_size, start)\n\n output = torch.stack(output).transpose(0, 1)\n output = output.cpu().numpy()\n output = output.astype(np.float64)\n\n if mu_law:\n output = decode_mu_law(output, self.n_classes, False)\n\n if batched:\n output = self.xfade_and_unfold(output, target, overlap)\n else:\n output = output[0]\n\n # Fade-out at the end to avoid signal cutting out suddenly\n fade_out = np.linspace(1, 0, 20 * self.hop_length)\n output = output[:wave_len]\n output[-20 * self.hop_length:] *= fade_out\n\n if save_path is not None:\n save_wav(output, save_path)\n\n self.train()\n\n return output\n\n\n def gen_display(self, i, seq_len, b_size, start):\n gen_rate = (i + 1) / (time.time() - start) * b_size / 1000\n pbar = progbar(i, seq_len)\n msg = f'| {pbar} {i*b_size}/{seq_len*b_size} | Batch Size: {b_size} | Gen Rate: {gen_rate:.1f}kHz | '\n stream(msg)\n\n def get_gru_cell(self, gru):\n gru_cell = nn.GRUCell(gru.input_size, gru.hidden_size)\n gru_cell.weight_hh.data = gru.weight_hh_l0.data\n gru_cell.weight_ih.data = gru.weight_ih_l0.data\n gru_cell.bias_hh.data = gru.bias_hh_l0.data\n gru_cell.bias_ih.data = gru.bias_ih_l0.data\n return gru_cell\n\n def pad_tensor(self, x, pad, side='both'):\n # NB - this is just a quick method i need right now\n # i.e., it won't generalise to other shapes/dims\n b, t, c = x.size()\n total = t + 2 * pad if side == 'both' else t + pad\n padded = torch.zeros(b, total, c, device=x.device)\n if side == 'before' or side == 'both':\n padded[:, pad:pad + t, :] = x\n elif side == 'after':\n padded[:, :t, :] = x\n return padded\n\n def fold_with_overlap(self, x, target, overlap):\n\n ''' Fold the tensor with overlap for quick batched inference.\n Overlap will be used for crossfading in xfade_and_unfold()\n\n Args:\n x (tensor) : Upsampled conditioning features.\n shape=(1, timesteps, features)\n target (int) : Target timesteps for each index of batch\n overlap (int) : Timesteps for both xfade and rnn warmup\n\n Return:\n (tensor) : shape=(num_folds, target + 2 * overlap, features)\n\n Details:\n x = [[h1, h2, ... hn]]\n\n Where each h is a vector of conditioning features\n\n Eg: target=2, overlap=1 with x.size(1)=10\n\n folded = [[h1, h2, h3, h4],\n [h4, h5, h6, h7],\n [h7, h8, h9, h10]]\n '''\n\n _, total_len, features = x.size()\n\n # Calculate variables needed\n num_folds = (total_len - overlap) // (target + overlap)\n extended_len = num_folds * (overlap + target) + overlap\n remaining = total_len - extended_len\n\n # Pad if some time steps poking out\n if remaining != 0:\n num_folds += 1\n padding = target + 2 * overlap - remaining\n x = self.pad_tensor(x, padding, side='after')\n\n folded = torch.zeros(num_folds, target + 2 * overlap, features, device=x.device)\n\n # Get the values for the folded tensor\n for i in range(num_folds):\n start = i * (target + overlap)\n end = start + target + 2 * overlap\n folded[i] = x[:, start:end, :]\n\n return folded\n\n def xfade_and_unfold(self, y, target, overlap):\n\n ''' Applies a crossfade and unfolds into a 1d array.\n\n Args:\n y (ndarry) : Batched sequences of audio samples\n shape=(num_folds, target + 2 * overlap)\n dtype=np.float64\n overlap (int) : Timesteps for both xfade and rnn warmup\n\n Return:\n (ndarry) : audio samples in a 1d array\n shape=(total_len)\n dtype=np.float64\n\n Details:\n y = [[seq1],\n [seq2],\n [seq3]]\n\n Apply a gain envelope at both ends of the sequences\n\n y = [[seq1_in, seq1_target, seq1_out],\n [seq2_in, seq2_target, seq2_out],\n [seq3_in, seq3_target, seq3_out]]\n\n Stagger and add up the groups of samples:\n\n [seq1_in, seq1_target, (seq1_out + seq2_in), seq2_target, ...]\n\n '''\n\n num_folds, length = y.shape\n target = length - 2 * overlap\n total_len = num_folds * (target + overlap) + overlap\n\n # Need some silence for the rnn warmup\n silence_len = overlap // 2\n fade_len = overlap - silence_len\n silence = np.zeros((silence_len), dtype=np.float64)\n linear = np.ones((silence_len), dtype=np.float64)\n\n # Equal power crossfade\n t = np.linspace(-1, 1, fade_len, dtype=np.float64)\n fade_in = np.sqrt(0.5 * (1 + t))\n fade_out = np.sqrt(0.5 * (1 - t))\n\n # Concat the silence to the fades\n fade_in = np.concatenate([silence, fade_in])\n fade_out = np.concatenate([linear, fade_out])\n\n # Apply the gain to the overlap samples\n y[:, :overlap] *= fade_in\n y[:, -overlap:] *= fade_out\n\n unfolded = np.zeros((total_len), dtype=np.float64)\n\n # Loop to add up all the samples\n for i in range(num_folds):\n start = i * (target + overlap)\n end = start + target + 2 * overlap\n unfolded[start:end] += y[i]\n\n return unfolded\n\n def get_step(self):\n return self.step.data.item()\n\n def log(self, path, msg):\n with open(path, 'a') as f:\n print(msg, file=f)\n\n def load(self, path: Union[str, Path]):\n # Use device of model params as location for loaded state\n device = next(self.parameters()).device\n self.load_state_dict(torch.load(path, map_location=device), strict=False)\n\n def save(self, path: Union[str, Path]):\n # No optimizer argument because saving a model should not include data\n # only relevant in the training process - it should only be properties\n # of the model itself. Let caller take care of saving optimzier state.\n torch.save(self.state_dict(), path)\n\n def num_params(self, print_out=False):\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000\n if print_out:\n print('Trainable Parameters: %.3fM' % parameters)\n return parameters\n\n def _flatten_parameters(self):\n \"\"\"Calls `flatten_parameters` on all the rnns used by the WaveRNN. Used\n to improve efficiency and avoid PyTorch yelling at us.\"\"\"\n [m.flatten_parameters() for m in self._to_flatten]\n" ]
[ [ "torch.nn.functional.softmax", "numpy.sqrt", "numpy.linspace", "torch.zeros", "torch.cat", "torch.load", "torch.nn.GRU", "numpy.concatenate", "torch.no_grad", "numpy.cumproduct", "torch.nn.functional.relu", "torch.nn.GRUCell", "numpy.zeros", "torch.nn.BatchNorm1d", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.Conv1d", "torch.stack", "torch.as_tensor", "numpy.ones", "torch.distributions.Categorical" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Kthyeon/FINE
[ "ae8a24a4a2514feafd9a9ed394af87f397708ccf", "ae8a24a4a2514feafd9a9ed394af87f397708ccf" ]
[ "dynamic_selection/trainer/archive/svd_classifier.py", "dynamic_selection/loss/gce.py" ]
[ "import torch\nimport numpy as np\nfrom tqdm import tqdm\nfrom sklearn import cluster\n\n#bol_norm True -> Divide by norm of feature\ndef same_score(v_ortho_dict, features, labels, bol_norm=False):\n features = torch.from_numpy(features).cuda()\n scores = torch.zeros(features.shape[0])\n \n for indx, feat in enumerate(features):\n tmp_scores = torch.dot(v_ortho_dict[labels[indx]][0], feat).abs() \n scores[indx] = (tmp_scores / torch.norm(feat, p=2)) if bol_norm else tmp_scores\n return scores\n\ndef same_topk(label_list, scores, p):\n \n output = []\n for idx in range(len(np.unique(label_list))):\n num_inst = int(p * np.sum(label_list==idx))\n indexs = torch.tensor(range(len(label_list)))[label_list==idx]\n tmp_sort, tmp_idx = torch.sort(scores[label_list==idx], descending=False)\n # 못 들어간 애가 필요한거니까 이렇게!\n output += indexs[tmp_idx[num_inst:]].numpy().tolist()\n \n return torch.tensor(output).long()\n\n#Classswise kmenas\ndef same_kmeans(label_list, scores, p=None):\n \n output = []\n for idx in range(len(np.unique(label_list))):\n indexs = torch.tensor(range(len(scores)))[label_list==idx]\n kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(scores[indexs].reshape(-1, 1))\n \n if torch.mean(scores[indexs][kmeans.labels_==0]) < torch.mean(scores[indexs][kmeans.labels_==1]):\n kmeans.labels_ = 1 - kmeans.labels_\n output += indexs[kmeans.labels_ == 0].numpy().tolist()\n \n return torch.tensor(output).long()\n \n#Total Kmeans\ndef same_kmeans_total(scores, p=None):\n output = []\n indexs = torch.tensor(range(len(scores)))\n kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(scores.reshape(-1, 1))\n \n if torch.mean(scores[kmeans.labels_==0]) < torch.mean(scores[kmeans.labels_==1]):\n kmeans.labels_ = 1 - kmeans.labels_\n \n for idx, value in enumerate(kmeans.labels_):\n if value == 0:\n output.append(idx)\n \n return torch.tensor(output).long(), None\n\ndef same_topk_index(orig_label_list, orig_out_list, prev_label_list, prev_out_list, p=None):\n \n singular_dict, v_ortho_dict = get_singular_value_vector(prev_label_list, prev_out_list)\n for key in v_ortho_dict.keys():\n v_ortho_dict[key] = v_ortho_dict[key].cuda()\n \n scores = same_score(v_ortho_dict, orig_out_list, orig_label_list)\n output = same_topk(orig_label_list, scores, p)\n return output.numpy()\n\ndef same_kmeans_index(orig_label_list, orig_out_list, prev_label_list, prev_out_list, p=None):\n \n singular_dict, v_ortho_dict = get_singular_value_vector(prev_label_list, prev_out_list)\n for key in v_ortho_dict.keys():\n v_ortho_dict[key] = v_ortho_dict[key].cuda()\n \n scores = same_score(v_ortho_dict, orig_out_list, orig_label_list)\n output = same_kmeans(orig_label_list, scores, p)\n return output.numpy()\n \ndef compute_noisy_ratio(data_loader):\n isNoisy_list = np.empty((0,))\n \n with tqdm(data_loader) as progress:\n for _, (_, label, index, label_gt) in enumerate(progress):\n isNoisy = label == label_gt\n isNoisy_list = np.concatenate((isNoisy_list, isNoisy.cpu()))\n\n print ('#############################')\n print (isNoisy_list.sum(), isNoisy_list.shape)\n print('purity in this dataset: {}'.format(isNoisy_list.sum() / isNoisy_list.shape))\n\n\ndef get_loss_list(model, data_loader):\n loss_list = np.empty((0,))\n \n with tqdm(data_loader) as progress:\n for batch_idx, (data, label, index, label_gt) in enumerate(progress):\n data = data.cuda()\n label, label_gt = label.long().cuda(), label_gt.long().cuda()\n\n _, prediction = model(data)\n loss = torch.nn.CrossEntropyLoss(reduction='none')(prediction, label)\n\n loss_list = np.concatenate((loss_list, loss.detach().cpu()))\n \n kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(loss_list.reshape(-1,1))\n \n if np.mean(loss_list[kmeans.labels_==0]) > np.mean(loss_list[kmeans.labels_==1]):\n clean_label = 1\n else:\n clean_label = 0\n \n output=[]\n for idx, value in enumerate(kmeans.labels_):\n if value==clean_label:\n output.append(idx)\n \n return output\n\ndef iterative_eigen(number, label_list, out_list, teacher_idx=None):\n sin_lbls = {}\n for i in range(number):\n tmp_lbl = torch.zeros(50000)\n if teacher_idx !=None:\n for num in (set(range(0,50000)) - set(teacher_idx)):\n tmp_lbl[num] += 1\n print(tmp_lbl.sum().item())\n for k in range(i):\n tmp_lbl += sin_lbls[k] \n singular_dict, v_ortho_dict = get_singular_value_vector(label_list[tmp_lbl==0], out_list[tmp_lbl==0])\n\n for key in v_ortho_dict.keys():\n v_ortho_dict[key] = v_ortho_dict[key].cuda()\n\n sing_lbl, sin_score_lbl = singular_label(v_ortho_dict, out_list, label_list)\n sin_lbls[i]=sing_lbl\n if i>0 and torch.all(torch.eq(sin_lbls[i], sin_lbls[i-1])):\n print(i)\n break\n if number ==1:\n output=[]\n for idx, value in enumerate(sing_lbl):\n if value==0:\n output.append(idx)\n else:\n kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(loss_list.reshape(-1,1))\n \n if np.mean(sin_score_lbl[kmeans.labels_==0]) > np.mean(sin_score_lbl[kmeans.labels_==1]):\n clean_label = 0\n else:\n clean_label = 1\n \n output=[]\n for idx, value in enumerate(kmeans.labels_):\n if value==clean_label:\n output.append(idx)\n \n \n return output\n\n \ndef get_out_list(model, data_loader):\n\n label_list = np.empty((0,))\n\n model.eval()\n model.cuda()\n with tqdm(data_loader) as progress:\n for batch_idx, (data, label, index, _) in enumerate(progress):\n data = data.cuda()\n# label, label_gt = label.long().cuda(), label_gt.long().cuda()\n label = label.long()\n output, _ = model(data)\n\n label_list = np.concatenate((label_list, label.cpu()))\n if batch_idx == 0:\n out_list = output.detach().cpu()\n else:\n out_list = np.concatenate((out_list, output.detach().cpu()), axis=0)\n \n return label_list, out_list\n\n\ndef get_singular_value_vector(label_list, out_list):\n \n singular_dict = {}\n v_ortho_dict = {}\n \n for index in np.unique(label_list):\n u, s, v = np.linalg.svd(out_list[label_list==index])\n singular_dict[index] = s[0] / s[1]\n v_ortho_dict[index] = torch.from_numpy(v[:2])\n\n return singular_dict, v_ortho_dict\n\ndef singular_label(v_ortho_dict, model_represents, label):\n \n model_represents = torch.from_numpy(model_represents).cuda()\n sing_lbl = torch.zeros(model_represents.shape[0]) \n sin_score_lbl = torch.zeros(model_represents.shape[0])\n \n for i, data in enumerate(model_represents):\n sin_score_lbl[i] = torch.dot(v_ortho_dict[label[i]][0], data).abs() - torch.dot(v_ortho_dict[label[i]][1], data).abs()\n if torch.dot(v_ortho_dict[label[i]][0], data).abs() < torch.dot(v_ortho_dict[label[i]][1], data).abs():\n sing_lbl[i] = 1\n \n return sing_lbl, sin_score_lbl\n\ndef kmean_singular_label(v_ortho_dict, model_represents, label):\n \n model_represents = torch.from_numpy(model_represents).cuda()\n sing_lbl = torch.zeros(model_represents.shape[0])\n sin_score_lbl = torch.zeros(model_represents.shape[0])\n \n for i, data in enumerate(model_represents):\n sin_score_lbl[i] = torch.dot(v_ortho_dict[label[i]][0], data).abs() - torch.dot(v_ortho_dict[label[i]][1], data).abs()\n \n kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(sin_score_lbl.reshape(-1, 1))\n \n if torch.mean(sin_score_lbl[kmeans.labels_==0]) < torch.mean(sin_score_lbl[kmeans.labels_==1]):\n kmeans.labels_ = 1 - kmeans.labels_\n \n output = []\n for idx, value in enumerate(kmeans.labels_):\n if value == 0:\n output.append(idx)\n \n return output\n\ndef kmean_singular_label2(v_ortho_dict, model_represents, label):\n \n model_represents = torch.from_numpy(model_represents).cuda()\n sing_lbl = torch.zeros(model_represents.shape[0])\n sin_score_lbl = torch.zeros(model_represents.shape[0])\n \n for i, data in enumerate(model_represents):\n sin_score_lbl[i] = torch.dot(v_ortho_dict[label[i]][0], data).abs() / torch.norm(data, p=2)\n \n kmeans = cluster.KMeans(n_clusters=2, random_state=0).fit(sin_score_lbl.reshape(-1, 1))\n \n if torch.mean(sin_score_lbl[kmeans.labels_==0]) < torch.mean(sin_score_lbl[kmeans.labels_==1]):\n kmeans.labels_ = 1 - kmeans.labels_\n \n output = []\n for idx, value in enumerate(kmeans.labels_):\n if value == 0:\n output.append(idx)\n \n return output\n\ndef kmean_eigen_out(label_list, out_list, teacher_idx=None):\n singular_dict, v_ortho_dict = get_singular_value_vector(label_list, out_list)\n \n for key in v_ortho_dict.keys():\n v_ortho_dict[key] = v_ortho_dict[key].cuda()\n \n output = kmean_singular_label(v_ortho_dict, out_list, label_list)\n \n return output\n\ndef topk_eigen_kmean(label_list, out_list, teacher_idx=None):\n singular_dict, v_ortho_dict = get_singular_value_vector(label_list, out_list)\n \n for key in v_ortho_dict.keys():\n v_ortho_dict[key] = v_ortho_dict[key].cuda()\n \n output = kmean_singular_label2(v_ortho_dict, out_list, label_list)\n \n return output\n\ndef get_anchor(label_list, out_list, teacher_idx=None):\n \n label_list = torch.from_numpy(label_list).long().numpy()\n singular_dict, v_ortho_dict = get_singular_value_vector(label_list, out_list)\n \n for key in v_ortho_dict.keys():\n v_ortho_dict[key] = v_ortho_dict[key].cuda()\n \n model_represents = torch.from_numpy(out_list).cuda()\n sin_score_lbl = [[] for _ in range(len(np.unique(label_list)))]\n \n for i, data in enumerate(model_represents):\n sin_score_lbl[label_list[i]].append(torch.dot(v_ortho_dict[label_list[i]][0], data).abs())\n \n # classwise topk\n v_ortho_dict_ = {}\n for index in np.unique(label_list):\n cls_score_lbl = sin_score_lbl[index]\n topk_v, topk_i = torch.topk(torch.tensor(cls_score_lbl), k=50)\n \n u, s, v = np.linalg.svd(model_represents[label_list==index][topk_i].cpu().numpy())\n v_ortho_dict_[index] = torch.from_numpy(v[0]).unsqueeze(0).cuda()\n \n output = kmean_singular_label2(v_ortho_dict_, model_represents.cpu().numpy(), label_list)\n return output\n \n\ndef isNoisy_ratio(data_loader):\n isNoisy_list = np.empty((0,))\n with tqdm(data_loader) as progress:\n for _, (_, label, index, label_gt) in enumerate(progress):\n isNoisy = label == label_gt\n isNoisy_list = np.concatenate((isNoisy_list, isNoisy.cpu()))\n\n print ('#############################')\n print (isNoisy_list.sum(), isNoisy_list.shape)\n print('purity in this dataset: {}'.format(isNoisy_list.sum() / isNoisy_list.shape))\n\n \ndef extract_teacherIdx(teacher, data_loader, parse):\n teacher.load_state_dict(torch.load('./checkpoint/' + parse.load_name)['state_dict'])\n teacher = teacher.cuda()\n if not parse.reinit:\n model.load_state_dict(torch.load('./checkpoint/' + parse.load_name)['state_dict'])\n for params in teacher.parameters():\n params.requires_grad = False\n if parse.distill_mode == 'eigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx = iterative_eigen(1,tea_label_list,tea_out_list)\n elif parse.distill_mode == 'fulleigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx = iterative_eigen(100,tea_label_list,tea_out_list)\n elif parse.distill_mode == 'kmean_eigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx = kmean_eigen_out(tea_label_list, tea_out_list)\n elif parse.distill_mode == 'topk_eigen_kmean':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx = topk_eigen_kmean(tea_label_list, tea_out_list)\n else:\n teacher_idx = get_loss_list(teacher, data_loader)\n print('||||||original||||||')\n isNoisy_ratio(data_loader)\n if parse.second_load_name !=None:\n teacher.load_state_dict(torch.load('./checkpoint/' + parse.second_load_name)['state_dict'])\n teacher = teacher.cuda()\n if not parse.reinit:\n model.load_state_dict(torch.load('./checkpoint/' + parse.second_load_name)['state_dict'])\n for params in teacher.parameters():\n params.requires_grad = False\n if parse.distill_mode == 'eigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx2 = iterative_eigen(1,tea_label_list,tea_out_list,teacher_idx)\n elif parse.distill_mode == 'fulleigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx2 = iterative_eigen(100,tea_label_list,tea_out_list)\n else:\n teacher_idx2 = get_loss_list(teacher, data_loader)\n teacher_idx = list(set(teacher_idx) & set(teacher_idx2))\n print('second_distillation')\n if parse.third_load_name !=None:\n teacher.load_state_dict(torch.load('./checkpoint/' + parse.third_load_name)['state_dict'])\n teacher = teacher.cuda()\n if not parse.reinit:\n model.load_state_dict(torch.load('./checkpoint/' + parse.third_load_name)['state_dict'])\n for params in teacher.parameters():\n params.requires_grad = False\n if parse.distill_mode == 'eigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx3 = iterative_eigen(1,tea_label_list,tea_out_list, teacher_idx)\n elif parse.distill_mode == 'fulleigen':\n tea_label_list, tea_out_list = get_out_list(teacher, data_loader)\n teacher_idx3 = iterative_eigen(100,tea_label_list,tea_out_list)\n else:\n teacher_idx3 = get_loss_list(teacher, data_loader)\n teacher_idx = list(set(teacher_idx) & set(teacher_idx3))\n print('third_ distillation')\n\n return teacher_idx\n\n\n# def get_loss_list_2d(model, data_loader, n_clusters=2, c_clusters=1):\n# loss_list = np.empty((0, 2))\n# model.cuda()\n \n# with tqdm(data_loader) as progress:\n# for batch_idx, (data, label, index, label_gt) in enumerate(progress):\n# data = data.cuda()\n# label, label_gt = label.long().cuda(), label_gt.long().cuda()\n\n# _, pred = model(data)\n# loss = torch.nn.CrossEntropyLoss(reduction='none')(pred, label)\n \n# prob = torch.softmax(pred, dim=-1)\n \n# top2_log_pred, top2_ind = torch.topk(torch.log(prob), k=n_clusters, dim=-1)\n# is_pred_wrong = (top2_ind[:, 0] != label).bool()\n# is_pred_correct = (top2_ind[:, 0] == label).bool()\n \n# label_top1 = torch.stack([loss, -top2_log_pred[:, 0]], dim=1) # for pred wrong\n# top2_log_pred = -top2_log_pred\n# top2_log_pred[is_pred_wrong] = label_top1[is_pred_wrong]\n\n# loss_list = np.concatenate((loss_list, top2_log_pred.detach().cpu().numpy()), axis=0)\n \n# kmeans = cluster.KMeans(n_clusters=n_clusters, random_state=0).fit(loss_list.reshape(50000,2))\n \n# mean_losses = []\n# for itr in range(n_clusters):\n# mean_losses.append(np.mean(loss_list[kmeans.labels_==itr][:, 0]))\n \n# _, clean_labels = torch.topk(-torch.tensor(mean_losses), k=c_clusters)\n \n# output=[]\n# for idx, value in enumerate(kmeans.labels_):\n# if value in clean_labels:\n# output.append(idx)\n \n# return output\n", "# https://github.com/AlanChou/Truncated-Loss/blob/master/TruncatedLoss.py\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nimport numpy as np\n\n__all__=['GCELoss', 'GCE_GTLoss']\n\nclass GCELoss(nn.Module):\n\n def __init__(self, q=0.7, k=0.5, trainset_size=50000, truncated=False):\n super().__init__()\n self.q = q\n self.k = k\n self.truncated = truncated\n self.weight = torch.nn.Parameter(data=torch.ones(trainset_size, 1), requires_grad=False)\n \n def forward(self, logits, targets, indexes, mode=None):\n p = F.softmax(logits, dim=1)\n Yg = torch.gather(p, 1, torch.unsqueeze(targets, 1))\n \n if self.truncated == True:\n if mode == 'ce':\n ce = nn.CrossEntropyLoss(reduction='none')\n loss = ce(logits, targets)\n loss = torch.mean(loss)\n else:\n loss = ((1-(Yg**self.q))/self.q)*self.weight[indexes] - ((1-(self.k**self.q))/self.q)*self.weight[indexes]\n loss = torch.mean(loss)\n else:\n if mode == 'ce':\n ce = nn.CrossEntropyLoss(reduction='none')\n loss = ce(logits, targets)\n loss = torch.mean(loss)\n else:\n loss = (1-(Yg**self.q))/self.q\n loss = torch.mean(loss)\n\n return loss\n\n def update_weight(self, logits, targets, indexes):\n p = F.softmax(logits, dim=1)\n Yg = torch.gather(p, 1, torch.unsqueeze(targets, 1))\n Lq = ((1-(Yg**self.q))/self.q)\n Lqk = np.repeat(((1-(self.k**self.q))/self.q), targets.size(0))\n Lqk = torch.from_numpy(Lqk).type(torch.cuda.FloatTensor)\n Lqk = torch.unsqueeze(Lqk, 1)\n \n condition = torch.gt(Lqk, Lq)\n self.weight[indexes] = condition.type(torch.cuda.FloatTensor)\n\nclass GCE_GTLoss(GCELoss):\n def __init__(self, q=0.7, k=0.5, trainset_size=50000, truncated=False):\n super().__init__(q, k, trainset_size, truncated)\n \n def forward(self, logits, targets, clean_indexs, index=None):\n \n # index : redundant variable. This is only used in ELR.\n p = F.softmax(logits, dim=1)\n Yg = torch.gather(p, 1, torch.unsqueeze(targets, 1))\n size = logits.shape[0] if torch.sum(clean_indexs) == 0 else torch.sum(clean_indexs)\n# print (torch.mean(((1-(Yg**self.q))/self.q)))\n \n loss = (1-(Yg**self.q))/self.q\n loss = torch.sum(loss[clean_indexs]) / size\n \n return loss" ]
[ [ "torch.mean", "numpy.linalg.svd", "torch.norm", "torch.nn.CrossEntropyLoss", "sklearn.cluster.KMeans", "numpy.unique", "torch.zeros", "torch.load", "torch.eq", "torch.from_numpy", "torch.tensor", "numpy.mean", "torch.sort", "torch.dot", "numpy.sum", "numpy.empty" ], [ "torch.mean", "torch.nn.functional.softmax", "torch.nn.CrossEntropyLoss", "torch.ones", "torch.sum", "torch.from_numpy", "torch.unsqueeze", "torch.gt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
maria-kuruvilla/temp_collective_new
[ "c45b72cee7c17072507eb67790d1699f5684098a", "c45b72cee7c17072507eb67790d1699f5684098a", "c45b72cee7c17072507eb67790d1699f5684098a", "c45b72cee7c17072507eb67790d1699f5684098a", "c45b72cee7c17072507eb67790d1699f5684098a", "c45b72cee7c17072507eb67790d1699f5684098a", "c45b72cee7c17072507eb67790d1699f5684098a" ]
[ "stats_csv_latency.py", "dtc_csv.py", "speed_before_loom.py", "individual_based_speed.py", "prop_ind_startles.py", "percentile_speed.py", "predictions_figures.py" ]
[ "\"\"\"\nGoal - to produce a csv file with temp, gs rep, loom and latency\n\"\"\" \n\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\n\n\n\ndef position(tr):\n return(tr.s)\n\n\ndef speed(tr):\n v = (position(tr)[2:] - position(tr)[:-2]) / 2\n b = np.linalg.norm(v, axis=-1)\n return(b*60)\n\ndef acceleration(tr):\n a = position(tr)[2:] - 2 * position(tr)[1:-1] + position(tr)[:-2]\n aa = np.linalg.norm(a, axis=-1) \n return(aa*3600)\n\n\ndef filter(tr, roi = 5): #ind (for individual) starts from 0, roi - edge of region of interest\n position_mask0 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,0],copy=False)\n position_mask1 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,1],copy=False)\n return(position_mask0,position_mask1) \n \ndef filter_speed(tr, roi = 5): \n speed_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), speed(tr),copy=False)\n \n return(speed_mask) \n\n\n\ndef filter_acc(tr, roi = 5): \n acc_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\ndef spikes_position_new(tr): #uses filter_speed\n list1 = []\n for j in range(tr.number_of_individuals):\n list2 = [i for i, value in enumerate(filter_speed(tr,5)[:,j]) if value > 10]\n list2.insert(0,100000000)\n list1 = list1 + [value for i,value in enumerate(list2[1:]) if (value != (list2[i]+1))]\n \n return(list1)\n\nrows = []\nwith open('../../data/temp_collective/looms_roi.csv', 'r') as csvfile:\n looms = csv.reader(csvfile)\n for row in looms:\n rows.append(row)\n \n \n\n\ndef loom_frame(temp, groupsize, rep):\n if temp == 29:\n cam = 'Cam 7'\n elif temp == 25:\n cam = 'Cam 8'\n elif temp == 17:\n cam = 'Cam 9'\n elif temp == 13:\n cam = 'Cam 10'\n elif temp == 21:\n cam = 'Cam 11'\n elif temp == 9:\n cam = 'Cam 12'\n g = str(groupsize)\n r = str(rep)\n loom = np.zeros([5,1]) \n for i in range(len(rows)):\n if rows[i][1]==cam and rows[i][3]==g and rows[i][4]==r:\n for j in range(5):\n loom[j] = int(rows[i][2]) + j*11403 \n \n return(loom)\n\n\ndef accurate_startles_frame(tr, temp, groupsize, rep,i): #i starts from 0 #uses filtered data\n list1 = spikes_position_new(tr)\n loom = loom_frame(temp, groupsize, rep)\n list2 = [value for value in list1 if (value < (loom[i] + 700) and value > (loom[i]+500)) ]\n return(list2) \n \n\ndef first_startle(tr, temp, groupsize, rep,i): #uses filtered data\n a = accurate_startles_frame(tr, temp, groupsize, rep,i) # i starts from 0\n if not a:\n return(np.nan)\n else:\n return(min(a)) \n \n\ndef latency(tr, temp, groupsize, rep): #uses filtred data\n a = np.empty([5,1])\n a.fill(np.nan)\n b = loom_frame(temp, groupsize, rep)\n\n for i in range(5):\n a[i] = first_startle(tr, temp, groupsize, rep,i) - b[i]\n \n return(np.nanmean(a))\n\ndef latency_loom(tr, temp, groupsize, rep, loom): #uses filtred data #loom starts from 0\n \n b = loom_frame(temp, groupsize, rep)\n\n lat_loom = first_startle(tr, temp, groupsize, rep,loom) - b[loom]\n \n return(lat_loom)\n\n\ntemperature = range(9,30,4)\n\n\n\ngroup = [1,2,4,8,16,32]\n\n\n\nreplication = range(10) # number of replicates per treatment\n\n#output parent directory\nparent_dir = '../../output/temp_collective/roi'\n\nwith open('../../data/temp_collective/roi/stats_loom_latency_nan.csv', mode='w') as stats_speed:\n writer = csv.writer(stats_speed, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n writer.writerow(['Temperature', 'Groupsize', 'Replicate', 'loom','latency'])\n for i in temperature:\n print(i)\n jj = 0 # to keep count of groups\n for j in group:\n for k in replication:\n if j == 1:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories.npy'\n else:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories_wo_gaps.npy'\n try:\n tr = tt.Trajectories.from_idtrackerai(trajectories_file_path, \t\t center=True).normalise_by('body_length')\n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\n except FileNotFoundError:\n print(i,j,k)\n print('File not found')\n continue\n #perc_speed = np.percentile(filter_speed(tr,5).compressed(),90)\n #perc_acc = np.percentile(filter_acc(tr,5).compressed(),90)\n for loom in range(5):\n lat = latency_loom(tr,i,j,k+1, loom)[0]\n if np.isnan(lat) != True:\n writer.writerow([i, j, k+1, loom+1,lat])\n\n", "\"\"\"\nCreated on thu Jan 28 2021\n\n@author: Maria Kuruvilla\n\nGoal - Write csv file containing all covariates and distance to center before loom - the first 20k frames\n\"\"\"\n\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\nimport pandas as pd \n\n#temperatures used in the experiment - used for files naminf=g \ntemperature = range(9,30,4)\n\n#group sizes used in the experiment - used for naming files\ngroup = [1,2,4,8,16]\n\n#latest tracked replicate\nreplication = range(10) # number of replicates per treatment\n\nmet = pd.read_csv('../../data/temp_collective/roi/metadata_w_loom.csv')\n\n\n\n\n\nwith open('../../data/temp_collective/roi/stats_dtc_before_loom.csv', mode='w') as stats_speed:\n writer = csv.writer(stats_speed, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n writer.writerow(['Temperature', 'Groupsize', 'Replicate', 'Trial', 'Date', 'Subtrial','Time_fish_in', 'Time_start_record','dtc_before_loom','dtc_before_loom_norm'])\n\n for i in temperature:\n \n for j in group:\n \n\n for k in replication:\n print(i,j,k+1)\n if j == 1:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories.npy'\n else:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories_wo_gaps.npy'\n try:\n tr = tt.Trajectories.from_idtrackerai(trajectories_file_path, center=True).normalise_by('body_length')\n tr1 = tt.Trajectories.from_idtrackerai(trajectories_file_path, center=True)\n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\n tr1.new_time_unit(tr.params['frame_rate'], 'seconds')\n except FileNotFoundError:\n print(i,j,k)\n print('File not found')\n continue\n \n \n \n for m in range(len(met.Temperature)):\n if met.Temperature[m] == i and met.Groupsize[m] == j and met.Replicate[m] == (k+1): \n writer.writerow([i,j,k+1,met.Trial[m],met.Date[m],met.Subtrial[m],met.Time_fish_in[m],met.Time_start_record[m],np.nanmean(tr1.distance_to_origin[0:20000,:]),np.nanmean(tr.distance_to_origin[0:20000,:])]) \n \n", "\"\"\"\nGoal - to write one csv file with speed right before each loom and with\nloom as covariate and that have both speed and acc masks\nThu, Jul 1st 2021\n\n\"\"\"\n\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\nimport pandas as pd\nfrom scipy.spatial import ConvexHull\n\ndef position(tr): #shape returns tr.s.shape\n return(tr.s)\n\n\ndef speed(tr): #speed(tr).shape returns tr.speed.shape - 2\n v = (position(tr)[2:] - position(tr)[:-2]) / 2\n b = np.linalg.norm(v, axis=-1)\n return(b*60)\n\ndef acceleration(tr): #shape returns tr.acceleration.shape - 2\n a = position(tr)[2:] - 2 * position(tr)[1:-1] + position(tr)[:-2]\n aa = np.linalg.norm(a, axis=-1) \n return(aa*3600)\n \ndef e(tr): #e.shape returns tr.speed.shape - 2\n vel = (position(tr)[2:] - position(tr)[:-2]) / 2\n n = np.linalg.norm(v,axis = 2) \n return(vel/n[...,np.newaxis])\n\n\ndef filter_low_pass(tr, roi1 = 30, roi2 = 3340): #ind (for individual) starts from 0, roi - edge of region of interest\n position_mask0 = np.ma.masked_where((speed(tr)[1:-1] > roi1)|(speed(tr)[0:-2] > roi1)|(speed(tr)[2:] > roi1)|(acceleration(tr)[1:-1] > roi2)|(acceleration(tr)[0:-2] > roi2)|(acceleration(tr)[2:] > roi2), position(tr)[2:-2,:,0],copy=False)\n position_mask1 = np.ma.masked_where((speed(tr)[1:-1] > roi1)|(speed(tr)[0:-2] > roi1)|(speed(tr)[2:] > roi1)|(acceleration(tr)[1:-1] > roi2)|(acceleration(tr)[0:-2] > roi2)|(acceleration(tr)[2:] > roi2), position(tr)[2:-2,:,1],copy=False)\n return(position_mask0,position_mask1) \n\ndef filter_speed_low_pass(tr, roi1 = 30, roi2 = 3340):\n speed_mask = np.ma.masked_where((speed(tr) > roi1)|(acceleration(tr) > roi2), speed(tr),copy=False)\n \n return(speed_mask) \n\ndef filter_acc_low_pass(tr, roi1 = 30, roi2 = 3340):\n acc_mask = np.ma.masked_where((speed(tr) > roi1)|(acceleration(tr) > roi2), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\n\n#prop of ind that startles\n\ndef prop_startles(tr, loom,n,s1=30,s2=3340, t=10):\n count = 0\n for j in range(tr.number_of_individuals):\n list2 = []\n list2 = [i for i, value in enumerate(filter_speed_low_pass(tr,s1,s2)[(loom[n]+500):(loom[n]+700),j]) if value > t]\n \n if list2:\n count = count + 1\n #if count == 0:\n # return(np.nan)\n else:\n return(count/tr.number_of_individuals) \n\n#latency \n\ndef spikes_position_new(tr,roi1 = 30, roi2 = 3340, t = 10): #uses filter_speed\n list1 = []\n for j in range(tr.number_of_individuals):\n list2 = [i for i, value in enumerate(filter_speed_low_pass(tr, roi1, roi2)[:,j]) if value > t]\n list2.insert(0,100000000)\n list1 = list1 + [value for i,value in enumerate(list2[1:]) if (value != (list2[i]+1))]\n \n return(list1)\n\ndef accurate_startles(tr, loom, n, roi1 = 30, roi2 = 3340, t = 10): #uses filtered speed # n starts from 0\n list1 = spikes_position_new(tr,roi1 , roi2 , t)\n \n list2 = [i for i, value in enumerate(list1[:]) if value < (loom[n] + 700) and value > (loom[n]+500) ]\n \n return(len(list2))\n\ndef accurate_startles_frame(tr, loom, n, roi1 = 30, roi2 = 3340, t = 10): #uses filtered speed # n starts from 0\n list1 = spikes_position_new(tr,roi1 , roi2 , t)\n \n list2 = [value for value in list1 if value < (loom[n] + 700) and value > (loom[n]+500) ]\n \n return(list2)\n\ndef startles_list_new(tr,roi1 = 30, roi2 = 3340, t = 10): #uses filtered data\n return(len(spikes_position_new(tr,roi1 , roi2 , t)))\n\ndef first_startle(tr, loom,n,roi1 = 30, roi2 = 3340, t = 10):\n a = accurate_startles_frame(tr,loom,n,roi1 , roi2 , t)\n if not a:\n return(accurate_startles_frame(tr,loom,n,roi1 , roi2 , t))\n else:\n return(min(a)) \n \n\ndef latency(tr, loom,n,roi1 = 30, roi2 = 3340, t = 10):\n a = first_startle(tr,loom,n,roi1 , roi2 , t)\n if not a:\n return(float('nan'))\n else:\n return(a - loom[n])\n \n#number of startles\n#accurate startles()\n\n#speed\ndef speed_percentile(tr, percentile, loom, n,roi1=30,roi2=3340):\n s_p = np.percentile(filter_speed_low_pass(tr,roi1,roi2)[(loom[n]+500):(loom[n]+700),:].compressed(),percentile)\n return(s_p)\n\n#acc\ndef acc_percentile(tr, percentile, loom, n,roi1=30,roi2=3340):\n a_p = np.percentile(filter_acc_low_pass(tr,roi1,roi2)[(loom[n]+500):(loom[n]+700),:].compressed(),percentile)\n return(a_p)\n\n\n#speed before each loom\ndef speed_percentile_before(tr, percentile, loom, n,roi1=30,roi2=3340):\n s_p = np.percentile(filter_speed_low_pass(tr,roi1,roi2)[(loom[n]-200):(loom[n]),:].compressed(),percentile)\n return(s_p)\n\n#acc before each loom\ndef acc_percentile_before(tr, percentile, loom, n,roi1=30,roi2=3340):\n a_p = np.percentile(filter_acc_low_pass(tr,roi1,roi2)[(loom[n]-200):(loom[n]),:].compressed(),percentile)\n return(a_p)\n\n\n\n\n#annd\n\ndef annd(trajectory,looms,n, roi1 = 30, roi2 = 3340):\n if tr.number_of_individuals==1:\n annd = np.nan\n else:\n nnd = np.empty([200, trajectory.number_of_individuals])\n nnd.fill(np.nan)\n \n nd = np.empty([200,trajectory.number_of_individuals])\n nd.fill(np.nan)\n \n for i in range(trajectory.number_of_individuals):\n for j in range(trajectory.number_of_individuals):\n if i!=j:\n nd[:,j] = np.sqrt((filter_low_pass(tr, roi1, roi2)[0][(looms[n]+700):(looms[n]+900),i] - filter_low_pass(tr, roi1, roi2)[0][(looms[n]+700):(looms[n]+900),j])**2 + (filter_low_pass(tr, roi1, roi2)[1][(looms[n]+700):(looms[n]+900),i] - filter_low_pass(tr, roi1, roi2)[1][(looms[n]+700):(looms[n]+900),i])**2)\n \n nnd[:,i] = np.nanmin(nd,1)\n \n annd = np.nanmean(nnd)\n return(annd)\n \n \n \n\n#convex hull area #does not use masked data because tracking errors will not affect convex hull area\ndef convex_hull(tr,looms,n, roi1 = 30, roi2 = 3340):\n if tr.number_of_individuals<4:\n return(np.nan)\n else:\n frame_list = list(range(looms[n]+700, looms[n]+900)) \n convex_hull_area = np.empty([200])\n count = 0\n convex_hull_area.fill(np.nan)\n for n in frame_list :\n convex_hull_area[count]=ConvexHull(tr.s[n]).area\n count += 1\n return(np.nanmean(convex_hull_area))\n\n#startle data\ndef startle_data(tr,t=10,roi1=30,roi2=3340):\n speed_mask2 = np.ma.masked_where((speed(tr) > roi1)|(speed(tr) < t)|(acceleration(tr) > roi2), speed(tr),copy=False)\n return(speed_mask2) \n\n#startle data percentile\ndef startle_data_percentile(tr, percentile, loom, n,t=10,roi1=30,roi2=3340):\n a = startle_data(tr,t,roi1,roi2)[(loom[n]+500):(loom[n]+700),:]\n if (a.all() is np.ma.masked) == True:\n s_p = np.nan\n else:\n s_p = np.percentile(a.compressed(),percentile)\n return(s_p)\n\n\n#dtc #not masked\ndef dtc(tr,loom,n):\n dto = np.nanmean(tr.distance_to_origin[(loom[n]+700):(loom[n]+900),:])\n return(dto)\n\n\ntemperature = [9,13,17,21,25,29]#range(9,30,4)\n\ngroup = [1,2,4,8,16]\n\nreplication = range(10) # number of replicates per treatment\n\nmet = pd.read_csv('../../data/temp_collective/roi/metadata_w_loom.csv')\n\nwith open('../../data/temp_collective/roi/speed_acc_before_loom_params_w_loom.csv', mode='w') as stats_speed:\n writer = csv.writer(stats_speed, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n writer.writerow([\n 'Temperature', 'Groupsize', 'Replicate', 'Trial', 'Date', 'Subtrial',\n 'Time_fish_in', 'Time_start_record','Loom','avg_speed','speed_percentile50',\n 'speed_percentile90','speed_percentile99','speed_percentile999','avg_acc',\n 'acc_percentile50','acc_percentile90','acc_percentile99','acc_percentile999'])\n\n\n for i in temperature:\n \n for j in group:\n \n\n for k in replication:\n #print(i,j,k+1)\n if j == 1:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories.npy'\n else:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(i)+'/' +str(j)+'/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories_wo_gaps.npy'\n try:\n tr = tt.Trajectories.from_idtrackerai(trajectories_file_path, center=True).normalise_by('body_length')\n \n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\n \n except FileNotFoundError:\n print(i,j,k)\n print('File not found')\n continue\n \n \n looms = []\n for m in range(len(met.Temperature)):\n if met.Temperature[m] == i and met.Groupsize[m] == j and met.Replicate[m] == (k+1): \n looms.append(met['Loom 1'][m]) \n looms.append(met['Loom 2'][m]) \n looms.append(met['Loom 3'][m]) \n looms.append(met['Loom 4'][m]) \n looms.append(met['Loom 5'][m])\n for n in range(5):\n frame_list=list(range(looms[n]-200,looms[n]))\n \n writer.writerow([\n i,j,k+1,met.Trial[m],met.Date[m],met.Subtrial[m],\n met.Time_fish_in[m],met.Time_start_record[m],n+1,\n np.nanmean(filter_speed_low_pass(tr)[frame_list]),\n speed_percentile_before(tr,50,looms,n),speed_percentile_before(tr,90,looms,n),\n speed_percentile_before(tr,99,looms,n),speed_percentile_before(tr,99.9,looms,n),\n np.nanmean(filter_acc_low_pass(tr)[frame_list]),\n acc_percentile_before(tr,50,looms,n),acc_percentile_before(tr,90,looms,n),\n acc_percentile_before(tr,99,looms,n),acc_percentile_before(tr,99.9,looms,n)]) \n\n\n", "\"\"\"\nMon Jan 25th\nGoal - To have prelim code for individual based speed ratio - speed during loom:speed before loom\n\"\"\"\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\nimport pandas as pd\n\nmet = pd.read_csv('../../data/temp_collective/roi/metadata_w_loom.csv')\n\n#output parent directory\nparent_dir = '../../data/temp_collective/roi'\n\ndef position(tr): #shape returns tr.s.shape\n return(tr.s)\n\ndef speed(tr): #speed(tr).shape returns tr.speed.shape - 2\n v = (position(tr)[2:] - position(tr)[:-2]) / 2\n b = np.linalg.norm(v, axis=-1)\n return(b*60)\n\ndef acceleration(tr): #shape returns tr.acceleration.shape - 2\n a = position(tr)[2:] - 2 * position(tr)[1:-1] + position(tr)[:-2]\n aa = np.linalg.norm(a, axis=-1) \n return(aa*3600)\n \ndef e(tr): #e.shape returns tr.speed.shape - 2\n vel = (position(tr)[2:] - position(tr)[:-2]) / 2\n n = np.linalg.norm(v,axis = 2) \n return(vel/n[...,np.newaxis])\n\ndef filter_low_pass(tr, roi1 = 30, roi2 = 3340): #ind (for individual) starts from 0, roi - edge of region of interest\n position_mask0 = np.ma.masked_where((speed(tr)[1:-1] > roi1)|(speed(tr)[0:-2] > roi1)|(speed(tr)[2:] > roi1)|(acceleration(tr)[1:-1] > roi2)|(acceleration(tr)[0:-2] > roi2)|(acceleration(tr)[2:] > roi2), position(tr)[2:-2,:,0],copy=False)\n position_mask1 = np.ma.masked_where((speed(tr)[1:-1] > roi1)|(speed(tr)[0:-2] > roi1)|(speed(tr)[2:] > roi1)|(acceleration(tr)[1:-1] > roi2)|(acceleration(tr)[0:-2] > roi2)|(acceleration(tr)[2:] > roi2), position(tr)[2:-2,:,1],copy=False)\n return(position_mask0,position_mask1) \n\ndef filter_speed_low_pass(tr, roi = 30): \n speed_mask = np.ma.masked_where((speed(tr) > roi), speed(tr),copy=False)\n \n return(speed_mask) \n\ndef filter_acc_low_pass(tr, roi = 3340): \n acc_mask = np.ma.masked_where((acceleration(tr) > roi), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\ndef spikes_position_new(tr,j): #uses filter_speed\n list1 = []\n \n list2 = [i for i, value in enumerate(filter_speed_low_pass(tr)[:,j]) if value > 10]\n list2.insert(0,100000000)\n list1 = list1 + [value for i,value in enumerate(list2[1:]) if (value != (list2[i]+1))]\n \n return(list1)\n\ndef accurate_startles(tr, loom, ind): #uses filtered speed\n list1 = spikes_position_new(tr, ind)\n \n\n \n list2 = [i for i, value in enumerate(list1[:]) if value < (loom[0] + 700) and value > (loom[0]+500) ]\n list2 = list2 + [i for i, value in enumerate(list1[:]) if value < (loom[1] + 700) and value > (loom[1]+500) ]\n list2 = list2 + [i for i, value in enumerate(list1[:]) if value < (loom[2] + 700) and value > (loom[2]+500) ]\n list2 = list2 + [i for i, value in enumerate(list1[:]) if value < (loom[3] + 700) and value > (loom[3]+500) ]\n list2 = list2 + [i for i, value in enumerate(list1[:]) if value < (loom[4] + 700) and value > (loom[4]+500) ]\n \n return(len(list2))\n\n #argparse\ndef boolean_string(s):\n # this function helps with getting Boolean input\n if s not in ['False', 'True']:\n raise ValueError('Not a valid boolean string')\n return s == 'True' # note use of ==\n\n# create the parser object\nparser = argparse.ArgumentParser()\n\n# NOTE: argparse will throw an error if:\n# - a flag is given with no value\n# - the value does not match the type\n# and if a flag is not given it will be filled with the default.\nparser.add_argument('-a', '--a_string', default='hi', type=str)\nparser.add_argument('-b1', '--integer_b1', default=29, type=int)\nparser.add_argument('-b2', '--integer_b2', default=16, type=int)\nparser.add_argument('-b3', '--integer_b3', default=3, type=int)\nparser.add_argument('-c', '--float_c', default=1.5, type=float)\nparser.add_argument('-v', '--verbose', default=True, type=boolean_string)\n# Note that you assign a short name and a long name to each argument.\n# You can use either when you call the program, but you have to use the\n# long name when getting the values back from \"args\".\n\n# get the arguments\nargs = parser.parse_args()\n\nparent_dir = '../../output/temp_collective/roi'\n\ninput_dir = parent_dir + '/' + str(args.integer_b1) + '/' + str(args.integer_b2) + '/' \ninput_file = input_dir + str(args.integer_b3) + '_nosmooth.p'\n#sigma_values = 1.5 #smoothing parameter\nif args.integer_b2 == 1:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(args.integer_b1)+'/' +str(args.integer_b2)+'/GS_'+str(args.integer_b2)+'_T_'+str(args.integer_b1)+'_roi_'+str(args.integer_b3)+'/trajectories.npy'\nelse:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(args.integer_b1)+'/' +str(args.integer_b2)+'/GS_'+str(args.integer_b2)+'_T_'+str(args.integer_b1)+'_roi_'+str(args.integer_b3)+'/trajectories_wo_gaps.npy'\ntry:\n tr = tt.Trajectories.from_idtrackerai(trajectories_file_path, center=True).normalise_by('body_length')\n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\nexcept FileNotFoundError:\n print(args.integer_b1,args.integer_b2,args.integer_b3)\n print('File not found')\n pass\n\nlooms = []\n\nfor m in range(len(met.Temperature)):\n if met.Temperature[m] == args.integer_b1 and met.Groupsize[m] == args.integer_b2 and met.Replicate[m] == args.integer_b3: \n looms.append(met['Loom 1'][m]) \n looms.append(met['Loom 2'][m]) \n looms.append(met['Loom 3'][m]) \n looms.append(met['Loom 4'][m]) \n looms.append(met['Loom 5'][m])\n\nframe_list = np.r_[(looms[0]+500):(looms[0]+700),(looms[1]+500):(looms[1]+700),(looms[2]+500):(looms[2]+700),(looms[3]+500):(looms[3]+700),(looms[4]+500):(looms[4]+700)]\nmax_speed = np.empty([tr.number_of_individuals, 1])\nmax_speed.fill(np.nan)\nfor ind in range(tr.number_of_individuals):\n\tif accurate_startles(tr,looms, ind) != 0:\n\t\tmax_speed[ind,0] = np.nanmax(filter_speed_low_pass(tr)[frame_list,ind])\n\nprint(np.nanmean(max_speed))\n\n", "\"\"\"\nCreated on Thu Dec 3 2020\n\n@author: Maria Kuruvilla\n\nGoal - proportion of individuals that startle (using only masked data)\n\"\"\"\n\n\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\nimport pandas as pd\n\n\n#argparse\ndef boolean_string(s):\n # this function helps with getting Boolean input\n if s not in ['False', 'True']:\n raise ValueError('Not a valid boolean string')\n return s == 'True' # note use of ==\n\n# create the parser object\nparser = argparse.ArgumentParser()\n\n# NOTE: argparse will throw an error if:\n# - a flag is given with no value\n# - the value does not match the type\n# and if a flag is not given it will be filled with the default.\nparser.add_argument('-a', '--a_string', default='hi', type=str)\nparser.add_argument('-b1', '--integer_b1', default=29, type=int)\nparser.add_argument('-b2', '--integer_b2', default=1, type=int)\nparser.add_argument('-b3', '--integer_b3', default=1, type=int)\nparser.add_argument('-c', '--float_c', default=1.5, type=float)\nparser.add_argument('-v', '--verbose', default=True, type=boolean_string)\n# Note that you assign a short name and a long name to each argument.\n# You can use either when you call the program, but you have to use the\n# long name when getting the values back from \"args\".\ndef position(tr): #shape returns tr.s.shape\n return(tr.s)\n\n\ndef speed(tr): #speed(tr).shape returns tr.speed.shape - 2\n v = (position(tr)[2:] - position(tr)[:-2]) / 2\n b = np.linalg.norm(v, axis=-1)\n return(b*60)\n\ndef acceleration(tr): #shape returns tr.acceleration.shape - 2\n a = position(tr)[2:] - 2 * position(tr)[1:-1] + position(tr)[:-2]\n aa = np.linalg.norm(a, axis=-1) \n return(aa*3600)\n \ndef e(tr): #e.shape returns tr.speed.shape - 2\n vel = (position(tr)[2:] - position(tr)[:-2]) / 2\n n = np.linalg.norm(v,axis = 2) \n return(vel/n[...,np.newaxis])\n\n \n\ndef filter(tr, roi = 5): #ind (for individual) starts from 0, roi - edge of region of interest\n#shape returns tr.s.shape -2 \n position_mask0 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,0],copy=False)\n position_mask1 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,1],copy=False)\n return(np.ma.dstack((position_mask0,position_mask1))) \n \ndef filter_speed(tr, roi = 5): #shape returns tr.s.shape -2 \n speed_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), speed(tr),copy=False)\n \n return(speed_mask) \n\n\n\ndef filter_acc(tr, roi = 5): #shape returns tr.s.shape -2 \n acc_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\n \ndef filter_e(tr, roi =5):\n x = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), e(tr)[:,:,0],copy=False)\n y = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), e(tr)[:,:,1],copy=False)\n return(np.ma.dstack((x,y))) \n# get the arguments\nargs = parser.parse_args()\n\nmet = pd.read_csv('../../data/temp_collective/roi/metadata_w_loom.csv')\n\nlooms = []\nmet = pd.read_csv('../../data/temp_collective/roi/metadata_w_loom.csv')\nfor i in range(len(met.Temperature)):\n if met.Temperature[i] == args.integer_b1 and met.Groupsize[i] == args.integer_b2 and met.Replicate[i] == args.integer_b3 : \n looms.append(met['Loom 1'][i]) \n looms.append(met['Loom 2'][i]) \n looms.append(met['Loom 3'][i]) \n looms.append(met['Loom 4'][i]) \n looms.append(met['Loom 5'][i]) \n\n\ndef prop_startles(tr, loom):\n count = 0\n for j in range(tr.number_of_individuals):\n list2 = []\n list2 = [i for i, value in enumerate(filter_speed(tr,5)[(loom+500):(loom+700),j]) if value > 10]\n \n if list2:\n count = count + 1\n if count == 0:\n return(np.nan)\n else:\n return(count/tr.number_of_individuals) \n\nif args.integer_b2 == 1:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(args.integer_b1)+'/' +str(args.integer_b2)+'/GS_'+str(args.integer_b2)+'_T_'+str(args.integer_b1)+'_roi_'+str(args.integer_b3)+'/trajectories.npy'\nelse:\n trajectories_file_path = '../../data/temp_collective/roi/'+str(args.integer_b1)+'/' +str(args.integer_b2)+'/GS_'+str(args.integer_b2)+'_T_'+str(args.integer_b1)+'_roi_'+str(args.integer_b3)+'/trajectories_wo_gaps.npy'\ntry:\n tr = tt.Trajectories.from_idtrackerai(trajectories_file_path, center=True).normalise_by('body_length')\n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\nexcept FileNotFoundError:\n print(args.integer_b1,args.integer_b2,args.integer_b3)\n print('File not found')\n pass \n \nstartles_prop = np.empty([5, 1]) # empty array to calculate average no. of startles per treatment\nstartles_prop.fill(np.nan)\n\nfor i in range(5): \n startles_prop[i] = prop_startles(tr,looms[i])\naverage_startles_prop = np.nanmean(startles_prop)\n\nprint(average_startles_prop)\n", "\"\"\"\nGoal - To calculate x percentile speed for each group size and temperature.\n\nCreated - 10/20/20\n\"\"\"\n\n\n\nimport os\nimport pathlib\nfrom pprint import pprint\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.spatial import distance\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nimport trajectorytools as tt\nimport trajectorytools.plot as ttplot\nimport trajectorytools.socialcontext as ttsocial\nfrom trajectorytools.constants import dir_of_data\nimport csv\nimport pickle\nimport argparse\n\ndef position(tr):\n return(tr.s)\n\n\ndef speed(tr):\n v = (position(tr)[2:] - position(tr)[:-2]) / 2\n b = np.linalg.norm(v, axis=-1)\n return(b*60)\n\ndef acceleration(tr):\n a = position(tr)[2:] - 2 * position(tr)[1:-1] + position(tr)[:-2]\n aa = np.linalg.norm(a, axis=-1) \n return(aa*3600)\n \n\ndef filter(tr, roi = 5): #ind (for individual) starts from 0, roi - edge of region of interest\n position_mask0 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,0],copy=False)\n position_mask1 = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), position(tr)[1:-1,:,1],copy=False)\n return(position_mask0,position_mask1) \n \ndef filter_speed(tr, roi = 5): \n speed_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), speed(tr),copy=False)\n \n return(speed_mask) \n\n\n\ndef filter_acc(tr, roi = 5): \n acc_mask = np.ma.masked_where((tr.distance_to_origin[1:-1] > roi)|(tr.distance_to_origin[0:-2] > roi)|(tr.distance_to_origin[2:] > roi), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\ndef filter_low_pass(tr, roi1 = 30, roi2 = 3340): #ind (for individual) starts from 0, roi - edge of region of interest\n position_mask0 = np.ma.masked_where((speed(tr)[1:-1] > roi1)|(speed(tr)[0:-2] > roi1)|(speed(tr)[2:] > roi1)|(acceleration(tr)[1:-1] > roi2)|(acceleration(tr)[0:-2] > roi2)|(acceleration(tr)[2:] > roi2), position(tr)[2:-2,:,0],copy=False)\n position_mask1 = np.ma.masked_where((speed(tr)[1:-1] > roi1)|(speed(tr)[0:-2] > roi1)|(speed(tr)[2:] > roi1)|(acceleration(tr)[1:-1] > roi2)|(acceleration(tr)[0:-2] > roi2)|(acceleration(tr)[2:] > roi2), position(tr)[2:-2,:,1],copy=False)\n return(position_mask0,position_mask1) \n\ndef filter_speed_low_pass(tr, roi = 30): \n speed_mask = np.ma.masked_where((speed(tr) > roi), speed(tr),copy=False)\n \n return(speed_mask) \n\n\n\ndef filter_acc_low_pass(tr, roi = 3340): \n acc_mask = np.ma.masked_where((acceleration(tr) > roi), acceleration(tr),copy=False)\n \n return(acc_mask)#[~acc_mask.mask].data) \n\n\n#argparse\ndef boolean_string(s):\n # this function helps with getting Boolean input\n if s not in ['False', 'True']:\n raise ValueError('Not a valid boolean string')\n return s == 'True' # note use of ==\n\n# create the parser object\nparser = argparse.ArgumentParser()\n\n# NOTE: argparse will throw an error if:\n# - a flag is given with no value\n# - the value does not match the type\n# and if a flag is not given it will be filled with the default.\nparser.add_argument('-a', '--a_string', default='hi', type=str)\nparser.add_argument('-b', '--integer_b', default=90, type=int)\nparser.add_argument('-c', '--float_c', default=99.5, type=float)\nparser.add_argument('-d', '--integer_d', default=1, type=int)\nparser.add_argument('-v', '--verbose', default=True, type=boolean_string)\n# Note that you assign a short name and a long name to each argument.\n# You can use either when you call the program, but you have to use the\n# long name when getting the values back from \"args\".\n\n# get the arguments\nargs = parser.parse_args()\n\n#functions\n \n\ntemperature = range(9,30,4)\n\n\n\ngroup = [1,2,4,8,16]\n\n\n\nreplication = range(10) # number of replicates per treatment\n\n\npercentile_speed = np.empty([len(temperature), len(group)])\npercentile_speed.fill(np.nan)\n\nstd_percentile_speed = np.empty([len(temperature), len(group)])\nstd_percentile_speed.fill(np.nan)\n\n\n\n#output parent directory\nparent_dir = '../../data/temp_collective/roi'\n\nii = 0 # to keep count of temperature\n\n#frames = 5000 #number of frames for which annd is calculated\n\nfor i in temperature:\n jj = 0 # to keep count of groups\n for j in group:\n out_dir = parent_dir + '/' + str(i) + '/' + str(j) + '/' \n \n average_replicate_percentile_speed = np.empty([len(replication), 1])\n average_replicate_percentile_speed.fill(np.nan)\n\n for k in replication:\n \n if j == 1:\n input_file = out_dir + '/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories.npy'\n else: \n input_file = out_dir + '/GS_'+str(j)+'_T_'+str(i)+'_roi_'+str(k+1)+'/trajectories_wo_gaps.npy'\n \n \n \n \n try:\n tr = tt.Trajectories.from_idtrackerai(input_file, \t\t center=True).normalise_by('body_length')\n tr.new_time_unit(tr.params['frame_rate'], 'seconds')\t\t\n \n except FileNotFoundError:\n print(i,j,k)\n print('File not found')\n continue\n \n average_replicate_percentile_speed[k] = np.percentile(filter_speed_low_pass(tr).compressed(),args.float_c)\n \n \n \n \n percentile_speed[ii, jj] = np.nanmean(average_replicate_percentile_speed)\n std_percentile_speed[ii,jj] = np.nanstd(average_replicate_percentile_speed)\n\n \n \n jj= jj + 1\n \n ii = ii + 1\n\nout_dir = '../../output/temp_collective/roi/'\n\n# save it as a pickle file\np_c_fn1 = out_dir + 'percentile_speed_low_pass' + str(args.float_c)+ '.p'\npickle.dump(percentile_speed, open(p_c_fn1, 'wb')) # 'wb' is for write binary\n\np_c_fn2 = out_dir + 'percentile_speed_low_pass' + str(args.float_c) + '_std.p'\npickle.dump(std_percentile_speed, open(p_c_fn2, 'wb')) # 'wb' is for write binary\n \n", "\"\"\"\nGoal - make figures of the predictions with and without data\n\"\"\"\n\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndata1 = pd.read_csv('../../data/temp_collective/roi/loom_speed_predictions.csv')\n\ndata2 = pd.read_csv('../../data/temp_collective/roi/stats_loom_low_pass_data.csv')\n\n\ncolors = plt.cm.viridis(np.linspace(0,1,5))\n#Plotting\nlw=1.25\nfs=12\nfig = plt.figure(figsize=(10,6))\nax = fig.add_subplot(111)\n\"\"\"\nax.scatter(data2.Temperature[data2.Groupsize == 16][data2.loom == 1],\n data2[\"99_speed\"][data2.Groupsize == 16][data2.loom == 1], alpha = 0.5, color = colors[0])\n\nax.plot(\n data1.Temperature[data1.Groupsize == 16][data1.loom == 1], \n (data1.loom_speed[data1.Groupsize==16][data1.loom == 1])**2, color = colors[0])\nax.fill_between(\n data1.Temperature[data1.Groupsize == 16][data1.loom == 1], \n (data1.loom_speed025[data1.Groupsize==16][data1.loom == 1])**2, \n (data1.loom_speed975[data1.Groupsize==16][data1.loom == 1])**2, alpha = 0.3, color = colors[0])\nplt.xlabel('Temperature', size = fs)\nplt.ylabel('99th percentile of speed during loom', size = fs)\nax.set_title('Groupsize = 16, Loom = 1', fontsize = fs)\nout_dir = '../../output/temp_collective/roi_figures/predictions/loom_speed_predictions_wo_data.png'\nfig.savefig(out_dir, dpi = 300)\nplt.show()\n\n\n####################################\ngs = [1,2,4,8,16]\nloom = [1,2,3,4,5]\ncount = 0\ni = 16\nfor j in loom:\n \n ax.scatter(data2.Temperature[data2.Groupsize == i][data2.loom == j],\n data2[\"99_speed\"][data2.Groupsize == i][data2.loom == j], alpha = 0.5, color = colors[count])\n \n ax.plot(\n data1.Temperature[data1.Groupsize == i][data1.loom == j], \n (data1.loom_speed[data1.Groupsize==i][data1.loom == j])**2, color = colors[count], \n label = str(j))\n ax.fill_between(\n data1.Temperature[data1.Groupsize == i][data1.loom == j], \n (data1.loom_speed025[data1.Groupsize==i][data1.loom == j])**2, \n (data1.loom_speed975[data1.Groupsize==i][data1.loom == j])**2, alpha = 0.3, color = colors[count])\n count += 1\nplt.xlabel('Temperature', size = fs)\nplt.ylabel('99th percentile of speed during loom', size = fs)\nplt.legend(fontsize=fs, loc='upper right', title = 'Loom', framealpha = 0.5)\nax.set_title('Groupsize= 16', fontsize = fs)\nplt.xticks(ticks = [9,13,17,21,25,29], labels = [9,13,17,21,25,29])\nout_dir = '../../output/temp_collective/roi_figures/predictions/loom_speed_predictions_all_loom_wo_data.png'\nfig.savefig(out_dir, dpi = 300)\n\n\nplt.show()\n\"\"\"\n\n\n#annd after loom predictions\n\ndata1 = pd.read_csv('../../data/temp_collective/roi/annd_after_loom_predictions.csv')\n\ndata2 = pd.read_csv('../../data/temp_collective/roi/all_params_w_loom.csv')\n\ngs = [2,4,8,16]\n\n\n\ncolors = plt.cm.viridis(np.linspace(0,1,5))\n#Plotting\nlw=1.25\nfs=12\nfig = plt.figure(figsize=(10,6))\nax = fig.add_subplot(111)\ncount = 0\nfor i in gs:\n \"\"\"\n ax.scatter(data2.Temperature[data2.Groupsize == i],\n data2[\"annd\"][data2.Groupsize == i], alpha = 0.5, color = colors[count])\n \"\"\"\n ax.plot(\n data1.temp[data1.gs == i][data1.date == 18106][data1.trial == 10], \n exp(data1.annd[data1.gs==i][data1.date == 18106][data1.trial == 10]), color = colors[count],\n label = str(i))\n\n ax.fill_between(\n data1.temp[data1.gs == i][data1.date == 18106][data1.trial == 10], \n exp(data1.annd025[data1.gs==i][data1.date == 18106][data1.trial == 10]), \n exp(data1.annd975[data1.gs==i][data1.date == 18106][data1.trial == 10]), alpha = 0.3, color = colors[count])\n count += 1\nplt.xlabel('Temperature', size = fs)\nplt.ylabel('ANND after loom', size = fs)\nax.set_title('Groupsize = 16', fontsize = fs)\nplt.legend(fontsize=fs, loc='upper right', title = 'Groupsize', framealpha = 0.5)\nax.set_title('ANND with groupsize', fontsize = fs)\nplt.xticks(ticks = [9,13,17,21,25,29], labels = [9,13,17,21,25,29])\nout_dir = '../../output/temp_collective/roi_figures/predictions/annd_after_loom_predictions_wo_data_all.png'\nfig.savefig(out_dir, dpi = 300)\nplt.show()\n" ]
[ [ "numpy.isnan", "numpy.linalg.norm", "numpy.nanmean", "numpy.zeros", "numpy.empty" ], [ "pandas.read_csv", "numpy.nanmean" ], [ "pandas.read_csv", "numpy.nanmin", "numpy.linalg.norm", "numpy.nanmean", "scipy.spatial.ConvexHull", "numpy.empty" ], [ "pandas.read_csv", "numpy.nanmean", "numpy.linalg.norm", "numpy.empty" ], [ "pandas.read_csv", "numpy.linalg.norm", "numpy.nanmean", "numpy.ma.dstack", "numpy.empty" ], [ "numpy.nanstd", "numpy.linalg.norm", "numpy.nanmean" ], [ "matplotlib.pyplot.legend", "pandas.read_csv", "numpy.linspace", "matplotlib.pyplot.figure", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
pyinduct/pyinduct
[ "f743ecfcee3b940505ec95b48fa07bb1648cfcc1" ]
[ "pyinduct/parabolic/general.py" ]
[ "from collections.abc import Callable\nimport warnings\n\nimport numpy as np\nfrom scipy.optimize import fsolve\n\nfrom ..core import Function, find_roots, ConstantFunction\nfrom ..eigenfunctions import SecondOrderOperator\nfrom ..placeholder import (ScalarFunction, TestFunction, FieldVariable, ScalarTerm,\n IntegralTerm, Input, Product)\nfrom ..simulation import WeakFormulation\n\n__all__ = [\"compute_rad_robin_eigenfrequencies\", \"eliminate_advection_term\", \"get_parabolic_dirichlet_weak_form\",\n \"get_parabolic_robin_weak_form\", \"get_in_domain_transformation_matrix\"]\n\n\ndef compute_rad_robin_eigenfrequencies(param, l, n_roots=10, show_plot=False):\n r\"\"\"\n Return the first :code:`n_roots` eigenfrequencies :math:`\\omega`\n (and eigenvalues :math:`\\lambda`)\n\n .. math:: \\omega = \\sqrt{-\\frac{a_1^2}{4a_2^2}+\\frac{a_0-\\lambda}{a_2}}\n\n to the eigenvalue problem\n\n .. math::\n a_2\\varphi''(z) + a_1&\\varphi'(z) + a_0\\varphi(z) = \\lambda\\varphi(z) \\\\\n \\varphi'(0) &= \\alpha\\varphi(0) \\\\\n \\varphi'(l) &= -\\beta\\varphi(l).\n\n Args:\n param (array_like): :math:`\\Big( a_2, a_1, a_0, \\alpha, \\beta \\Big)^T`\n l (numbers.Number): Right boundary value of the domain\n :math:`[0,l]\\ni z`.\n n_roots (int): Amount of eigenfrequencies to be compute.\n show_plot (bool): A plot window of the characteristic equation appears\n if it is :code:`True`.\n\n Return:\n tuple --> two numpy.ndarrays of length :code:`nroots`:\n .. math:: \\Big(\\big[\\omega_1,...,\\omega_\\text{n\\_roots}\\Big],\n \\Big[\\lambda_1,...,\\lambda_\\text{n\\_roots}\\big]\\Big)\n \"\"\"\n\n a2, a1, a0, alpha, beta = param\n eta = -a1 / 2. / a2\n\n def characteristic_equation(om):\n if np.round(om, 200) != 0.:\n zero = (alpha + beta) * np.cos(om * l) + ((eta + beta) * (alpha - eta) / om - om) * np.sin(om * l)\n else:\n zero = (alpha + beta) * np.cos(om * l) + (eta + beta) * (alpha - eta) * l - om * np.sin(om * l)\n return zero\n\n def complex_characteristic_equation(om):\n if np.round(om, 200) != 0.:\n zero = (alpha + beta) * np.cosh(om * l) + ((eta + beta) * (alpha - eta) / om + om) * np.sinh(om * l)\n else:\n zero = (alpha + beta) * np.cosh(om * l) + (eta + beta) * (alpha - eta) * l + om * np.sinh(om * l)\n return zero\n\n # assume 1 root per pi/l (safety factor = 3)\n om_end = 3 * n_roots * np.pi / l\n start_values = np.arange(0, om_end, .1)\n om = find_roots(characteristic_equation,\n start_values,\n 2 * n_roots,\n rtol=l*1e-6).tolist()\n\n # delete all around om = 0\n om.reverse()\n for i in range(np.sum(np.array(om) < np.pi / l / 2e1)):\n om.pop()\n om.reverse()\n\n # if om = 0 is a root then add 0 to the list\n zero_limit = alpha + beta + (eta + beta) * (alpha - eta) * l\n if np.round(zero_limit, 6 + int(np.log10(l))) == 0.:\n om.insert(0, 0.)\n\n # regard complex roots\n om_squared = np.power(om, 2).tolist()\n complex_root = fsolve(complex_characteristic_equation, om_end)\n if np.round(complex_root, 6 + int(np.log10(l))) != 0.:\n om_squared.insert(0, -complex_root[0] ** 2)\n\n # basically complex eigenfrequencies\n om = np.sqrt(np.array(om_squared).astype(complex))\n\n if len(om) < n_roots:\n raise ValueError(\"RadRobinEigenvalues.compute_eigen_frequencies()\"\n \"can not find enough roots\")\n\n eig_frequencies = om[:n_roots]\n eig_values = a0 - a2 * eig_frequencies ** 2 - a1 ** 2 / 4. / a2\n return eig_frequencies, eig_values\n\n\ndef eliminate_advection_term(param, domain_end):\n r\"\"\"\n This method performs a transformation\n\n .. math:: \\tilde x(z,t)=x(z,t)\n e^{\\int_0^z \\frac{a_1(\\bar z)}{2 a_2}\\,d\\bar z} ,\n\n on the system, which eliminates the advection term :math:`a_1 x(z,t)` from a\n reaction-advection-diffusion equation of the type:\n\n .. math:: \\dot x(z,t) = a_2 x''(z,t) + a_1(z) x'(z,t) + a_0(z) x(z,t) .\n\n The boundary can be given by robin\n\n .. math:: x'(0,t) = \\alpha x(0,t), \\quad x'(l,t) = -\\beta x(l,t) ,\n\n dirichlet\n\n .. math:: x(0,t) = 0, \\quad x(l,t) = 0\n\n or mixed boundary conditions.\n\n Args:\n param (array_like): :math:`\\Big( a_2, a_1, a_0, \\alpha, \\beta \\Big)^T`\n domain_end (float): upper bound of the spatial domain\n\n Raises:\n TypeError: If :math:`a_1(z)` is callable but no derivative handle is\n defined for it.\n\n Return:\n SecondOrderOperator or tuple:\n Parameters\n\n .. math:: \\big(a_2, \\tilde a_1=0, \\tilde a_0(z),\n \\tilde \\alpha, \\tilde \\beta \\big) for\n\n the transformed system\n\n .. math:: \\dot{\\tilde{x}}(z,t) = a_2 \\tilde x''(z,t) +\n \\tilde a_0(z) \\tilde x(z,t)\n\n and the corresponding boundary conditions (:math:`\\alpha` and/or\n :math:`\\beta` set to None by dirichlet boundary condition).\n\n \"\"\"\n # TODO remove this compatibility wrapper and promote use of new Operator\n # class over the entire toolbox.\n if isinstance(param, SecondOrderOperator):\n a2 = param.a2\n a1 = param.a1\n a0 = param.a0\n alpha = -param.alpha0\n beta = param.beta0\n\n else:\n if not isinstance(param, (tuple, list)) or not len(param) == 5:\n raise TypeError(\"pyinduct.utils.transform_2_intermediate(): \"\n \"argument param must from type tuple or list\")\n\n a2, a1, a0, alpha, beta = param\n\n if isinstance(a1, Function):\n if not isinstance(a0, Callable):\n a0_z = ConstantFunction(a0)\n else:\n a0_z = a0\n\n def a0_n(z):\n return a0_z(z) - a1(z) ** 2 / 4 / a2 - a1.derive(1)(z) / 2\n else:\n a0_n = a0 - a1 ** 2 / 4 / a2\n\n if alpha is None:\n alpha_n = None\n elif isinstance(a1, Callable):\n alpha_n = a1(0) / 2. / a2 + alpha\n else:\n alpha_n = a1 / 2. / a2 + alpha\n\n if beta is None:\n beta_n = None\n elif isinstance(a1, Function):\n beta_n = -a1(domain_end) / 2. / a2 + beta\n else:\n beta_n = -a1 / 2. / a2 + beta\n\n a2_n = a2\n a1_n = 0\n\n # TODO see above.\n if isinstance(param, SecondOrderOperator):\n return SecondOrderOperator(a2=a2_n, a1=0, a0=a0_n,\n alpha1=param.beta1, alpha0=-alpha_n,\n beta1=param.beta1, beta0=beta_n)\n else:\n return a2_n, a1_n, a0_n, alpha_n, beta_n\n\n\ndef get_parabolic_dirichlet_weak_form(init_func_label,\n test_func_label,\n input_handle,\n param,\n spatial_domain):\n \"\"\"\n Return the weak formulation of a parabolic 2nd order system, using an\n inhomogeneous dirichlet boundary at both sides.\n\n Args:\n init_func_label(str): Label of shape base to use.\n test_func_label(str): Label of test base to use.\n input_handle(:py:class:`.SimulationInput`): Input.\n param(tuple): Parameters of the spatial operator.\n spatial_domain(tuple): Spatial domain of the problem.\n # spatial_domain(:py:class:`.Domain`): Spatial domain of the\n # problem.\n\n Returns:\n :py:class:`.WeakFormulation`: Weak form of the system.\n \"\"\"\n a2, a1, a0, alpha, beta = param\n l = spatial_domain[1]\n\n x = FieldVariable(init_func_label)\n x_dt = x.derive(temp_order=1)\n x_dz = x.derive(spat_order=1)\n x_ddz = x.derive(spat_order=2)\n\n psi = TestFunction(test_func_label)\n psi_dz = psi.derive(1)\n psi_ddz = psi.derive(2)\n\n # integral terms\n int1 = IntegralTerm(Product(x_dt, psi), spatial_domain)\n int2 = IntegralTerm(Product(x, psi_ddz), spatial_domain, -a2)\n int2h = IntegralTerm(Product(x_ddz, psi), spatial_domain, -a2)\n int3 = IntegralTerm(Product(x, psi_dz), spatial_domain, a1)\n int4 = IntegralTerm(Product(x, psi), spatial_domain, -a0)\n\n if input_handle is None:\n # homogeneous case\n return WeakFormulation([int1, int2h, int3, int4],\n name=\"parabolic_dirichlet_hom\")\n\n # scalar terms\n s1 = ScalarTerm(Product(Input(input_handle), psi_dz(l)), a2)\n s2 = ScalarTerm(Product(Input(input_handle), psi(l)), -a1)\n s3 = ScalarTerm(Product(x_dz(l), psi(l)), -a2)\n s4 = ScalarTerm(Product(x_dz(0), psi(0)), a2)\n\n return WeakFormulation([int1, int2, int3, int4, s1, s2, s3, s4],\n name=\"parabolic_dirichlet\")\n\n\ndef get_parabolic_robin_weak_form(shape_base_label, test_base_label,\n input_handle, param, spatial_domain,\n actuation_type_point=None):\n r\"\"\"\n Provide the weak formulation for the diffusion system with advection term,\n reaction term, robin boundary condition and robin actuation.\n\n .. math::\n :nowrap:\n\n \\begin{align*}\n \\dot x(z,t) &= a_2 x''(z,t) + a_1(z) x'(z,t) + a_0(z) x(z,t),\n && z\\in (0, l) \\\\\n x'(0,t) &= \\alpha x(0,t) \\\\\n x'(l,t) &= -\\beta x(l,t) + u(t)\n \\end{align*}\n\n Args:\n shape_base_label (str): State space base label\n test_base_label (str): Test base label\n input_handle (:py:class:`.SimulationInput`): System input\n param (array-like): List of parameters:\n\n - :math:`a_2` (numbers.Number) ~ diffusion coefficient\n - :math:`a_1(z)` (callable) ~ advection coefficient\n - :math:`a_0(z)` (callable) ~ reaction coefficient\n - :math:`\\alpha, \\beta` (numbers.Number) ~ constants for robin\n boundary conditions\n\n spatial_domain (tuple): Limits of the spatial domain :math:`(0,l) \\ni z`\n actuation_type_point (numbers.number): Here you can shift the point of\n actuation from :math:`z=l` to a other point in the spatial domain.\n\n Returns:\n tuple:\n\n - :py:class:`.WeakFormulation`\n - strings for the created base lables for the advection and reaction\n coefficient\n\n \"\"\"\n\n if actuation_type_point is None:\n actuation_type_point = spatial_domain[1]\n\n a2, a1, a0, alpha, beta = param\n l = spatial_domain[1]\n\n # init ScalarFunction for a1 and a0 to handle spatially varying coefficients\n created_base_labels = (shape_base_label + \"a0_z\", shape_base_label + \"a1_z\")\n a0_z = ScalarFunction.from_scalar(a0, created_base_labels[0])\n a1_z = ScalarFunction.from_scalar(a1, created_base_labels[1])\n\n x = FieldVariable(shape_base_label)\n x_dt = x.derive(temp_order=1)\n x_dz = x.derive(spat_order=1)\n\n psi = TestFunction(test_base_label, order=0)\n psi_dz = psi.derive(1)\n\n # integral terms\n int1 = IntegralTerm(Product(x_dt, psi), spatial_domain)\n int2 = IntegralTerm(Product(x_dz, psi_dz), spatial_domain, a2)\n int3 = IntegralTerm(Product(Product(x_dz, a1_z), psi), spatial_domain, -1)\n int4 = IntegralTerm(Product(Product(x, a0_z), psi), spatial_domain, -1)\n\n # scalar terms\n s1 = ScalarTerm(Product(x(0), psi(0)), a2 * alpha)\n s2 = ScalarTerm(Product(x(l), psi(l)), a2 * beta)\n\n terms = [int1, int2, int3, int4, s1, s2]\n\n # consider input if given\n if input_handle is not None:\n terms.append(ScalarTerm(\n Product(Input(input_handle), psi(actuation_type_point)), -a2))\n\n # derive state-space system\n weak_form = WeakFormulation(\n terms, name=\"parabolic_robin_{}_{}\".format(param, shape_base_label))\n\n return weak_form, created_base_labels\n\n\ndef get_in_domain_transformation_matrix(k1, k2, mode='n_plus_1'):\n r\"\"\"\n Returns the transformation matrix M.\n\n M is one part of a transformation\n\n .. math::\n\n x = My + Ty\n\n where x is the field variable of an interior point controlled parabolic\n system and y is the field variable of an boundary controlled parabolic\n system. T is a (Fredholm-) integral transformation (which can be\n approximated with M).\n\n Args:\n k1:\n k2:\n mode: Available modes\n\n - `n_plus_1`:\n M.shape = :math:`(n+1,n+1), w = (w(0),...,w(n))^T, w \\in {x,y}`\n - `2n`:\n M.shape = (2n,2n), :math:`w = (w(0),...,w(n),...,w(1))^T, w \\in {x,y}`\n\n Return:\n numpy.array: Transformation matrix M.\n \"\"\"\n if not all(isinstance(i, (int, float)) for i in [k1, k2]):\n raise TypeError(\"TypeErrorMessage\")\n if not all(i % 1 == 0 for i in [k1, k2]):\n raise TypeError(\"TypeErrorMessage\")\n n = k1 + k2\n if k1 + k2 != n or n < 2 or k1 < 0 or k2 < 0:\n raise ValueError(\"The sum of two positive integers k1 and k2 must be n.\")\n if (k1 != 0 and k2 != 0) and n % 2 == 0:\n warnings.warn(\"Transformation matrix M is not invertible.\")\n\n mod_diag = lambda n, k: np.diag(np.ones(n - np.abs(k)), k)\n\n if mode == 'n_plus_1':\n M = np.zeros((n + 1, n + 1))\n if k2 < n:\n M += mod_diag(n + 1, k2) + mod_diag(n + 1, -k2)\n if k2 != 0:\n M += np.fliplr(mod_diag(n + 1, n - k2) + mod_diag(n + 1, -n + k2))\n elif mode == '2n':\n M = mod_diag(2 * n, k2) + mod_diag(2 * n, -k2) + mod_diag(2 * n, n + k1) + mod_diag(2 * n, -n - k1)\n else:\n raise ValueError(\"String in variable 'mode' not understood.\")\n return M * 0.5\n\n" ]
[ [ "scipy.optimize.fsolve", "numpy.cosh", "numpy.abs", "numpy.power", "numpy.arange", "numpy.cos", "numpy.sinh", "numpy.sin", "numpy.round", "numpy.log10", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
HudsonHuang/tacotron2
[ "fa55a0b633abe358e1258e1dc3b40d85e17b3450" ]
[ "tacotron2/model.py" ]
[ "# *****************************************************************************\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the NVIDIA CORPORATION nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# *****************************************************************************\n\nfrom math import sqrt\nimport torch\nfrom torch.autograd import Variable\nfrom torch import nn\nfrom torch.nn import functional as F\nimport sys\nfrom os.path import abspath, dirname\n# enabling modules discovery from global entrypoint\nsys.path.append(abspath(dirname(__file__)+'/../'))\nfrom common.layers import ConvNorm, LinearNorm\nfrom common.utils import to_gpu, get_mask_from_lengths\n\n\nclass LocationLayer(nn.Module):\n def __init__(self, attention_n_filters, attention_kernel_size,\n attention_dim):\n super(LocationLayer, self).__init__()\n padding = int((attention_kernel_size - 1) / 2)\n self.location_conv = ConvNorm(2, attention_n_filters,\n kernel_size=attention_kernel_size,\n padding=padding, bias=False, stride=1,\n dilation=1)\n self.location_dense = LinearNorm(attention_n_filters, attention_dim,\n bias=False, w_init_gain='tanh')\n\n def forward(self, attention_weights_cat):\n processed_attention = self.location_conv(attention_weights_cat)\n processed_attention = processed_attention.transpose(1, 2)\n processed_attention = self.location_dense(processed_attention)\n return processed_attention\n\n\nclass Attention(nn.Module):\n def __init__(self, attention_rnn_dim, embedding_dim,\n attention_dim, attention_location_n_filters,\n attention_location_kernel_size):\n super(Attention, self).__init__()\n self.query_layer = LinearNorm(attention_rnn_dim, attention_dim,\n bias=False, w_init_gain='tanh')\n self.memory_layer = LinearNorm(embedding_dim, attention_dim, bias=False,\n w_init_gain='tanh')\n self.v = LinearNorm(attention_dim, 1, bias=False)\n self.location_layer = LocationLayer(attention_location_n_filters,\n attention_location_kernel_size,\n attention_dim)\n self.score_mask_value = -float(\"inf\")\n\n def get_alignment_energies(self, query, processed_memory,\n attention_weights_cat):\n \"\"\"\n PARAMS\n ------\n query: decoder output (batch, n_mel_channels * n_frames_per_step)\n processed_memory: processed encoder outputs (B, T_in, attention_dim)\n attention_weights_cat: cumulative and prev. att weights (B, 2, max_time)\n\n RETURNS\n -------\n alignment (batch, max_time)\n \"\"\"\n\n processed_query = self.query_layer(query.unsqueeze(1))\n processed_attention_weights = self.location_layer(attention_weights_cat)\n energies = self.v(torch.tanh(\n processed_query + processed_attention_weights + processed_memory))\n\n energies = energies.squeeze(-1)\n return energies\n\n def forward(self, attention_hidden_state, memory, processed_memory,\n attention_weights_cat, mask):\n \"\"\"\n PARAMS\n ------\n attention_hidden_state: attention rnn last output\n memory: encoder outputs\n processed_memory: processed encoder outputs\n attention_weights_cat: previous and cummulative attention weights\n mask: binary mask for padded data\n \"\"\"\n alignment = self.get_alignment_energies(\n attention_hidden_state, processed_memory, attention_weights_cat)\n\n if mask is not None:\n alignment.data.masked_fill_(mask, self.score_mask_value)\n\n attention_weights = F.softmax(alignment, dim=1)\n attention_context = torch.bmm(attention_weights.unsqueeze(1), memory)\n attention_context = attention_context.squeeze(1)\n\n return attention_context, attention_weights\n\n\nclass Prenet(nn.Module):\n def __init__(self, in_dim, sizes):\n super(Prenet, self).__init__()\n in_sizes = [in_dim] + sizes[:-1]\n self.layers = nn.ModuleList(\n [LinearNorm(in_size, out_size, bias=False)\n for (in_size, out_size) in zip(in_sizes, sizes)])\n\n def forward(self, x, inference=False):\n if inference:\n for linear in self.layers:\n x = F.relu(linear(x))\n x0 = x[0].unsqueeze(0)\n mask = Variable(torch.bernoulli(x0.data.new(x0.data.size()).fill_(0.5)))\n mask = mask.expand(x.size(0), x.size(1))\n x = x*mask*2\n else:\n for linear in self.layers:\n x = F.dropout(F.relu(linear(x)), p=0.5, training=True)\n return x\n\n\nclass Postnet(nn.Module):\n \"\"\"Postnet\n - Five 1-d convolution with 512 channels and kernel size 5\n \"\"\"\n def __init__(self, n_mel_channels, postnet_embedding_dim,\n postnet_kernel_size, postnet_n_convolutions):\n super(Postnet, self).__init__()\n self.convolutions = nn.ModuleList()\n\n self.convolutions.append(\n nn.Sequential(\n ConvNorm(n_mel_channels, postnet_embedding_dim,\n kernel_size=postnet_kernel_size, stride=1,\n padding=int((postnet_kernel_size - 1) / 2),\n dilation=1, w_init_gain='tanh'),\n nn.BatchNorm1d(postnet_embedding_dim))\n )\n\n for i in range(1, postnet_n_convolutions - 1):\n self.convolutions.append(\n nn.Sequential(\n ConvNorm(postnet_embedding_dim,\n postnet_embedding_dim,\n kernel_size=postnet_kernel_size, stride=1,\n padding=int((postnet_kernel_size - 1) / 2),\n dilation=1, w_init_gain='tanh'),\n nn.BatchNorm1d(postnet_embedding_dim))\n )\n\n self.convolutions.append(\n nn.Sequential(\n ConvNorm(postnet_embedding_dim, n_mel_channels,\n kernel_size=postnet_kernel_size, stride=1,\n padding=int((postnet_kernel_size - 1) / 2),\n dilation=1, w_init_gain='linear'),\n nn.BatchNorm1d(n_mel_channels))\n )\n\n def forward(self, x):\n for i in range(len(self.convolutions) - 1):\n x = F.dropout(torch.tanh(self.convolutions[i](x)), 0.5, self.training)\n x = F.dropout(self.convolutions[-1](x), 0.5, self.training)\n\n return x\n\n\nclass Encoder(nn.Module):\n \"\"\"Encoder module:\n - Three 1-d convolution banks\n - Bidirectional LSTM\n \"\"\"\n def __init__(self, encoder_n_convolutions,\n encoder_embedding_dim, encoder_kernel_size):\n super(Encoder, self).__init__()\n\n convolutions = []\n for _ in range(encoder_n_convolutions):\n conv_layer = nn.Sequential(\n ConvNorm(encoder_embedding_dim,\n encoder_embedding_dim,\n kernel_size=encoder_kernel_size, stride=1,\n padding=int((encoder_kernel_size - 1) / 2),\n dilation=1, w_init_gain='relu'),\n nn.BatchNorm1d(encoder_embedding_dim))\n convolutions.append(conv_layer)\n\n self.convolutions = nn.ModuleList(convolutions)\n self.lstm = nn.LSTM(encoder_embedding_dim,\n int(encoder_embedding_dim / 2), 1,\n batch_first=True, bidirectional=True)\n\n def forward(self, x, input_lengths):\n for conv in self.convolutions:\n x = F.dropout(F.relu(conv(x)), 0.5, self.training)\n\n x = x.transpose(1, 2)\n\n # pytorch tensor are not reversible, hence the conversion\n input_lengths = input_lengths.cpu().numpy()\n x = nn.utils.rnn.pack_padded_sequence(\n x, input_lengths, batch_first=True)\n\n self.lstm.flatten_parameters()\n outputs, _ = self.lstm(x)\n\n outputs, _ = nn.utils.rnn.pad_packed_sequence(\n outputs, batch_first=True)\n\n return outputs\n\n def infer(self, x):\n for conv in self.convolutions:\n x = F.dropout(F.relu(conv(x)), 0.5, self.training)\n\n x = x.transpose(1, 2)\n\n self.lstm.flatten_parameters()\n outputs, _ = self.lstm(x)\n\n return outputs\n\n\nclass Decoder(nn.Module):\n def __init__(self, n_mel_channels, n_frames_per_step,\n encoder_embedding_dim, attention_dim,\n attention_location_n_filters,\n attention_location_kernel_size,\n attention_rnn_dim, decoder_rnn_dim,\n prenet_dim, max_decoder_steps, gate_threshold,\n p_attention_dropout, p_decoder_dropout,\n early_stopping):\n super(Decoder, self).__init__()\n self.n_mel_channels = n_mel_channels\n self.n_frames_per_step = n_frames_per_step\n self.encoder_embedding_dim = encoder_embedding_dim\n self.attention_rnn_dim = attention_rnn_dim\n self.decoder_rnn_dim = decoder_rnn_dim\n self.prenet_dim = prenet_dim\n self.max_decoder_steps = max_decoder_steps\n self.gate_threshold = gate_threshold\n self.p_attention_dropout = p_attention_dropout\n self.p_decoder_dropout = p_decoder_dropout\n self.early_stopping = early_stopping\n\n self.prenet = Prenet(\n n_mel_channels,\n [prenet_dim, prenet_dim])\n\n self.attention_rnn = nn.LSTMCell(\n prenet_dim + encoder_embedding_dim,\n attention_rnn_dim)\n\n self.attention_layer = Attention(\n attention_rnn_dim, encoder_embedding_dim,\n attention_dim, attention_location_n_filters,\n attention_location_kernel_size)\n\n self.decoder_rnn = nn.LSTMCell(\n attention_rnn_dim + encoder_embedding_dim,\n decoder_rnn_dim, 1)\n\n self.linear_projection = LinearNorm(\n decoder_rnn_dim + encoder_embedding_dim,\n n_mel_channels * n_frames_per_step)\n\n self.gate_layer = LinearNorm(\n decoder_rnn_dim + encoder_embedding_dim, 1,\n bias=True, w_init_gain='sigmoid')\n\n def get_go_frame(self, memory):\n \"\"\" Gets all zeros frames to use as first decoder input\n PARAMS\n ------\n memory: decoder outputs\n\n RETURNS\n -------\n decoder_input: all zeros frames\n \"\"\"\n B = memory.size(0)\n decoder_input = Variable(memory.data.new(\n B, self.n_mel_channels * self.n_frames_per_step).zero_())\n\n return decoder_input\n\n def initialize_decoder_states(self, memory, mask):\n \"\"\" Initializes attention rnn states, decoder rnn states, attention\n weights, attention cumulative weights, attention context, stores memory\n and stores processed memory\n PARAMS\n ------\n memory: Encoder outputs\n mask: Mask for padded data if training, expects None for inference\n \"\"\"\n B = memory.size(0)\n MAX_TIME = memory.size(1)\n\n self.attention_hidden = Variable(memory.data.new(\n B, self.attention_rnn_dim).zero_())\n self.attention_cell = Variable(memory.data.new(\n B, self.attention_rnn_dim).zero_())\n\n self.decoder_hidden = Variable(memory.data.new(\n B, self.decoder_rnn_dim).zero_())\n self.decoder_cell = Variable(memory.data.new(\n B, self.decoder_rnn_dim).zero_())\n\n self.attention_weights = Variable(memory.data.new(\n B, MAX_TIME).zero_())\n self.attention_weights_cum = Variable(memory.data.new(\n B, MAX_TIME).zero_())\n self.attention_context = Variable(memory.data.new(\n B, self.encoder_embedding_dim).zero_())\n\n self.memory = memory\n self.processed_memory = self.attention_layer.memory_layer(memory)\n self.mask = mask\n\n def parse_decoder_inputs(self, decoder_inputs):\n \"\"\" Prepares decoder inputs, i.e. mel outputs\n PARAMS\n ------\n decoder_inputs: inputs used for teacher-forced training, i.e. mel-specs\n\n RETURNS\n -------\n inputs: processed decoder inputs\n\n \"\"\"\n # (B, n_mel_channels, T_out) -> (B, T_out, n_mel_channels)\n\n decoder_inputs = decoder_inputs.transpose(1, 2).contiguous()\n decoder_inputs = decoder_inputs.view(\n decoder_inputs.size(0),\n int(decoder_inputs.size(1)/self.n_frames_per_step), -1)\n # (B, T_out, n_mel_channels) -> (T_out, B, n_mel_channels)\n decoder_inputs = decoder_inputs.transpose(0, 1)\n\n\n return decoder_inputs\n\n def parse_decoder_outputs(self, mel_outputs, gate_outputs, alignments):\n \"\"\" Prepares decoder outputs for output\n PARAMS\n ------\n mel_outputs:\n gate_outputs: gate output energies\n alignments:\n\n RETURNS\n -------\n mel_outputs:\n gate_outputs: gate output energies\n alignments:\n \"\"\"\n # (T_out, B) -> (B, T_out)\n alignments = torch.stack(alignments).transpose(0, 1)\n # (T_out, B) -> (B, T_out)\n\n gate_outputs = torch.stack(gate_outputs).transpose(0, 1)\n gate_outputs = gate_outputs.contiguous()\n # (T_out, B, n_mel_channels) -> (B, T_out, n_mel_channels)\n mel_outputs = torch.stack(mel_outputs).transpose(0, 1).contiguous()\n # decouple frames per step\n mel_outputs = mel_outputs.view(\n mel_outputs.size(0), -1, self.n_mel_channels)\n # (B, T_out, n_mel_channels) -> (B, n_mel_channels, T_out)\n mel_outputs = mel_outputs.transpose(1, 2)\n\n return mel_outputs, gate_outputs, alignments\n\n\n\n def decode(self, decoder_input):\n \"\"\" Decoder step using stored states, attention and memory\n PARAMS\n ------\n decoder_input: previous mel output\n\n RETURNS\n -------\n mel_output:\n gate_output: gate output energies\n attention_weights:\n \"\"\"\n cell_input = torch.cat((decoder_input, self.attention_context), -1)\n\n\n self.attention_hidden, self.attention_cell = self.attention_rnn(\n cell_input, (self.attention_hidden, self.attention_cell))\n self.attention_hidden = F.dropout(\n self.attention_hidden, self.p_attention_dropout, self.training)\n\n attention_weights_cat = torch.cat(\n (self.attention_weights.unsqueeze(1),\n self.attention_weights_cum.unsqueeze(1)), dim=1)\n self.attention_context, self.attention_weights = self.attention_layer(\n self.attention_hidden, self.memory, self.processed_memory,\n attention_weights_cat, self.mask)\n\n self.attention_weights_cum += self.attention_weights\n decoder_input = torch.cat(\n (self.attention_hidden, self.attention_context), -1)\n\n self.decoder_hidden, self.decoder_cell = self.decoder_rnn(\n decoder_input, (self.decoder_hidden, self.decoder_cell))\n self.decoder_hidden = F.dropout(\n self.decoder_hidden, self.p_decoder_dropout, self.training)\n\n decoder_hidden_attention_context = torch.cat(\n (self.decoder_hidden, self.attention_context), dim=1)\n decoder_output = self.linear_projection(\n decoder_hidden_attention_context)\n\n\n gate_prediction = self.gate_layer(decoder_hidden_attention_context)\n\n return decoder_output, gate_prediction, self.attention_weights\n\n def forward(self, memory, decoder_inputs, memory_lengths):\n \"\"\" Decoder forward pass for training\n PARAMS\n ------\n memory: Encoder outputs\n decoder_inputs: Decoder inputs for teacher forcing. i.e. mel-specs\n memory_lengths: Encoder output lengths for attention masking.\n\n RETURNS\n -------\n mel_outputs: mel outputs from the decoder\n gate_outputs: gate outputs from the decoder\n alignments: sequence of attention weights from the decoder\n \"\"\"\n\n decoder_input = self.get_go_frame(memory).unsqueeze(0)\n decoder_inputs = self.parse_decoder_inputs(decoder_inputs)\n decoder_inputs = torch.cat((decoder_input, decoder_inputs), dim=0)\n\n decoder_input_frames = []\n z = int(decoder_inputs.size(2) / self.n_frames_per_step)\n for i in range(self.n_frames_per_step):\n decoder_input_frames.append(self.prenet(decoder_inputs[:, :, i*z:(i+1)*z]))\n\n self.initialize_decoder_states(\n memory, mask=~get_mask_from_lengths(memory_lengths))\n\n mel_outputs, gate_outputs, alignments = [], [], []\n\n while len(mel_outputs) < decoder_input_frames[0].size(0) - 1:\n for input_frame in decoder_input_frames:\n decoder_input = input_frame[len(mel_outputs)]\n\n mel_output, gate_output, attention_weights = self.decode(\n decoder_input)\n gate_outputs += [gate_output.squeeze() if memory.shape[0] > 1 else gate_output]\n alignments += [attention_weights]\n\n mel_outputs += [mel_output.squeeze(1)]\n\n mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs(\n mel_outputs, gate_outputs, alignments)\n\n return mel_outputs, gate_outputs, alignments\n\n def infer(self, memory):\n \"\"\" Decoder inference\n PARAMS\n ------\n memory: Encoder outputs\n\n RETURNS\n -------\n mel_outputs: mel outputs from the decoder\n gate_outputs: gate outputs from the decoder\n alignments: sequence of attention weights from the decoder\n \"\"\"\n decoder_input = self.get_go_frame(memory)\n\n self.initialize_decoder_states(memory, mask=None)\n\n mel_lengths = torch.zeros([memory.size(0)], dtype=torch.int32).cuda()\n not_finished = torch.ones([memory.size(0)], dtype=torch.int32).cuda()\n mel_outputs, gate_outputs, alignments = [], [], []\n z = int(decoder_input.size(1) / self.n_frames_per_step)\n while True:\n decoder_input_frames = []\n for i in range(self.n_frames_per_step):\n decoder_input_frames.append(decoder_input[:, i * z:(i + 1) * z])\n\n for input_frame in decoder_input_frames:\n mel_output, gate_output, alignment = self.decode(self.prenet(input_frame))\n gate_outputs += [gate_output]\n alignments += [alignment]\n\n mel_outputs += [mel_output.squeeze(1)]\n\n dec = torch.le(torch.sigmoid(gate_output.data),\n self.gate_threshold).to(torch.int32).squeeze(1)\n\n not_finished = not_finished*dec\n mel_lengths += not_finished\n\n if self.early_stopping and torch.sum(not_finished) == 0:\n break\n if len(mel_outputs) == self.max_decoder_steps:\n print(\"Warning! Reached max decoder steps\")\n break\n\n decoder_input = mel_output\n\n mel_outputs, gate_outputs, alignments = self.parse_decoder_outputs(\n mel_outputs, gate_outputs, alignments)\n\n return mel_outputs, gate_outputs, alignments\n\n\nclass Tacotron2(nn.Module):\n def __init__(self, mask_padding, n_mel_channels,\n n_symbols, symbols_embedding_dim, n_speakers, speakers_embedding_dim,\n use_emotions, n_emotions, emotions_embedding_dim,\n encoder_kernel_size, encoder_n_convolutions, encoder_embedding_dim,\n attention_rnn_dim, attention_dim, attention_location_n_filters,\n attention_location_kernel_size, n_frames_per_step,\n decoder_rnn_dim, prenet_dim, max_decoder_steps, gate_threshold,\n p_attention_dropout, p_decoder_dropout,\n postnet_embedding_dim, postnet_kernel_size,\n postnet_n_convolutions, decoder_no_early_stopping, **kwargs):\n super(Tacotron2, self).__init__()\n\n self.mask_padding = mask_padding\n self.n_mel_channels = n_mel_channels\n self.n_frames_per_step = n_frames_per_step\n\n self.symbols_embedding = nn.Embedding(\n n_symbols, symbols_embedding_dim)\n std = sqrt(2.0 / (n_symbols + symbols_embedding_dim))\n val = sqrt(3.0) * std # uniform bounds for std\n self.symbols_embedding.weight.data.uniform_(-val, val)\n\n self.speakers_embedding = nn.Embedding(n_speakers, speakers_embedding_dim)\n torch.nn.init.xavier_uniform_(self.speakers_embedding.weight)\n\n self.encoder = Encoder(encoder_n_convolutions,\n encoder_embedding_dim,\n encoder_kernel_size)\n\n encoder_out_embedding_dim = encoder_embedding_dim + speakers_embedding_dim\n\n self.use_emotions = use_emotions\n if self.use_emotions:\n self.emotions_embedding = nn.Embedding(n_emotions, emotions_embedding_dim)\n torch.nn.init.xavier_uniform_(self.emotions_embedding.weight)\n encoder_out_embedding_dim += emotions_embedding_dim\n\n self.decoder = Decoder(n_mel_channels, n_frames_per_step,\n encoder_out_embedding_dim, attention_dim,\n attention_location_n_filters,\n attention_location_kernel_size,\n attention_rnn_dim, decoder_rnn_dim,\n prenet_dim, max_decoder_steps,\n gate_threshold, p_attention_dropout,\n p_decoder_dropout,\n not decoder_no_early_stopping)\n\n self.postnet = Postnet(n_mel_channels, postnet_embedding_dim,\n postnet_kernel_size,\n postnet_n_convolutions)\n\n def parse_batch(self, batch):\n text_padded, input_lengths, mel_padded, gate_padded, \\\n output_lengths, speaker_ids, emotion_ids = batch\n text_padded = to_gpu(text_padded).long()\n input_lengths = to_gpu(input_lengths).long()\n max_len = torch.max(input_lengths.data).item()\n mel_padded = to_gpu(mel_padded).float()\n gate_padded = to_gpu(gate_padded).float()\n output_lengths = to_gpu(output_lengths).long()\n speaker_ids = to_gpu(speaker_ids).long()\n emotion_ids = to_gpu(emotion_ids).long()\n\n return ((text_padded, input_lengths, mel_padded, max_len, output_lengths, speaker_ids, emotion_ids),\n (mel_padded, gate_padded))\n\n def parse_output(self, outputs, output_lengths=None):\n if self.mask_padding and output_lengths is not None:\n mask = ~get_mask_from_lengths(output_lengths)\n mask = mask.expand(self.n_mel_channels, mask.size(0), mask.size(1))\n mask = mask.permute(1, 0, 2)\n\n outputs[0].data.masked_fill_(mask, 0.0)\n outputs[1].data.masked_fill_(mask, 0.0)\n outputs[2].data.masked_fill_(mask[:, 0, :], 1e3) # gate energies\n\n return outputs\n\n def forward(self, inputs):\n # Parse inputs\n inputs, input_lengths, targets, max_len, output_lengths, speaker_ids, emotion_ids = inputs\n input_lengths, output_lengths = input_lengths.data, output_lengths.data\n\n # Outputs\n outputs = []\n\n # Get symbols encoder outputs\n embedded_inputs = self.symbols_embedding(inputs).transpose(1, 2)\n encoder_outputs = self.encoder(embedded_inputs, input_lengths)\n outputs.append(encoder_outputs)\n\n # Extract speaker embeddings\n speaker_ids = speaker_ids.unsqueeze(1)\n embedded_speakers = self.speakers_embedding(speaker_ids)\n embedded_speakers = embedded_speakers.expand(-1, max_len, -1)\n outputs.append(embedded_speakers)\n\n # Extract emotion embeddings\n if self.use_emotions:\n emotion_ids = emotion_ids.unsqueeze(1)\n embedded_emotions = self.emotions_embedding(emotion_ids)\n embedded_emotions = embedded_emotions.expand(-1, max_len, -1)\n outputs.append(embedded_emotions)\n # Combine all embeddings embeddings\n merged_outputs = torch.cat(outputs, -1)\n\n mel_outputs, gate_outputs, alignments = self.decoder(\n merged_outputs, targets, memory_lengths=input_lengths)\n\n mel_outputs_postnet = self.postnet(mel_outputs)\n mel_outputs_postnet = mel_outputs + mel_outputs_postnet\n\n return self.parse_output(\n [mel_outputs, mel_outputs_postnet, gate_outputs, alignments],\n output_lengths)\n\n def infer(self, input, speaker_id, emotion_id=None):\n # Outputs\n outputs = []\n\n # Get symbols encoder output\n embedded_input = self.symbols_embedding(input).transpose(1, 2)\n encoder_output = self.encoder.infer(embedded_input)\n outputs.append(encoder_output)\n\n # Get speaker embedding\n speaker_id = speaker_id.unsqueeze(1)\n embedded_speaker = self.speakers_embedding(speaker_id)\n embedded_speaker = embedded_speaker.expand(-1, encoder_output.shape[1], -1)\n outputs.append(embedded_speaker)\n\n # Extract emotion embeddings\n if self.use_emotions:\n emotion_id = emotion_id.unsqueeze(1)\n embedded_emotion = self.emotions_embedding(emotion_id)\n embedded_emotion = embedded_emotion.expand(-1, encoder_output.shape[1], -1)\n outputs.append(embedded_emotion)\n\n # Merge embeddings\n merged_outputs = torch.cat(outputs, -1)\n\n # Decode\n mel_outputs, gate_outputs, alignments = self.decoder.infer(\n merged_outputs)\n\n # Post\n mel_outputs_postnet = self.postnet(mel_outputs)\n mel_outputs_postnet = mel_outputs + mel_outputs_postnet\n\n # Parse\n outputs = self.parse_output(\n [mel_outputs, mel_outputs_postnet, gate_outputs, alignments])\n\n return outputs\n" ]
[ [ "torch.nn.BatchNorm1d", "torch.nn.functional.softmax", "torch.sigmoid", "torch.max", "torch.cat", "torch.nn.functional.dropout", "torch.nn.ModuleList", "torch.sum", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Embedding", "torch.nn.LSTMCell", "torch.tanh", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.init.xavier_uniform_", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
peter3125/WaveRNN
[ "ef34b9d91dfbff3197c8cc20d3ed272b222a5ec2" ]
[ "models/tacotron.py" ]
[ "import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass HighwayNetwork(nn.Module):\n def __init__(self, size):\n super().__init__()\n self.W1 = nn.Linear(size, size)\n self.W2 = nn.Linear(size, size)\n self.W1.bias.data.fill_(0.)\n \n def forward(self, x):\n x1 = self.W1(x)\n x2 = self.W2(x)\n g = torch.sigmoid(x2)\n y = g * F.relu(x1) + (1. - g) * x\n return y\n\n\nclass Encoder(nn.Module): \n def __init__(self, embed_dims, num_chars, cbhg_channels, K, num_highways, dropout):\n super().__init__()\n self.embedding = nn.Embedding(num_chars, embed_dims)\n self.pre_net = PreNet(embed_dims)\n self.cbhg = CBHG(K=K, in_channels=cbhg_channels, channels=cbhg_channels, \n proj_channels=[cbhg_channels, cbhg_channels], \n num_highways=num_highways)\n \n def forward(self, x):\n x = self.embedding(x)\n x = self.pre_net(x)\n x.transpose_(1, 2)\n x = self.cbhg(x)\n return x\n\n\nclass BatchNormConv(nn.Module):\n def __init__(self, in_channels, out_channels, kernel, relu=True):\n super().__init__()\n self.conv = nn.Conv1d(in_channels, out_channels, kernel, stride=1, padding=kernel // 2, bias=False)\n self.bnorm = nn.BatchNorm1d(out_channels)\n self.relu = relu\n \n def forward(self, x):\n x = self.conv(x)\n x = F.relu(x) if self.relu is True else x\n return self.bnorm(x)\n \n \nclass CBHG(nn.Module):\n def __init__(self, K, in_channels, channels, proj_channels, num_highways):\n super().__init__()\n \n self.bank_kernels = [i for i in range(1, K + 1)]\n self.conv1d_bank = nn.ModuleList()\n for k in self.bank_kernels:\n conv = BatchNormConv(in_channels, channels, k)\n self.conv1d_bank.append(conv)\n\n self.maxpool = nn.MaxPool1d(kernel_size=2, stride=1, padding=1)\n \n self.conv_project1 = BatchNormConv(len(self.bank_kernels) * channels, proj_channels[0], 3)\n self.conv_project2 = BatchNormConv(proj_channels[0], proj_channels[1], 3, relu=False)\n \n # Fix the highway input if necessary\n if proj_channels[-1] != channels:\n self.highway_mismatch = True\n self.pre_highway = nn.Linear(proj_channels[-1], channels, bias=False)\n else:\n self.highway_mismatch = False\n \n self.highways = nn.ModuleList()\n for i in range(num_highways):\n hn = HighwayNetwork(channels)\n self.highways.append(hn)\n \n self.rnn = nn.GRU(channels, channels, batch_first=True, bidirectional=True)\n \n def forward(self, x):\n\n # Save these for later\n residual = x\n seq_len = x.size(-1)\n conv_bank = []\n \n # Convolution Bank\n for conv in self.conv1d_bank:\n c = conv(x) # Convolution\n conv_bank.append(c[:, :, :seq_len])\n \n # Stack along the channel axis\n conv_bank = torch.cat(conv_bank, dim=1)\n \n # dump the last padding to fit residual\n x = self.maxpool(conv_bank)[:, :, :seq_len] \n \n # Conv1d projections\n x = self.conv_project1(x)\n x = self.conv_project2(x)\n \n # Residual Connect\n x = x + residual\n \n # Through the highways\n x = x.transpose(1, 2)\n if self.highway_mismatch is True:\n x = self.pre_highway(x)\n for h in self.highways: x = h(x)\n\n # And then the RNN\n x, _ = self.rnn(x)\n return x\n\n\nclass PreNet(nn.Module):\n def __init__(self, in_dims, fc1_dims=256, fc2_dims=128, dropout=0.5):\n super().__init__()\n self.fc1 = nn.Linear(in_dims, fc1_dims)\n self.fc2 = nn.Linear(fc1_dims, fc2_dims)\n self.p = dropout\n \n def forward(self, x):\n x = self.fc1(x)\n x = F.relu(x)\n x = F.dropout(x, self.p, training=self.training)\n x = self.fc2(x)\n x = F.relu(x)\n x = F.dropout(x, self.p, training=self.training)\n return x\n \n \nclass Attention(nn.Module):\n def __init__(self, attn_dims):\n super().__init__()\n self.W = nn.Linear(attn_dims, attn_dims, bias=False)\n self.v = nn.Linear(attn_dims, 1, bias=False)\n \n def forward(self, encoder_seq_proj, query, t):\n\n # print(encoder_seq_proj.shape)\n # Transform the query vector\n query_proj = self.W(query).unsqueeze(1)\n \n # Compute the scores \n u = self.v(torch.tanh(encoder_seq_proj + query_proj))\n scores = F.softmax(u, dim=1)\n\n return scores.transpose(1, 2)\n\n\nclass LSA(nn.Module):\n def __init__(self, attn_dim, kernel_size=31, filters=32):\n super().__init__()\n self.conv = nn.Conv1d(2, filters, padding=(kernel_size - 1) // 2, kernel_size=kernel_size, bias=False)\n self.L = nn.Linear(filters, attn_dim, bias=True)\n self.W = nn.Linear(attn_dim, attn_dim, bias=True)\n self.v = nn.Linear(attn_dim, 1, bias=False)\n self.cumulative = None\n self.attention = None\n\n def init_attention(self, encoder_seq_proj):\n device = next(self.parameters()).device # use same device as parameters\n b, t, c = encoder_seq_proj.size()\n self.cumulative = torch.zeros(b, t, device=device)\n self.attention = torch.zeros(b, t, device=device)\n\n def forward(self, encoder_seq_proj, query, t):\n\n if t == 0: self.init_attention(encoder_seq_proj)\n\n processed_query = self.W(query).unsqueeze(1)\n\n location = torch.cat([self.cumulative.unsqueeze(1), self.attention.unsqueeze(1)], dim=1)\n processed_loc = self.L(self.conv(location).transpose(1, 2))\n\n u = self.v(torch.tanh(processed_query + encoder_seq_proj + processed_loc))\n u = u.squeeze(-1)\n\n # Smooth Attention\n scores = torch.sigmoid(u) / torch.sigmoid(u).sum(dim=1, keepdim=True)\n # scores = F.softmax(u, dim=1)\n self.attention = scores\n self.cumulative += self.attention\n\n return scores.unsqueeze(-1).transpose(1, 2)\n\n\nclass Decoder(nn.Module):\n def __init__(self, n_mels, decoder_dims, lstm_dims):\n super().__init__()\n self.max_r = 20\n self.r = None\n self.generating = False\n self.n_mels = n_mels\n self.prenet = PreNet(n_mels)\n self.attn_net = LSA(decoder_dims)\n self.attn_rnn = nn.GRUCell(decoder_dims + decoder_dims // 2, decoder_dims)\n self.rnn_input = nn.Linear(2 * decoder_dims, lstm_dims)\n self.res_rnn1 = nn.LSTMCell(lstm_dims, lstm_dims)\n self.res_rnn2 = nn.LSTMCell(lstm_dims, lstm_dims)\n self.mel_proj = nn.Linear(lstm_dims, n_mels * self.max_r, bias=False)\n \n def zoneout(self, prev, current, p=0.1):\n device = prev.device\n assert prev.device == current.device\n mask = torch.zeros(prev.size(), device=device).bernoulli_(p)\n return prev * mask + current * (1 - mask)\n \n def forward(self, encoder_seq, encoder_seq_proj, prenet_in, \n hidden_states, cell_states, context_vec, t):\n \n # Need this for reshaping mels\n batch_size = encoder_seq.size(0)\n \n # Unpack the hidden and cell states\n attn_hidden, rnn1_hidden, rnn2_hidden = hidden_states\n rnn1_cell, rnn2_cell = cell_states\n \n # PreNet for the Attention RNN\n prenet_out = self.prenet(prenet_in)\n \n # Compute the Attention RNN hidden state\n attn_rnn_in = torch.cat([context_vec, prenet_out], dim=-1) \n attn_hidden = self.attn_rnn(attn_rnn_in.squeeze(1), attn_hidden)\n \n # Compute the attention scores \n scores = self.attn_net(encoder_seq_proj, attn_hidden, t)\n \n # Dot product to create the context vector \n context_vec = scores @ encoder_seq\n context_vec = context_vec.squeeze(1)\n\n # Concat Attention RNN output w. Context Vector & project\n x = torch.cat([context_vec, attn_hidden], dim=1)\n x = self.rnn_input(x)\n \n # Compute first Residual RNN\n rnn1_hidden_next, rnn1_cell = self.res_rnn1(x, (rnn1_hidden, rnn1_cell))\n if not self.generating:\n rnn1_hidden = self.zoneout(rnn1_hidden, rnn1_hidden_next)\n else:\n rnn1_hidden = rnn1_hidden_next\n x = x + rnn1_hidden\n \n # Compute second Residual RNN\n rnn2_hidden_next, rnn2_cell = self.res_rnn2(x, (rnn2_hidden, rnn2_cell))\n if not self.generating:\n rnn2_hidden = self.zoneout(rnn2_hidden, rnn2_hidden_next)\n else:\n rnn2_hidden = rnn2_hidden_next\n x = x + rnn2_hidden\n \n # Project Mels\n mels = self.mel_proj(x)\n mels = mels.view(batch_size, self.n_mels, self.max_r)[:, :, :self.r]\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n cell_states = (rnn1_cell, rnn2_cell)\n \n return mels, scores, hidden_states, cell_states, context_vec\n \n \nclass Tacotron(nn.Module):\n def __init__(self, embed_dims, num_chars, encoder_dims, decoder_dims, n_mels, fft_bins, postnet_dims,\n encoder_K, lstm_dims, postnet_K, num_highways, dropout):\n super().__init__()\n self.n_mels = n_mels\n self.lstm_dims = lstm_dims\n self.decoder_dims = decoder_dims\n self.encoder = Encoder(embed_dims, num_chars, encoder_dims, \n encoder_K, num_highways, dropout)\n self.encoder_proj = nn.Linear(decoder_dims, decoder_dims, bias=False)\n self.decoder = Decoder(n_mels, decoder_dims, lstm_dims)\n self.postnet = CBHG(postnet_K, n_mels, postnet_dims, [256, 80], num_highways)\n self.post_proj = nn.Linear(postnet_dims * 2, fft_bins, bias=False)\n\n self.init_model()\n self.num_params()\n\n # Unfortunately I have to put these settings into params in order to save\n # if anyone knows a better way of doing this please open an issue in the repo\n self.step = nn.Parameter(torch.zeros(1).long(), requires_grad=False)\n self.r = nn.Parameter(torch.tensor(0).long(), requires_grad=False)\n\n def set_r(self, r):\n self.r.data = torch.tensor(r)\n self.decoder.r = r\n\n def get_r(self):\n return self.r.item()\n\n def forward(self, x, m, generate_gta=False):\n device = next(self.parameters()).device # use same device as parameters\n\n self.step += 1\n\n if generate_gta:\n self.encoder.eval()\n self.postnet.eval()\n self.decoder.generating = True\n else:\n self.encoder.train()\n self.postnet.train()\n self.decoder.generating = False\n \n batch_size, _, steps = m.size()\n \n # Initialise all hidden states and pack into tuple\n attn_hidden = torch.zeros(batch_size, self.decoder_dims, device=device)\n rnn1_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n \n # Initialise all lstm cell states and pack into tuple\n rnn1_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n cell_states = (rnn1_cell, rnn2_cell)\n \n # <GO> Frame for start of decoder loop\n go_frame = torch.zeros(batch_size, self.n_mels, device=device)\n \n # Need an initial context vector\n context_vec = torch.zeros(batch_size, self.decoder_dims, device=device)\n \n # Project the encoder outputs to avoid \n # unnecessary matmuls in the decoder loop\n encoder_seq = self.encoder(x)\n encoder_seq_proj = self.encoder_proj(encoder_seq)\n \n # Need a couple of lists for outputs\n mel_outputs, attn_scores = [], []\n \n # Run the decoder loop\n for t in range(0, steps, self.r):\n prenet_in = m[:, :, t - 1] if t > 0 else go_frame\n mel_frames, scores, hidden_states, cell_states, context_vec = \\\n self.decoder(encoder_seq, encoder_seq_proj, prenet_in, \n hidden_states, cell_states, context_vec, t)\n mel_outputs.append(mel_frames)\n attn_scores.append(scores)\n \n # Concat the mel outputs into sequence\n mel_outputs = torch.cat(mel_outputs, dim=2)\n \n # Post-Process for Linear Spectrograms\n postnet_out = self.postnet(mel_outputs)\n linear = self.post_proj(postnet_out)\n linear = linear.transpose(1, 2)\n \n # For easy visualisation\n attn_scores = torch.cat(attn_scores, 1)\n attn_scores = attn_scores.cpu().data.numpy()\n \n return mel_outputs, linear, attn_scores\n \n def generate(self, x, steps=2000):\n device = next(self.parameters()).device # use same device as parameters\n\n self.encoder.eval()\n self.postnet.eval()\n self.decoder.generating = True\n \n batch_size = 1\n x = torch.as_tensor(x, dtype=torch.long, device=device).unsqueeze(0)\n \n # Need to initialise all hidden states and pack into tuple for tidyness\n attn_hidden = torch.zeros(batch_size, self.decoder_dims, device=device)\n rnn1_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_hidden = torch.zeros(batch_size, self.lstm_dims, device=device)\n hidden_states = (attn_hidden, rnn1_hidden, rnn2_hidden)\n \n # Need to initialise all lstm cell states and pack into tuple for tidyness\n rnn1_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n rnn2_cell = torch.zeros(batch_size, self.lstm_dims, device=device)\n cell_states = (rnn1_cell, rnn2_cell)\n \n # Need a <GO> Frame for start of decoder loop\n go_frame = torch.zeros(batch_size, self.n_mels, device=device)\n \n # Need an initial context vector\n context_vec = torch.zeros(batch_size, self.decoder_dims, device=device)\n \n # Project the encoder outputs to avoid \n # unnecessary matmuls in the decoder loop\n encoder_seq = self.encoder(x)\n encoder_seq_proj = self.encoder_proj(encoder_seq)\n \n # Need a couple of lists for outputs\n mel_outputs, attn_scores = [], []\n \n # Run the decoder loop\n for t in range(0, steps, self.r):\n prenet_in = mel_outputs[-1][:, :, -1] if t > 0 else go_frame\n mel_frames, scores, hidden_states, cell_states, context_vec = \\\n self.decoder(encoder_seq, encoder_seq_proj, prenet_in, \n hidden_states, cell_states, context_vec, t)\n mel_outputs.append(mel_frames)\n attn_scores.append(scores)\n # Stop the loop if silent frames present\n if (mel_frames < -3.8).all() and t > 10: break\n \n # Concat the mel outputs into sequence\n mel_outputs = torch.cat(mel_outputs, dim=2)\n \n # Post-Process for Linear Spectrograms\n postnet_out = self.postnet(mel_outputs)\n linear = self.post_proj(postnet_out)\n \n \n linear = linear.transpose(1, 2)[0].cpu().data.numpy()\n mel_outputs = mel_outputs[0].cpu().data.numpy()\n \n # For easy visualisation\n attn_scores = torch.cat(attn_scores, 1)\n attn_scores = attn_scores.cpu().data.numpy()[0]\n \n self.encoder.train()\n self.postnet.train()\n self.decoder.generating = False\n \n return mel_outputs, linear, attn_scores\n \n def init_model(self):\n for p in self.parameters():\n if p.dim() > 1: nn.init.xavier_uniform_(p)\n\n def get_step(self):\n return self.step.data.item()\n\n def reset_step(self):\n self.step = nn.Parameter(torch.zeros(1).long(), requires_grad=False)\n\n def checkpoint(self, path):\n k_steps = self.get_step() // 1000\n self.save(f'{path}/checkpoint_{k_steps}k_steps.pyt')\n\n def log(self, path, msg):\n with open(path, 'a') as f:\n print(msg, file=f)\n\n def restore(self, path):\n if not os.path.exists(path):\n print('\\nNew Tacotron Training Session...\\n')\n self.save(path)\n else:\n print(f'\\nLoading Weights: \"{path}\"\\n')\n self.load(path)\n self.decoder.r = self.r.item()\n\n def load(self, path, device='cpu'):\n # because PyTorch places on CPU by default, we follow those semantics by using CPU as default.\n print(\"models/tacotron.py loading {}\".format(path))\n self.load_state_dict(torch.load(path, map_location=device), strict=False)\n\n def save(self, path):\n torch.save(self.state_dict(), path)\n\n def num_params(self, print_out=True):\n parameters = filter(lambda p: p.requires_grad, self.parameters())\n parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000\n if print_out:\n print('Trainable Parameters: %.3fM' % parameters)\n" ]
[ [ "torch.nn.functional.softmax", "torch.cat", "torch.nn.functional.dropout", "torch.zeros", "torch.load", "torch.nn.GRU", "torch.nn.Embedding", "torch.tanh", "torch.tensor", "torch.nn.LSTMCell", "torch.nn.MaxPool1d", "torch.nn.functional.relu", "torch.nn.GRUCell", "torch.nn.BatchNorm1d", "torch.sigmoid", "torch.nn.ModuleList", "torch.nn.Linear", "torch.nn.Conv1d", "torch.as_tensor", "torch.nn.init.xavier_uniform_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
skoppula/ternarynet
[ "1a67251f7f5a1cdf854f87f90f841655c7c9f11c", "1a67251f7f5a1cdf854f87f90f841655c7c9f11c" ]
[ "tensorpack/RL/expreplay.py", "tensorpack/utils/loadcaffe.py" ]
[ "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# File: expreplay.py\n# Author: Yuxin Wu <[email protected]>\n\nimport numpy as np\nfrom collections import deque, namedtuple\nimport threading\nfrom tqdm import tqdm\nimport six\nfrom six.moves import queue\n\nfrom ..dataflow import DataFlow\nfrom ..utils import *\nfrom ..utils.concurrency import LoopThread\nfrom ..callbacks.base import Callback\n\n__all__ = ['ExpReplay']\n\nExperience = namedtuple('Experience',\n ['state', 'action', 'reward', 'isOver'])\n\nclass ExpReplay(DataFlow, Callback):\n \"\"\"\n Implement experience replay in the paper\n `Human-level control through deep reinforcement learning`.\n\n This implementation provides the interface as an DataFlow.\n This DataFlow is not fork-safe (doesn't support multiprocess prefetching)\n \"\"\"\n def __init__(self,\n predictor_io_names,\n player,\n batch_size=32,\n memory_size=1e6,\n populate_size=None, # deprecated\n init_memory_size=50000,\n exploration=1,\n end_exploration=0.1,\n exploration_epoch_anneal=0.002,\n reward_clip=None,\n update_frequency=1,\n history_len=1\n ):\n \"\"\"\n :param predictor: a callabale running the up-to-date network.\n called with a state, return a distribution.\n :param player: an `RLEnvironment`\n :param history_len: length of history frames to concat. zero-filled initial frames\n :param update_frequency: number of new transitions to add to memory\n after sampling a batch of transitions for training\n \"\"\"\n # XXX back-compat\n if populate_size is not None:\n logger.warn(\"populate_size in ExpReplay is deprecated in favor of init_memory_size\")\n init_memory_size = populate_size\n init_memory_size = int(init_memory_size)\n\n for k, v in locals().items():\n if k != 'self':\n setattr(self, k, v)\n self.num_actions = player.get_action_space().num_actions()\n logger.info(\"Number of Legal actions: {}\".format(self.num_actions))\n self.mem = deque(maxlen=memory_size)\n self.rng = get_rng(self)\n self._init_memory_flag = threading.Event() # tell if memory has been initialized\n self._predictor_io_names = predictor_io_names\n\n def _init_memory(self):\n logger.info(\"Populating replay memory...\")\n\n # fill some for the history\n old_exploration = self.exploration\n self.exploration = 1\n for k in range(self.history_len):\n self._populate_exp()\n self.exploration = old_exploration\n\n with tqdm(total=self.init_memory_size) as pbar:\n while len(self.mem) < self.init_memory_size:\n #from copy import deepcopy # quickly fill the memory for debug\n #self.mem.append(deepcopy(self.mem[0]))\n self._populate_exp()\n pbar.update()\n self._init_memory_flag.set()\n\n def _populate_exp(self):\n \"\"\" populate a transition by epsilon-greedy\"\"\"\n old_s = self.player.current_state()\n if self.rng.rand() <= self.exploration:\n act = self.rng.choice(range(self.num_actions))\n else:\n # build a history state\n # XXX assume a state can be representated by one tensor\n ss = [old_s]\n\n isOver = False\n for k in range(1, self.history_len):\n hist_exp = self.mem[-k]\n if hist_exp.isOver:\n isOver = True\n if isOver:\n ss.append(np.zeros_like(ss[0]))\n else:\n ss.append(hist_exp.state)\n ss.reverse()\n ss = np.concatenate(ss, axis=2)\n # XXX assume batched network\n q_values = self.predictor([[ss]])[0][0]\n act = np.argmax(q_values)\n reward, isOver = self.player.action(act)\n if self.reward_clip:\n reward = np.clip(reward, self.reward_clip[0], self.reward_clip[1])\n self.mem.append(Experience(old_s, act, reward, isOver))\n\n def get_data(self):\n self._init_memory_flag.wait()\n # new s is considered useless if isOver==True\n while True:\n batch_exp = [self._sample_one() for _ in range(self.batch_size)]\n\n #import cv2 # for debug\n #def view_state(state, next_state):\n #\"\"\" for debugging state representation\"\"\"\n #r = np.concatenate([state[:,:,k] for k in range(self.history_len)], axis=1)\n #r2 = np.concatenate([next_state[:,:,k] for k in range(self.history_len)], axis=1)\n #r = np.concatenate([r, r2], axis=0)\n #print r.shape\n #cv2.imshow(\"state\", r)\n #cv2.waitKey()\n #exp = batch_exp[0]\n #print(\"Act: \", exp[3], \" reward:\", exp[2], \" isOver: \", exp[4])\n #if exp[2] or exp[4]:\n #view_state(exp[0], exp[1])\n\n yield self._process_batch(batch_exp)\n self._populate_job_queue.put(1)\n\n def _sample_one(self):\n \"\"\" return the transition tuple for\n [idx, idx+history_len) -> [idx+1, idx+1+history_len)\n it's the transition from state idx+history_len-1 to state idx+history_len\n \"\"\"\n # look for a state to start with\n # when x.isOver==True, (x+1).state is of a different episode\n idx = self.rng.randint(len(self.mem) - self.history_len - 1)\n\n samples = [self.mem[k] for k in range(idx, idx+self.history_len+1)]\n def concat(idx):\n v = [x.state for x in samples[idx:idx+self.history_len]]\n return np.concatenate(v, axis=2)\n state = concat(0)\n next_state = concat(1)\n start_mem = samples[-2]\n reward, action, isOver = start_mem.reward, start_mem.action, start_mem.isOver\n\n start_idx = self.history_len - 1\n\n # zero-fill state before starting\n zero_fill = False\n for k in range(1, self.history_len):\n if samples[start_idx-k].isOver:\n zero_fill = True\n if zero_fill:\n state[:,:,-k-1] = 0\n if k + 2 <= self.history_len:\n next_state[:,:,-k-2] = 0\n return (state, next_state, reward, action, isOver)\n\n def _process_batch(self, batch_exp):\n state = np.array([e[0] for e in batch_exp])\n next_state = np.array([e[1] for e in batch_exp])\n reward = np.array([e[2] for e in batch_exp])\n action = np.array([e[3] for e in batch_exp], dtype='int8')\n isOver = np.array([e[4] for e in batch_exp], dtype='bool')\n return [state, action, reward, next_state, isOver]\n\n def _setup_graph(self):\n self.predictor = self.trainer.get_predict_func(*self._predictor_io_names)\n\n # Callback-related:\n def _before_train(self):\n # spawn a separate thread to run policy, can speed up 1.3x\n self._populate_job_queue = queue.Queue(maxsize=1)\n def populate_job_func():\n self._populate_job_queue.get()\n with self.trainer.sess.as_default():\n for _ in range(self.update_frequency):\n self._populate_exp()\n self._populate_job_th = LoopThread(populate_job_func, False)\n self._populate_job_th.start()\n\n self._init_memory()\n\n def _trigger_epoch(self):\n if self.exploration > self.end_exploration:\n self.exploration -= self.exploration_epoch_anneal\n logger.info(\"Exploration changed to {}\".format(self.exploration))\n # log player statistics\n stats = self.player.stats\n for k, v in six.iteritems(stats):\n try:\n mean, max = np.mean(v), np.max(v)\n self.trainer.write_scalar_summary('expreplay/mean_' + k, mean)\n self.trainer.write_scalar_summary('expreplay/max_' + k, max)\n except:\n pass\n self.player.reset_stat()\n\nif __name__ == '__main__':\n from .atari import AtariPlayer\n import sys\n predictor = lambda x: np.array([1,1,1,1])\n player = AtariPlayer(sys.argv[1], viz=0, frame_skip=10, height_range=(36, 204))\n E = ExpReplay(predictor,\n player=player,\n num_actions=player.get_action_space().num_actions(),\n populate_size=1001,\n history_len=4)\n E._init_memory()\n\n for k in E.get_data():\n import IPython as IP;\n IP.embed(config=IP.terminal.ipapp.load_default_config())\n pass\n #import IPython;\n #IPython.embed(config=IPython.terminal.ipapp.load_default_config())\n #break\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: loadcaffe.py\n# Author: Yuxin Wu <[email protected]>\n\nfrom collections import namedtuple, defaultdict\nfrom abc import abstractmethod\nimport numpy as np\nimport copy\nimport os\n\nfrom six.moves import zip\n\nfrom .utils import change_env, get_dataset_path\nfrom .fs import download\nfrom . import logger\n\n__all__ = ['load_caffe', 'get_caffe_pb']\n\nCAFFE_PROTO_URL = \"https://github.com/BVLC/caffe/raw/master/src/caffe/proto/caffe.proto\"\n\ndef get_processor():\n ret = {}\n def process_conv(layer_name, param, input_data_shape):\n assert len(param) == 2\n # caffe: ch_out, ch_in, h, w\n return {layer_name + '/W': param[0].data.transpose(2,3,1,0),\n layer_name + '/b': param[1].data}\n ret['Convolution'] = process_conv\n\n # TODO caffe has an 'transpose' option for fc/W\n def process_fc(layer_name, param, input_data_shape):\n assert len(param) == 2\n if len(input_data_shape) == 3:\n logger.info(\"{} is right after spatial data.\".format(layer_name))\n W = param[0].data\n # original: outx(CxHxW)\n W = W.reshape((-1,) + input_data_shape).transpose(2,3,1,0)\n # become: (HxWxC)xout\n else:\n W = param[0].data.transpose()\n return {layer_name + '/W': W,\n layer_name + '/b': param[1].data}\n ret['InnerProduct'] = process_fc\n\n return ret\n\ndef load_caffe(model_desc, model_file):\n \"\"\"\n return a dict of params\n \"\"\"\n param_dict = {}\n param_processors = get_processor()\n\n with change_env('GLOG_minloglevel', '2'):\n import caffe\n caffe.set_mode_cpu()\n net = caffe.Net(model_desc, model_file, caffe.TEST)\n layer_names = net._layer_names\n blob_names = net.blobs.keys()\n for layername, layer in zip(layer_names, net.layers):\n try:\n prev_blob_name = blob_names[blob_names.index(layername)-1]\n prev_data_shape = net.blobs[prev_blob_name].data.shape[1:]\n except ValueError:\n prev_data_shape = None\n logger.info(\"Processing layer {} of type {}\".format(\n layername, layer.type))\n if layer.type in param_processors:\n param_dict.update(param_processors[layer.type](\n layername, layer.blobs, prev_data_shape))\n else:\n if len(layer.blobs) != 0:\n logger.warn(\"Layer type {} not supported!\".format(layer.type))\n logger.info(\"Model loaded from caffe. Params: \" + \\\n \" \".join(sorted(param_dict.keys())))\n return param_dict\n\ndef get_caffe_pb():\n dir = get_dataset_path('caffe')\n caffe_pb_file = os.path.join(dir, 'caffe_pb2.py')\n if not os.path.isfile(caffe_pb_file):\n proto_path = download(CAFFE_PROTO_URL, dir)\n ret = os.system('cd {} && protoc caffe.proto --python_out .'.format(dir))\n assert ret == 0, \\\n \"caffe proto compilation failed! Did you install protoc?\"\n import imp\n return imp.load_source('caffepb', caffe_pb_file)\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('model')\n parser.add_argument('weights')\n parser.add_argument('output')\n args = parser.parse_args()\n ret = load_caffe(args.model, args.weights)\n\n import numpy as np\n np.save(args.output, ret)\n\n" ]
[ [ "numpy.clip", "numpy.concatenate", "numpy.max", "numpy.argmax", "numpy.mean", "numpy.zeros_like", "numpy.array" ], [ "numpy.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BlindBMan/Facial-Recognition
[ "1f0c65174de2223a81797fee7722227a712a37bc" ]
[ "Visualize.py" ]
[ "import cv2 as cv\nimport os\nimport numpy as np\nimport pdb\nimport ntpath\nimport glob\nfrom Parameters import *\n\n\ndef show_detections_without_ground_truth(detections, scores, file_names, params: Parameters):\n \"\"\"\n Afiseaza si salveaza imaginile adnotate.\n detections: numpy array de dimensiune NX4, unde N este numarul de detectii pentru toate imaginile.\n detections[i, :] = [x_min, y_min, x_max, y_max]\n scores: numpy array de dimensiune N, scorurile pentru toate detectiile pentru toate imaginile.\n file_names: numpy array de dimensiune N, pentru fiecare detectie trebuie sa salvam numele imaginii.\n (doar numele, nu toata calea).\n \"\"\"\n test_images_path = os.path.join(params.dir_test_examples, '*.jpg')\n test_files = glob.glob(test_images_path)\n\n for test_file in test_files:\n image = cv.imread(test_file)\n short_file_name = ntpath.basename(test_file)\n indices_detections_current_image = np.where(file_names == short_file_name)\n current_detections = detections[indices_detections_current_image]\n current_scores = scores[indices_detections_current_image]\n\n for idx, detection in enumerate(current_detections):\n cv.rectangle(image, (detection[0], detection[1]), (detection[2], detection[3]), (0, 0, 255), thickness=1)\n cv.putText(image, 'score:' + str(current_scores[idx])[:4], (detection[0], detection[1]),\n cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)\n cv.imwrite(os.path.join(params.dir_save_files, \"detections_\" + short_file_name), image)\n print('Apasa orice tasta pentru a continua...')\n cv.imshow('image', np.uint8(image))\n cv.waitKey(0)\n\n\ndef show_detections_with_ground_truth(detections, scores, file_names, params: Parameters):\n \"\"\"\n Afiseaza si salveaza imaginile adnotate. Deseneaza bounding box-urile prezice si cele corecte.\n detections: numpy array de dimensiune NX4, unde N este numarul de detectii pentru toate imaginile.\n detections[i, :] = [x_min, y_min, x_max, y_max]\n scores: numpy array de dimensiune N, scorurile pentru toate detectiile pentru toate imaginile.\n file_names: numpy array de dimensiune N, pentru fiecare detectie trebuie sa salvam numele imaginii.\n (doar numele, nu toata calea).\n \"\"\"\n\n ground_truth_bboxes = np.loadtxt(params.path_annotations, dtype='str')\n test_images_path = os.path.join(params.dir_test_examples, '*.jpg')\n test_files = glob.glob(test_images_path)\n\n for test_file in test_files:\n image = cv.imread(test_file)\n short_file_name = ntpath.basename(test_file)\n indices_detections_current_image = np.where(file_names == short_file_name)\n current_detections = detections[indices_detections_current_image]\n current_scores = scores[indices_detections_current_image]\n\n for idx, detection in enumerate(current_detections):\n cv.rectangle(image, (detection[0], detection[1]), (detection[2], detection[3]), (0, 0, 255), thickness=1)\n cv.putText(image, 'score:' + str(current_scores[idx])[:4], (detection[0], detection[1]),\n cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1)\n annotations = ground_truth_bboxes[ground_truth_bboxes[:, 0] == short_file_name]\n\n # show ground truth bboxes\n for detection in annotations:\n cv.rectangle(image, (int(detection[1]), int(detection[2])), (int(detection[3]), int(detection[4])), (0, 255, 0), thickness=1)\n\n cv.imwrite(os.path.join(params.dir_save_files, \"detections_\" + short_file_name), image)\n print('Apasa orice tasta pentru a continua...')\n cv.imshow('image', np.uint8(image))\n cv.waitKey(0)\n\n\n" ]
[ [ "numpy.uint8", "numpy.where", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
VisualMine/PlaneNet
[ "88eb76d88bb678bd26b7f101f0bb273e4897e92d" ]
[ "pool/models/move_to_origin.py" ]
[ "import csv\nimport sys\nimport numpy as np\n\nwith open(sys.argv[1]) as modelFile:\n modelLoader = csv.reader(modelFile, delimiter=' ')\n xs = []\n ys = []\n zs = [] \n for lineIndex, line in enumerate(modelLoader):\n if len(line) == 0:\n continue\n if line[0] == 'v':\n xs.append(float(line[1]))\n ys.append(float(line[2]))\n zs.append(float(line[3]))\n pass\n continue\n modelFile.close()\n pass\n\nxs = np.array(xs)\nys = np.array(ys)\nzs = np.array(zs)\nprint(xs.shape)\nminX = xs.min()\nmaxX = xs.max()\nminY = ys.min()\nmaxY = ys.max()\nminZ = zs.min()\nmaxZ = zs.max()\ncenterX = (minX + maxX) / 2\ncenterY = (minY + maxY) / 2\ncenterZ = (minZ + maxZ) / 2\nsizeX = (maxX - minX)\nsizeY = (maxY - minY)\nsizeZ = (maxZ - minZ)\nscale = 2 / max(sizeX, sizeY, sizeZ)\n\nwith open(sys.argv[1]) as modelFile, open(sys.argv[2], 'w') as outputFile:\n modelLoader = csv.reader(modelFile, delimiter=' ')\n xs = []\n ys = []\n zs = [] \n for lineIndex, line in enumerate(modelLoader):\n if len(line) == 0:\n outputFile.write('\\n')\n continue\n if line[0] == 'v':\n line[1] = str((float(line[1]) - centerX) * scale)\n line[2] = str((float(line[2]) - centerY) * scale)\n line[3] = str((float(line[3]) - centerZ) * scale)\n pass\n outputFile.write(' '.join(line) + '\\n')\n continue\n modelFile.close()\n outputFile.close()\n pass\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mfarrera/algorithm-reference-library
[ "7331812aa7cc3501a15d3392cecf6ea65b43f91e", "7331812aa7cc3501a15d3392cecf6ea65b43f91e" ]
[ "tests/workflows/test_imaging_component_workflows.py", "tests/libs/test_coordinate_support.py" ]
[ "\"\"\" Unit tests for pipelines expressed via dask.delayed\n\n\n\"\"\"\n\nimport logging\nimport sys\nimport unittest\n\nimport numpy\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\n\nfrom data_models.polarisation import PolarisationFrame\nfrom processing_components.image.operations import export_image_to_fits, smooth_image\nfrom processing_components.imaging.base import predict_skycomponent_visibility\nfrom processing_components.skycomponent.operations import find_skycomponents, find_nearest_skycomponent, insert_skycomponent\nfrom processing_components.simulation.testing_support import create_named_configuration, ingest_unittest_visibility, create_unittest_model, \\\n insert_unittest_errors, create_unittest_components\n\nfrom workflows.arlexecute.execution_support.arlexecute import arlexecute\nfrom workflows.arlexecute.imaging.imaging_workflows import zero_vislist_workflow, predict_workflow, \\\n invert_workflow, subtract_vislist_workflow\n\nlog = logging.getLogger(__name__)\n\nlog.setLevel(logging.DEBUG)\nlog.addHandler(logging.StreamHandler(sys.stdout))\nlog.addHandler(logging.StreamHandler(sys.stderr))\n\nclass TestImaging(unittest.TestCase):\n def setUp(self):\n \n from data_models.parameters import arl_path\n self.dir = arl_path('test_results')\n\n def tearDown(self):\n arlexecute.close()\n\n def actualSetUp(self, add_errors=False, freqwin=1, block=False, dospectral=True, dopol=False, zerow=False):\n \n arlexecute.set_client(use_dask=False)\n \n self.npixel = 256\n self.low = create_named_configuration('LOWBD2', rmax=750.0)\n self.freqwin = freqwin\n self.vis_list = list()\n self.ntimes = 5\n self.times = numpy.linspace(-3.0, +3.0, self.ntimes) * numpy.pi / 12.0\n \n if freqwin > 1:\n self.frequency = numpy.linspace(0.8e8, 1.2e8, self.freqwin)\n self.channelwidth = numpy.array(freqwin * [self.frequency[1] - self.frequency[0]])\n else:\n self.frequency = numpy.array([0.8e8])\n self.channelwidth = numpy.array([1e6])\n \n if dopol:\n self.vis_pol = PolarisationFrame('linear')\n self.image_pol = PolarisationFrame('stokesIQUV')\n f = numpy.array([100.0, 20.0, -10.0, 1.0])\n else:\n self.vis_pol = PolarisationFrame('stokesI')\n self.image_pol = PolarisationFrame('stokesI')\n f = numpy.array([100.0])\n \n if dospectral:\n flux = numpy.array([f * numpy.power(freq / 1e8, -0.7) for freq in self.frequency])\n else:\n flux = numpy.array([f])\n \n self.phasecentre = SkyCoord(ra=+180.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')\n self.vis_list = [arlexecute.execute(ingest_unittest_visibility)(self.low,\n [self.frequency[freqwin]],\n [self.channelwidth[freqwin]],\n self.times,\n self.vis_pol,\n self.phasecentre, block=block,\n zerow=zerow)\n for freqwin, _ in enumerate(self.frequency)]\n \n self.model_graph = [arlexecute.execute(create_unittest_model, nout=freqwin)(self.vis_list[freqwin],\n self.image_pol,\n npixel=self.npixel)\n for freqwin, _ in enumerate(self.frequency)]\n \n self.components_graph = [arlexecute.execute(create_unittest_components)(self.model_graph[freqwin],\n flux[freqwin, :][numpy.newaxis, :])\n for freqwin, _ in enumerate(self.frequency)]\n \n self.model_graph = [arlexecute.execute(insert_skycomponent, nout=1)(self.model_graph[freqwin],\n self.components_graph[freqwin])\n for freqwin, _ in enumerate(self.frequency)]\n \n self.vis_list = [arlexecute.execute(predict_skycomponent_visibility)(self.vis_list[freqwin],\n self.components_graph[freqwin])\n for freqwin, _ in enumerate(self.frequency)]\n \n # Calculate the model convolved with a Gaussian.\n self.model = arlexecute.compute(self.model_graph[0], sync=True)\n \n self.cmodel = smooth_image(self.model)\n export_image_to_fits(self.model, '%s/test_imaging_model.fits' % self.dir)\n export_image_to_fits(self.cmodel, '%s/test_imaging_cmodel.fits' % self.dir)\n \n if add_errors and block:\n self.vis_list = [arlexecute.execute(insert_unittest_errors)(self.vis_list[i])\n for i, _ in enumerate(self.frequency)]\n \n self.vis = arlexecute.compute(self.vis_list[0], sync=True)\n \n self.components = arlexecute.compute(self.components_graph[0], sync=True)\n \n def test_time_setup(self):\n self.actualSetUp()\n \n def _checkcomponents(self, dirty, fluxthreshold=0.6, positionthreshold=1.0):\n comps = find_skycomponents(dirty, fwhm=1.0, threshold=10 * fluxthreshold, npixels=5)\n assert len(comps) == len(self.components), \"Different number of components found: original %d, recovered %d\" % \\\n (len(self.components), len(comps))\n cellsize = abs(dirty.wcs.wcs.cdelt[0])\n \n for comp in comps:\n # Check for agreement in direction\n ocomp, separation = find_nearest_skycomponent(comp.direction, self.components)\n assert separation / cellsize < positionthreshold, \"Component differs in position %.3f pixels\" % \\\n separation / cellsize\n \n def _predict_base(self, context='2d', extra='', fluxthreshold=1.0, facets=1, vis_slices=1, **kwargs):\n vis_list = zero_vislist_workflow(self.vis_list)\n vis_list = predict_workflow(vis_list, self.model_graph, context=context,\n vis_slices=vis_slices, facets=facets, **kwargs)\n vis_list = subtract_vislist_workflow(self.vis_list, vis_list)[0]\n \n vis_list = arlexecute.compute(vis_list, sync=True)\n \n dirty = invert_workflow([vis_list], [self.model_graph[0]], context='2d', dopsf=False,\n normalize=True)[0]\n dirty = arlexecute.compute(dirty, sync=True)\n \n assert numpy.max(numpy.abs(dirty[0].data)), \"Residual image is empty\"\n export_image_to_fits(dirty[0], '%s/test_imaging_predict_%s%s_%s_dirty.fits' %\n (self.dir, context, extra, arlexecute.type()))\n \n maxabs = numpy.max(numpy.abs(dirty[0].data))\n assert maxabs < fluxthreshold, \"Error %.3f greater than fluxthreshold %.3f \" % (maxabs, fluxthreshold)\n \n def _invert_base(self, context, extra='', fluxthreshold=1.0, positionthreshold=1.0, check_components=True,\n facets=1, vis_slices=1, **kwargs):\n \n dirty = invert_workflow(self.vis_list, self.model_graph, context=context,\n dopsf=False, normalize=True, facets=facets, vis_slices=vis_slices,\n **kwargs)[0]\n dirty = arlexecute.compute(dirty, sync=True)\n \n export_image_to_fits(dirty[0], '%s/test_imaging_invert_%s%s_%s_dirty.fits' %\n (self.dir, context, extra, arlexecute.type()))\n \n assert numpy.max(numpy.abs(dirty[0].data)), \"Image is empty\"\n \n if check_components:\n self._checkcomponents(dirty[0], fluxthreshold, positionthreshold)\n \n def test_predict_2d(self):\n self.actualSetUp(zerow=True)\n self._predict_base(context='2d')\n \n @unittest.skip(\"Facets requires overlap\")\n def test_predict_facets(self):\n self.actualSetUp()\n self._predict_base(context='facets', fluxthreshold=15.0, facets=4)\n \n @unittest.skip(\"Timeslice predict needs better interpolation\")\n def test_predict_facets_timeslice(self):\n self.actualSetUp()\n self._predict_base(context='facets_timeslice', fluxthreshold=19.0, facets=8, vis_slices=self.ntimes)\n \n @unittest.skip(\"Facets requires overlap\")\n def test_predict_facets_wprojection(self):\n self.actualSetUp()\n self._predict_base(context='facets', extra='_wprojection', facets=8, wstep=8.0, fluxthreshold=15.0,\n oversampling=2)\n \n @unittest.skip(\"Correcting twice?\")\n def test_predict_facets_wstack(self):\n self.actualSetUp()\n self._predict_base(context='facets_wstack', fluxthreshold=15.0, facets=8, vis_slices=41)\n \n @unittest.skip(\"Timeslice predict needs better interpolation\")\n def test_predict_timeslice(self):\n self.actualSetUp()\n self._predict_base(context='timeslice', fluxthreshold=19.0, vis_slices=self.ntimes)\n \n @unittest.skip(\"Timeslice predict needs better interpolation\")\n def test_predict_timeslice_wprojection(self):\n self.actualSetUp()\n self._predict_base(context='timeslice', extra='_wprojection', fluxthreshold=3.0, wstep=10.0,\n vis_slices=self.ntimes, oversampling=2)\n \n def test_predict_wprojection(self):\n self.actualSetUp()\n self._predict_base(context='2d', extra='_wprojection', wstep=10.0, fluxthreshold=2.0, oversampling=2)\n \n def test_predict_wstack(self):\n self.actualSetUp()\n self._predict_base(context='wstack', fluxthreshold=2.0, vis_slices=41)\n \n def test_predict_wstack_wprojection(self):\n self.actualSetUp()\n self._predict_base(context='wstack', extra='_wprojection', fluxthreshold=3.0, wstep=2.5, vis_slices=11,\n oversampling=2)\n \n def test_predict_wstack_spectral(self):\n self.actualSetUp(dospectral=True)\n self._predict_base(context='wstack', extra='_spectral', fluxthreshold=4.0, vis_slices=41)\n \n def test_predict_wstack_spectral_pol(self):\n self.actualSetUp(dospectral=True, dopol=True)\n self._predict_base(context='wstack', extra='_spectral', fluxthreshold=4.0, vis_slices=41)\n \n def test_invert_2d(self):\n self.actualSetUp(zerow=True)\n self._invert_base(context='2d', positionthreshold=2.0, check_components=False)\n \n def test_invert_facets(self):\n self.actualSetUp()\n self._invert_base(context='facets', positionthreshold=2.0, check_components=True, facets=8)\n \n @unittest.skip(\"Correcting twice?\")\n def test_invert_facets_timeslice(self):\n self.actualSetUp()\n self._invert_base(context='facets_timeslice', check_components=True, vis_slices=self.ntimes,\n positionthreshold=5.0, flux_threshold=1.0, facets=8)\n \n def test_invert_facets_wprojection(self):\n self.actualSetUp()\n self._invert_base(context='facets', extra='_wprojection', check_components=True,\n positionthreshold=2.0, wstep=10.0, oversampling=2, facets=4)\n \n @unittest.skip(\"Correcting twice?\")\n def test_invert_facets_wstack(self):\n self.actualSetUp()\n self._invert_base(context='facets_wstack', positionthreshold=1.0, check_components=False, facets=4,\n vis_slices=11)\n \n def test_invert_timeslice(self):\n self.actualSetUp()\n self._invert_base(context='timeslice', positionthreshold=1.0, check_components=True,\n vis_slices=self.ntimes)\n \n def test_invert_timeslice_wprojection(self):\n self.actualSetUp()\n self._invert_base(context='timeslice', extra='_wprojection', positionthreshold=1.0,\n check_components=True, wstep=20.0, vis_slices=self.ntimes, oversampling=2)\n \n def test_invert_wprojection(self):\n self.actualSetUp()\n self._invert_base(context='2d', extra='_wprojection', positionthreshold=2.0, wstep=10.0, oversampling=2)\n \n def test_invert_wprojection_wstack(self):\n self.actualSetUp()\n self._invert_base(context='wstack', extra='_wprojection', positionthreshold=1.0, wstep=2.5, vis_slices=11,\n oversampling=2)\n \n def test_invert_wstack(self):\n self.actualSetUp()\n self._invert_base(context='wstack', positionthreshold=1.0, vis_slices=41)\n \n def test_invert_wstack_spectral(self):\n self.actualSetUp(dospectral=True)\n self._invert_base(context='wstack', extra='_spectral', positionthreshold=2.0,\n vis_slices=41)\n \n def test_invert_wstack_spectral_pol(self):\n self.actualSetUp(dospectral=True, dopol=True)\n self._invert_base(context='wstack', extra='_spectral_pol', positionthreshold=2.0,\n vis_slices=41)\n \n def test_weighting(self):\n \n self.actualSetUp()\n \n context = 'wstack'\n vis_slices = 41\n facets = 1\n \n dirty_graph = invert_workflow(self.vis_list, self.model_graph, context=context,\n dopsf=False, normalize=True, facets=facets, vis_slices=vis_slices)\n dirty = arlexecute.compute(dirty_graph[0], sync=True)\n export_image_to_fits(dirty[0], '%s/test_imaging_noweighting_%s_dirty.fits' % (self.dir,\n arlexecute.type()))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "\"\"\" Unit libs for coordinate support\n\n\"\"\"\n\nimport unittest\n\nimport numpy\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom numpy.testing import assert_allclose\n\nfrom libs.util.coordinate_support import xyz_to_uvw, xyz_at_latitude, simulate_point, baselines, uvw_to_xyz, \\\n skycoord_to_lmn\n\n\nclass TestCoordinates(unittest.TestCase):\n def test_xyz_at_latitude(self):\n def transform(x, y, z, lat):\n \"\"\"\n\n :param x:\n :param y:\n :param z:\n :param lat:\n :return:\n \"\"\"\n res = xyz_at_latitude(numpy.array([x, y, z]), numpy.radians(lat))\n assert_allclose(numpy.linalg.norm(res), numpy.linalg.norm([x, y, z]))\n return res\n \n # At the north pole the zenith is the celestial north\n assert_allclose(transform(1, 0, 0, 90), [1, 0, 0], atol=1e-15)\n assert_allclose(transform(0, 1, 0, 90), [0, 1, 0], atol=1e-15)\n assert_allclose(transform(0, 0, 1, 90), [0, 0, 1], atol=1e-15)\n \n # At the equator the zenith is negative Y\n assert_allclose(transform(1, 0, 0, 0), [1, 0, 0], atol=1e-15)\n assert_allclose(transform(0, 1, 0, 0), [0, 0, 1], atol=1e-15)\n assert_allclose(transform(0, 0, 1, 0), [0, -1, 0], atol=1e-15)\n \n # At the south pole we have flipped Y and Z\n assert_allclose(transform(1, 0, 0, -90), [1, 0, 0], atol=1e-15)\n assert_allclose(transform(0, 1, 0, -90), [0, -1, 0], atol=1e-15)\n assert_allclose(transform(0, 0, 1, -90), [0, 0, -1], atol=1e-15)\n \n def test_xyz_to_uvw(self):\n def transform(x, y, z, ha, dec):\n \"\"\"\n\n :param x:\n :param y:\n :param z:\n :param ha:\n :param dec:\n :return:\n \"\"\"\n res = xyz_to_uvw(numpy.array([x, y, z]), numpy.radians(ha), numpy.radians(dec))\n assert_allclose(numpy.linalg.norm(res), numpy.linalg.norm([x, y, z]))\n assert_allclose(uvw_to_xyz(res, numpy.radians(ha), numpy.radians(dec)), [x, y, z])\n return res\n \n # Derived from http://casa.nrao.edu/Memos/CoordConvention.pdf\n \n # 1. For ha=0,dec=90, we should have UVW=XYZ\n assert_allclose(transform(0, 0, 1, 0, 90), [0, 0, 1], atol=1e-15)\n assert_allclose(transform(0, 1, 0, 0, 90), [0, 1, 0], atol=1e-15)\n assert_allclose(transform(1, 0, 0, 0, 90), [1, 0, 0], atol=1e-15)\n \n # Extra test: For dec=90, we always have Z=W\n assert_allclose(transform(0, 0, 1, -90, 90), [0, 0, 1], atol=1e-15)\n assert_allclose(transform(0, 0, 1, 90, 90), [0, 0, 1], atol=1e-15)\n \n # 2. V and W are always on a Great circle with the NCP\n \n # ... we need the inverse transform, I guess?\n \n # 3. when W is on the local meridian (hour angle 0), U points\n # east (positive X)\n assert_allclose(transform(1, 0, 0, 0, 0), [1, 0, 0], atol=1e-15)\n assert_allclose(transform(1, 0, 0, 0, 30), [1, 0, 0], atol=1e-15)\n assert_allclose(transform(1, 0, 0, 0, -20), [1, 0, 0], atol=1e-15)\n assert_allclose(transform(1, 0, 0, 0, -90), [1, 0, 0], atol=1e-15)\n \n # 4. when the direction of observation is at zero declination,\n # an hour-angle of -6 hours (-90 degreees) makes W point to\n # the east (positive X).\n assert_allclose(transform(1, 0, 0, -90, 0), [0, 0, 1], atol=1e-15)\n assert_allclose(transform(1, 0, 0, 90, 0), [0, 0, -1], atol=1e-15)\n \n def test_baselines(self):\n # There should be exactly npixel*(npixel-1)/2 baselines\n def test(ants_uvw):\n \"\"\"\n\n :param ants_uvw:\n \"\"\"\n bls = baselines(ants_uvw)\n l = len(ants_uvw)\n self.assertEqual(len(bls), l * (l - 1) // 2)\n \n for i in range(10):\n test(numpy.repeat(numpy.array(range(10 + i)), 3))\n \n def test_simulate_point(self):\n # Prepare a synthetic layout\n uvw = numpy.concatenate(numpy.concatenate(numpy.transpose(numpy.mgrid[-3:4, -3:4, 0:1])))\n bls = baselines(uvw)\n \n # Should have positive amplitude for the middle of the picture\n vis = simulate_point(bls, 0, 0)\n assert_allclose(vis, numpy.ones(len(vis)))\n \n # For the half-way point the result is either -1 or 1\n # depending on whether the baseline length is even\n bl_even = 1 - 2 * (numpy.sum(bls, axis=1) % 2)\n vis = simulate_point(bls, 0.5, 0.5)\n assert_allclose(vis, bl_even)\n vis = simulate_point(bls, -0.5, 0.5)\n assert_allclose(vis, bl_even)\n vis = simulate_point(bls, 0.5, -0.5)\n assert_allclose(vis, bl_even)\n vis = simulate_point(bls, -0.5, -0.5)\n assert_allclose(vis, bl_even)\n \n def test_skycoord_to_lmn(self):\n center = SkyCoord(ra=0, dec=0, unit=u.deg)\n north = SkyCoord(ra=0, dec=90, unit=u.deg)\n south = SkyCoord(ra=0, dec=-90, unit=u.deg)\n east = SkyCoord(ra=90, dec=0, unit=u.deg)\n west = SkyCoord(ra=-90, dec=0, unit=u.deg)\n assert_allclose(skycoord_to_lmn(center, center), (0, 0, 0))\n assert_allclose(skycoord_to_lmn(north, center), (0, 1, -1))\n assert_allclose(skycoord_to_lmn(south, center), (0, -1, -1))\n assert_allclose(skycoord_to_lmn(south, north), (0, 0, -2), atol=1e-14)\n assert_allclose(skycoord_to_lmn(east, center), (1, 0, -1))\n assert_allclose(skycoord_to_lmn(west, center), (-1, 0, -1))\n assert_allclose(skycoord_to_lmn(center, west), (1, 0, -1))\n assert_allclose(skycoord_to_lmn(north, west), (0, 1, -1), atol=1e-14)\n assert_allclose(skycoord_to_lmn(south, west), (0, -1, -1), atol=1e-14)\n assert_allclose(skycoord_to_lmn(north, east), (0, 1, -1), atol=1e-14)\n assert_allclose(skycoord_to_lmn(south, east), (0, -1, -1), atol=1e-14)\n \n def test_phase_rotate(self):\n \n uvw = numpy.array([(1, 0, 0), (0, 1, 0), (0, 0, 1)])\n \n pos = [SkyCoord(17, 35, unit=u.deg), SkyCoord(17, 30, unit=u.deg),\n SkyCoord(12, 30, unit=u.deg), SkyCoord(11, 35, unit=u.deg),\n SkyCoord(51, 35, unit=u.deg), SkyCoord(15, 70, unit=u.deg)]\n \n # Sky coordinates to reproject to\n for phasecentre in pos:\n for newphasecentre in pos:\n \n # Rotate UVW\n xyz = uvw_to_xyz(uvw, -phasecentre.ra.rad, phasecentre.dec.rad)\n uvw_rotated = xyz_to_uvw(xyz, -newphasecentre.ra.rad, newphasecentre.dec.rad)\n \n # Determine phasor\n l_p, m_p, n_p = skycoord_to_lmn(phasecentre, newphasecentre)\n phasor = simulate_point(uvw_rotated, l_p, m_p)\n \n for sourcepos in pos:\n # Simulate visibility at old and new phase centre\n l, m, _ = skycoord_to_lmn(sourcepos, phasecentre)\n vis = simulate_point(uvw, l, m)\n l_r, m_r, _ = skycoord_to_lmn(sourcepos, newphasecentre)\n vis_rotated = simulate_point(uvw_rotated, l_r, m_r)\n \n # Difference should be given by phasor\n assert_allclose(vis * phasor, vis_rotated, atol=1e-10)\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "numpy.array", "numpy.abs", "numpy.linspace", "numpy.power" ], [ "numpy.radians", "numpy.linalg.norm", "numpy.transpose", "numpy.array", "numpy.sum", "numpy.testing.assert_allclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
YujieLu10/tslam
[ "1341dbecdf02ee6b1b6cdd1a538272fffdea6ffd", "1341dbecdf02ee6b1b6cdd1a538272fffdea6ffd" ]
[ "mjrl/algos/model_accel/sampling.py", "mjrl/policies/gaussian_mlp_3d.py" ]
[ "import logging\nimport numpy as np\nfrom mjrl.utils.gym_env import GymEnv\nfrom mjrl.utils import tensor_utils\nlogging.disable(logging.CRITICAL)\nimport multiprocessing as mp\nfrom multiprocessing import set_start_method\ntry:\n set_start_method('spawn')\nexcept RuntimeError:\n pass\nimport time as timer\nimport torch\nlogging.disable(logging.CRITICAL)\n\n\n# ===========================================================\n# Rollout parameteric policy on fitted env to collect data\n# ===========================================================\n\ndef policy_rollout(\n num_traj,\n env,\n policy,\n fitted_model,\n init_state=None,\n eval_mode=False,\n horizon=1e6,\n env_kwargs=None,\n seed=None,\n):\n\n # get the correct env behavior\n if type(env) == str:\n env = GymEnv(env)\n elif isinstance(env, GymEnv):\n env = env\n elif callable(env):\n env = env(**env_kwargs)\n else:\n print(\"Unsupported environment format\")\n raise AttributeError\n\n if seed is not None:\n env.set_seed(seed)\n torch.manual_seed(seed)\n\n # get initial states\n if init_state is None:\n st = np.array([env.reset() for _ in range(num_traj)])\n st = torch.from_numpy(st).float()\n elif type(init_state) == np.ndarray:\n st = torch.from_numpy(init_state).float()\n elif type(init_state) == list:\n st = torch.from_numpy(np.array(init_state)).float()\n else:\n print(\"Unsupported format for init state\")\n quit()\n\n # perform batched rollouts\n horizon = min(horizon, env.horizon)\n obs = []\n act = []\n for t in range(horizon):\n at = policy.model.forward(st)\n if eval_mode is not True:\n at = at + torch.randn(at.shape) * torch.exp(policy.log_std)\n stp1 = fitted_model.forward(st, at)\n obs.append(st.to('cpu').data.numpy())\n act.append(at.to('cpu').data.numpy())\n st = stp1\n\n obs = np.array(obs)\n obs = np.swapaxes(obs, 0, 1) # (num_traj, horizon, state_dim)\n act = np.array(act)\n act = np.swapaxes(act, 0, 1) # (num_traj, horizon, action_dim)\n paths = dict(observations = obs,\n actions = act)\n\n return paths\n\n\n# ===========================================================\n# Rollout action sequences on the fitted model\n# ===========================================================\n\ndef trajectory_rollout(actions, fitted_model, init_states):\n # init_states: (num_traj, state_dim) : numpy array\n # actions : (num_traj, horizon, action_dim) : numpy array\n # fitted_model : model(s, a) = s_tp1\n\n actions = np.array(actions) if type(actions) == list else actions\n num_traj = actions.shape[0]\n horizon = actions.shape[1]\n\n if len(init_states.shape) == 1:\n init_states = np.tile(init_states, (num_traj, 1))\n\n obs = []\n st = torch.from_numpy(init_states).float()\n for t in range(horizon):\n at = actions[:, t, :]\n at = torch.from_numpy(at).float()\n stp1 = fitted_model.forward(st, at)\n obs.append(st.data.numpy().copy())\n st = stp1\n\n obs = np.array(obs)\n obs = np.swapaxes(obs, 0, 1)\n paths = dict(observations=obs, actions=actions)\n return paths\n\n\n# ===========================================================\n# Rollout policy (parametric or implicit MPC) on real env\n# ===========================================================\n# TODO(Aravind): Remove redundancy. This can be coupled with the standard sample_paths in MJRL utils\n\ndef sample_paths(num_traj,\n env,\n policy, # mpc policy on fitted model\n horizon=1e6,\n eval_mode=True,\n base_seed=None,\n noise_level=0.1,\n ):\n\n # get the correct env behavior\n if type(env) == str:\n env = GymEnv(env)\n elif isinstance(env, GymEnv):\n env = env\n elif callable(env):\n env = env()\n else:\n print(\"Unsupported environment format\")\n raise AttributeError\n if base_seed is not None:\n env.set_seed(base_seed)\n horizon = min(horizon, env.horizon)\n paths = []\n for ep in range(num_traj):\n env.reset()\n observations=[]\n actions=[]\n rewards=[]\n env_infos=[]\n t = 0\n done = False\n while t < horizon and done is False:\n obs = env.get_obs()\n ifo = env.get_env_infos()\n act = policy.get_action(obs)\n if eval_mode is False and type(act) != list:\n act = act + np.random.uniform(low=-noise_level, high=noise_level, size=act.shape[0])\n if type(act) == list:\n act = act[0] if eval_mode is False else act[1]['evaluation']\n next_obs, reward, done, _ = env.step(act)\n t = t + 1\n observations.append(obs)\n actions.append(act)\n rewards.append(reward)\n env_infos.append(ifo)\n path = dict(\n observations=np.array(observations),\n actions=np.array(actions),\n rewards=np.array(rewards),\n terminated=done,\n env_infos=tensor_utils.stack_tensor_dict_list(env_infos)\n )\n paths.append(path)\n return paths\n\n\n# ===========================================================\n# Utility functions\n# ===========================================================\n\ndef discount_sum(x, gamma, discounted_terminal=0.0):\n \"\"\"\n discount sum a sequence with terminal value\n \"\"\"\n y = []\n run_sum = discounted_terminal\n for t in range( len(x)-1, -1, -1):\n run_sum = x[t] + gamma*run_sum\n y.append(run_sum)\n\n return np.array(y[::-1])\n\n\ndef generate_perturbed_actions(base_act, filter_coefs):\n \"\"\"\n Generate perturbed actions around a base action sequence\n \"\"\"\n sigma, beta_0, beta_1, beta_2 = filter_coefs\n eps = np.random.normal(loc=0, scale=1.0, size=base_act.shape) * sigma\n eps = base_act + eps\n eps[0] = eps[0] * (beta_0 + beta_1 + beta_2)\n eps[1] = beta_0 * eps[1] + (beta_1 + beta_2) * eps[0]\n for i in range(2, eps.shape[0]):\n eps[i] = beta_0*eps[i] + beta_1*eps[i-1] + beta_2*eps[i-2]\n return eps\n\n\ndef generate_paths(num_traj, fitted_model, start_state, base_act, filter_coefs, base_seed=None):\n \"\"\"\n first generate enough perturbed actions\n then do rollouts with generated actions\n set seed inside this function for multiprocessing\n \"\"\"\n if base_seed is not None:\n np.random.seed(base_seed)\n act_list = []\n for i in range(num_traj):\n act = generate_perturbed_actions(base_act, filter_coefs)\n act_list.append(act)\n act = np.array(act_list)\n paths = trajectory_rollout(act, fitted_model, start_state)\n return paths\n\n\ndef evaluate_policy(e, policy, fitted_model, noise_level=0.0,\n real_step=False, num_episodes=10, visualize=False):\n # rollout the policy on env and record performance\n paths = []\n for ep in range(num_episodes):\n e.reset()\n observations = []\n actions = []\n rewards = []\n env_infos = []\n t = 0\n done = False\n while t < e.horizon and done is False:\n o = e.get_obs()\n ifo = e.get_env_infos()\n a = policy.get_action(o)\n if type(a) == list:\n a = a[1]['evaluation']\n if noise_level > 0.0:\n a = a + e.env.env.np_random.uniform(low=-noise_level, high=noise_level, size=a.shape[0])\n if real_step is False:\n next_s = fitted_model.predict(o, a)\n r = 0.0 # temporarily\n e.env.env.set_fitted_state(next_s)\n else:\n next_o, r, done, ifo2 = e.step(a)\n ifo = ifo2 if ifo == {} else ifo\n if visualize:\n e.render()\n\n t = t + 1\n observations.append(o)\n actions.append(a)\n rewards.append(r)\n env_infos.append(ifo)\n\n path = dict(observations=np.array(observations), actions=np.array(actions),\n rewards=np.array(rewards),\n env_infos=tensor_utils.stack_tensor_dict_list(env_infos))\n if real_step is False:\n e.env.env.compute_path_rewards(path)\n try:\n path = e.env.env.truncate_paths([path])[0]\n except:\n pass\n paths.append(path)\n if visualize:\n print(\"episode score = %f \" % np.sum(path['rewards']))\n return paths", "import numpy as np\nfrom mjrl.utils.fc_network_3d import FCNetwork3D\nimport torch\nfrom torch.autograd import Variable\n\nvoxelobs_dim = 8\nvoxel_dim = voxelobs_dim * voxelobs_dim * voxelobs_dim\nclass MLP:\n def __init__(self, env_spec,\n hidden_sizes=(64,64),\n min_log_std=-3,\n init_log_std=0,\n m_f=1,\n n_f=1,\n reinitialize=False,\n seed=None):\n \"\"\"\n :param env_spec: specifications of the env (see utils/gym_env.py)\n :param hidden_sizes: network hidden layer sizes (currently 2 layers only)\n :param min_log_std: log_std is clamped at this value and can't go below\n :param init_log_std: initial log standard deviation\n :param seed: random seed\n \"\"\"\n self.n = env_spec.observation_dim # number of states\n self.m = env_spec.action_dim # number of actions\n self.min_log_std = min_log_std\n self.mean_factor = m_f\n self.noise_factor = n_f\n self.reinitialize = reinitialize\n # Set seed\n # ------------------------\n if seed is not None:\n torch.manual_seed(seed)\n np.random.seed(seed)\n\n # Policy network\n # ------------------------\n self.model = FCNetwork3D(self.n, self.m, hidden_sizes).to('cuda')\n # make weights small\n for param in list(self.model.parameters())[-2:]: # only last layer\n param.data = 1e-2 * param.data\n self.log_std = Variable(torch.ones(self.m) * init_log_std, requires_grad=True)\n self.trainable_params = list(self.model.parameters()) + [self.log_std]\n\n # Old Policy network\n # ------------------------\n self.old_model = FCNetwork3D(self.n, self.m, hidden_sizes).to('cuda')\n self.old_log_std = Variable(torch.ones(self.m) * init_log_std)\n self.old_params = list(self.old_model.parameters()) + [self.old_log_std]\n for idx, param in enumerate(self.old_params):\n param.data = self.trainable_params[idx].data.clone()\n\n # Easy access variables\n # -------------------------\n self.log_std_val = np.float64(self.log_std.data.numpy().ravel())\n self.param_shapes = [p.cpu().data.numpy().shape for p in self.trainable_params]\n self.param_sizes = [p.cpu().data.numpy().size for p in self.trainable_params]\n self.d = np.sum(self.param_sizes) # total number of params\n\n # Placeholders\n # ------------------------\n self.obs_var = Variable(torch.randn(self.n), requires_grad=False)\n\n # Utility functions\n # ============================================\n def get_param_values(self):\n params = np.concatenate([p.contiguous().view(-1).to('cpu').data.numpy()\n for p in self.trainable_params])\n return params.copy()\n\n def set_param_values(self, new_params, set_new=True, set_old=True):\n if set_new:\n current_idx = 0\n for idx, param in enumerate(self.trainable_params):\n vals = new_params[current_idx:current_idx + self.param_sizes[idx]]\n vals = vals.reshape(self.param_shapes[idx])\n param.data = torch.from_numpy(vals).float()\n current_idx += self.param_sizes[idx]\n # clip std at minimum value\n self.trainable_params[-1].data = \\\n torch.clamp(self.trainable_params[-1], self.min_log_std).data\n # update log_std_val for sampling\n self.log_std_val = np.float64(self.log_std.data.numpy().ravel())\n if set_old:\n current_idx = 0\n for idx, param in enumerate(self.old_params):\n vals = new_params[current_idx:current_idx + self.param_sizes[idx]]\n vals = vals.reshape(self.param_shapes[idx])\n param.data = torch.from_numpy(vals).float()\n current_idx += self.param_sizes[idx]\n # clip std at minimum value\n self.old_params[-1].data = \\\n torch.clamp(self.old_params[-1], self.min_log_std).data\n\n # Main functions\n # ============================================\n def get_action(self, observation):\n o = np.float32(observation.reshape(1, -1))\n self.obs_var.data = torch.from_numpy(o)\n mean = self.model(self.obs_var[:, :-voxel_dim].to('cuda'), self.obs_var[:, -voxel_dim:].to('cuda')).cpu().data.numpy().ravel()\n noise = np.exp(self.log_std_val) * np.random.randn(self.m)\n action = mean + noise\n return [action, {'mean': mean, 'log_std': self.log_std_val, 'evaluation': mean}]\n\n def mean_LL(self, observations, actions, model=None, log_std=None):\n model = self.model if model is None else model\n log_std = self.log_std if log_std is None else log_std\n if type(observations) is not torch.Tensor:\n obs_var = Variable(torch.from_numpy(observations).float(), requires_grad=False)\n else:\n obs_var = observations\n if type(actions) is not torch.Tensor:\n act_var = Variable(torch.from_numpy(actions).float(), requires_grad=False)\n else:\n act_var = actions\n mean = model(obs_var[:, :-voxel_dim].to('cuda'), obs_var[:, -voxel_dim:].to('cuda')).cpu()\n zs = (act_var - mean) / torch.exp(log_std)\n LL = - 0.5 * torch.sum(zs ** 2, dim=1) + \\\n - torch.sum(log_std) + \\\n - 0.5 * self.m * np.log(2 * np.pi)\n return mean, LL\n\n def log_likelihood(self, observations, actions, model=None, log_std=None):\n mean, LL = self.mean_LL(observations, actions, model, log_std)\n return LL.data.numpy()\n\n def old_dist_info(self, observations, actions):\n mean, LL = self.mean_LL(observations, actions, self.old_model, self.old_log_std)\n return [LL, mean, self.old_log_std]\n\n def new_dist_info(self, observations, actions):\n mean, LL = self.mean_LL(observations, actions, self.model, self.log_std)\n return [LL, mean, self.log_std]\n\n def likelihood_ratio(self, new_dist_info, old_dist_info):\n LL_old = old_dist_info[0]\n LL_new = new_dist_info[0]\n LR = torch.exp(LL_new - LL_old)\n return LR\n\n def mean_kl(self, new_dist_info, old_dist_info):\n old_log_std = old_dist_info[2]\n new_log_std = new_dist_info[2]\n old_std = torch.exp(old_log_std)\n new_std = torch.exp(new_log_std)\n old_mean = old_dist_info[1]\n new_mean = new_dist_info[1]\n Nr = (old_mean - new_mean) ** 2 + old_std ** 2 - new_std ** 2\n Dr = 2 * new_std ** 2 + 1e-8\n sample_kl = torch.sum(Nr / Dr + new_log_std - old_log_std, dim=1)\n return torch.mean(sample_kl)\n" ]
[ [ "numpy.swapaxes", "numpy.random.seed", "torch.manual_seed", "torch.randn", "numpy.tile", "torch.from_numpy", "torch.exp", "numpy.random.normal", "numpy.random.uniform", "numpy.array", "numpy.sum" ], [ "torch.mean", "numpy.log", "torch.ones", "numpy.random.seed", "torch.manual_seed", "torch.randn", "torch.sum", "torch.from_numpy", "torch.exp", "numpy.random.randn", "torch.clamp", "numpy.exp", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
emiliocuestaf/CycloRec
[ "cf0bf39ff185f0b1ef8d1c6fe1d424a23c7716f7" ]
[ "src/data_layers/ffeedbackcm100k_layer.py" ]
[ "import pandas as pd\nimport numpy as np\n#import random as rd\n#from sklearn.neighbors import NearestNeighbors\n#from scipy.sparse import csr_matrix\n\n# OWN\nfrom cyclorec.data_layers.data_layer import DataLayer\n\nclass FFeedbackCm100kLayer(DataLayer):\n \"\"\" The only difference between this layer and Cm100kLayer is the feedback the algorihtms are receiving. \n In the typical version, if an algorithm succeded in a recommendation it would be updated with a reward.\n However, in FFeedback the algorithm will only be rewarded if the recommended item was known by the user. \n \"\"\"\n \n def __init__(self, name, test_proportion):\n \"\"\" Constructor\n\n Args:\n name (str): DataLayer name\n test_proportion (float): proportion of the whole set to be assigned to the test set\n \"\"\"\n # CUSTOMIZABLE RATING VARIABLES\n rating_normalization = 'bin'\n if rating_normalization == 'bin':\n rating_conversor = dict({1: 0, 2: 0, 3: 1, 4: 1})\n relevanceThreshold = 0.5\n antiRelevanceThreshold = 0.5\n else:\n rating_conversor = dict({1: -1, 2: 0, 3: 1, 4: 1})\n relevanceThreshold = 0.5\n antiRelevanceThreshold = -0.5\n\n # ITEMS\n # index = id || item_id | url | title | artist\n items = pd.read_csv(\"./data/cm100k/items.txt\", sep=\"\\t\")\n items.columns = items.columns.str.lower()\n items = items.rename(columns={\"item\": \"item_id\"})\n items.index = items.item_id\n\n\n # ALL RATINGS\n ### Dataframe with ratings\n # index || user | item | rating | known\n ratings = pd.read_csv(\"./data/cm100k/ratings.txt\", sep=\"\\t\", names=['user_id', 'item_id', 'rating', 'known'], header=None)\n ratings.columns = ratings.columns.str.lower()\n ratings['rating'] = ratings['rating'].replace(rating_conversor)\n super().__init__(name, items=items, splitted=False, whole_set=ratings, test_proportion=test_proportion, \\\n relevance_threshold=relevanceThreshold, antiRelevance_threshold=antiRelevanceThreshold )\n\n\n #override\n def get_bandit_reward(self, user_id, item_id, rating):\n \n if np.isnan(rating['rating']):\n return np.nan\n elif rating['known'] == 1:\n return rating['rating']\n else:\n return np.nan\n\n " ]
[ [ "numpy.isnan", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
hellolele/PoseFromShape
[ "7daf9e4889af065861d2719cd2bca2de8a45d185" ]
[ "auxiliary/model.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.utils.data\nfrom torch.autograd import Variable\nimport resnet\n\n\n# ============================================================================ #\n# Baseline network #\n# ============================================================================ #\nclass BaselineEstimator(nn.Module):\n \"\"\"Pose estimator using image feature with shape feature\n\n Arguments:\n img_feature_dim: output feature dimension for image\n pretrained_resnet: use the ResNet pretrained on ImageNet if True\n\n Return:\n Three angle bin classification probability with a delta value regression for each bin\n \"\"\"\n def __init__(self, img_feature_dim=1024, separate_branch=False,\n azi_classes=24, ele_classes=12, inp_classes=24, pretrained_resnet=False):\n super(BaselineEstimator, self).__init__()\n\n # RGB image encoder\n self.img_encoder = resnet.resnet18(pretrained=pretrained_resnet, num_classes=img_feature_dim)\n\n self.compress = nn.Sequential(nn.Linear(img_feature_dim, 800), nn.BatchNorm1d(800), nn.ReLU(inplace=True),\n nn.Linear(800, 400), nn.BatchNorm1d(400), nn.ReLU(inplace=True),\n nn.Linear(400, 200), nn.BatchNorm1d(200), nn.ReLU(inplace=True))\n self.separate_branch = separate_branch\n\n # separate branch for classification and regression\n if separate_branch:\n self.compress_delta = nn.Sequential(nn.Linear(img_feature_dim, 800), nn.BatchNorm1d(800), nn.ReLU(inplace=True),\n nn.Linear(800, 400), nn.BatchNorm1d(400), nn.ReLU(inplace=True),\n nn.Linear(400, 200), nn.BatchNorm1d(200), nn.ReLU(inplace=True))\n\n self.fc_cls_azi = nn.Linear(200, azi_classes)\n self.fc_cls_ele = nn.Linear(200, ele_classes)\n self.fc_cls_inp = nn.Linear(200, inp_classes)\n self.fc_reg_azi = nn.Linear(200, azi_classes)\n self.fc_reg_ele = nn.Linear(200, ele_classes)\n self.fc_reg_inp = nn.Linear(200, inp_classes)\n\n def forward(self, im):\n # pass the image through image encoder\n img_feature = self.img_encoder(im)\n\n # concatenate the features obtained from two encoders into one feature\n x = self.compress(img_feature)\n cls_azi = self.fc_cls_azi(x)\n cls_ele = self.fc_cls_ele(x)\n cls_inp = self.fc_cls_inp(x)\n\n # use the shared features if share branch\n x_delta = self.compress_delta(img_feature) if self.separate_branch else x\n reg_azi = self.fc_reg_azi(x_delta)\n reg_ele = self.fc_reg_ele(x_delta)\n reg_inp = self.fc_reg_inp(x_delta)\n return [cls_azi, cls_ele, cls_inp, reg_azi, reg_ele, reg_inp]\n\n\n# ============================================================================ #\n# Proposed network #\n# ============================================================================ #\nclass ShapeEncoderMV(nn.Module):\n \"\"\"Shape Encoder using rendering images under multiple views\n\n Arguments:\n feature_dim: output feature dimension for each rendering image\n channels: 3 for normal rendering image, 4 for normal map with depth map, and 3*12 channels for concatenating\n pretrained_resnet: use the ResNet pretrained on ImageNet if True\n\n Return:\n A tensor of size NxC, where N is the batch size and C is the feature_dim\n \"\"\"\n def __init__(self, feature_dim=256, channels=3, pretrained_resnet=False):\n super(ShapeEncoderMV, self).__init__()\n self.render_encoder = resnet.resnet18(input_channel=channels, num_classes=feature_dim, pretrained=pretrained_resnet)\n\n def forward(self, renders):\n # reshape render images from dimension N*K*C*H*W to (N*K)*C*H*W\n N, K, C, H, W = renders.size()\n renders = renders.view(N*K, C, H, W)\n\n # pass the encoder and reshape render features from dimension (N*K)*D1 to N*(K*D1)\n render_feature = self.render_encoder(renders)\n render_feature = render_feature.view(N, -1)\n return render_feature\n\n\nclass ShapeEncoderPC(nn.Module):\n \"\"\"Shape Encoder using point cloud TO BE MODIFIED\n \"\"\"\n def __init__(self, feature_dim=256, channels=3, pretrained_resnet=False):\n super(ShapeEncoderPC, self).__init__()\n self.pc_encoder = resnet.resnet18(input_channel=channels, num_classes=feature_dim, pretrained=pretrained_resnet)\n\n def forward(self, shapes):\n shape_feature = self.pc_encoder(shapes)\n return shape_feature\n\n\nclass PoseEstimator(nn.Module):\n \"\"\"Pose estimator using image feature with shape feature\n\n Arguments:\n img_feature_dim: output feature dimension for image\n shape_feature_dim: output feature dimension for shape\n shape: shape representation in PointCloud or MultiView\n channels: channel number for multi-view encoder\n pretrained_resnet: use the ResNet pretrained on ImageNet if True\n\n Return:\n Three angle bin classification probability with a delta value regression for each bin\n \"\"\"\n def __init__(self, render_number=12, img_feature_dim=1024, shape_feature_dim=256, channels=3, separate_branch=False,\n azi_classes=24, ele_classes=12, inp_classes=24, pretrained_resnet=False, shape='PointCloud'):\n super(PoseEstimator, self).__init__()\n\n # 3D shape encoder\n if shape == 'PointCloud':\n self.shape_encoder = ShapeEncoderPC()\n else:\n self.shape_encoder = ShapeEncoderMV(feature_dim=shape_feature_dim, channels=channels, pretrained_resnet=pretrained_resnet)\n shape_feature_dim = shape_feature_dim * render_number if shape != 'PointCloud' else shape_feature_dim\n\n # RGB image encoder\n self.img_encoder = resnet.resnet18(pretrained=pretrained_resnet, num_classes=img_feature_dim)\n\n self.compress = nn.Sequential(nn.Linear(shape_feature_dim + img_feature_dim, 800),\n nn.BatchNorm1d(800), nn.ReLU(inplace=True),\n nn.Linear(800, 400), nn.BatchNorm1d(400), nn.ReLU(inplace=True),\n nn.Linear(400, 200), nn.BatchNorm1d(200), nn.ReLU(inplace=True))\n self.separate_branch = separate_branch\n\n # separate branch for classification and regression\n if separate_branch:\n self.compress_delta = nn.Sequential(nn.Linear(shape_feature_dim + img_feature_dim, 800),\n nn.BatchNorm1d(800), nn.ReLU(inplace=True),\n nn.Linear(800, 400), nn.BatchNorm1d(400), nn.ReLU(inplace=True),\n nn.Linear(400, 200), nn.BatchNorm1d(200), nn.ReLU(inplace=True))\t\n\n self.fc_cls_azi = nn.Linear(200, azi_classes)\n self.fc_cls_ele = nn.Linear(200, ele_classes)\n self.fc_cls_inp = nn.Linear(200, inp_classes)\n self.fc_reg_azi = nn.Linear(200, azi_classes)\n self.fc_reg_ele = nn.Linear(200, ele_classes)\n self.fc_reg_inp = nn.Linear(200, inp_classes)\n\n def forward(self, im, shape):\n # pass the image through image encoder\n img_feature = self.img_encoder(im)\n\n # pass the shape through shape encoder\n shape_feature = self.shape_encoder(shape)\n\n # concatenate the features obtained from two encoders into one feature\n global_feature = torch.cat((shape_feature, img_feature), 1)\n x = self.compress(global_feature)\n cls_azi = self.fc_cls_azi(x)\n cls_ele = self.fc_cls_ele(x)\n cls_inp = self.fc_cls_inp(x)\n\n # use the shared features if share branch\n x_delta = self.compress_delta(global_feature) if self.separate_branch else x\n reg_azi = self.fc_reg_azi(x_delta)\n reg_ele = self.fc_reg_ele(x_delta)\n reg_inp = self.fc_reg_inp(x_delta)\n return [cls_azi, cls_ele, cls_inp, reg_azi, reg_ele, reg_inp]\n\n\nif __name__ == '__main__':\n print('test model')\n\n sim_im = Variable(torch.rand(4, 3, 224, 224))\n sim_renders = Variable(torch.rand(4, 12, 3, 224, 224))\n sim_im = sim_im.cuda()\n sim_renders = sim_renders.cuda()\n #model = PoseEstimator(shape='MultiView', separate_branch=False)\n model = BaselineEstimator(separate_branch=False, pretrained_resnet=False)\n model.cuda()\n #cls_azi, cls_ele, cls_inp, reg_azi, reg_ele, reg_inp = model(sim_im, sim_renders)\n cls_azi, cls_ele, cls_inp, reg_azi, reg_ele, reg_inp = model(sim_im)\n print(cls_azi.size(), cls_ele.size(), cls_inp.size(), reg_azi.size(), reg_ele.size(), reg_inp.size())\n" ]
[ [ "torch.nn.BatchNorm1d", "torch.cat", "torch.nn.Linear", "torch.rand", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
prestononeal/CS-7641-assignments
[ "c3a6815ba1be837084c60c3dd0dc8e8e702aa9b7" ]
[ "assignment1/learners/ANN.py" ]
[ "from sklearn import neural_network\n\nimport learners\n\n\nclass ANNLearner(learners.BaseLearner):\n def __init__(self,\n hidden_layer_sizes=(100,),\n activation=\"relu\",\n solver='adam',\n alpha=0.0001,\n batch_size='auto',\n learning_rate=\"constant\",\n learning_rate_init=0.001,\n power_t=0.5,\n max_iter=200,\n shuffle=True,\n random_state=None,\n tol=1e-4,\n verbose=False,\n warm_start=False,\n momentum=0.9,\n nesterovs_momentum=True,\n early_stopping=False,\n validation_fraction=0.1,\n beta_1=0.9,\n beta_2=0.999,\n epsilon=1e-8,\n ):\n super().__init__(verbose)\n self._learner = neural_network.MLPClassifier(\n hidden_layer_sizes=hidden_layer_sizes,\n activation=activation,\n solver=solver,\n alpha=alpha,\n batch_size=batch_size,\n learning_rate=learning_rate,\n learning_rate_init=learning_rate_init,\n power_t=power_t,\n max_iter=max_iter,\n shuffle=shuffle,\n random_state=random_state,\n tol=tol,\n verbose=verbose,\n warm_start=warm_start,\n momentum=momentum,\n nesterovs_momentum=nesterovs_momentum,\n early_stopping=early_stopping,\n validation_fraction=validation_fraction,\n beta_1=beta_1,\n beta_2=beta_2,\n epsilon=epsilon\n )\n\n def learner(self):\n return self._learner\n" ]
[ [ "sklearn.neural_network.MLPClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MingzheWu418/plastering
[ "322531e934c3acf2ecc8f520b37a6d255b9959c2" ]
[ "plastering/evaluator.py" ]
[ "from copy import deepcopy\nfrom sklearn.metrics import f1_score\nfrom sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\nimport pdb\n\ndef binarize_labels(true_labels, pred_labels):\n srcids = list(pred_labels.keys())\n tot_labels = [list(labels) for labels in\n list(pred_labels.values()) + list(true_labels.values())]\n mlb = MultiLabelBinarizer().fit(tot_labels)\n pred_mat = mlb.transform(pred_labels.values())\n true_mat = mlb.transform(true_labels.values())\n return true_mat, pred_mat\n\ndef get_micro_f1(true_labels, pred_labels):\n true_mat, pred_mat = binarize_labels(true_labels, pred_labels)\n return get_micro_f1_mat(true_mat, pred_mat)\n\ndef get_macro_f1(true_labels, pred_labels):\n true_mat, pred_mat = binarize_labels(true_labels, pred_labels)\n return get_macro_f1_mat(true_mat, pred_mat)\n\ndef get_macro_f1_mat(true_mat, pred_mat):\n assert true_mat.shape == pred_mat.shape\n f1s = []\n for i in range(0, true_mat.shape[1]):\n if 1 not in true_mat[:,i]:\n continue\n f1 = f1_score(true_mat[:,i], pred_mat[:,i])\n f1s.append(f1)\n return np.mean(f1s)\n\ndef get_multiclass_micro_f1(true_labels, pred_labels):\n le = LabelEncoder()\n #pred_mat, true_mat = binarize_labels(true_labels, pred_labels)\n #f1_custom = get_micro_f1_mat(true_mat, pred_mat)\n srcids = list(true_labels.keys())\n true_label_list = [true_labels[srcid] for srcid in srcids]\n pred_label_list = [pred_labels[srcid] for srcid in srcids]\n le = LabelEncoder()\n le.fit(true_label_list + pred_label_list)\n true_encoded = le.transform(true_label_list)\n pred_encoded = le.transform(pred_label_list)\n f1_micro = f1_score(true_encoded, pred_encoded, average='micro')\n #f1_weighted = f1_score(true_encoded, pred_encoded, average='weighted')\n #pdb.set_trace()\n return f1_micro\n\ndef get_multiclass_macro_f1(true_labels, pred_labels):\n le = LabelEncoder()\n #pred_mat, true_mat = binarize_labels(true_labels, pred_labels)\n #f1_custom = get_micro_f1_mat(true_mat, pred_mat)\n srcids = list(true_labels.keys())\n true_label_list = [true_labels[srcid] for srcid in srcids]\n pred_label_list = [pred_labels[srcid] for srcid in srcids]\n le = LabelEncoder()\n le.fit(true_label_list + pred_label_list)\n true_encoded = le.transform(true_label_list)\n pred_encoded = le.transform(pred_label_list)\n f1_micro = f1_score(true_encoded, pred_encoded, average='macro')\n #f1_weighted = f1_score(true_encoded, pred_encoded, average='weighted')\n #pdb.set_trace()\n return f1_micro\n\n\n\ndef get_micro_f1_mat(true_mat, pred_mat):\n TP = np.sum(np.bitwise_and(true_mat==1, pred_mat==1))\n TN = np.sum(np.bitwise_and(true_mat==0, pred_mat==0))\n FN = np.sum(np.bitwise_and(true_mat==1, pred_mat==0))\n FP = np.sum(np.bitwise_and(true_mat==0, pred_mat==1))\n micro_prec = TP / (TP + FP)\n micro_rec = TP / (TP + FN)\n return 2 * micro_prec * micro_rec / (micro_prec + micro_rec)\n\ndef get_point_accuracy(true_tagsets, pred_tagsets):\n target_srcids = pred_tagsets.keys()\n return sum([true_tagsets[srcid].lower() == pred_tagsets[srcid].lower()\n for srcid in target_srcids]) / len(target_srcids)\n\ndef get_accuracy(true_tagsets_sets, pred_tagsets_sets):\n acc = 0\n for srcid, pred_tagsets in pred_tagsets_sets.items():\n pred = set(pred_tagsets)\n true = set(true_tagsets_sets[srcid])\n jaccard = len(pred.intersection(true)) / len(pred.union(true))\n acc += jaccard\n return acc / len(pred_tagsets_sets)\n\ndef exclude_common_tagsets(tagsets):\n return [tagset for tagset in tagsets\n if tagset.split('-')[0] != 'networkadapter' and\n tagset.split('-')[0] != 'building'\n ]\n\ndef get_accuracy_conservative(true_tagsets_sets, pred_tagsets_sets):\n acc = 0\n for srcid, pred_tagsets in pred_tagsets_sets.items():\n pred = set(exclude_common_tagsets(pred_tagsets))\n true = set(exclude_common_tagsets(true_tagsets_sets[srcid]))\n if len(true) == 0:\n jaccard = 1\n else:\n jaccard = len(pred.intersection(true)) / len(pred.union(true))\n acc += jaccard\n return acc / len(pred_tagsets_sets)\n\n\ndef get_set_accuracy(true_label_sets, pred_tagset_sets):\n # Accuracy per sample = #intersection / #union\n # Accuracy over set = average of the accuracy per sample\n # Input params dictionary based on the srcids\n for srcid, pred_tagset_set in pred_tagset_sets.items():\n pass #TODO\n\n" ]
[ [ "sklearn.preprocessing.MultiLabelBinarizer", "numpy.bitwise_and", "numpy.mean", "sklearn.metrics.f1_score", "sklearn.preprocessing.LabelEncoder" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Ukasz09/Clothing-recognition
[ "9332b0d3eac59782c0e8a72078ba97d67805d512" ]
[ "app/utils/prediction_utils.py" ]
[ "import time\nimport datetime\nimport numpy as np\n\n__start_time = time.time()\n__end_time = time.time()\n\n\ndef calc_accuracy(predicted_labels, real_labels):\n correct_qty = 0\n for i in range(len(predicted_labels)):\n if predicted_labels[i] == real_labels[i]:\n correct_qty += 1\n return correct_qty * 100 / len(predicted_labels)\n\n\ndef predict_labels(pyx):\n \"\"\"\n :param pyx: matrix with probability distribution p(y|x) for every class and *X_test* object\n :return: list with predicted class labels\n \"\"\"\n return [np.argmax(row, axis=0) for row in pyx]\n\n\ndef convert_time(sec):\n return str(datetime.timedelta(seconds=sec))\n" ]
[ [ "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EquinoxOmega0/timedomain
[ "b9c6c2e6804d7dde56311d9402769be545d505d0" ]
[ "desitrip/py/desitrip/scripts/process.py" ]
[ "#!/usr/bin/env python\n\"\"\"Apply the DESITrIP CNN classifier to observed spectra,\nchosen by tile ID and date.\n\"\"\"\n\nfrom desispec.io import read_spectra, write_spectra\nfrom desispec.spectra import Spectra\nfrom desitarget.cmx.cmx_targetmask import cmx_mask\n\nfrom desitrip.preproc import rebin_flux, rescale_flux\n\nfrom astropy.io import fits\nfrom astropy.table import Table, vstack, hstack\n\nfrom glob import glob\nfrom datetime import date\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\nimport os\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\nfrom tensorflow import keras\n\np = ArgumentParser(description='DESITrIP data processing',\n formatter_class=ArgumentDefaultsHelpFormatter)\np.add_argument('--tile', type=int, default=0,\n help='Tile ID for processing.')\np.add_argument('--date', default=date.today().strftime('%Y%m%d'),\n help='Date of observation [YYYYMMDD]')\np.add_argument('--tfmodel', default=None,\n help='TensorFlow model HDF5 definition')\nargs = p.parse_args()\n\n# Access redux folder.\nredux='/global/project/projectdirs/desi/spectro/redux/daily/tiles'\nprefix_in='/'.join([redux, '{:05d}'.format(args.tile), args.date]) \nif not os.path.isdir(prefix_in):\n raise SystemExit('{} does not exist.'.format(prefix_in))\n\n# Set up BGS target bit selection.\ncmx_bgs_bits = '|'.join([_ for _ in cmx_mask.names() if 'BGS' in _])\n\n# List zbest and coadd files.\nzbfiles = sorted(glob('{}/zbest*.fits'.format(prefix_in)))\ncafiles = sorted(glob('{}/coadd*.fits'.format(prefix_in)))\n\nif args.tfmodel is not None:\n classifier = keras.models.load_model(args.tfmodel)\n\n# Loop through zbest and coadd files for each petal.\n# Extract the fibermaps, ZBEST tables, and spectra.\n# Keep only BGS targets passing basic event selection.\nallzbest = None\nallfmap = None\nallwave = None\nallflux = None\nallivar = None\nallmask = None\nallres = None\n\nfor cafile, zbfile in zip(cafiles, zbfiles):\n # Access data per petal.\n zbest = Table.read(zbfile, 'ZBEST')\n fibermap = Table.read(zbfile, 'FIBERMAP')\n pspectra = read_spectra(cafile)\n\n # Apply standard event selection.\n isTGT = fibermap['OBJTYPE'] == 'TGT'\n isGAL = zbest['SPECTYPE'] == 'GALAXY'\n isBGS = fibermap['CMX_TARGET'] & cmx_mask.mask(cmx_bgs_bits) != 0\n select = isTGT & isGAL & isBGS\n\n # Accumulate spectrum data.\n if allzbest is None:\n allzbest = zbest[select]\n allfmap = fibermap[select]\n allwave = pspectra.wave['brz']\n allflux = pspectra.flux['brz'][select]\n allivar = pspectra.ivar['brz'][select]\n allmask = pspectra.mask['brz'][select]\n allres = pspectra.resolution_data['brz'][select]\n else:\n allzbest = vstack([allzbest, zbest[select]])\n allfmap = vstack([allfmap, fibermap[select]])\n allflux = np.vstack([allflux, pspectra.flux['brz'][select]])\n allivar = np.vstack([allivar, pspectra.ivar['brz'][select]])\n allmask = np.vstack([allmask, pspectra.mask['brz'][select]])\n allres = np.vstack([allres, pspectra.resolution_data['brz'][select]])\n\n# Apply the DESITrIP preprocessing to selected spectra.\nrewave, reflux, reivar = rebin_flux(allwave, allflux, allivar, allzbest['Z'],\n minwave=2500., maxwave=9500., nbins=150,\n log=True, clip=True)\nrsflux = rescale_flux(reflux)\n\n# Run the classification.\nif args.tfmodel is not None:\n pred = classifier.predict(rsflux)\n\n# Create output: selected target spectra.\nselected_spectra = Spectra(bands=['brz'],\n wave={'brz' : allwave},\n flux={'brz' : allflux},\n ivar={'brz' : allivar},\n mask={'brz' : allmask},\n resolution_data={'brz' : allres},\n fibermap=allfmap)\n\nwrite_spectra('selected-{}-{}.fits'.format(args.tile, args.date), selected_spectra)\n\n# Append preprocess spectra to output.\nhx = fits.HDUList()\n\nhdu_rewave = fits.PrimaryHDU(rewave)\nhdu_rewave.header['EXTNAME'] = 'REWAVE'\nhdu_rewave.header['BUNIT'] = 'Angstrom'\nhdu_rewave.header['AIRORVAC'] = ('vac', 'Vacuum wavelengths')\nhx.append(hdu_rewave)\n\nhdu_reflux = fits.ImageHDU(reflux)\nhdu_reflux.header['EXTNAME'] = 'REFLUX'\nhx.append(hdu_reflux)\n\nhdu_rsflux = fits.ImageHDU(rsflux)\nhdu_rsflux.header['EXTNAME'] = 'RSFLUX'\nhx.append(hdu_rsflux)\n\nhdu_classify = fits.ImageHDU(pred)\nhdu_classify.header['EXTNAME'] = 'OBJCLASS'\nhx.append(hdu_classify)\n\nhx.append(fits.BinTableHDU(allzbest))\nhx.writeto('reduced-{}-{}.fits'.format(args.tile, args.date), overwrite=True)\n" ]
[ [ "tensorflow.keras.models.load_model", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
umd-huang-lab/reinforcement-learning-via-spectral-methods
[ "c7bd04d7eea6869807ed70af76960dcc542b0a82", "c7bd04d7eea6869807ed70af76960dcc542b0a82" ]
[ "tensor_rl/agents/bandits/LinUCBAgentClass.py", "tensor_rl/tasks/general/GeneralMDPClass.py" ]
[ "'''\nBasic LinUCB implementation.\n'''\n\n# Python imports.\nimport numpy as np\nfrom collections import defaultdict\n\n# Other imports.\nfrom tensor_rl.agents.AgentClass import Agent\n\nclass LinUCBAgent(Agent):\n '''\n From:\n Lihong Li, et al. \"A Contextual-Bandit Approach to Personalized\n News Article Recommendation.\" In Proceedings of the 19th\n International Conference on World Wide Web (WWW), 2010.\n '''\n\n def __init__(self, actions, name=\"LinUCB\", rand_init=True, context_size=1, alpha=1.5):\n '''\n Args:\n actions (list): Contains a string for each action.\n name (str)\n context_size (int)\n alpha (float): Uncertainty parameter.\n '''\n Agent.__init__(self, name, actions)\n self.alpha = alpha\n self.context_size = context_size\n self.prev_context = None\n self.step_number = 0\n self.rand_init = rand_init\n self._init_action_model(rand_init)\n\n\n def get_parameters(self):\n '''\n Returns:\n (dict) key=param_name (str) --> val=param_val (object).\n '''\n param_dict = defaultdict(int)\n \n param_dict[\"rand_init\"] = self.rand_init\n param_dict[\"context_size\"] = self.context_size\n param_dict[\"alpha\"] = self.alpha\n\n return param_dict\n\n def _init_action_model(self, rand_init=True):\n '''\n Summary:\n Initializes model parameters\n '''\n self.model = {'act': {}, 'act_inv': {}, 'theta': {}, 'b': {}}\n for action_id in range(len(self.actions)):\n self.model['act'][action_id] = np.identity(self.context_size)\n self.model['act_inv'][action_id] = np.identity(self.context_size)\n if rand_init:\n self.model['theta'][action_id] = np.random.random((self.context_size, 1))\n else:\n self.model['theta'][action_id] = np.zeros((self.context_size, 1))\n self.model['b'][action_id] = np.zeros((self.context_size,1))\n\n def _compute_score(self, context):\n '''\n Args:\n context (list)\n\n Returns:\n (dict):\n K (str): action\n V (float): score\n '''\n\n a_inv = self.model['act_inv']\n theta = self.model['theta']\n\n estimated_reward = {}\n uncertainty = {}\n score_dict = {}\n max_score = 0\n for action_id in range(len(self.actions)):\n action_context = np.reshape(context[action_id], (-1, 1))\n estimated_reward[action_id] = float(theta[action_id].T.dot(action_context))\n uncertainty[action_id] = float(self.alpha * np.sqrt(action_context.T.dot(a_inv[action_id]).dot(action_context)))\n score_dict[action_id] = estimated_reward[action_id] + uncertainty[action_id]\n\n return score_dict\n\n def update(self, reward):\n '''\n Args:\n reward (float)\n\n Summary:\n Updates self.model according to self.prev_context, self.prev_action, @reward.\n '''\n action_id = self.actions.index(self.prev_action)\n action_context = np.reshape(self.prev_context[action_id], (-1, 1))\n self.model['act'][action_id] += action_context.dot(action_context.T)\n self.model['act_inv'][action_id] = np.linalg.inv(self.model['act'][action_id])\n self.model['b'][action_id] += reward * action_context\n self.model['theta'][action_id] = self.model['act_inv'][action_id].dot(self.model['b'][action_id])\n\n def act(self, context, reward):\n '''\n Args:\n context (iterable)\n reward (float)\n\n Returns:\n (str): action.\n '''\n\n # Update previous context-action pair.\n if self.prev_action is not None:\n self.update(reward)\n\n # Compute score.\n context = self._pre_process_context(context)\n score = self._compute_score(context)\n\n # Compute best action.\n best_action = np.random.choice(self.actions)\n max_score = float(\"-inf\")\n for action_id in range(len(self.actions)):\n if score[action_id] > max_score:\n max_score = score[action_id]\n best_action = self.actions[action_id]\n\n\n # Update prev pointers.\n self.prev_action = best_action\n self.prev_context = context\n self.step_number += 1\n \n return best_action\n\n def _pre_process_context(self, context):\n if context.get_num_feats() == 1:\n # If there's no context (that is, we're just in a regular bandit).\n context = context.features()\n\n if not hasattr(context[0], '__iter__'):\n # If we only have a single context.\n new_context = {}\n for action_id in range(len(self.actions)):\n new_context[action_id] = context\n context = new_context\n\n return context\n", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 18 20:27:33 2019\n\n\"\"\"\n\n# Python imports.\nfrom __future__ import print_function\nimport random\nimport math\nimport sys, os\nimport scipy\nimport numpy as np\nfrom collections import defaultdict\n\n# Other imports.\nfrom tensor_rl.mdp.MDPClass import MDP\nfrom tensor_rl.tasks.general.GeneralStateClass import GeneralState\n\n# Fix input to cooperate with python 2 and 3.\ntry:\n input = raw_input\nexcept NameError:\n pass\n\nclass GeneralMDP(MDP):\n ''' Class for a general MDP '''\n\n # Static constants.\n# ACTIONS = [0, 1, 2]\n# N_ACTIONS = 3\n\n def __init__(self,\n n_states,\n n_actions,\n tuples=[],\n init_state = 0,\n gamma = 0.5,\n name=\"general\",\n par_tensor=None):\n self.n_actions = n_actions\n self.actions = list(range(n_actions))\n self.n_states = n_states\n init_state = GeneralState(init_state)\n \n MDP.__init__(self, self.actions, self._transition_func, self._reward_func, init_state=init_state, gamma=gamma)\n \n self.name = name\n self._init_states()\n \n self.par_tensor = self._init_par_tensor(tuples)\n \n def _init_par_tensor(self, tuples):\n '''tuples: [(state, action, next_state, probability, reward)]'''\n tensor = np.zeros((self.n_actions, self.n_states, self.n_states+1))\n for tup in tuples:\n s, a, s1, prob, r = tup\n tensor[a][s][s1] = prob\n tensor[a][s][-1] += r * prob\n return tensor\n \n\n def _init_states(self):\n self.states = []\n self.state_map = {}\n for i in range(self.n_states):\n self.states.append(GeneralState(i))\n self.state_map[GeneralState(i)] = i\n\n def _choose_by_dist(self, prob_vec):\n ''' return a chosen state number '''\n \n rand = random.random()\n# print(\"a random number:\", rand)\n# print(\"prob_dist\", prob_vec)\n s = 0\n for i in range(len(prob_vec)-1):\n s += prob_vec[i]\n if s > rand:\n return GeneralState(i)\n# print(\"nothing has been chosen!\")\n return None \n\n def _transition_func(self, state, action):\n# print(\"(\", action, \")\", end=\" \")\n next_state = self._choose_by_dist(self.par_tensor[action][state.get_data()])\n# print(\"next\", next_state, end=' ')\n return next_state\n \n \n def _reward_func(self, state, action, next_state):\n\n return self.par_tensor[action][state.get_data()][self.n_states]\n\n \n def __str__(self):\n return self.name\n \n \n \n \n \n \n\n " ]
[ [ "numpy.random.random", "numpy.random.choice", "numpy.reshape", "numpy.linalg.inv", "numpy.identity", "numpy.zeros" ], [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
harshkasyap/PySyft
[ "4575a50f38b78728dafe2615aad9145dae17b085" ]
[ "test/generic/pointers/test_pointer_tensor.py" ]
[ "import torch\nimport torch as th\nimport syft\n\nfrom syft.frameworks.torch.tensors.interpreters.additive_shared import AdditiveSharingTensor\nfrom syft.frameworks.torch.tensors.interpreters.precision import FixedPrecisionTensor\nfrom syft.generic.pointers.pointer_tensor import PointerTensor\nimport pytest\n\n\ndef test_init(workers):\n alice, me = workers[\"alice\"], workers[\"me\"]\n pointer = PointerTensor(id=1000, location=alice, owner=me)\n pointer.__str__()\n\n\ndef test_create_pointer():\n x = torch.Tensor([1, 2])\n x.create_pointer()\n\n\ndef test_send_default_garbage_collector_true(workers):\n \"\"\"\n Remote tensor should be garbage collected by default on\n deletion of the Pointer tensor pointing to remote tensor\n \"\"\"\n alice = workers[\"alice\"]\n\n x = torch.Tensor([-1, 2])\n x_ptr = x.send(alice)\n assert x_ptr.child.garbage_collect_data\n\n\ndef test_send_garbage_collect_data_false(workers):\n \"\"\"\n Remote tensor should be not garbage collected on\n deletion of the Pointer tensor pointing to remote tensor\n \"\"\"\n alice = workers[\"alice\"]\n\n x = torch.Tensor([-1, 2])\n x_ptr = x.send(alice)\n x_ptr.garbage_collection = False\n assert x_ptr.child.garbage_collect_data is False\n\n\ndef test_send_gc_false(workers):\n \"\"\"\n Remote tensor should be not garbage collected on\n deletion of the Pointer tensor pointing to remote tensor\n \"\"\"\n alice = workers[\"alice\"]\n x = torch.Tensor([-1, 2])\n x_ptr = x.send(alice)\n x_ptr.gc = False\n assert x_ptr.child.garbage_collect_data is False\n assert x_ptr.gc is False, \"property GC is not in sync\"\n assert x_ptr.garbage_collection is False, \"property garbage_collection is not in sync\"\n\n\ndef test_send_gc_true(workers):\n \"\"\"\n Remote tensor by default is garbage collected on\n deletion of Pointer Tensor\n \"\"\"\n alice = workers[\"alice\"]\n\n x = torch.Tensor([-1, 2])\n x_ptr = x.send(alice)\n\n assert x_ptr.gc\n\n\ndef test_send_disable_gc(workers):\n \"\"\"Pointer tensor should be not garbage collected.\"\"\"\n alice = workers[\"alice\"]\n\n x = torch.Tensor([-1, 2])\n x_ptr = x.send(alice).disable_gc\n assert x_ptr.child.garbage_collect_data is False\n assert x_ptr.gc is False, \"property GC is not in sync\"\n assert x_ptr.garbage_collection is False, \"property garbage_collection is not in sync\"\n\n\ndef test_send_get(workers):\n \"\"\"Test several send get usages\"\"\"\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n\n # simple send\n x = torch.Tensor([1, 2])\n x_ptr = x.send(bob)\n x_back = x_ptr.get()\n assert (x == x_back).all()\n\n # send with variable overwriting\n x = torch.Tensor([1, 2])\n x = x.send(bob)\n x_back = x.get()\n assert (torch.Tensor([1, 2]) == x_back).all()\n\n # double send\n x = torch.Tensor([1, 2])\n x_ptr = x.send(bob)\n x_ptr_ptr = x_ptr.send(alice)\n x_ptr_back = x_ptr_ptr.get()\n x_back_back = x_ptr_back.get()\n assert (x == x_back_back).all()\n\n # double send with variable overwriting\n x = torch.Tensor([1, 2])\n x = x.send(bob)\n x = x.send(alice)\n x = x.get()\n x_back = x.get()\n assert (torch.Tensor([1, 2]) == x_back).all()\n\n # chained double send\n x = torch.Tensor([1, 2])\n x = x.send(bob).send(alice)\n x_back = x.get().get()\n assert (torch.Tensor([1, 2]) == x_back).all()\n\n\ndef test_inplace_send_get(workers):\n bob = workers[\"bob\"]\n\n tensor = torch.tensor([1.0, -1.0, 3.0, 4.0])\n tensor_ptr = tensor.send_(bob)\n\n assert tensor_ptr.id == tensor.id\n assert id(tensor_ptr) == id(tensor)\n\n tensor_back = tensor_ptr.get_()\n\n assert tensor_back.id == tensor_ptr.id\n assert tensor_back.id == tensor.id\n assert id(tensor_back) == id(tensor)\n assert id(tensor_back) == id(tensor)\n\n assert (tensor_back == tensor).all()\n\n\ndef test_repeated_send(workers):\n \"\"\"Tests that repeated calls to .send(bob) works gracefully.\n Previously garbage collection deleted the remote object\n when .send() was called twice. This test ensures the fix still\n works.\"\"\"\n\n bob = workers[\"bob\"]\n\n # create tensor\n x = torch.Tensor([1, 2])\n\n # send tensor to bob\n x_ptr = x.send(bob)\n\n # send tensor again\n x_ptr = x.send(bob)\n\n # ensure bob has tensor\n assert x.id in bob.object_store._objects\n\n\ndef test_remote_autograd(workers):\n \"\"\"Tests the ability to backpropagate gradients on a remote\n worker.\"\"\"\n\n bob = workers[\"bob\"]\n\n # TEST: simple remote grad calculation\n\n # create a tensor\n x = torch.tensor([1, 2, 3, 4.0], requires_grad=True)\n\n # send tensor to bob\n x = x.send(bob)\n\n # do some calculation\n y = (x + x).sum()\n\n # backpropagate on remote machine\n y.backward()\n\n # check that remote gradient is correct\n x_grad = bob.object_store.get_obj(x.id_at_location).grad\n x_grad_target = torch.ones(4).float() + 1\n assert (x_grad == x_grad_target).all()\n\n # TEST: Ensure remote grad calculation gets properly serded\n\n # create tensor\n x = torch.tensor([1, 2, 3, 4.0], requires_grad=True).send(bob)\n\n # compute function\n y = x.sum()\n\n # backpropagate\n y.backward()\n\n # get the gradient created from backpropagation manually\n x_grad = bob.object_store.get_obj(x.id_at_location).grad\n\n # get the entire x tensor (should bring the grad too)\n x = x.get()\n\n # make sure that the grads match\n assert (x.grad == x_grad).all()\n\n\ndef test_gradient_send_recv(workers):\n \"\"\"Tests that gradients are properly sent and received along\n with their tensors.\"\"\"\n\n bob = workers[\"bob\"]\n\n # create a tensor\n x = torch.tensor([1, 2, 3, 4.0], requires_grad=True)\n\n # create gradient on tensor\n x.sum().backward(th.tensor(1.0))\n\n # save gradient\n orig_grad = x.grad\n\n # send and get back\n t = x.send(bob).get()\n\n # check that gradient was properly serde\n assert (t.grad == orig_grad).all()\n\n\ndef test_method_on_attribute(workers):\n\n bob = workers[\"bob\"]\n\n # create remote object with children\n x = torch.Tensor([1, 2, 3])\n x = syft.LoggingTensor().on(x).send(bob)\n\n # call method on data tensor directly\n x.child.point_to_attr = \"child.child\"\n y = x.add(x)\n assert isinstance(y.get(), torch.Tensor)\n\n # call method on loggingtensor directly\n x.child.point_to_attr = \"child\"\n y = x.add(x)\n y = y.get()\n assert isinstance(y.child, syft.LoggingTensor)\n\n # # call method on zeroth attribute\n # x.child.point_to_attr = \"\"\n # y = x.add(x)\n # y = y.get()\n #\n # assert isinstance(y, torch.Tensor)\n # assert isinstance(y.child, syft.LoggingTensor)\n # assert isinstance(y.child.child, torch.Tensor)\n\n # call .get() on pinter to attribute (should error)\n x.child.point_to_attr = \"child\"\n try:\n x.get()\n except syft.exceptions.CannotRequestObjectAttribute as e:\n assert True\n\n\ndef test_grad_pointer(workers):\n \"\"\"Tests the automatic creation of a .grad pointer when\n calling .send() on a tensor with requires_grad==True\"\"\"\n\n bob = workers[\"bob\"]\n\n x = torch.tensor([1, 2, 3.0], requires_grad=True).send(bob)\n y = (x + x).sum()\n y.backward()\n\n assert (bob.object_store.get_obj(x.id_at_location).grad == torch.tensor([2, 2, 2.0])).all()\n\n\ndef test_move(workers):\n alice, bob, james, me = workers[\"alice\"], workers[\"bob\"], workers[\"james\"], workers[\"me\"]\n\n x = torch.tensor([1, 2, 3, 4, 5]).send(bob)\n\n assert x.id_at_location in bob.object_store._objects\n assert x.id_at_location not in alice.object_store._objects\n\n p = x.move(alice)\n\n assert x.id_at_location not in bob.object_store._objects\n assert x.id_at_location in alice.object_store._objects\n\n x = torch.tensor([1.0, 2, 3, 4, 5], requires_grad=True).send(bob)\n\n assert x.id_at_location in bob.object_store._objects\n assert x.id_at_location not in alice.object_store._objects\n\n p = x.move(alice)\n\n assert x.id_at_location not in bob.object_store._objects\n assert x.id_at_location in alice.object_store._objects\n\n alice.clear_objects()\n bob.clear_objects()\n x = torch.tensor([1.0, 2, 3, 4, 5]).send(bob)\n p = x.move(alice)\n\n assert len(alice.object_store._tensors) == 1\n\n # Test .move on remote objects\n\n james.clear_objects()\n x = th.tensor([1.0]).send(james)\n remote_x = james.object_store.get_obj(x.id_at_location)\n remote_ptr = remote_x.send(bob)\n assert remote_ptr.id in james.object_store._objects.keys()\n remote_ptr2 = remote_ptr.move(alice)\n assert remote_ptr2.id in james.object_store._objects.keys()\n\n # Test .move back to myself\n\n alice.clear_objects()\n bob.clear_objects()\n t = torch.tensor([1.0, 2, 3, 4, 5])\n x = t.send(bob)\n y = x.move(alice)\n z = y.move(me)\n assert (z == t).all()\n\n # Move object to same location\n alice.clear_objects()\n t = torch.tensor([1.0, 2, 3, 4, 5]).send(bob)\n t = t.move(bob)\n assert torch.all(torch.eq(t.get(), torch.tensor([1.0, 2, 3, 4, 5])))\n\n\ndef test_combine_pointers(workers):\n \"\"\"\n Ensure that the sy.combine_pointers works as expected\n \"\"\"\n\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n\n x = th.tensor([1, 2, 3, 4, 5]).send(bob)\n y = th.tensor([1, 2, 3, 4, 5]).send(alice)\n\n a = x.combine(y)\n b = a + a\n\n c = b.get(sum_results=True)\n assert (c == th.tensor([4, 8, 12, 16, 20])).all()\n\n b = a + a\n c = b.get(sum_results=False)\n assert len(c) == 2\n assert (c[0] == th.tensor([2, 4, 6, 8, 10])).all\n\n\ndef test_remote_to_cpu_device(workers):\n \"\"\"Ensure remote .to cpu works\"\"\"\n device = torch.device(\"cpu\")\n bob = workers[\"bob\"]\n\n x = th.tensor([1, 2, 3, 4, 5]).send(bob)\n x.to(device)\n\n\ndef test_get_remote_shape(workers):\n \"\"\"Test pointer.shape functionality\"\"\"\n bob = workers[\"bob\"]\n # tensor directly sent: shape stored at sending\n x = th.tensor([1, 2, 3, 4, 5]).send(bob)\n assert x.shape == torch.Size([5])\n # result of an operation: need to make a call to the remote worker\n y = x + x\n assert y.shape == torch.Size([5])\n\n\ndef test_get_remote_ndim(workers):\n \"\"\"Test pointer.ndim functionality\"\"\"\n bob = workers[\"bob\"]\n x = th.rand(2, 3, 4).send(bob)\n assert x.ndim == 3\n\n\ndef test_remote_T(workers):\n \"\"\"Test pointer.T functionality\"\"\"\n bob = workers[\"bob\"]\n x = th.rand(2, 3, 4)\n bob_x = x.send(bob)\n bob_xT = bob_x.T\n assert bob_x.shape == torch.Size([2, 3, 4])\n assert bob_xT.shape == torch.Size([4, 3, 2])\n assert (bob_x.get() == x).all()\n assert (bob_xT.get() == x.T).all()\n\n\ndef test_remote_function_with_multi_ouput(workers):\n \"\"\"\n Functions like .split return several tensors, registration and response\n must be made carefully in this case\n \"\"\"\n bob = workers[\"bob\"]\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n r_ptr = torch.split(ptr, 2)\n assert (r_ptr[0].get() == torch.tensor([1, 2.0])).all()\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n max_value, argmax_idx = torch.max(ptr, 0)\n\n assert max_value.get().item() == 4.0\n assert argmax_idx.get().item() == 3\n\n\ndef test_inplace_binary_method_with_non_pointers(workers):\n \"\"\"Under very specific conditions, ie inplace methods containing a\n single argument which is a Tensor, we allow automatic sending of\n this tensor. This is helpful to facilitate utilizing python code\n of other library for remote execution\"\"\"\n alice = workers[\"alice\"]\n p = th.tensor([1.0, 2]).send(alice)\n x = th.tensor([1.0, 1])\n p += x\n assert (p.get() == th.tensor([2.0, 3])).all()\n\n\ndef test_raising_error_when_item_func_called(workers):\n pointer = PointerTensor(id=1000, location=workers[\"alice\"], owner=workers[\"me\"])\n with pytest.raises(RuntimeError):\n pointer.item()\n\n\ndef test_fix_prec_on_pointer_tensor(workers):\n \"\"\"\n Ensure .fix_precision() works as expected.\n Also check that fix_precision() is not inplace.\n \"\"\"\n bob = workers[\"bob\"]\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n\n ptr_fp = ptr.fix_precision()\n\n remote_tensor = bob.object_store.get_obj(ptr.id_at_location)\n remote_fp_tensor = bob.object_store.get_obj(ptr_fp.id_at_location)\n\n # check that fix_precision is not inplace\n assert (remote_tensor == tensor).all()\n\n assert isinstance(ptr.child, PointerTensor)\n assert isinstance(remote_fp_tensor.child, FixedPrecisionTensor)\n\n\ndef test_fix_prec_on_pointer_of_pointer(workers):\n \"\"\"\n Ensure .fix_precision() works along a chain of pointers.\n \"\"\"\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n ptr = ptr.send(alice)\n\n ptr = ptr.fix_precision()\n\n alice_tensor = alice.object_store.get_obj(ptr.id_at_location)\n remote_tensor = bob.object_store.get_obj(alice_tensor.id_at_location)\n\n assert isinstance(ptr.child, PointerTensor)\n assert isinstance(remote_tensor.child, FixedPrecisionTensor)\n\n\ndef test_float_prec_on_pointer_tensor(workers):\n \"\"\"\n Ensure .float_precision() works as expected.\n \"\"\"\n bob = workers[\"bob\"]\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n ptr = ptr.fix_precision()\n\n ptr = ptr.float_precision()\n remote_tensor = bob.object_store.get_obj(ptr.id_at_location)\n\n assert isinstance(ptr.child, PointerTensor)\n assert isinstance(remote_tensor, torch.Tensor)\n\n\ndef test_float_prec_on_pointer_of_pointer(workers):\n \"\"\"\n Ensure .float_precision() works along a chain of pointers.\n \"\"\"\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n ptr = ptr.send(alice)\n ptr = ptr.fix_precision()\n\n ptr = ptr.float_precision()\n\n alice_tensor = alice.object_store.get_obj(ptr.id_at_location)\n remote_tensor = bob.object_store.get_obj(alice_tensor.id_at_location)\n\n assert isinstance(ptr.child, PointerTensor)\n assert isinstance(remote_tensor, torch.Tensor)\n\n\ndef test_share_get(workers):\n \"\"\"\n Ensure .share() works as expected.\n \"\"\"\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n charlie = workers[\"charlie\"]\n\n tensor = torch.tensor([1, 2, 3])\n ptr = tensor.send(bob)\n\n ptr = ptr.share(charlie, alice)\n remote_tensor = bob.object_store.get_obj(ptr.id_at_location)\n\n assert isinstance(ptr.child, PointerTensor)\n assert isinstance(remote_tensor.child, AdditiveSharingTensor)\n\n\ndef test_registration_of_action_on_pointer_of_pointer(workers):\n \"\"\"\n Ensure actions along a chain of pointers are registered as expected.\n \"\"\"\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n\n tensor = torch.tensor([1, 2, 3, 4.0])\n ptr = tensor.send(bob)\n ptr = ptr.send(alice)\n ptr_action = ptr + ptr\n\n assert len(alice.object_store._tensors) == 2\n assert len(bob.object_store._tensors) == 2\n\n\ndef test_setting_back_grad_to_origin_after_send(workers):\n \"\"\"\n Calling .backward() on a tensor sent using `.send(..., requires_grad=True)`\n should update the origin tensor gradient\n \"\"\"\n me = workers[\"me\"]\n alice = workers[\"alice\"]\n\n with me.registration_enabled():\n x = th.tensor([1.0, 2.0, 3, 4, 5], requires_grad=True)\n y = x + x\n me.register_obj(y) # registration on the local worker is sometimes buggy\n\n y_ptr = y.send(alice, requires_grad=True)\n z_ptr = y_ptr * 2\n\n z = z_ptr.sum()\n z.backward()\n\n assert (x.grad == th.tensor([4.0, 4.0, 4.0, 4.0, 4.0])).all()\n\n\ndef test_setting_back_grad_to_origin_after_move(workers):\n \"\"\"\n Calling .backward() on a tensor moved using `.move(..., requires_grad=True)`\n should update the origin tensor gradient\n \"\"\"\n me = workers[\"me\"]\n bob = workers[\"bob\"]\n alice = workers[\"alice\"]\n\n with me.registration_enabled():\n x = th.tensor([1.0, 2.0, 3, 4, 5], requires_grad=True)\n y = x + x\n me.register_obj(y) # registration on the local worker is sometimes buggy\n\n y_ptr = y.send(alice, requires_grad=True)\n z_ptr = y_ptr * 2\n\n z_ptr2 = z_ptr.move(bob, requires_grad=True)\n z = z_ptr2.sum()\n z.backward()\n\n assert (x.grad == th.tensor([4.0, 4.0, 4.0, 4.0, 4.0])).all()\n\n\ndef test_remote_grad_fn(workers):\n \"\"\"\n Test that grad_fn can be accessed remotely\n \"\"\"\n alice = workers[\"alice\"]\n\n t = th.tensor([1.0, 1], requires_grad=True)\n p = t.sum()\n p.backward()\n expected_type = type(p.grad_fn)\n\n x = th.tensor([1.0, 1], requires_grad=True).send(alice)\n p = x.sum()\n p.backward()\n p_grad_fn = p.child.grad_fn.child\n\n assert isinstance(p_grad_fn, syft.PointerTensor)\n\n remote_grad_fn = alice._objects[p_grad_fn.id_at_location]\n\n assert type(remote_grad_fn.grad_fn) == expected_type\n\n\ndef test_iadd(workers):\n alice = workers[\"alice\"]\n a = torch.ones(1, 5)\n b = torch.ones(1, 5)\n a_pt = a.send(alice)\n b_pt = b.send(alice)\n\n b_pt += a_pt\n\n assert len(alice.object_store._objects) == 2\n\n\ndef test_inplace_ops_on_remote_long_tensor(workers):\n alice = workers[\"alice\"]\n\n t = torch.LongTensor([2])\n p = t.send_(alice) * 2\n p.get_()\n\n assert p == torch.LongTensor([4])\n\n\ndef test_iterable_pointer(workers):\n alice = workers[\"alice\"]\n\n t = torch.Tensor([[1, 2], [4, 5], [7, 8]])\n\n p = t.send(alice)\n\n assert len(alice.object_store) == 1\n for idx, tensor in enumerate(p):\n assert len(alice.object_store) == 2\n assert isinstance(tensor, PointerTensor)\n assert torch.all(tensor.get() == t[idx])\n\n assert len(alice.object_store) == 1\n\n l = []\n for idx, tensor in enumerate(p):\n l.append(tensor)\n\n assert len(alice.object_store) == 4\n\n del l\n del tensor\n\n assert len(alice.object_store) == 1\n for idx, tensor in enumerate(p[:, 1]):\n\n # Should be 3 because p[:, 1] will create another tensor on alice side\n assert len(alice.object_store) == 3\n assert isinstance(tensor, PointerTensor)\n assert torch.all(tensor.get() == t[:, 1][idx])\n\n\ndef test_register_hook_on_remote_tensor_or_modules(workers):\n alice = workers[\"alice\"]\n # we need to set a storage object on the local worker\n\n with syft.local_worker.registration_enabled():\n\n ## Tensor hook\n\n flag = []\n\n def hook_function(inputs, outputs):\n flag.append(True) # pragma: no cover\n\n p = th.tensor([1.0, 2], requires_grad=True).send(alice)\n p.register_hook(hook_function)\n\n assert len(flag) == 0\n p.sum().backward()\n assert len(flag) == 1\n\n ## Module hook\n\n flag = []\n\n def hook_function(model, inputs, outputs):\n flag.append(True) # pragma: no cover\n\n x = th.tensor([1.0, 2])\n model = torch.nn.Linear(2, 1)\n model.register_backward_hook(hook_function)\n loss = model(x)\n\n assert len(flag) == 0\n loss.backward()\n assert len(flag) == 1\n" ]
[ [ "torch.LongTensor", "torch.Size", "torch.ones", "torch.max", "torch.Tensor", "torch.tensor", "torch.nn.Linear", "torch.rand", "torch.split", "torch.device" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jihuacao/Putil
[ "b753fc94bea4cbda00f483681c55f0e9f54adef2", "b753fc94bea4cbda00f483681c55f0e9f54adef2", "b753fc94bea4cbda00f483681c55f0e9f54adef2", "b753fc94bea4cbda00f483681c55f0e9f54adef2" ]
[ "data/torch_151_data/sampler.py", "demo/deep_learning/main.py", "torch/pretrained_model/vgg.py", "sampling/MCMC/metropolis_hasting.py" ]
[ "import torch\nfrom torch._six import int_classes as _int_classes\n\n\nclass Sampler(object):\n r\"\"\"Base class for all Samplers.\n\n Every Sampler subclass has to provide an :meth:`__iter__` method, providing a\n way to iterate over indices of dataset elements, and a :meth:`__len__` method\n that returns the length of the returned iterators.\n\n .. note:: The :meth:`__len__` method isn't strictly required by\n :class:`~torch.utils.data.DataLoader`, but is expected in any\n calculation involving the length of a :class:`~torch.utils.data.DataLoader`.\n \"\"\"\n\n def __init__(self, data_source):\n pass\n\n def __iter__(self):\n raise NotImplementedError\n\n # NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ]\n #\n # Many times we have an abstract class representing a collection/iterable of\n # data, e.g., `torch.utils.data.Sampler`, with its subclasses optionally\n # implementing a `__len__` method. In such cases, we must make sure to not\n # provide a default implementation, because both straightforward default\n # implementations have their issues:\n #\n # + `return NotImplemented`:\n # Calling `len(subclass_instance)` raises:\n # TypeError: 'NotImplementedType' object cannot be interpreted as an integer\n #\n # + `raise NotImplementedError()`:\n # This prevents triggering some fallback behavior. E.g., the built-in\n # `list(X)` tries to call `len(X)` first, and executes a different code\n # path if the method is not found or `NotImplemented` is returned, while\n # raising an `NotImplementedError` will propagate and and make the call\n # fail where it could have use `__iter__` to complete the call.\n #\n # Thus, the only two sensible things to do are\n #\n # + **not** provide a default `__len__`.\n #\n # + raise a `TypeError` instead, which is what Python uses when users call\n # a method that is not defined on an object.\n # (@ssnl verifies that this works on at least Python 3.7.)\n\n\nclass SequentialSampler(Sampler):\n r\"\"\"Samples elements sequentially, always in the same order.\n\n Arguments:\n data_source (Dataset): dataset to sample from\n \"\"\"\n\n def __init__(self, data_source):\n self.data_source = data_source\n\n def __iter__(self):\n return iter(range(len(self.data_source)))\n\n def __len__(self):\n return len(self.data_source)\n\n\nclass RandomSampler(Sampler):\n r\"\"\"Samples elements randomly. If without replacement, then sample from a shuffled dataset.\n If with replacement, then user can specify :attr:`num_samples` to draw.\n\n Arguments:\n data_source (Dataset): dataset to sample from\n replacement (bool): samples are drawn with replacement if ``True``, default=``False``\n num_samples (int): number of samples to draw, default=`len(dataset)`. This argument\n is supposed to be specified only when `replacement` is ``True``.\n \"\"\"\n\n def __init__(self, data_source, replacement=False, num_samples=None):\n self.data_source = data_source\n self.replacement = replacement\n self._num_samples = num_samples\n\n if not isinstance(self.replacement, bool):\n raise ValueError(\"replacement should be a boolean value, but got \"\n \"replacement={}\".format(self.replacement))\n\n if self._num_samples is not None and not replacement:\n raise ValueError(\"With replacement=False, num_samples should not be specified, \"\n \"since a random permute will be performed.\")\n\n if not isinstance(self.num_samples, int) or self.num_samples <= 0:\n raise ValueError(\"num_samples should be a positive integer \"\n \"value, but got num_samples={}\".format(self.num_samples))\n\n @property\n def num_samples(self):\n # dataset size might change at runtime\n if self._num_samples is None:\n return len(self.data_source)\n return self._num_samples\n\n def __iter__(self):\n n = len(self.data_source)\n if self.replacement:\n return iter(torch.randint(high=n, size=(self.num_samples,), dtype=torch.int64).tolist())\n return iter(torch.randperm(n).tolist())\n\n def __len__(self):\n return self.num_samples\n\n\nclass SubsetRandomSampler(Sampler):\n r\"\"\"Samples elements randomly from a given list of indices, without replacement.\n\n Arguments:\n indices (sequence): a sequence of indices\n \"\"\"\n\n def __init__(self, indices):\n self.indices = indices\n\n def __iter__(self):\n return (self.indices[i] for i in torch.randperm(len(self.indices)))\n\n def __len__(self):\n return len(self.indices)\n\n\nclass WeightedRandomSampler(Sampler):\n r\"\"\"Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights).\n\n Args:\n weights (sequence) : a sequence of weights, not necessary summing up to one\n num_samples (int): number of samples to draw\n replacement (bool): if ``True``, samples are drawn with replacement.\n If not, they are drawn without replacement, which means that when a\n sample index is drawn for a row, it cannot be drawn again for that row.\n\n Example:\n >>> list(WeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True))\n [4, 4, 1, 4, 5]\n >>> list(WeightedRandomSampler([0.9, 0.4, 0.05, 0.2, 0.3, 0.1], 5, replacement=False))\n [0, 1, 4, 3, 2]\n \"\"\"\n\n def __init__(self, weights, num_samples, replacement=True):\n if not isinstance(num_samples, _int_classes) or isinstance(num_samples, bool) or \\\n num_samples <= 0:\n raise ValueError(\"num_samples should be a positive integer \"\n \"value, but got num_samples={}\".format(num_samples))\n if not isinstance(replacement, bool):\n raise ValueError(\"replacement should be a boolean value, but got \"\n \"replacement={}\".format(replacement))\n self.weights = torch.as_tensor(weights, dtype=torch.double)\n self.num_samples = num_samples\n self.replacement = replacement\n\n def __iter__(self):\n return iter(torch.multinomial(self.weights, self.num_samples, self.replacement).tolist())\n\n def __len__(self):\n return self.num_samples\n\n\nclass BatchSampler(Sampler):\n r\"\"\"Wraps another sampler to yield a mini-batch of indices.\n\n Args:\n sampler (Sampler): Base sampler.\n batch_size (int): Size of mini-batch.\n drop_last (bool): If ``True``, the sampler will drop the last batch if\n its size would be less than ``batch_size``\n\n Example:\n >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))\n [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))\n [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n \"\"\"\n\n def __init__(self, sampler, batch_size, drop_last):\n if not isinstance(sampler, Sampler):\n raise ValueError(\"sampler should be an instance of \"\n \"torch.utils.data.Sampler, but got sampler={}\"\n .format(sampler))\n if not isinstance(batch_size, _int_classes) or isinstance(batch_size, bool) or \\\n batch_size <= 0:\n raise ValueError(\"batch_size should be a positive integer value, \"\n \"but got batch_size={}\".format(batch_size))\n if not isinstance(drop_last, bool):\n raise ValueError(\"drop_last should be a boolean value, but got \"\n \"drop_last={}\".format(drop_last))\n self.sampler = sampler\n self.batch_size = batch_size\n self.drop_last = drop_last\n\n def __iter__(self):\n batch = []\n for idx in self.sampler:\n batch.append(idx)\n if len(batch) == self.batch_size:\n yield batch\n batch = []\n if len(batch) > 0 and not self.drop_last:\n yield batch\n\n def __len__(self):\n if self.drop_last:\n return len(self.sampler) // self.batch_size\n else:\n return (len(self.sampler) + self.batch_size - 1) // self.batch_size\n", "# coding=utf-8\nfrom __future__ import absolute_import\nfrom collections import Iterable\nfrom colorama import Fore\nimport numpy as np\nimport re\nfrom colorama import Fore\nimport sys\nimport json\nimport os\nfrom enum import Enum\nimport torch\nfrom torch import multiprocessing as mp\nfrom tensorboardX import SummaryWriter\n\nbase_optimization_source_property_type = 'optimization_source'\nbase_optimization_name_property_type = 'optimization_name'\nbase_backbone_source_property_type = 'backbone_source'\nbase_backbone_name_property_type = 'backbone_name'\nbase_backend_source_property_type = 'backend_source'\nbase_backend_name_property_type = 'backend_name'\nbase_dataset_source_property_type = 'dataset_source'\nbase_dataset_name_property_type = 'dataset_name'\nbase_aug_source_property_type = 'aug_source'\nbase_aug_name_property_type = 'aug_name'\nbase_encode_source_property_type = 'encode_source'\nbase_encode_name_property_type = 'encode_name'\nbase_data_type_adapter_source_property_type = 'data_type_adapter_source'\nbase_data_type_adapter_name_property_type = 'data_type_adapter_name'\nbase_data_loader_source_property_type = 'data_loader_source'\nbase_data_loader_name_property_type = 'data_loader_name'\nbase_data_sampler_source_property_type = 'data_sampler_source'\nbase_data_sampler_name_property_type = 'data_sampler_name'\nbase_fit_to_loss_input_source_property_type = 'fit_to_loss_input_source'\nbase_fit_to_loss_input_name_property_type = 'fit_to_loss_input_name'\nbase_fit_to_indicator_input_source_property_type = 'fit_to_indicator_input_source'\nbase_fit_to_indicator_input_name_property_type = 'fit_to_indicator_input_name'\nbase_indicator_source_property_type = 'indicator_source'\nbase_indicator_name_property_type = 'indicator_name'\nbase_indicator_statistic_source_property_type = 'indicator_statistic_source'\nbase_indicator_statistic_name_property_type = 'indicator_statistic_name'\nbase_fit_to_decode_input_source_property_type = 'fit_to_decode_input_source'\nbase_fit_to_decode_input_name_property_type = 'fit_to_decode_input_name'\nbase_decode_source_property_type = 'decode_source'\nbase_decode_name_property_type = 'decode_name'\nbase_loss_source_property_type = 'loss_source'\nbase_loss_name_property_type = 'loss_name'\nbase_auto_stop_source_property_type = 'auto_stop_source'\nbase_auto_stop_name_property_type = 'auto_stop_name'\nbase_lr_reduce_source_property_type = 'lr_reduce_source'\nbase_lr_reduce_name_property_type = 'lr_reduce_name'\nbase_auto_save_name_property_type = 'auto_save_name'\nbase_auto_save_source_property_type = 'auto_save_source'\n\ndef do_save():\n MainLogger.info('run checkpoint') if args.debug else None\n eval('checkpoint(epoch, args.save_dir, {}=backbone, {}=backend, {}=lr_reduce, {}=auto_save, {}=auto_stop, {}=optimization)'.format(\n '{}-{}'.format(args.backbone_source, args.backbone_name),\n '{}-{}'.format(args.backend_source, args.backend_name),\n '{}-{}'.format(args.lr_reduce_source, args.lr_reduce_name),\n '{}-{}'.format(args.auto_save_source, args.auto_save_name),\n '{}-{}'.format(args.auto_stop_source, args.auto_stop_name),\n '{}-{}'.format(args.optimization_source, args.optimization_name)\n ))\n checkpoint(epoch, args.save_dir, backbone=backbone, lr_reduce=lr_reduce, auto_save=auto_save, \\\n auto_stop=auto_stop, optimization=optimization)\n MainLogger.info('run save') if args.debug else None\n save(util_with_args.TemplateModelDecodeCombine, epoch, args.save_dir, backbone, backend, decode)\n MainLogger.info('run deploy') if args.debug else None\n deploy(util_with_args.TemplateModelDecodeCombine, \\\n torch.from_numpy(np.zeros(shape=(1, 3, args.input_height, args.input_width))).cuda(), \\\n recorder.epoch, args.save_dir, backbone, backend, decode)\n\ndef lr_update(optimization, lr_reduces):\n pass\n\ndef do_epoch_end_process(epoch_result):\n indicator = util.all_reduce(epoch_result['eloss'], 'train_indicator')\n save = auto_save.save_or_not(indicator)\n if save or args.debug:\n # :save the backbone in rank0\n do_save() if hvd.rank() == 0 else None\n # 此日志保存了保存模型的epoch数,为clear_train提供了依据\n MainLogger.info('save in epoch: {}'.format(recorder.epoch)) if hvd.rank() == 0 else None\n # :stop or not\n MainLogger.info('run ')\n stop = auto_stop.stop_or_not(indicator)\n # :lr_reduce\n _reduce = lr_reduce.reduce_or_not(indicator)\n # TODO: change the lr\n optimizations.__dict__['param_group'][0]['lr'] = lr_reduce.reduce(optimization.__dict__['param_groups'][0]['lr']) if _reduce \\\n else optimization.__dict__['param_groups'][0]['lr']\n if hvd.rank() == 0:\n writer.add_scalar('lr', lr_reduce.LrNow, global_step=recorder.step)\n return stop, lr_reduce.LrNow, save\n\ndef train(epoch):\n ret = run_train_stage.train_stage_common(args, util_with_args.Stage.Train, epoch, fit_data_to_input, backbone, backend, decode, fit_decode_to_result, \\\n loss, optimization, train_indicator, indicator_statistic, accumulated_opt, train_loader, recorder, writer, MainLogger)\n if args.evaluate_off:\n if args.debug:\n if epoch == 0:\n return False, \n elif epoch == 1:\n do_epoch_end_process(ret)\n return False,\n else:\n raise RuntimeError('all_process_test would only run train two epoch')\n else:\n return do_epoch_end_process(ret)\n else:\n return False,\n\ndef evaluate(epoch):\n ret = run_train_stage.train_stage_common(args, util_with_args.Stage.TrainEvaluate if util_with_args.evaluate_stage(args) else util_with_args.Stage.Evaluate, \\\n epoch, fit_data_to_input, backbone, backend, decode, fit_decode_to_result, loss, optimization, \\\n evaluate_indicator, indicator_statistic, accumulated_opt, train_loader, recorder, writer, MainLogger)\n if util_with_args.train_stage(args):\n if args.debug:\n if epoch == 0:\n # 当在all_process_test时,第二个epoch返回stop为True\n do_epoch_end_process(ret)\n return False, None, True\n else:\n # 当在all_process_test时,第一个epoch返回stop为True\n return True, None, False\n else:\n return do_epoch_end_process(ret)\n return False, None, False\n\ndef test(epoch):\n pass\n\ndef run_test(model, data_loader, fit_data_to_input, fit_decode_to_result):\n model.eval()\n with torch.no_grad():\n for index, datas in data_loader:\n data_input = fit_data_to_input(datas)\n output = model(data_input, args)\n result = fit_decode_to_result(output)\n data_loader.dataset.save_result(prefix='test', save=False if index != len(data_loader) else True)\n\ndef test_stage():\n MainLogger.info('run test') \n assert args.weight_path != '' and args.weight_epoch is not None, 'specify the trained weight_path and the epoch in test stage'\n MainLogger.info('load trained backbone: path: {} epoch: {}'.format(args.weight_path, args.weight_epoch))\n model = load_saved(args.weight_epoch, args.weight_path, map_location=torch.device(args.gpu))\n run_test(model, test_loader, fit_data_to_input, fit_decode_to_result)\n # release the model\n MainLogger.debug('del the model')\n del model\n torch.cuda.empty_cache()\n pass\n\ndef run_evaluate(model, data_loader, fit_data_to_input, fit_decode_to_result):\n model.eval()\n with torch.no_grad():\n for index, datas in data_loader:\n data_input = fit_data_to_input(datas)\n output = model(data_input, args)\n decode = decode(datas, output)\n result = fit_decode_to_result(decode)\n data_loader.dataset.save_result(prefix='evaluate', save=False if index != len(data_loader) else True)\n pass\n pass\n pass\n\ndef evaluate_stage():\n MainLogger.info('run evaluate')\n assert args.weight_path != '' and args.weight_epoch is not None, 'specify the trained weight_path and the epoch in test stage'\n MainLogger.info('load trained backbone: path: {} epoch: {}'.format(args.weight_path, args.weight_epoch))\n model = load_saved(args.run_evaluate_epoch, args.run_evaluate_full_path, map_location='cuda:{}'.format(args.run_evaluate_gpu))\n run_evaluate(model, evaluate_loader, fit_data_to_input, fit_decode_to_result)\n # release the model\n MainLogger.debug('del the model')\n del model\n torch.cuda.empty_cache()\n pass\n\ndef get_the_saved_epoch(train_time, path):\n pass\n\nif __name__ == '__main__':\n import argparse\n import os\n import Putil.base.arg_base as pab\n import Putil.base.save_fold_base as psfb\n from Putil.demo.deep_learning.base import horovod\n from Putil.demo.deep_learning.base import util\n from Putil.demo.deep_learning.base import util_with_env\n import Putil.base.logger as plog\n remote_debug = util.fix_env_param(os.environ['remote_debug'])\n framework = util.fix_env_param(os.environ['framework'])\n util.print_env_param(remote_debug, 'remote_debug')\n util.print_env_param(framework, 'framework')\n hvd = horovod.horovod(framework)\n hvd.init()\n empty_tensor = util.empty_tensor_factory(framework)()\n # the method for remote debug\n if remote_debug and hvd.rank() == 0:\n import ptvsd\n host = '127.0.0.1'\n port = 12345\n ptvsd.enable_attach(address=(host, port), redirect_output=True)\n if __name__ == '__main__':\n print('waiting for remote attach')\n ptvsd.wait_for_attach()\n pass\n pass\n if remote_debug:\n hvd.broadcast_object(empty_tensor(), 0, 'sync_waiting_for_the_attach')\n name = util.fix_env_param(os.environ['name'])\n run_stage = util.fix_env_param(os.environ['run_stage'])\n save_dir = util.fix_env_param(os.environ['save_dir'])\n save_dir = '.'.join(save_dir) if isinstance(save_dir, Iterable) else weight_path\n weight_path = util.fix_env_param(os.environ['weight_path'])\n weight_path = '.'.join(weight_path) if isinstance(weight_path, Iterable) else weight_path\n weight_epoch = util.fix_env_param(os.environ['weight_epoch'])\n train_name = util.fix_env_param(os.environ['train_name'])\n debug = util.fix_env_param(os.environ['debug'])\n clean_train = util.fix_env_param(os.environ['clean_train'])\n # 生成存储位置,更新args.save_dir, 让server与worker都在同一save_dir\n save_dir = util.make_sure_the_save_dir(name, run_stage, save_dir, weight_path, weight_epoch, debug, framework)\n log_level = util.fix_env_param(os.environ['log_level'])\n # 删除clear_train指定的train_time结果\n if clean_train is not None:\n for _train_time in clean_train:\n hvd.broadcast_object(empty_tensor(), 0, 'sync_before_checking_clean')\n make_sure_clean_the_train_result = input(Fore.RED + 'clean the train time {} in {} (y/n):'.format(_train_time, save_dir) + Fore.RESET) if hvd.rank() == 0 else False\n hvd.broadcast_object(empty_tensor(), 0, 'sync_after_checking_clean')\n util.clean_train_result(save_dir, _train_time) if make_sure_clean_the_train_result and hvd.rank() == 0 else None\n hvd.broadcast_object(empty_tensor(), 0, 'sync_after_clean')\n pass\n pass\n # 确定当前的train_time, 需要args.save_dir,生成args.train_time\n train_time = util.make_sure_the_train_time(run_stage, save_dir, framework)\n save_dir = util.subdir_base_on_train_time(save_dir, train_time, train_name)\n hvd.broadcast_object(empty_tensor(), 0, 'sync_before_make_save_dir')\n assert not os.path.exists(save_dir) if hvd.rank() == 0 else True\n os.mkdir(save_dir) if hvd.rank() == 0 else None\n hvd.broadcast_object(empty_tensor(), 0, 'sync_after_make_save_dir')\n print('rank {} train time {} save to {}'.format(hvd.rank(), train_time, save_dir))\n log_level = plog.LogReflect(log_level).Level\n plog.PutilLogConfig.config_format(plog.FormatRecommend)\n plog.PutilLogConfig.config_log_level(stream=log_level, file=log_level)\n plog.PutilLogConfig.config_file_handler(filename=os.path.join(save_dir, \\\n 'train.log' if run_stage == util.RunStage.Train else 'evaluate.log' if stage == util.RunStage.Evaluate else 'test.log'), mode='a')\n plog.PutilLogConfig.config_handler(plog.stream_method | plog.file_method)\n root_logger = plog.PutilLogConfig('train').logger()\n root_logger.setLevel(log_level)\n MainLogger = root_logger.getChild('Trainer')\n MainLogger.setLevel(log_level)\n from Putil.base.arg_operation import args_save as ArgsSave\n from util.run_train_stage import train_stage_common \n from Putil.data import aug as pAug\n from util import run_train_stage\n # 确定性设置\n from Putil.base import base_setting\n from Putil.demo.deep_learning.base import auto_save_factory as AutoSaveFactory\n from Putil.demo.deep_learning.base import auto_stop_factory as AutoStopFactory\n from Putil.demo.deep_learning.base import lr_reduce_factory as LrReduceFactory\n from Putil.demo.deep_learning.base import dataset_factory as DatasetFactory\n from Putil.demo.deep_learning.base import data_loader_factory as DataLoaderFactory\n from Putil.demo.deep_learning.base import data_sampler_factory as DataSamplerFactory\n from Putil.demo.deep_learning.base import encode_factory as EncodeFactory\n from Putil.demo.deep_learning.base import backbone_factory as BackboneFactory\n from Putil.demo.deep_learning.base import backend_factory as BackendFactory\n from Putil.demo.deep_learning.base import decode_factory as DecodeFactory\n from Putil.demo.deep_learning.base import loss_factory as LossFactory\n from Putil.demo.deep_learning.base import indicator_factory as IndicatorFactory\n from Putil.demo.deep_learning.base import indicator_statistic_factory as IndicatorStatisticFactory\n from Putil.demo.deep_learning.base import optimization_factory as OptimizationFactory\n from Putil.demo.deep_learning.base import aug_factory as AugFactory\n from Putil.demo.deep_learning.base import data_type_adapter_factory as DataTypeAdapterFactory\n from Putil.demo.deep_learning.base import fit_data_to_input_factory as FitDataToInputFactory\n from Putil.demo.deep_learning.base import fit_to_loss_input_factory as FitToLossInputFactory\n from Putil.demo.deep_learning.base import fit_to_indicator_input_factory as FitToIndicatorInputFactory\n from Putil.demo.deep_learning.base import fit_decode_to_result_factory as FitDecodeToResultFactory\n from Putil.demo.deep_learning.base import fit_to_decode_input_factory as FitToDecodeInputFactory\n from Putil.demo.deep_learning.base import model_factory as ModelFactory\n from Putil.demo.deep_learning.base import recorder_factory as RecorderFactory\n from Putil.demo.deep_learning.base import util_with_args\n from Putil.demo.deep_learning.base import base_operation_factory as BaseOperationFactory\n from Putil.demo.deep_learning.base import accumulated_opt_factory as AccumulatedOptFactory\n parser = argparse.ArgumentParser()\n horovod.horovod_arg(parser)\n auto_save_sources = util.get_relatived_environ(base_auto_save_source_property_type)\n auto_stop_sources = util.get_relatived_environ(base_auto_stop_source_property_type)\n lr_reduce_sources = util.get_relatived_environ(base_lr_reduce_source_property_type)\n dataset_sources = util.get_relatived_environ(base_dataset_source_property_type)\n data_loader_sources = util.get_relatived_environ(base_data_loader_source_property_type)\n data_sampler_sources = util.get_relatived_environ(base_data_sampler_source_property_type)\n encode_sources = util.get_relatived_environ(base_encode_source_property_type)\n backbone_sources = util.get_relatived_environ(base_backbone_source_property_type)\n backend_sources = util.get_relatived_environ(base_backend_source_property_type)\n decode_sources = util.get_relatived_environ(base_decode_source_property_type)\n loss_sources = util.get_relatived_environ(base_loss_source_property_type)\n indicator_sources = util.get_relatived_environ(base_indicator_source_property_type)\n indicator_statistic_sources = util.get_relatived_environ(base_indicator_statistic_source_property_type)\n ## optimization可以支持多个类型,是为了多中optimization进行优化的需求,key表示功能定向(空key表示默认功能),name与source构成optimization的类型\n optimization_sources = util.get_relatived_environ(base_optimization_source_property_type)\n aug_sources = util.get_relatived_environ(base_aug_source_property_type)\n data_type_adapter_sources = util.get_relatived_environ(base_data_type_adapter_source_property_type)\n fit_data_to_input_source = os.environ.get('fit_data_to_input_source', 'standard')\n fit_to_loss_input_sources = util.get_relatived_environ(base_fit_to_loss_input_source_property_type)\n fit_to_indicator_input_sources = util.get_relatived_environ(base_fit_to_indicator_input_source_property_type)\n fit_to_decode_input_sources = util.get_relatived_environ(base_fit_to_decode_input_source_property_type)\n fit_decode_to_result_source = os.environ.get('fit_decode_to_result_source', 'standard')\n model_source = os.environ.get('model_source', 'standard')\n recorder_source = os.environ.get('recorder_source', 'standard')\n accumulated_opt_source = os.environ.get('accumulated_opt', 'standard')\n auto_save_names = util.get_relatived_environ(base_auto_save_name_property_type)\n util.complete_environ(auto_save_names, auto_save_sources, 'standard')\n auto_stop_names = util.get_relatived_environ(base_auto_stop_name_property_type)\n util.complete_environ(auto_stop_names, auto_stop_sources, 'standard')\n lr_reduce_names = util.get_relatived_environ(base_lr_reduce_name_property_type)\n util.complete_environ(lr_reduce_names, lr_reduce_sources, 'standard')\n dataset_names = util.get_relatived_environ(base_dataset_name_property_type)\n util.complete_environ(dataset_names, dataset_sources, 'standard')\n data_loader_names = util.get_relatived_environ(base_data_loader_name_property_type)\n util.complete_environ(data_loader_names, data_loader_sources, 'standard')\n data_sampler_names = util.get_relatived_environ(base_data_sampler_name_property_type)\n util.complete_environ(data_sampler_names, data_sampler_sources, 'standard')\n encode_names = util.get_relatived_environ(base_encode_name_property_type)\n util.complete_environ(encode_names, encode_sources, 'standard')\n backbone_names = util.get_relatived_environ(base_backbone_name_property_type)\n util.complete_environ(backbone_names, backbone_sources, 'standard')\n backend_names = util.get_relatived_environ(base_backend_name_property_type)\n util.complete_environ(backend_names, backend_sources, 'standard')\n decode_names = util.get_relatived_environ(base_decode_name_property_type)\n util.complete_environ(decode_names, decode_sources, 'standard')\n loss_names = util.get_relatived_environ(base_loss_name_property_type)\n util.complete_environ(loss_names, loss_sources, 'standard')\n indicator_names = util.get_relatived_environ(base_indicator_name_property_type)\n util.complete_environ(indicator_names, indicator_sources, 'standard')\n indicator_statistic_names = util.get_relatived_environ(base_indicator_statistic_name_property_type)\n util.complete_environ(indicator_statistic_names, indicator_statistic_sources, 'standard')\n ## optimization可以支持多个类型,是为了多中optimization进行优化的需求,key表示功能定向(空key表示默认功能),name与source构成optimization的类型\n optimization_names = {property_type.replace(base_optimization_name_property_type, ''): os.environ[property_type] for property_type in util.find_repeatable_environ(base_optimization_name_property_type)}\n util.complete_environ(optimization_names, optimization_sources, 'standard')\n aug_names = util.get_relatived_environ(base_aug_name_property_type)\n util.complete_environ(aug_names, aug_sources, 'standard')\n data_type_adapter_names = util.get_relatived_environ(base_data_type_adapter_name_property_type)\n util.complete_environ(data_type_adapter_names, data_type_adapter_sources, 'standard')\n fit_data_to_input_name = os.environ.get('fit_data_to_input_name', 'DefaultFitDataToInput')\n fit_to_loss_input_names = util.get_relatived_environ(base_fit_to_loss_input_name_property_type)\n util.complete_environ(fit_to_loss_input_names, fit_to_loss_input_sources, 'standard')\n fit_to_indicator_input_names = util.get_relatived_environ(base_fit_to_indicator_input_name_property_type)\n util.complete_environ(fit_to_indicator_input_names, fit_to_indicator_input_sources, 'standard')\n fit_to_decode_input_names = util.get_relatived_environ(base_fit_to_decode_input_name_property_type)\n util.complete_environ(fit_to_decode_input_names, fit_to_decode_input_sources, 'standard')\n fit_decode_to_result_name = os.environ.get('fit_decode_to_result_name', 'DefaultFitDecodeToResult')\n model_name = os.environ.get('model_name', 'DefaultModel')\n recorder_name = os.environ.get('recorder_name', 'DefaultRecorder')\n accumulated_opt_name = os.environ.get('accumulated_opt_name', 'DefaultAccumulatedOpt')\n [AutoSaveFactory.auto_save_arg_factory(parser, auto_save_sources[property_type], auto_save_names[property_type], property_type) for property_type in auto_save_names.keys()]\n [AutoStopFactory.auto_stop_arg_factory(parser, auto_stop_sources[property_type], auto_stop_names[property_type], property_type) for property_type in auto_stop_names.keys()]\n [LrReduceFactory.lr_reduce_arg_factory(parser, lr_reduce_sources[property_type], lr_reduce_names[property_type], property_type) for property_type in lr_reduce_names.keys()]\n [DataLoaderFactory.data_loader_arg_factory(parser, data_loader_sources[property_type], data_loader_names[property_type], property_type) for property_type in data_loader_names.keys()]\n [DataSamplerFactory.data_sampler_arg_factory(parser, data_sampler_sources[property_type], data_sampler_names[property_type], property_type) for property_type in data_sampler_names.keys()]\n [EncodeFactory.encode_arg_factory(parser, encode_sources[property_type], encode_names[property_type], property_type) for property_type in encode_names.keys()]\n [BackboneFactory.backbone_arg_factory(parser, backbone_sources[property_type], backbone_names[property_type], property_type) for property_type in backbone_names.keys()]\n [BackendFactory.backend_arg_factory(parser, backend_sources[property_type], backend_names[property_type], property_type) for property_type in backend_names.keys()]\n [LossFactory.loss_arg_factory(parser, loss_sources[property_type], loss_names[property_type], property_type) for property_type in loss_names.keys()]\n [IndicatorFactory.indicator_arg_factory(parser, indicator_sources[property_type], indicator_names[property_type], property_type) for property_type in indicator_names.keys()]\n [IndicatorStatisticFactory.indicator_statistic_arg_factory(parser, indicator_statistic_sources[property_type], indicator_statistic_names[property_type]) for property_type in indicator_statistic_names.keys()]\n [OptimizationFactory.optimization_arg_factory(parser, optimization_sources[property_type], optimization_names[property_type], property_type) for property_type in optimization_names.keys()]\n [AugFactory.aug_arg_factory(parser, aug_sources[property_type], aug_names[property_type], property_type) for property_type in aug_names.keys()]\n [DataTypeAdapterFactory.data_type_adapter_arg_factory(parser, data_type_adapter_sources[property_type], data_type_adapter_names[property_type]) for property_type in data_type_adapter_names.keys()]\n FitDataToInputFactory.fit_data_to_input_arg_factory(parser, fit_data_to_input_source, fit_data_to_input_name)\n [FitToLossInputFactory.fit_to_loss_input_arg_factory(parser, fit_to_loss_input_sources[property_type], fit_to_loss_input_names[property_type], property_type) for property_type in fit_to_loss_input_names.keys()]\n [FitToIndicatorInputFactory.fit_to_indicator_input_arg_factory(parser, fit_to_indicator_input_sources[property_type], fit_to_indicator_input_names[property_type], property_type) for property_type in fit_to_indicator_input_names.keys()]\n [FitToDecodeInputFactory.fit_to_decode_input_arg_factory(parser, fit_to_decode_input_sources[property_type], fit_to_decode_input_names[property_type], property_type) for property_type in fit_to_decode_input_names.keys()]\n FitDecodeToResultFactory.fit_decode_to_result_arg_factory(parser, fit_decode_to_result_source, fit_decode_to_result_name)\n ModelFactory.model_arg_factory(parser, model_source, model_name)\n # data setting\n [DatasetFactory.dataset_arg_factory(parser, dataset_sources[property_type], dataset_names[property_type], property_type) for property_type in dataset_names.keys()]\n ## decode setting\n [DecodeFactory.decode_arg_factory(parser, decode_sources[property_type], decode_names[property_type], property_type) for property_type in decode_names.keys()]\n RecorderFactory.recorder_arg_factory(parser, recorder_source, recorder_name)\n AccumulatedOptFactory.accumulated_opt_arg_factory(parser, accumulated_opt_source, accumulated_opt_name)\n # : the base information set\n parser.add_argument('--seed', action='store', type=int, default=66, \\\n help='the seed for the random')\n # train evaluate test setting\n ### ~train_off and ~evaluate_off: run train stage with evaluate\n ### ~train_off and evaluate_off: run train stage without evaluate\n ### train_off and ~evaluate_off: run evaluate stage\n ### ~test_off: run test stage\n parser.add_argument('--train_off', action='store_true', default=False, \\\n help='do not run train if set')\n parser.add_argument('--evaluate_off', action='store_true', default=False, \\\n help='do not run evaluate if set')\n parser.add_argument('--test_off', action='store_true', default=False, \\\n help='do not run test if set')\n ## train set\n parser.add_argument('--weight_decay', type=float, action='store', default=1e-4, \\\n help='the weight decay, default is 1e-4')\n parser.add_argument('--gpus', type=str, nargs='+', default=None, \\\n help='specify the gpu, this would influence the gpu set in the code')\n parser.add_argument('--epochs', type=int, default=10, metavar='N', \\\n help='number of epochs to train (default: 10)')\n parser.add_argument('--batch_size', type=int, default=64, metavar='N', \\\n help='input batch size for training (default: 64)')\n parser.add_argument('--summary_interval', type=int, default=100, metavar='N', \\\n help='how many batchees to wait before save the summary(default: 100)')\n parser.add_argument('--evaluate_interval', type=int, default=1, metavar='N', \\\n help='how many epoch to wait before evaluate the backbone(default: 1), '\\\n 'test the mode while the backbone is savd, would not run evaluate while -1')\n parser.add_argument('--evaluate_batch_size', type=int, default=64, metavar='N', \\\n help='input batch size for evaluate (default: 64)')\n parser.add_argument('--test_batch_size', type=int, default=1000, metavar='N', \\\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--log_interval', type=int, default=10, metavar='N', \\\n help='how many batches to wait before logging training status(default: 10)')\n parser.add_argument('--compute_efficiency', action='store_true', default=False, \\\n help='evaluate the efficiency in the test or not')\n parser.add_argument('--data_rate_in_compute_efficiency', type=int, default=200, metavar='N', \\\n help='how many sample used in test to evaluate the efficiency(default: 200)')\n # continue train setting\n retrain_mode_header = 'retrain_mode'\n parser.add_argument('--{}_continue'.format(retrain_mode_header), default=False, action='store_true', \\\n help='continue train while this is set and the weight_path, weight_epoch is specified, ' \\\n 'the lr_reduce, auto_save, auto_stop would be load')\n parser.add_argument('--{}_reset'.format(retrain_mode_header), default=False, action='store_true', \\\n help='reset train while this is set and the weight_path, weight_epoch is specified, ' \\\n 'the lr_reduce, auto_save, auto_stop would not be load')\n args = parser.parse_args()\n args.auto_save_sources = auto_save_sources\n args.lr_reduce_sources = lr_reduce_sources\n args.auto_stop_sources = auto_stop_sources\n args.dataset_sources = dataset_sources\n args.data_loader_sources = data_loader_sources\n args.data_sampler_sources = data_sampler_sources\n args.encode_sources = encode_sources\n args.backbone_sources = backbone_sources\n args.backend_sources = backend_sources\n args.decode_sources = decode_sources\n args.fit_to_decode_input_sources = fit_to_decode_input_sources\n args.loss_sources = loss_sources\n args.indicator_sources = indicator_sources\n args.indicator_statistic_sources = indicator_statistic_sources\n args.optimization_sources = optimization_sources\n args.aug_sources = aug_sources\n args.data_type_adapter_sources = data_type_adapter_sources\n args.fit_data_to_input_source = fit_data_to_input_source\n args.fit_to_loss_input_sources = fit_to_loss_input_sources\n args.fit_to_indicator_input_sources = fit_to_indicator_input_sources\n args.fit_decode_to_result_source = fit_decode_to_result_source\n args.model_source = model_source\n args.recorder_source = recorder_source\n args.accumulated_opt_source = accumulated_opt_source\n args.auto_save_names = auto_save_names\n args.auto_stop_names = auto_stop_names\n args.lr_reduce_names = lr_reduce_names\n args.dataset_names = dataset_names\n args.data_loader_names = data_loader_names\n args.data_sampler_names = data_sampler_names\n args.encode_names = encode_names\n #args.backbone_name = backbone_name\n args.backbone_names = backbone_names\n args.backend_names = backend_names\n args.decode_names = decode_names\n args.fit_to_decode_input_names = fit_to_decode_input_names\n args.loss_names = loss_names\n args.indicator_names = indicator_names\n args.indicator_statistic_names = indicator_statistic_names\n args.optimization_names = optimization_names\n args.aug_names = aug_names\n args.data_type_adapter_names = data_type_adapter_names\n args.fit_data_to_input_name = fit_data_to_input_name\n args.fit_to_loss_input_names = fit_to_loss_input_names\n args.fit_to_indicator_input_names = fit_to_indicator_input_names\n args.fit_decode_to_result_name = fit_decode_to_result_name\n args.model_name = model_name\n args.recorder_name = recorder_name\n args.accumulated_opt_name = accumulated_opt_name\n args.gpus = [[int(g) for g in gpu.split('.')] for gpu in args.gpus]\n args.name = name\n args.remote_debug = remote_debug\n args.run_stage = run_stage\n args.save_dir = save_dir\n args.weight_path = weight_path\n args.weight_epoch = weight_epoch\n args.train_name = train_name\n args.train_time = train_time\n args.clean_train = clean_train\n args.debug = debug\n args.framework = framework\n args.log_level = log_level\n def _init_fn(worker_id):\n np.random.seed(int(args.seed) + worker_id)\n pass\n args.dataloader_deterministic_work_init_fn = _init_fn\n # : set the args item\n checkpoint = BaseOperationFactory.checkpoint_factory(args)() if util_with_args.train_stage(args) else None\n save = BaseOperationFactory.save_factory(args)() if util_with_args.train_stage(args) else None\n deploy = BaseOperationFactory.deploy_factory(args)() if util_with_args.train_stage(args) else None\n load_saved = BaseOperationFactory.load_saved_factory(args)()\n load_checkpointed = BaseOperationFactory.load_checkpointed_factory(args)()\n is_cudable = BaseOperationFactory.is_cudable_factory(args)()\n combine_optimization = BaseOperationFactory.combine_optimization_factory(args)()\n #empty_tensor = BaseOperationFactory.generate_model_element_factory(args)()\n\n if hvd.rank() == 0:\n writer = SummaryWriter(args.save_dir, filename_suffix='-{}'.format(args.train_time))\n # prepare the GPU\n if util_with_args.iscuda(args):\n # Horovod: pin GPU to local rank. TODO: rank is the global process index, local_rank is the local process index in a machine\n # such as -np 6 -H *.1:1 *.2:2 *.3:3 would get the rank: 0, 1, 2, 3, 4, 5 and the local rank: {[0], [0, 1], [0, 1, 2]}\n gpu_accumualation = [len(gs) for gs in args.gpus]\n for gpu_group, (gpus, amount) in enumerate(zip(args.gpus, gpu_accumualation)):\n if hvd.rank() < amount:\n break\n else:\n continue\n pass\n args.gpu = args.gpus[gpu_group][hvd.local_rank()]\n MainLogger.info(\"rank: {}; local_rank: {}; gpu: {}; gpu_group: {}\".format( \\\n hvd.rank(), hvd.local_rank(), args.gpu, gpu_group))\n torch.cuda.set_device(args.gpu)\n torch.cuda.manual_seed(args.seed)\n # Horovod: limnit # of CPU threads to be used per worker\n torch.set_num_threads(1)\n kwargs = {'num_workers': args.n_worker_per_dataset, 'pin_memory': True}\n # When supported, use 'forkserver' to spawn dataloader workers instead of 'fork' to prevent\n # issues with Infiniband implementations that are not fork-safe\n if (kwargs.get('num_workers', 0) > 0 and hasattr(mp, '_supports_context') and\n mp._supports_context and 'forkserver' in mp.get_all_start_methods()):\n kwargs['multiprocessing_context'] = 'forkserver'\n #<tag========================================the arg would not change after this=========================================\n pab.args_log(args, MainLogger) if hvd.rank() == 0 else None\n ArgsSave(args, os.path.join(args.save_dir, 'args')) if hvd.rank() == 0 else None\n #========================================the arg would not change after this=============================================>\n fit_to_loss_input = {property_type: FitToLossInputFactory.fit_to_loss_input_factory(args, property_type)() for property_type in args.fit_to_loss_input_names.keys()} # 从data获取的datas提取loss的input(label)\n fit_to_loss_input = util_with_args.get_module(fit_to_loss_input)\n fit_to_indicator_input = {property_type: FitToIndicatorInputFactory.fit_to_indicator_input_factory(args, args.fit_to_indicator_input_sources[property_type], args.fit_to_indicator_input_names[property_type], property_type)() for property_type in args.fit_to_indicator_input_names.keys()}\n fit_to_indicator_input = util_with_args.get_module(fit_to_indicator_input)\n fit_to_decode_input = {property_type: FitToDecodeInputFactory.fit_to_decode_input_factory(args, args.fit_to_decode_input_sources[property_type], args.fit_to_decode_input_names[property_type], property_type)() for property_type in args.fit_to_decode_input_names.keys()}\n fit_to_decode_input = util_with_args.get_module(fit_to_decode_input)\n fit_decode_to_result = FitDecodeToResultFactory.fit_decode_to_result_factory(args)() # 从decode的结果生成通用的result格式,可供dataset直接保存\n if util_with_args.train_stage(args):\n # : build the backbone\n backbone = {property_type: BackboneFactory.backbone_factory(args, args.backbone_sources[property_type], args.backbone_names[property_type], property_type)() for property_type in args.backbone_names.keys()}\n backbone = util_with_args.get_module(backbone)\n # : build backend\n backend = {property_type: BackendFactory.backend_factory(args, args.backend_sources[property_type], args.backend_names[property_type], property_type)() for property_type in args.backend_names.keys()}\n backend = util_with_args.get_module(backend)\n # : build decode\n decode = {property_type: DecodeFactory.decode_factory(args, args.decode_sources[property_type], args.decode_names[property_type], property_type=property_type)() for property_type in args.decode_names.keys()}\n decode = util_with_args.get_module(decode)\n # : build the loss\n loss = {property_type: LossFactory.loss_factory(args, args.loss_sources[property_type], args.loss_names[property_type], property_type, fit_to_loss_input=fit_to_loss_input)() for property_type in args.loss_names.keys()}\n loss = util_with_args.get_module(loss)\n # : build the indicator\n train_indicator = {property_type: IndicatorFactory.indicator_factory(args, args.indicator_sources[property_type], args.indicator_names[property_type], fit_to_indicator_input=fit_to_indicator_input)() for property_type in args.indicator_names.keys()}\n train_indicator = util_with_args.get_module(train_indicator)\n evaluate_indicator = {property_type: IndicatorFactory.indicator_factory(args, args.indicator_sources[property_type], args.indicator_names[property_type], fit_to_indicator_input=fit_to_indicator_input)() for property_type in args.indicator_names.keys()} if args.evaluate_off is not True else None\n evaluate_indicator = util_with_args.get_module(evaluate_indicator) if args.evaluate_off is not True else None\n # : build the statistic indicator\n indicator_statistic = {property_type: IndicatorStatisticFactory.indicator_statistic_factory(args, args.indicator_statistic_sources[property_type], args.indicator_statistic_names[property_type], property_type=property_type)() for property_type in args.indicator_statistic_names.keys()}\n indicator_statistic = util_with_args.get_module(indicator_statistic)\n ##TODO: build the optimization, the optimization_source\n # 通过environ指定了几种属性类型的optimization,使用在哪些参数需要自己定制\n # 如果出现参数调整,则需要另外使用key,否则在load_checkpointed的时候会出现错误,可以查看load_checkpointed的代码\n # 如果出现需要增加参数,建议新增一个key-val,这用容易管理,load_checkpointed不会出现错误\n optimizations = dict()\n optimization = {property_type: OptimizationFactory.optimization_factory(args, property_type=property_type) for property_type, v in args.optimization_names.items()}\n optimizations.update({'opt-backbone': (backbone, util_with_args.get_module(optimization)(backbone.parameters()))})\n #optimizations.update({'opt-backend': (backend, util_with_args.get_module(optimization)(backend.parameters()))})\n # Horovod: broadcast parameters & optimizer state.\n hvd.broadcast_parameters(backbone.state_dict(), root_rank=0)\n hvd.broadcast_parameters(backend.state_dict(), root_rank=0)\n [hvd.broadcast_optimizer_state(optimization, root_rank=0) for k, (module, optimization) in optimizations.items()]\n ##Horovod: wrap optimizer with DistributedOptimizer.\n # 影响参数:hvd_fp16_util.all_reduce、hvd_reduce_mode\n import horovod.torch as hvd\n optimizations = {k: hvd.DistributedOptimizer(optimization, named_parameters=module.named_parameters(), \\\n compression=hvd.Compression.fp16 if args.hvd_compression_mode == 'fp16' else hvd.Compression.mro if args.hvd_compression_mode == 'mro' else hvd.Compression.none, \\\n op=hvd.Adasum if args.hvd_reduce_mode == 'AdaSum' else hvd.Average if args.hvd_reduce_mode == 'Average' else hvd.Sum) \\\n for k, (module, optimization) in optimizations.items()}\n optimization = combine_optimization(optimizations)\n accumulated_opt = AccumulatedOptFactory.accumulated_opt_factory(args)(optimization)\n # : the auto save\n auto_save = {property_type: AutoSaveFactory.auto_save_factory(args, args.auto_save_sources[property_type], args.auto_save_names[property_type], property_type)() for property_type in args.auto_save_names.keys()}\n auto_save = util_with_args.get_module(auto_save)\n # : the auto stop\n auto_stop = {property_type: AutoStopFactory.auto_stop_factory(args, args.auto_stop_sources[property_type], args.auto_stop_names[property_type], property_type)() for property_type in args.auto_stop_names.keys()}\n auto_stop = util_with_args.get_module(auto_stop)\n # : the lr reduce\n lr_reduce = {property_type: LrReduceFactory.lr_reduce_factory(args, args.lr_reduce_sources[property_type], args.lr_reduce_names[property_type], property_type)() for property_type in args.lr_reduce_names.keys()}\n lr_reduce = util_with_args.get_module(lr_reduce)\n if util_with_args.iscuda(args):\n backbone.cuda() if is_cudable(backbone) else None\n backend.cuda() if is_cudable(backend) else None\n decode.cuda() if is_cudable(decode) else None\n loss.cuda() if is_cudable(loss) else None\n train_indicator.cuda() if is_cudable(train_indicator) else None\n evaluate_indicator.cuda() if args.evaluate_off is not True else None\n indicator_statistic.cuda() if is_cudable(indicator_statistic) else None\n if args.hvd_reduce_mode and hvd.nccl_built():\n lr_scaler = hvd.local_size()\n pass\n pass\n pass\n recorder = RecorderFactory.recorder_factory(args)()\n encode = {property_type: EncodeFactory.encode_factory(args, property_type)() for property_type in args.encode_names.keys()}\n encode = util_with_args.get_module(encode)\n template_model = ModelFactory.model_factory(args)()\n # : build the train dataset\n fit_data_to_input = FitDataToInputFactory.fit_data_to_input_factory(args)() # 从data获取的datas提取backbone的input\n data_type_adapter = {property_type: DataTypeAdapterFactory.data_type_adapter_factory(args, args.data_type_adapter_sources[property_type], args.data_type_adapter_names[property_type], property_type)() \\\n for property_type in data_type_adapter_names.keys()}\n data_type_adapter = util_with_args.get_module(data_type_adapter)\n dataset_train = None; train_sampler = None; evaluate_loader = None\n if args.train_off is not True:\n MainLogger.info('start to generate the train dataset data_sampler data_loader')\n dataset_train = {property_type: DatasetFactory.dataset_factory(args, property_type, stage=util_with_args.Stage.Train)() for property_type, name in args.dataset_names.items()}\n ##TODO: 根据实际需求,指定使用的dataset,但一般有多种性质的dataset的情况都是要进行combine,CombineDataset框架还不完善\n dataset_train = util_with_args.get_module(dataset_train)\n root_node = pAug.AugNode(pAug.AugFuncNoOp())\n # for the fack data field, maybe cause the nan or inf\n for i in range(0, args.fake_aug):\n root_node.add_child(pAug.AugNode(pAug.AugFuncNoOp()))\n if args.naug is False:\n Original = root_node.add_child(pAug.AugNode(pAug.AugFuncNoOp()))\n [root_node.add_child(pAug.AugNode(AugFactory.aug_factory(args, property_type)())) for property_type in args.aug_names.keys()]\n root_node.freeze_node()\n dataset_train.set_aug_node_root(root_node)\n dataset_train.set_convert_to_input_method(encode)\n dataset_train.set_data_type_adapter(data_type_adapter)\n train_sampler = {property_type: DataSamplerFactory.data_sampler_factory(args, args.data_sampler_sources[property_type], args.data_sampler_names[property_type], property_type)( \\\n dataset_train, rank_amount=hvd.size(), rank=hvd.rank()) for property_type in args.data_sampler_names.keys()} if dataset_train is not None else None\n train_sampler = util_with_args.get_module(train_sampler)\n train_loader = {property_type: DataLoaderFactory.data_loader_factory(args, args.data_loader_sources[property_type], args.data_loader_names[property_type], property_type)( \\\n dataset=dataset_train, data_sampler=train_sampler, stage=util_with_args.Stage.Train) for property_type in args.data_loader_names.keys()} if dataset_train is not None else None\n train_loader = util_with_args.get_module(train_loader)\n MainLogger.info('generate adataset train successful: {} sample'.format(len(dataset_train)))\n # : build the evaluate dataset\n dataset_evaluate = None; evaluate_sampler = None; evaluate_loader = None\n if args.evaluate_off is not True:\n MainLogger.info('start to generate the evaluate dataset data_sampler data_loader')\n dataset_evaluate = {property_type: DatasetFactory.dataset_factory(args, stage=util_with_args.Stage.Evaluate)() for property_type, name in args.dataset_names.items()}\n ##TODO: 根据实际需求,指定使用的dataset,但一般有多种性质的dataset的情况都是要进行combine,CombineDataset框架还不完善\n dataset_evaluate = util_with_args.get_module(dataset_evaluate)\n root_node = pAug.AugNode(pAug.AugFuncNoOp())\n root_node.add_child(pAug.AugNode(pAug.AugFuncNoOp()))\n root_node.freeze_node()\n dataset_evaluate.set_aug_node_root(root_node)\n dataset_evaluate.set_convert_to_input_method(encode)\n dataset_evaluate.set_data_type_adapter(data_type_adapter)\n evaluate_sampler = {property_type: DataSamplerFactory.data_sampler_factory(args, args.data_sampler_sources[property_type], args.data_sampler_names[property_type], property_type)( \\\n dataset=dataset_evaluate, rank_amount=hvd.size(), rank=hvd.rank()) for property_type in args.data_sampler_names.keys()} if dataset_evaluate is not None else None\n evaluate_sampler = util_with_args.get_module(evaluate_sampler)\n evaluate_loader = {property_type: DataLoaderFactory.data_loader_factory(args, args.data_loader_sources[property_type], args.data_loader_names[property_type], property_type)( \\\n dataset=dataset_evaluate, data_sampler=evaluate_sampler, stage=util_with_args.Stage.Evaluate) for property_type in args.data_loader_names.keys()} if dataset_evaluate is not None else None\n evaluate_loader = util_with_args.get_module(evaluate_loader)\n # : build the test dataset\n dataset_test = None; test_sampler = None; test_loader = None\n if args.test_off is not True:\n MainLogger.info('start to generate the evaluate dataset data_sampler data_loader')\n dataset_test = {property_type: DatasetFactory.dataset_factory(args, stage=util_with_args.Stage.Test)() for property_type, name in args.dataset_names.items()} if args.test_off is not True else None\n ##TODO: 根据实际需求,指定使用的dataset,但一般有多种性质的dataset的情况都是要进行combine,CombineDataset框架还不完善\n dataset_test = util_with_args.get_module(dataset_test)\n root_node = pAug.AugNode(pAug.AugFuncNoOp())\n root_node.add_child(pAug.AugNode(pAug.AugFuncNoOp()))\n root_node.freeze_node()\n dataset_test.set_aug_node_root(root_node)\n dataset_test.set_convert_to_input_method(encode)\n dataset_test.set_data_type_adapter(data_type_adapter)\n test_sampler = {property_type: DataSamplerFactory.data_sampler_factory(args, args.data_sampler_sources[property_type], args.data_sampler_names[property_type], property_type)( \\\n dataset_test, rank_amount=hvd.size(), rank=hvd.rank()) for property_type in args.data_sampler_names.keys()} if dataset_test is not None else None\n test_sampler = util_with_args.get_module(test_sampler)\n test_loader = {property_type: DataLoaderFactory.data_loader_factory(args, args.data_loader_sources[property_type], args.data_loader_names[property_type], property_type)( \\\n dataset_test, data_sampler=test_sampler, stage=util_with_args.Stage.Test) for property_type in args.data_loader_names.keys()} if dataset_test is not None else None\n test_loader = util_with_args.get_module(test_loader)\n test_stage() if util_with_args.test_stage(args) else None # 如果train_off为True 同时test_off为False,则为util.test_stage,util.evaluate_stage与util.test_stage可以同时存在\n evaluate_stage() if util_with_args.evaluate_stage(args) else None # 如果train_off为True 同时evaluate_off为False,则为util.evaluate_stage,util.evaluate_stage与util.test_stage可以同时存在\n if util_with_args.train_stage(args):\n # 如果train_off不为True,就是util.train_stage,只是util.train_stage中可以设定进不进行evaluate与test\n if args.weight_path != '' and args.weight_epoch is not None:\n assert np.sum([args.retrain_mode_continue_train, args.retrain_mode_reset_train])\n MainLogger.info(Fore.YELLOW + 'load trained backbone: path: {} epoch: {}'.format(args.weight_path, args.weight_epoch) + Fore.RESET)\n retrain_mode_field = dict()\n {retrain_mode_field.update({k: v}) if re.search(retrain_mode_header, k) is not None else None for k, v in args.__dict__.items()}\n assert np.sum(list(retrain_mode_field.values())) == 1\n MainLogger.info(Fore.YELLOW + 'this project contain retrain_mode: {}, set to: {}'.format(retrain_mode_field, ''.join([k if v else '' for k, v in retrain_mode_field.items()])) + Fore.RESET)\n target_dict = {}\n target_dict.update(optimization.state_dict())\n target_dict.update({'backbone': backbone})\n target_dict.update({'backend': backend})\n target_dict.update({'recorder': recorder})\n if eval('args.{}_continue'.format(retrain_mode_header)):\n target_dict.update({'lr_reduce': lr_reduce})\n target_dict.update({'auto_save': auto_save})\n target_dict.update({'auto_stop': auto_stop})\n elif eval('args.{}_reset'.format(retrain_mode_header)):\n pass\n else:\n raise NotImplementedError('continue_train_mode {} is not implemented'.format(args.continue_train_mode))\n #target_dict.update({'': }) if args.\n load_checkpointed(args.weight_epoch, args.weight_path, target_dict, map_location=torch.device(args.gpu))\n do_save() if util_with_args.is_continue_train(args) else None\n for epoch in range(recorder.epoch + 1, recorder.epoch + args.epochs + 1):\n train_ret = train(epoch)\n if train_ret[0] is True:\n break\n if ((epoch + 1) % args.evaluate_interval == 0) or (args.debug) and args.evaluate_off is False:\n evaluate_ret = evaluate(epoch) \n if evaluate_ret[0] is True:\n if args.debug:\n MainLogger.debug('del the backbone, backend, decode, optimization, lr_reduce, auto_save, auto_stop')\n del backbone, backend, decode, optimization, lr_reduce, auto_save, auto_stop\n torch.cuda.empty_cache()\n args.weight_path = args.save_dir\n args.weight_epoch = 1\n MainLogger.debug('run the evaluate stage')\n evaluate_stage() if not args.evaluate_off else None\n MainLogger.debug('run the test stage')\n test_stage() if not args.test_off else None\n break\n if evaluate_ret[2] is True and args.test_off is False:\n MainLogger.info('run test')\n test(epoch) if args.test_off is False else MainLogger.info('test_off, do not run test')\n else:\n MainLogger.info('evaluate_off, do not run the evaluate')\n pass\n pass\n pass\n pass", "# coding=utf-8\nfrom enum import Enum\nfrom torchviz.dot import make_dot\n\nimport torch\nfrom torch import nn\nfrom torch.nn import Module\nfrom torchvision.models import vgg\nfrom torchvision.models.utils import load_state_dict_from_url\nfrom torch.autograd import Variable\n\n\nimport Putil.base.logger as plog\n\nvgg_logger = plog.PutilLogConfig('vgg').logger()\nvgg_logger.setLevel(plog.DEBUG)\nVGGLogger = vgg_logger.getChild('VGG')\nVGGLogger.setLevel(plog.DEBUG)\n\n\ndef make_layers(cfg, downsample, batch_norm=False):\n resolution_output = []\n layers = []\n in_channels = 3\n downsample_time = 0\n final_cfg = list()\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n resolution_output.append(layers[-1])\n downsample_time += 1\n if downsample == 2 ** downsample_time:\n final_cfg.append(v)\n break\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n pass\n final_cfg.append(v)\n pass\n seq = nn.Sequential(*layers)\n return seq, resolution_output, final_cfg\n\n\nclass VGG(Module):\n class VGGArch(Enum):\n vgg11 = 'vgg11'\n vgg13 = 'vgg13'\n vgg16 = 'vgg16'\n vgg19 = 'vgg19'\n vgg11_bn = 'vgg11_bn'\n vgg13_bn = 'vgg13_bn' \n vgg16_bn = 'vgg16_bn' \n vgg19_bn = 'vgg19_bn' \n vgg_arch_url_dic = {\n VGGArch.vgg11.name: {'cfg': vgg.cfgs['A'], 'url': vgg.model_urls['vgg11']},\n VGGArch.vgg13.name: {'cfg': vgg.cfgs['B'], 'url': vgg.model_urls['vgg13']},\n VGGArch.vgg16.name: {'cfg': vgg.cfgs['D'], 'url': vgg.model_urls['vgg16']},\n VGGArch.vgg19.name: {'cfg': vgg.cfgs['E'], 'url': vgg.model_urls['vgg19']},\n VGGArch.vgg11_bn.name: {'cfg': vgg.cfgs['A'], 'url': vgg.model_urls['vgg11_bn']},\n VGGArch.vgg13_bn.name: {'cfg': vgg.cfgs['B'], 'url': vgg.model_urls['vgg13_bn']},\n VGGArch.vgg16_bn.name: {'cfg': vgg.cfgs['D'], 'url': vgg.model_urls['vgg16_bn']},\n VGGArch.vgg19_bn.name: {'cfg': vgg.cfgs['E'], 'url': vgg.model_urls['vgg19_bn']}\n }\n def __init__(self, vgg_arch, downsample, model_dir, load_pretrained):\n Module.__init__(self)\n self.features, self._resolution_output, self._final_cfg = make_layers(\n VGG.vgg_arch_url_dic[vgg_arch]['cfg'], downsample)\n if load_pretrained:\n VGGLogger.info('load pretrained: path: {} url: {}'.format(model_dir, VGG.vgg_arch_url_dic[vgg_arch]['url']))\n state_dict = load_state_dict_from_url(VGG.vgg_arch_url_dic[vgg_arch]['url'], progress=True, model_dir=model_dir)\n self.load_state_dict(state_dict, strict=False)\n \n def forward(self, x):\n return self.features(x)\n\n @property\n def resolution_output(self):\n return self._resolution_output\n\n @property\n def final_cfg(self):\n return self._final_cfg\n pass", "# coding=utf-8\nimport numpy as np\nimport Putil.sampling.MCMC.mcmc as mcmc\n\n\nclass MetropolisHasting(mcmc.MCMC):\n def __init__(self):\n mcmc.MCMC.__init__(self)\n pass\n\n def sample(self):\n new_x = self._random_func()\n acc = min(1, self.__get_tilde_p(new_x) / self.__get_tilde_p(self._x))\n u = np.random.random()\n if u < acc:\n self._x = new_x\n return new_x \n else:\n return self._x\n\n def __get_tilde_p(self, x):\n return self._pdf_func(x) * 20\n pass\n\n\n" ]
[ [ "torch.randperm", "torch.randint", "torch.multinomial", "torch.as_tensor" ], [ "torch.cuda.manual_seed", "torch.cuda.set_device", "torch.multiprocessing.get_all_start_methods", "torch.cuda.empty_cache", "torch.no_grad", "torch.set_num_threads", "torch.device", "numpy.zeros", "numpy.sum" ], [ "torch.nn.Sequential", "torch.nn.Module.__init__", "torch.nn.Conv2d", "torch.nn.MaxPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ], [ "numpy.random.random" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
leogao2/dask
[ "4e5dfe7463028a39a90e026c7fb9220969093ab3" ]
[ "dask/array/routines.py" ]
[ "from __future__ import annotations\n\nimport math\nimport warnings\nfrom collections.abc import Iterable\nfrom functools import partial, reduce, wraps\nfrom numbers import Integral, Real\n\nimport numpy as np\nfrom tlz import concat, interleave, sliding_window\n\nfrom dask.array import chunk\nfrom dask.array.core import (\n Array,\n asanyarray,\n asarray,\n blockwise,\n broadcast_arrays,\n broadcast_shapes,\n broadcast_to,\n concatenate,\n elemwise,\n from_array,\n implements,\n is_scalar_for_elemwise,\n map_blocks,\n stack,\n tensordot_lookup,\n)\nfrom dask.array.creation import arange, diag, empty, indices, tri\nfrom dask.array.einsumfuncs import einsum # noqa\nfrom dask.array.numpy_compat import _numpy_120\nfrom dask.array.reductions import reduction\nfrom dask.array.ufunc import multiply, sqrt\nfrom dask.array.utils import (\n array_safe,\n asarray_safe,\n meta_from_array,\n safe_wraps,\n validate_axis,\n)\nfrom dask.array.wrap import ones\nfrom dask.base import is_dask_collection, tokenize\nfrom dask.core import flatten\nfrom dask.delayed import Delayed, unpack_collections\nfrom dask.highlevelgraph import HighLevelGraph\nfrom dask.utils import apply, derived_from, funcname, is_arraylike, is_cupy_type\n\n# save built-in for histogram functions which use range as a kwarg.\n_range = range\n\n\n@derived_from(np)\ndef array(x, dtype=None, ndmin=None, *, like=None):\n if not _numpy_120 and like is not None:\n raise RuntimeError(\"The use of ``like`` required NumPy >= 1.20\")\n x = asarray(x, like=like)\n while ndmin is not None and x.ndim < ndmin:\n x = x[None, :]\n if dtype is not None and x.dtype != dtype:\n x = x.astype(dtype)\n return x\n\n\n@derived_from(np)\ndef result_type(*args):\n args = [a if is_scalar_for_elemwise(a) else a.dtype for a in args]\n return np.result_type(*args)\n\n\n@derived_from(np)\ndef atleast_3d(*arys):\n new_arys = []\n for x in arys:\n x = asanyarray(x)\n if x.ndim == 0:\n x = x[None, None, None]\n elif x.ndim == 1:\n x = x[None, :, None]\n elif x.ndim == 2:\n x = x[:, :, None]\n\n new_arys.append(x)\n\n if len(new_arys) == 1:\n return new_arys[0]\n else:\n return new_arys\n\n\n@derived_from(np)\ndef atleast_2d(*arys):\n new_arys = []\n for x in arys:\n x = asanyarray(x)\n if x.ndim == 0:\n x = x[None, None]\n elif x.ndim == 1:\n x = x[None, :]\n\n new_arys.append(x)\n\n if len(new_arys) == 1:\n return new_arys[0]\n else:\n return new_arys\n\n\n@derived_from(np)\ndef atleast_1d(*arys):\n new_arys = []\n for x in arys:\n x = asanyarray(x)\n if x.ndim == 0:\n x = x[None]\n\n new_arys.append(x)\n\n if len(new_arys) == 1:\n return new_arys[0]\n else:\n return new_arys\n\n\n@derived_from(np)\ndef vstack(tup, allow_unknown_chunksizes=False):\n if isinstance(tup, Array):\n raise NotImplementedError(\n \"``vstack`` expects a sequence of arrays as the first argument\"\n )\n\n tup = tuple(atleast_2d(x) for x in tup)\n return concatenate(tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes)\n\n\n@derived_from(np)\ndef hstack(tup, allow_unknown_chunksizes=False):\n if isinstance(tup, Array):\n raise NotImplementedError(\n \"``hstack`` expects a sequence of arrays as the first argument\"\n )\n\n if all(x.ndim == 1 for x in tup):\n return concatenate(\n tup, axis=0, allow_unknown_chunksizes=allow_unknown_chunksizes\n )\n else:\n return concatenate(\n tup, axis=1, allow_unknown_chunksizes=allow_unknown_chunksizes\n )\n\n\n@derived_from(np)\ndef dstack(tup, allow_unknown_chunksizes=False):\n if isinstance(tup, Array):\n raise NotImplementedError(\n \"``dstack`` expects a sequence of arrays as the first argument\"\n )\n\n tup = tuple(atleast_3d(x) for x in tup)\n return concatenate(tup, axis=2, allow_unknown_chunksizes=allow_unknown_chunksizes)\n\n\n@derived_from(np)\ndef swapaxes(a, axis1, axis2):\n if axis1 == axis2:\n return a\n if axis1 < 0:\n axis1 = axis1 + a.ndim\n if axis2 < 0:\n axis2 = axis2 + a.ndim\n ind = list(range(a.ndim))\n out = list(ind)\n out[axis1], out[axis2] = axis2, axis1\n\n return blockwise(np.swapaxes, out, a, ind, axis1=axis1, axis2=axis2, dtype=a.dtype)\n\n\n@derived_from(np)\ndef transpose(a, axes=None):\n if axes:\n if len(axes) != a.ndim:\n raise ValueError(\"axes don't match array\")\n axes = tuple(d + a.ndim if d < 0 else d for d in axes)\n else:\n axes = tuple(range(a.ndim))[::-1]\n return blockwise(\n np.transpose, axes, a, tuple(range(a.ndim)), dtype=a.dtype, axes=axes\n )\n\n\ndef flip(m, axis=None):\n \"\"\"\n Reverse element order along axis.\n\n Parameters\n ----------\n m : array_like\n Input array.\n axis : None or int or tuple of ints, optional\n Axis or axes to reverse element order of. None will reverse all axes.\n\n Returns\n -------\n dask.array.Array\n The flipped array.\n \"\"\"\n\n m = asanyarray(m)\n\n sl = m.ndim * [slice(None)]\n if axis is None:\n axis = range(m.ndim)\n if not isinstance(axis, Iterable):\n axis = (axis,)\n try:\n for ax in axis:\n sl[ax] = slice(None, None, -1)\n except IndexError as e:\n raise ValueError(\n f\"`axis` of {str(axis)} invalid for {str(m.ndim)}-D array\"\n ) from e\n sl = tuple(sl)\n\n return m[sl]\n\n\n@derived_from(np)\ndef flipud(m):\n return flip(m, 0)\n\n\n@derived_from(np)\ndef fliplr(m):\n return flip(m, 1)\n\n\n@derived_from(np)\ndef rot90(m, k=1, axes=(0, 1)):\n axes = tuple(axes)\n if len(axes) != 2:\n raise ValueError(\"len(axes) must be 2.\")\n\n m = asanyarray(m)\n\n if axes[0] == axes[1] or np.absolute(axes[0] - axes[1]) == m.ndim:\n raise ValueError(\"Axes must be different.\")\n\n if axes[0] >= m.ndim or axes[0] < -m.ndim or axes[1] >= m.ndim or axes[1] < -m.ndim:\n raise ValueError(f\"Axes={axes} out of range for array of ndim={m.ndim}.\")\n\n k %= 4\n\n if k == 0:\n return m[:]\n if k == 2:\n return flip(flip(m, axes[0]), axes[1])\n\n axes_list = list(range(0, m.ndim))\n (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]], axes_list[axes[0]])\n\n if k == 1:\n return transpose(flip(m, axes[1]), axes_list)\n else:\n # k == 3\n return flip(transpose(m, axes_list), axes[1])\n\n\ndef _tensordot(a, b, axes, is_sparse):\n x = max([a, b], key=lambda x: x.__array_priority__)\n tensordot = tensordot_lookup.dispatch(type(x))\n x = tensordot(a, b, axes=axes)\n if is_sparse and len(axes[0]) == 1:\n return x\n else:\n ind = [slice(None, None)] * x.ndim\n for a in sorted(axes[0]):\n ind.insert(a, None)\n x = x[tuple(ind)]\n return x\n\n\ndef _tensordot_is_sparse(x):\n is_sparse = \"sparse\" in str(type(x._meta))\n if is_sparse:\n # exclude pydata sparse arrays, no workaround required for these in tensordot\n is_sparse = \"sparse._coo.core.COO\" not in str(type(x._meta))\n return is_sparse\n\n\n@derived_from(np)\ndef tensordot(lhs, rhs, axes=2):\n if not isinstance(lhs, Array):\n lhs = from_array(lhs)\n if not isinstance(rhs, Array):\n rhs = from_array(rhs)\n\n if isinstance(axes, Iterable):\n left_axes, right_axes = axes\n else:\n left_axes = tuple(range(lhs.ndim - axes, lhs.ndim))\n right_axes = tuple(range(0, axes))\n if isinstance(left_axes, Integral):\n left_axes = (left_axes,)\n if isinstance(right_axes, Integral):\n right_axes = (right_axes,)\n if isinstance(left_axes, list):\n left_axes = tuple(left_axes)\n if isinstance(right_axes, list):\n right_axes = tuple(right_axes)\n is_sparse = _tensordot_is_sparse(lhs) or _tensordot_is_sparse(rhs)\n if is_sparse and len(left_axes) == 1:\n concatenate = True\n else:\n concatenate = False\n dt = np.promote_types(lhs.dtype, rhs.dtype)\n left_index = list(range(lhs.ndim))\n right_index = list(range(lhs.ndim, lhs.ndim + rhs.ndim))\n out_index = left_index + right_index\n adjust_chunks = {}\n for l, r in zip(left_axes, right_axes):\n out_index.remove(right_index[r])\n right_index[r] = left_index[l]\n if concatenate:\n out_index.remove(left_index[l])\n else:\n adjust_chunks[left_index[l]] = lambda c: 1\n intermediate = blockwise(\n _tensordot,\n out_index,\n lhs,\n left_index,\n rhs,\n right_index,\n dtype=dt,\n concatenate=concatenate,\n adjust_chunks=adjust_chunks,\n axes=(left_axes, right_axes),\n is_sparse=is_sparse,\n )\n if concatenate:\n return intermediate\n else:\n return intermediate.sum(axis=left_axes)\n\n\n@derived_from(np)\ndef dot(a, b):\n return tensordot(a, b, axes=((a.ndim - 1,), (b.ndim - 2,)))\n\n\n@derived_from(np)\ndef vdot(a, b):\n return dot(a.conj().ravel(), b.ravel())\n\n\ndef _chunk_sum(a, axis=None, dtype=None, keepdims=None):\n # Caution: this is not your conventional array-sum: due\n # to the special nature of the preceding blockwise con-\n # traction, each chunk is expected to have exactly the\n # same shape, with a size of 1 for the dimension given\n # by `axis` (the reduction axis). This makes mere ele-\n # ment-wise addition of the arrays possible. Besides,\n # the output can be merely squeezed to lose the `axis`-\n # dimension when keepdims = False\n if type(a) is list:\n out = reduce(partial(np.add, dtype=dtype), a)\n else:\n out = a\n\n if keepdims:\n return out\n else:\n return out.squeeze(axis[0])\n\n\ndef _sum_wo_cat(a, axis=None, dtype=None):\n if dtype is None:\n dtype = getattr(np.zeros(1, dtype=a.dtype).sum(), \"dtype\", object)\n\n if a.shape[axis] == 1:\n return a.squeeze(axis)\n\n return reduction(\n a, _chunk_sum, _chunk_sum, axis=axis, dtype=dtype, concatenate=False\n )\n\n\ndef _matmul(a, b):\n xp = np\n\n if is_cupy_type(a):\n # This branch appears to be unnecessary since cupy\n # version 9.0. See the following link:\n # https://github.com/dask/dask/pull/8423#discussion_r768291271\n # But it remains here for backward-compatibility.\n # Consider removing it in a future version of dask.\n import cupy\n\n xp = cupy\n\n chunk = xp.matmul(a, b)\n # Since we have performed the contraction via xp.matmul\n # but blockwise expects all dimensions back (including\n # the contraction-axis in the 2nd-to-last position of\n # the output), we must then put it back in the expected\n # the position ourselves:\n return chunk[..., xp.newaxis, :]\n\n\n@derived_from(np)\ndef matmul(a, b):\n a = asanyarray(a)\n b = asanyarray(b)\n\n if a.ndim == 0 or b.ndim == 0:\n raise ValueError(\"`matmul` does not support scalars.\")\n\n a_is_1d = False\n if a.ndim == 1:\n a_is_1d = True\n a = a[np.newaxis, :]\n\n b_is_1d = False\n if b.ndim == 1:\n b_is_1d = True\n b = b[:, np.newaxis]\n\n if a.ndim < b.ndim:\n a = a[(b.ndim - a.ndim) * (np.newaxis,)]\n elif a.ndim > b.ndim:\n b = b[(a.ndim - b.ndim) * (np.newaxis,)]\n\n # out_ind includes all dimensions to prevent contraction\n # in the blockwise below. We set the last two dimensions\n # of the output to the contraction axis and the 2nd\n # (last) dimension of b in that order\n out_ind = tuple(range(a.ndim + 1))\n # lhs_ind includes `a`/LHS dimensions\n lhs_ind = tuple(range(a.ndim))\n # on `b`/RHS everything above 2nd dimension, is the same\n # as `a`, -2 dimension is \"contracted\" with the last dimension\n # of `a`, last dimension of `b` is `b` specific\n rhs_ind = tuple(range(a.ndim - 2)) + (lhs_ind[-1], a.ndim)\n\n out = blockwise(\n _matmul,\n out_ind,\n a,\n lhs_ind,\n b,\n rhs_ind,\n adjust_chunks={lhs_ind[-1]: 1},\n dtype=result_type(a, b),\n concatenate=False,\n )\n\n # Because contraction + concatenate in blockwise leads to high\n # memory footprints, we want to avoid them. Instead we will perform\n # blockwise (without contraction) followed by reduction. More about\n # this issue: https://github.com/dask/dask/issues/6874\n\n # We will also perform the reduction without concatenation\n out = _sum_wo_cat(out, axis=-2)\n\n if a_is_1d:\n out = out.squeeze(-2)\n if b_is_1d:\n out = out.squeeze(-1)\n\n return out\n\n\n@derived_from(np)\ndef outer(a, b):\n a = a.flatten()\n b = b.flatten()\n\n dtype = np.outer(a.dtype.type(), b.dtype.type()).dtype\n\n return blockwise(np.outer, \"ij\", a, \"i\", b, \"j\", dtype=dtype)\n\n\ndef _inner_apply_along_axis(arr, func1d, func1d_axis, func1d_args, func1d_kwargs):\n return np.apply_along_axis(func1d, func1d_axis, arr, *func1d_args, **func1d_kwargs)\n\n\n@derived_from(np)\ndef apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs):\n \"\"\"\n This is a blocked variant of :func:`numpy.apply_along_axis` implemented via\n :func:`dask.array.map_blocks`\n\n Notes\n -----\n If either of `dtype` or `shape` are not provided, Dask attempts to\n determine them by calling `func1d` on a dummy array. This may produce\n incorrect values for `dtype` or `shape`, so we recommend providing them.\n \"\"\"\n arr = asarray(arr)\n\n # Verify that axis is valid and throw an error otherwise\n axis = len(arr.shape[:axis])\n\n # If necessary, infer dtype and shape of the output of func1d by calling it on test data.\n if shape is None or dtype is None:\n test_data = np.ones((1,), dtype=arr.dtype)\n test_result = np.array(func1d(test_data, *args, **kwargs))\n if shape is None:\n shape = test_result.shape\n if dtype is None:\n dtype = test_result.dtype\n\n # Rechunk so that func1d is applied over the full axis.\n arr = arr.rechunk(\n arr.chunks[:axis] + (arr.shape[axis : axis + 1],) + arr.chunks[axis + 1 :]\n )\n\n # Map func1d over the data to get the result\n # Adds other axes as needed.\n result = arr.map_blocks(\n _inner_apply_along_axis,\n name=funcname(func1d) + \"-along-axis\",\n dtype=dtype,\n chunks=(arr.chunks[:axis] + shape + arr.chunks[axis + 1 :]),\n drop_axis=axis,\n new_axis=list(range(axis, axis + len(shape), 1)),\n func1d=func1d,\n func1d_axis=axis,\n func1d_args=args,\n func1d_kwargs=kwargs,\n )\n\n return result\n\n\n@derived_from(np)\ndef apply_over_axes(func, a, axes):\n # Validate arguments\n a = asarray(a)\n try:\n axes = tuple(axes)\n except TypeError:\n axes = (axes,)\n\n sl = a.ndim * (slice(None),)\n\n # Compute using `apply_along_axis`.\n result = a\n for i in axes:\n result = apply_along_axis(func, i, result, 0)\n\n # Restore original dimensionality or error.\n if result.ndim == (a.ndim - 1):\n result = result[sl[:i] + (None,)]\n elif result.ndim != a.ndim:\n raise ValueError(\n \"func must either preserve dimensionality of the input\"\n \" or reduce it by one.\"\n )\n\n return result\n\n\n@derived_from(np)\ndef ptp(a, axis=None):\n return a.max(axis=axis) - a.min(axis=axis)\n\n\n@derived_from(np)\ndef diff(a, n=1, axis=-1, prepend=None, append=None):\n a = asarray(a)\n n = int(n)\n axis = int(axis)\n\n if n == 0:\n return a\n if n < 0:\n raise ValueError(\"order must be non-negative but got %d\" % n)\n\n combined = []\n if prepend is not None:\n prepend = asarray_safe(prepend, like=meta_from_array(a))\n if prepend.ndim == 0:\n shape = list(a.shape)\n shape[axis] = 1\n prepend = broadcast_to(prepend, tuple(shape))\n combined.append(prepend)\n\n combined.append(a)\n\n if append is not None:\n append = asarray_safe(append, like=meta_from_array(a))\n if append.ndim == 0:\n shape = list(a.shape)\n shape[axis] = 1\n append = np.broadcast_to(append, tuple(shape))\n combined.append(append)\n\n if len(combined) > 1:\n a = concatenate(combined, axis)\n\n sl_1 = a.ndim * [slice(None)]\n sl_2 = a.ndim * [slice(None)]\n\n sl_1[axis] = slice(1, None)\n sl_2[axis] = slice(None, -1)\n\n sl_1 = tuple(sl_1)\n sl_2 = tuple(sl_2)\n\n r = a\n for i in range(n):\n r = r[sl_1] - r[sl_2]\n\n return r\n\n\n@derived_from(np)\ndef ediff1d(ary, to_end=None, to_begin=None):\n ary = asarray(ary)\n\n aryf = ary.flatten()\n r = aryf[1:] - aryf[:-1]\n\n r = [r]\n if to_begin is not None:\n r = [asarray(to_begin).flatten()] + r\n if to_end is not None:\n r = r + [asarray(to_end).flatten()]\n r = concatenate(r)\n\n return r\n\n\ndef _gradient_kernel(x, block_id, coord, axis, array_locs, grad_kwargs):\n \"\"\"\n x: nd-array\n array of one block\n coord: 1d-array or scalar\n coordinate along which the gradient is computed.\n axis: int\n axis along which the gradient is computed\n array_locs:\n actual location along axis. None if coordinate is scalar\n grad_kwargs:\n keyword to be passed to np.gradient\n \"\"\"\n block_loc = block_id[axis]\n if array_locs is not None:\n coord = coord[array_locs[0][block_loc] : array_locs[1][block_loc]]\n grad = np.gradient(x, coord, axis=axis, **grad_kwargs)\n return grad\n\n\n@derived_from(np)\ndef gradient(f, *varargs, axis=None, **kwargs):\n f = asarray(f)\n\n kwargs[\"edge_order\"] = math.ceil(kwargs.get(\"edge_order\", 1))\n if kwargs[\"edge_order\"] > 2:\n raise ValueError(\"edge_order must be less than or equal to 2.\")\n\n drop_result_list = False\n if axis is None:\n axis = tuple(range(f.ndim))\n elif isinstance(axis, Integral):\n drop_result_list = True\n axis = (axis,)\n\n axis = validate_axis(axis, f.ndim)\n\n if len(axis) != len(set(axis)):\n raise ValueError(\"duplicate axes not allowed\")\n\n axis = tuple(ax % f.ndim for ax in axis)\n\n if varargs == ():\n varargs = (1,)\n if len(varargs) == 1:\n varargs = len(axis) * varargs\n if len(varargs) != len(axis):\n raise TypeError(\n \"Spacing must either be a single scalar, or a scalar / 1d-array per axis\"\n )\n\n if issubclass(f.dtype.type, (np.bool8, Integral)):\n f = f.astype(float)\n elif issubclass(f.dtype.type, Real) and f.dtype.itemsize < 4:\n f = f.astype(float)\n\n results = []\n for i, ax in enumerate(axis):\n for c in f.chunks[ax]:\n if np.min(c) < kwargs[\"edge_order\"] + 1:\n raise ValueError(\n \"Chunk size must be larger than edge_order + 1. \"\n \"Minimum chunk for axis {} is {}. Rechunk to \"\n \"proceed.\".format(ax, np.min(c))\n )\n\n if np.isscalar(varargs[i]):\n array_locs = None\n else:\n if isinstance(varargs[i], Array):\n raise NotImplementedError(\"dask array coordinated is not supported.\")\n # coordinate position for each block taking overlap into account\n chunk = np.array(f.chunks[ax])\n array_loc_stop = np.cumsum(chunk) + 1\n array_loc_start = array_loc_stop - chunk - 2\n array_loc_stop[-1] -= 1\n array_loc_start[0] = 0\n array_locs = (array_loc_start, array_loc_stop)\n\n results.append(\n f.map_overlap(\n _gradient_kernel,\n dtype=f.dtype,\n depth={j: 1 if j == ax else 0 for j in range(f.ndim)},\n boundary=\"none\",\n coord=varargs[i],\n axis=ax,\n array_locs=array_locs,\n grad_kwargs=kwargs,\n )\n )\n\n if drop_result_list:\n results = results[0]\n\n return results\n\n\ndef _bincount_agg(bincounts, dtype, **kwargs):\n if not isinstance(bincounts, list):\n return bincounts\n\n n = max(map(len, bincounts))\n out = np.zeros_like(bincounts[0], shape=n, dtype=dtype)\n for b in bincounts:\n out[: len(b)] += b\n return out\n\n\n@derived_from(np)\ndef bincount(x, weights=None, minlength=0, split_every=None):\n if x.ndim != 1:\n raise ValueError(\"Input array must be one dimensional. Try using x.ravel()\")\n if weights is not None:\n if weights.chunks != x.chunks:\n raise ValueError(\"Chunks of input array x and weights must match.\")\n\n token = tokenize(x, weights, minlength)\n args = [x, \"i\"]\n if weights is not None:\n meta = array_safe(np.bincount([1], weights=[1]), like=meta_from_array(x))\n args.extend([weights, \"i\"])\n else:\n meta = array_safe(np.bincount([]), like=meta_from_array(x))\n\n if minlength == 0:\n output_size = (np.nan,)\n else:\n output_size = (minlength,)\n\n chunked_counts = blockwise(\n partial(np.bincount, minlength=minlength), \"i\", *args, token=token, meta=meta\n )\n chunked_counts._chunks = (\n output_size * len(chunked_counts.chunks[0]),\n *chunked_counts.chunks[1:],\n )\n\n from dask.array.reductions import _tree_reduce\n\n output = _tree_reduce(\n chunked_counts,\n aggregate=partial(_bincount_agg, dtype=meta.dtype),\n axis=(0,),\n keepdims=True,\n dtype=meta.dtype,\n split_every=split_every,\n concatenate=False,\n )\n output._chunks = (output_size, *chunked_counts.chunks[1:])\n output._meta = meta\n return output\n\n\n@derived_from(np)\ndef digitize(a, bins, right=False):\n bins = asarray_safe(bins, like=meta_from_array(a))\n dtype = np.digitize(asarray_safe([0], like=bins), bins, right=False).dtype\n return a.map_blocks(np.digitize, dtype=dtype, bins=bins, right=right)\n\n\ndef _searchsorted_block(x, y, side):\n res = np.searchsorted(x, y, side=side)\n # 0 is only correct for the first block of a, but blockwise doesn't have a way\n # of telling which block is being operated on (unlike map_blocks),\n # so set all 0 values to a special value and set back at the end of searchsorted\n res[res == 0] = -1\n return res[np.newaxis, :]\n\n\n@derived_from(np)\ndef searchsorted(a, v, side=\"left\", sorter=None):\n if a.ndim != 1:\n raise ValueError(\"Input array a must be one dimensional\")\n\n if sorter is not None:\n raise NotImplementedError(\n \"da.searchsorted with a sorter argument is not supported\"\n )\n\n # call np.searchsorted for each pair of blocks in a and v\n meta = np.searchsorted(a._meta, v._meta)\n out = blockwise(\n _searchsorted_block,\n list(range(v.ndim + 1)),\n a,\n [0],\n v,\n list(range(1, v.ndim + 1)),\n side,\n None,\n meta=meta,\n adjust_chunks={0: 1}, # one row for each block in a\n )\n\n # add offsets to take account of the position of each block within the array a\n a_chunk_sizes = array_safe((0, *a.chunks[0]), like=meta_from_array(a))\n a_chunk_offsets = np.cumsum(a_chunk_sizes)[:-1]\n a_chunk_offsets = a_chunk_offsets[(Ellipsis,) + v.ndim * (np.newaxis,)]\n a_offsets = asarray(a_chunk_offsets, chunks=1)\n out = where(out < 0, out, out + a_offsets)\n\n # combine the results from each block (of a)\n out = out.max(axis=0)\n\n # fix up any -1 values\n out[out == -1] = 0\n\n return out\n\n\n# TODO: dask linspace doesn't support delayed values\ndef _linspace_from_delayed(start, stop, num=50):\n linspace_name = \"linspace-\" + tokenize(start, stop, num)\n (start_ref, stop_ref, num_ref), deps = unpack_collections([start, stop, num])\n if len(deps) == 0:\n return np.linspace(start, stop, num=num)\n\n linspace_dsk = {(linspace_name, 0): (np.linspace, start_ref, stop_ref, num_ref)}\n linspace_graph = HighLevelGraph.from_collections(\n linspace_name, linspace_dsk, dependencies=deps\n )\n\n chunks = ((np.nan,),) if is_dask_collection(num) else ((num,),)\n return Array(linspace_graph, linspace_name, chunks, dtype=float)\n\n\ndef _block_hist(x, bins, range=None, weights=None):\n return np.histogram(x, bins, range=range, weights=weights)[0][np.newaxis]\n\n\ndef histogram(a, bins=None, range=None, normed=False, weights=None, density=None):\n \"\"\"\n Blocked variant of :func:`numpy.histogram`.\n\n Parameters\n ----------\n a : dask.array.Array\n Input data; the histogram is computed over the flattened\n array. If the ``weights`` argument is used, the chunks of\n ``a`` are accessed to check chunking compatibility between\n ``a`` and ``weights``. If ``weights`` is ``None``, a\n :py:class:`dask.dataframe.Series` object can be passed as\n input data.\n bins : int or sequence of scalars, optional\n Either an iterable specifying the ``bins`` or the number of ``bins``\n and a ``range`` argument is required as computing ``min`` and ``max``\n over blocked arrays is an expensive operation that must be performed\n explicitly.\n If `bins` is an int, it defines the number of equal-width\n bins in the given range (10, by default). If `bins` is a\n sequence, it defines a monotonically increasing array of bin edges,\n including the rightmost edge, allowing for non-uniform bin widths.\n range : (float, float), optional\n The lower and upper range of the bins. If not provided, range\n is simply ``(a.min(), a.max())``. Values outside the range are\n ignored. The first element of the range must be less than or\n equal to the second. `range` affects the automatic bin\n computation as well. While bin width is computed to be optimal\n based on the actual data within `range`, the bin count will fill\n the entire range including portions containing no data.\n normed : bool, optional\n This is equivalent to the ``density`` argument, but produces incorrect\n results for unequal bin widths. It should not be used.\n weights : dask.array.Array, optional\n A dask.array.Array of weights, of the same block structure as ``a``. Each value in\n ``a`` only contributes its associated weight towards the bin count\n (instead of 1). If ``density`` is True, the weights are\n normalized, so that the integral of the density over the range\n remains 1.\n density : bool, optional\n If ``False``, the result will contain the number of samples in\n each bin. If ``True``, the result is the value of the\n probability *density* function at the bin, normalized such that\n the *integral* over the range is 1. Note that the sum of the\n histogram values will not be equal to 1 unless bins of unity\n width are chosen; it is not a probability *mass* function.\n Overrides the ``normed`` keyword if given.\n If ``density`` is True, ``bins`` cannot be a single-number delayed\n value. It must be a concrete number, or a (possibly-delayed)\n array/sequence of the bin edges.\n\n Returns\n -------\n hist : dask Array\n The values of the histogram. See `density` and `weights` for a\n description of the possible semantics.\n bin_edges : dask Array of dtype float\n Return the bin edges ``(length(hist)+1)``.\n\n Examples\n --------\n Using number of bins and range:\n\n >>> import dask.array as da\n >>> import numpy as np\n >>> x = da.from_array(np.arange(10000), chunks=10)\n >>> h, bins = da.histogram(x, bins=10, range=[0, 10000])\n >>> bins\n array([ 0., 1000., 2000., 3000., 4000., 5000., 6000., 7000.,\n 8000., 9000., 10000.])\n >>> h.compute()\n array([1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000])\n\n Explicitly specifying the bins:\n\n >>> h, bins = da.histogram(x, bins=np.array([0, 5000, 10000]))\n >>> bins\n array([ 0, 5000, 10000])\n >>> h.compute()\n array([5000, 5000])\n \"\"\"\n if isinstance(bins, Array):\n scalar_bins = bins.ndim == 0\n # ^ `np.ndim` is not implemented by Dask array.\n elif isinstance(bins, Delayed):\n scalar_bins = bins._length is None or bins._length == 1\n else:\n scalar_bins = np.ndim(bins) == 0\n\n if bins is None or (scalar_bins and range is None):\n raise ValueError(\n \"dask.array.histogram requires either specifying \"\n \"bins as an iterable or specifying both a range and \"\n \"the number of bins\"\n )\n\n if weights is not None and weights.chunks != a.chunks:\n raise ValueError(\"Input array and weights must have the same chunked structure\")\n\n if normed is not False:\n raise ValueError(\n \"The normed= keyword argument has been deprecated. \"\n \"Please use density instead. \"\n \"See the numpy.histogram docstring for more information.\"\n )\n\n if density and scalar_bins and isinstance(bins, (Array, Delayed)):\n raise NotImplementedError(\n \"When `density` is True, `bins` cannot be a scalar Dask object. \"\n \"It must be a concrete number or a (possibly-delayed) array/sequence of bin edges.\"\n )\n\n for argname, val in [(\"bins\", bins), (\"range\", range), (\"weights\", weights)]:\n if not isinstance(bins, (Array, Delayed)) and is_dask_collection(bins):\n raise TypeError(\n \"Dask types besides Array and Delayed are not supported \"\n \"for `histogram`. For argument `{}`, got: {!r}\".format(argname, val)\n )\n\n if range is not None:\n try:\n if len(range) != 2:\n raise ValueError(\n f\"range must be a sequence or array of length 2, but got {len(range)} items\"\n )\n if isinstance(range, (Array, np.ndarray)) and range.shape != (2,):\n raise ValueError(\n f\"range must be a 1-dimensional array of two items, but got an array of shape {range.shape}\"\n )\n except TypeError:\n raise TypeError(\n f\"Expected a sequence or array for range, not {range}\"\n ) from None\n\n token = tokenize(a, bins, range, weights, density)\n name = \"histogram-sum-\" + token\n\n if scalar_bins:\n bins = _linspace_from_delayed(range[0], range[1], bins + 1)\n # ^ NOTE `range[1]` is safe because of the above check, and the initial check\n # that range must not be None if `scalar_bins`\n else:\n if not isinstance(bins, (Array, np.ndarray)):\n bins = asarray(bins)\n if bins.ndim != 1:\n raise ValueError(\n f\"bins must be a 1-dimensional array or sequence, got shape {bins.shape}\"\n )\n\n (bins_ref, range_ref), deps = unpack_collections([bins, range])\n\n # Map the histogram to all bins, forming a 2D array of histograms, stacked for each chunk\n if weights is None:\n dsk = {\n (name, i, 0): (_block_hist, k, bins_ref, range_ref)\n for i, k in enumerate(flatten(a.__dask_keys__()))\n }\n dtype = np.histogram([])[0].dtype\n else:\n a_keys = flatten(a.__dask_keys__())\n w_keys = flatten(weights.__dask_keys__())\n dsk = {\n (name, i, 0): (_block_hist, k, bins_ref, range_ref, w)\n for i, (k, w) in enumerate(zip(a_keys, w_keys))\n }\n dtype = weights.dtype\n\n deps = (a,) + deps\n if weights is not None:\n deps += (weights,)\n graph = HighLevelGraph.from_collections(name, dsk, dependencies=deps)\n\n # Turn graph into a 2D Array of shape (nchunks, nbins)\n nchunks = len(list(flatten(a.__dask_keys__())))\n nbins = bins.size - 1 # since `bins` is 1D\n chunks = ((1,) * nchunks, (nbins,))\n mapped = Array(graph, name, chunks, dtype=dtype)\n\n # Sum over chunks to get the final histogram\n n = mapped.sum(axis=0)\n\n # We need to replicate normed and density options from numpy\n if density is not None:\n if density:\n db = asarray(np.diff(bins).astype(float), chunks=n.chunks)\n return n / db / n.sum(), bins\n else:\n return n, bins\n else:\n return n, bins\n\n\ndef histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None):\n \"\"\"Blocked variant of :func:`numpy.histogram2d`.\n\n Parameters\n ----------\n x : dask.array.Array\n An array containing the `x`-coordinates of the points to be\n histogrammed.\n y : dask.array.Array\n An array containing the `y`-coordinates of the points to be\n histogrammed.\n bins : sequence of arrays describing bin edges, int, or sequence of ints\n The bin specification. See the `bins` argument description for\n :py:func:`histogramdd` for a complete description of all\n possible bin configurations (this function is a 2D specific\n version of histogramdd).\n range : tuple of pairs, optional.\n The leftmost and rightmost edges of the bins along each\n dimension when integers are passed to `bins`; of the form:\n ((xmin, xmax), (ymin, ymax)).\n normed : bool, optional\n An alias for the density argument that behaves identically. To\n avoid confusion with the broken argument in the `histogram`\n function, `density` should be preferred.\n weights : dask.array.Array, optional\n An array of values weighing each sample in the input data. The\n chunks of the weights must be identical to the chunking along\n the 0th (row) axis of the data sample.\n density : bool, optional\n If False (the default) return the number of samples in each\n bin. If True, the returned array represents the probability\n density function at each bin.\n\n Returns\n -------\n dask.array.Array\n The values of the histogram.\n dask.array.Array\n The edges along the `x`-dimension.\n dask.array.Array\n The edges along the `y`-dimension.\n\n See Also\n --------\n histogram\n histogramdd\n\n Examples\n --------\n >>> import dask.array as da\n >>> x = da.array([2, 4, 2, 4, 2, 4])\n >>> y = da.array([2, 2, 4, 4, 2, 4])\n >>> bins = 2\n >>> range = ((0, 6), (0, 6))\n >>> h, xedges, yedges = da.histogram2d(x, y, bins=bins, range=range)\n >>> h\n dask.array<sum-aggregate, shape=(2, 2), dtype=float64, chunksize=(2, 2), chunktype=numpy.ndarray>\n >>> xedges\n dask.array<array, shape=(3,), dtype=float64, chunksize=(3,), chunktype=numpy.ndarray>\n >>> h.compute()\n array([[2., 1.],\n [1., 2.]])\n \"\"\"\n counts, edges = histogramdd(\n (x, y),\n bins=bins,\n range=range,\n normed=normed,\n weights=weights,\n density=density,\n )\n return counts, edges[0], edges[1]\n\n\ndef _block_histogramdd_rect(sample, bins, range, weights):\n \"\"\"Call numpy.histogramdd for a blocked/chunked calculation.\n\n Slurps the result into an additional outer axis; this new axis\n will be used to stack chunked calls of the numpy function and add\n them together later.\n\n Returns\n -------\n :py:object:`np.ndarray`\n NumPy array with an additional outer dimension.\n\n \"\"\"\n return np.histogramdd(sample, bins, range=range, weights=weights)[0:1]\n\n\ndef _block_histogramdd_multiarg(*args):\n \"\"\"Call numpy.histogramdd for a multi argument blocked/chunked calculation.\n\n Slurps the result into an additional outer axis; this new axis\n will be used to stack chunked calls of the numpy function and add\n them together later.\n\n The last three arguments _must be_ (bins, range, weights).\n\n The difference between this function and\n _block_histogramdd_rect is that here we expect the sample\n to be composed of multiple arguments (multiple 1D arrays, each one\n representing a coordinate), while _block_histogramdd_rect\n expects a single rectangular (2D array where columns are\n coordinates) sample.\n\n \"\"\"\n bins, range, weights = args[-3:]\n sample = args[:-3]\n return np.histogramdd(sample, bins=bins, range=range, weights=weights)[0:1]\n\n\ndef histogramdd(sample, bins, range=None, normed=None, weights=None, density=None):\n \"\"\"Blocked variant of :func:`numpy.histogramdd`.\n\n Chunking of the input data (``sample``) is only allowed along the\n 0th (row) axis (the axis corresponding to the total number of\n samples). Data chunked along the 1st axis (column) axis is not\n compatible with this function. If weights are used, they must be\n chunked along the 0th axis identically to the input sample.\n\n An example setup for a three dimensional histogram, where the\n sample shape is ``(8, 3)`` and weights are shape ``(8,)``, sample\n chunks would be ``((4, 4), (3,))`` and the weights chunks would be\n ``((4, 4),)`` a table of the structure:\n\n +-------+-----------------------+-----------+\n | | sample (8 x 3) | weights |\n +=======+=====+=====+=====+=====+=====+=====+\n | chunk | row | `x` | `y` | `z` | row | `w` |\n +-------+-----+-----+-----+-----+-----+-----+\n | | 0 | 5 | 6 | 6 | 0 | 0.5 |\n | +-----+-----+-----+-----+-----+-----+\n | | 1 | 8 | 9 | 2 | 1 | 0.8 |\n | 0 +-----+-----+-----+-----+-----+-----+\n | | 2 | 3 | 3 | 1 | 2 | 0.3 |\n | +-----+-----+-----+-----+-----+-----+\n | | 3 | 2 | 5 | 6 | 3 | 0.7 |\n +-------+-----+-----+-----+-----+-----+-----+\n | | 4 | 3 | 1 | 1 | 4 | 0.3 |\n | +-----+-----+-----+-----+-----+-----+\n | | 5 | 3 | 2 | 9 | 5 | 1.3 |\n | 1 +-----+-----+-----+-----+-----+-----+\n | | 6 | 8 | 1 | 5 | 6 | 0.8 |\n | +-----+-----+-----+-----+-----+-----+\n | | 7 | 3 | 5 | 3 | 7 | 0.7 |\n +-------+-----+-----+-----+-----+-----+-----+\n\n If the sample 0th dimension and weight 0th (row) dimension are\n chunked differently, a ``ValueError`` will be raised. If\n coordinate groupings ((x, y, z) trios) are separated by a chunk\n boundry, then a ``ValueError`` will be raised. We suggest that you\n rechunk your data if it is of that form.\n\n The chunks property of the data (and optional weights) are used to\n check for compatibility with the blocked algorithm (as described\n above); therefore, you must call `to_dask_array` on a collection\n from ``dask.dataframe``, i.e. :class:`dask.dataframe.Series` or\n :class:`dask.dataframe.DataFrame`.\n\n The function is also compatible with `x`, `y`, and `z` being\n individual 1D arrays with equal chunking. In that case, the data\n should be passed as a tuple: ``histogramdd((x, y, z), ...)``\n\n Parameters\n ----------\n sample : dask.array.Array (N, D) or sequence of dask.array.Array\n Multidimensional data to be histogrammed.\n\n Note the unusual interpretation of a sample when it is a\n sequence of dask Arrays:\n\n * When a (N, D) dask Array, each row is an entry in the sample\n (coordinate in D dimensional space).\n * When a sequence of dask Arrays, each element in the sequence\n is the array of values for a single coordinate.\n bins : sequence of arrays describing bin edges, int, or sequence of ints\n The bin specification.\n\n The possible binning configurations are:\n\n * A sequence of arrays describing the monotonically increasing\n bin edges along each dimension.\n * A single int describing the total number of bins that will\n be used in each dimension (this requires the ``range``\n argument to be defined).\n * A sequence of ints describing the total number of bins to be\n used in each dimension (this requires the ``range`` argument\n to be defined).\n\n When bins are described by arrays, the rightmost edge is\n included. Bins described by arrays also allows for non-uniform\n bin widths.\n range : sequence of pairs, optional\n A sequence of length D, each a (min, max) tuple giving the\n outer bin edges to be used if the edges are not given\n explicitly in `bins`. If defined, this argument is required to\n have an entry for each dimension. Unlike\n :func:`numpy.histogramdd`, if `bins` does not define bin\n edges, this argument is required (this function will not\n automatically use the min and max of of the value in a given\n dimension because the input data may be lazy in dask).\n normed : bool, optional\n An alias for the density argument that behaves identically. To\n avoid confusion with the broken argument to `histogram`,\n `density` should be preferred.\n weights : dask.array.Array, optional\n An array of values weighing each sample in the input data. The\n chunks of the weights must be identical to the chunking along\n the 0th (row) axis of the data sample.\n density : bool, optional\n If ``False`` (default), the returned array represents the\n number of samples in each bin. If ``True``, the returned array\n represents the probability density function at each bin.\n\n See Also\n --------\n histogram\n\n Returns\n -------\n dask.array.Array\n The values of the histogram.\n list(dask.array.Array)\n Sequence of arrays representing the bin edges along each\n dimension.\n\n Examples\n --------\n Computing the histogram in 5 blocks using different bin edges\n along each dimension:\n\n >>> import dask.array as da\n >>> x = da.random.uniform(0, 1, size=(1000, 3), chunks=(200, 3))\n >>> edges = [\n ... np.linspace(0, 1, 5), # 4 bins in 1st dim\n ... np.linspace(0, 1, 6), # 5 in the 2nd\n ... np.linspace(0, 1, 4), # 3 in the 3rd\n ... ]\n >>> h, edges = da.histogramdd(x, bins=edges)\n >>> result = h.compute()\n >>> result.shape\n (4, 5, 3)\n\n Defining the bins by total number and their ranges, along with\n using weights:\n\n >>> bins = (4, 5, 3)\n >>> ranges = ((0, 1),) * 3 # expands to ((0, 1), (0, 1), (0, 1))\n >>> w = da.random.uniform(0, 1, size=(1000,), chunks=x.chunksize[0])\n >>> h, edges = da.histogramdd(x, bins=bins, range=ranges, weights=w)\n >>> np.isclose(h.sum().compute(), w.sum().compute())\n True\n\n Using a sequence of 1D arrays as the input:\n\n >>> x = da.array([2, 4, 2, 4, 2, 4])\n >>> y = da.array([2, 2, 4, 4, 2, 4])\n >>> z = da.array([4, 2, 4, 2, 4, 2])\n >>> bins = ([0, 3, 6],) * 3\n >>> h, edges = da.histogramdd((x, y, z), bins)\n >>> h\n dask.array<sum-aggregate, shape=(2, 2, 2), dtype=float64, chunksize=(2, 2, 2), chunktype=numpy.ndarray>\n >>> edges[0]\n dask.array<array, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>\n >>> h.compute()\n array([[[0., 2.],\n [0., 1.]],\n <BLANKLINE>\n [[1., 0.],\n [2., 0.]]])\n >>> edges[0].compute()\n array([0, 3, 6])\n >>> edges[1].compute()\n array([0, 3, 6])\n >>> edges[2].compute()\n array([0, 3, 6])\n\n \"\"\"\n # logic used in numpy.histogramdd to handle normed/density.\n if normed is None:\n if density is None:\n density = False\n elif density is None:\n # an explicit normed argument was passed, alias it to the new name\n density = normed\n else:\n raise TypeError(\"Cannot specify both 'normed' and 'density'\")\n\n # check if any dask collections (dc) were passed to bins= or\n # range= these are unsupported.\n dc_bins = is_dask_collection(bins)\n if isinstance(bins, (list, tuple)):\n dc_bins = dc_bins or any([is_dask_collection(b) for b in bins])\n dc_range = (\n any([is_dask_collection(r) for r in range]) if range is not None else False\n )\n if dc_bins or dc_range:\n raise NotImplementedError(\n \"Passing dask collections to bins=... or range=... is not supported.\"\n )\n\n # generate token and name for task\n token = tokenize(sample, bins, range, weights, density)\n name = f\"histogramdd-sum-{token}\"\n\n # N == total number of samples\n # D == total number of dimensions\n if hasattr(sample, \"shape\"):\n if len(sample.shape) != 2:\n raise ValueError(\"Single array input to histogramdd should be columnar\")\n else:\n _, D = sample.shape\n n_chunks = sample.numblocks[0]\n rectangular_sample = True\n # Require data to be chunked along the first axis only.\n if sample.shape[1:] != sample.chunksize[1:]:\n raise ValueError(\"Input array can only be chunked along the 0th axis.\")\n elif isinstance(sample, (tuple, list)):\n rectangular_sample = False\n D = len(sample)\n n_chunks = sample[0].numblocks[0]\n for i in _range(1, D):\n if sample[i].chunks != sample[0].chunks:\n raise ValueError(\"All coordinate arrays must be chunked identically.\")\n else:\n raise ValueError(\n \"Incompatible sample. Must be a 2D array or a sequence of 1D arrays.\"\n )\n\n # Require only Array or Delayed objects for bins, range, and weights.\n for argname, val in [(\"bins\", bins), (\"range\", range), (\"weights\", weights)]:\n if not isinstance(bins, (Array, Delayed)) and is_dask_collection(bins):\n raise TypeError(\n \"Dask types besides Array and Delayed are not supported \"\n \"for `histogramdd`. For argument `{}`, got: {!r}\".format(argname, val)\n )\n\n # Require that the chunking of the sample and weights are compatible.\n if weights is not None:\n if rectangular_sample and weights.chunks[0] != sample.chunks[0]:\n raise ValueError(\n \"Input array and weights must have the same shape \"\n \"and chunk structure along the first dimension.\"\n )\n elif not rectangular_sample and weights.numblocks[0] != n_chunks:\n raise ValueError(\n \"Input arrays and weights must have the same shape \"\n \"and chunk structure.\"\n )\n\n # if bins is a list, tuple, then make sure the length is the same\n # as the number dimensions.\n if isinstance(bins, (list, tuple)):\n if len(bins) != D:\n raise ValueError(\n \"The dimension of bins must be equal to the dimension of the sample.\"\n )\n\n # if range is defined, check that it's the right length and also a\n # sequence of pairs.\n if range is not None:\n if len(range) != D:\n raise ValueError(\n \"range argument requires one entry, a min max pair, per dimension.\"\n )\n if not all(len(r) == 2 for r in range):\n raise ValueError(\"range argument should be a sequence of pairs\")\n\n # If bins is a single int, create a tuple of len `D` containing `bins`.\n if isinstance(bins, int):\n bins = (bins,) * D\n\n # we will return the edges to mimic the NumPy API (we also use the\n # edges later as a way to calculate the total number of bins).\n if all(isinstance(b, int) for b in bins) and all(len(r) == 2 for r in range):\n edges = [np.linspace(r[0], r[1], b + 1) for b, r in zip(bins, range)]\n else:\n edges = [np.asarray(b) for b in bins]\n\n if rectangular_sample:\n deps = (sample,)\n else:\n deps = tuple(sample)\n\n if weights is not None:\n w_keys = flatten(weights.__dask_keys__())\n deps += (weights,)\n dtype = weights.dtype\n else:\n w_keys = (None,) * n_chunks\n dtype = np.histogramdd([])[0].dtype\n\n # This tuple of zeros represents the chunk index along the columns\n # (we only allow chunking along the rows).\n column_zeros = tuple(0 for _ in _range(D))\n\n # With dsk below, we will construct a (D + 1) dimensional array\n # stacked for each chunk. For example, if the histogram is going\n # to be 3 dimensions, this creates a stack of cubes (1 cube for\n # each sample chunk) that will be collapsed into a final cube (the\n # result). Depending on the input data, we can do this in two ways\n #\n # 1. The rectangular case: when the sample is a single 2D array\n # where each column in the sample represents a coordinate of\n # the sample).\n #\n # 2. The sequence-of-arrays case, when the sample is a tuple or\n # list of arrays, with each array in that sequence representing\n # the entirety of one coordinate of the complete sample.\n\n if rectangular_sample:\n sample_keys = flatten(sample.__dask_keys__())\n dsk = {\n (name, i, *column_zeros): (_block_histogramdd_rect, k, bins, range, w)\n for i, (k, w) in enumerate(zip(sample_keys, w_keys))\n }\n else:\n sample_keys = [\n list(flatten(sample[i].__dask_keys__())) for i in _range(len(sample))\n ]\n fused_on_chunk_keys = [\n tuple(sample_keys[j][i] for j in _range(D)) for i in _range(n_chunks)\n ]\n dsk = {\n (name, i, *column_zeros): (\n _block_histogramdd_multiarg,\n *(*k, bins, range, w),\n )\n for i, (k, w) in enumerate(zip(fused_on_chunk_keys, w_keys))\n }\n\n graph = HighLevelGraph.from_collections(name, dsk, dependencies=deps)\n all_nbins = tuple((b.size - 1,) for b in edges)\n stacked_chunks = ((1,) * n_chunks, *all_nbins)\n mapped = Array(graph, name, stacked_chunks, dtype=dtype)\n # Finally, sum over chunks providing to get the final D\n # dimensional result array.\n n = mapped.sum(axis=0)\n\n if density:\n # compute array of values to divide by the bin width along\n # each dimension.\n width_divider = np.ones(n.shape)\n for i in _range(D):\n shape = np.ones(D, int)\n shape[i] = width_divider.shape[i]\n width_divider *= np.diff(edges[i]).reshape(shape)\n width_divider = asarray(width_divider, chunks=n.chunks)\n return n / width_divider / n.sum(), edges\n\n return n, [asarray(entry) for entry in edges]\n\n\n@derived_from(np)\ndef cov(m, y=None, rowvar=1, bias=0, ddof=None):\n # This was copied almost verbatim from np.cov\n # See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt\n # or NUMPY_LICENSE.txt within this directory\n if ddof is not None and ddof != int(ddof):\n raise ValueError(\"ddof must be integer\")\n\n # Handles complex arrays too\n m = asarray(m)\n if y is None:\n dtype = np.result_type(m, np.float64)\n else:\n y = asarray(y)\n dtype = np.result_type(m, y, np.float64)\n X = array(m, ndmin=2, dtype=dtype)\n\n if X.shape[0] == 1:\n rowvar = 1\n if rowvar:\n N = X.shape[1]\n axis = 0\n else:\n N = X.shape[0]\n axis = 1\n\n # check ddof\n if ddof is None:\n if bias == 0:\n ddof = 1\n else:\n ddof = 0\n fact = float(N - ddof)\n if fact <= 0:\n warnings.warn(\"Degrees of freedom <= 0 for slice\", RuntimeWarning)\n fact = 0.0\n\n if y is not None:\n y = array(y, ndmin=2, dtype=dtype)\n X = concatenate((X, y), axis)\n\n X = X - X.mean(axis=1 - axis, keepdims=True)\n if not rowvar:\n return (dot(X.T, X.conj()) / fact).squeeze()\n else:\n return (dot(X, X.T.conj()) / fact).squeeze()\n\n\n@derived_from(np)\ndef corrcoef(x, y=None, rowvar=1):\n c = cov(x, y, rowvar)\n if c.shape == ():\n return c / c\n d = diag(c)\n d = d.reshape((d.shape[0], 1))\n sqr_d = sqrt(d)\n return (c / sqr_d) / sqr_d.T\n\n\n@implements(np.round, np.round_)\n@derived_from(np)\ndef round(a, decimals=0):\n return a.map_blocks(np.round, decimals=decimals, dtype=a.dtype)\n\n\n@implements(np.ndim)\n@derived_from(np)\ndef ndim(a):\n return a.ndim\n\n\n@implements(np.iscomplexobj)\n@derived_from(np)\ndef iscomplexobj(x):\n return issubclass(x.dtype.type, np.complexfloating)\n\n\ndef _unique_internal(ar, indices, counts, return_inverse=False):\n \"\"\"\n Helper/wrapper function for :func:`numpy.unique`.\n\n Uses :func:`numpy.unique` to find the unique values for the array chunk.\n Given this chunk may not represent the whole array, also take the\n ``indices`` and ``counts`` that are in 1-to-1 correspondence to ``ar``\n and reduce them in the same fashion as ``ar`` is reduced. Namely sum\n any counts that correspond to the same value and take the smallest\n index that corresponds to the same value.\n\n To handle the inverse mapping from the unique values to the original\n array, simply return a NumPy array created with ``arange`` with enough\n values to correspond 1-to-1 to the unique values. While there is more\n work needed to be done to create the full inverse mapping for the\n original array, this provides enough information to generate the\n inverse mapping in Dask.\n\n Given Dask likes to have one array returned from functions like\n ``blockwise``, some formatting is done to stuff all of the resulting arrays\n into one big NumPy structured array. Dask is then able to handle this\n object and can split it apart into the separate results on the Dask side,\n which then can be passed back to this function in concatenated chunks for\n further reduction or can be return to the user to perform other forms of\n analysis.\n\n By handling the problem in this way, it does not matter where a chunk\n is in a larger array or how big it is. The chunk can still be computed\n on the same way. Also it does not matter if the chunk is the result of\n other chunks being run through this function multiple times. The end\n result will still be just as accurate using this strategy.\n \"\"\"\n\n return_index = indices is not None\n return_counts = counts is not None\n\n u = np.unique(ar)\n\n dt = [(\"values\", u.dtype)]\n if return_index:\n dt.append((\"indices\", np.intp))\n if return_inverse:\n dt.append((\"inverse\", np.intp))\n if return_counts:\n dt.append((\"counts\", np.intp))\n\n r = np.empty(u.shape, dtype=dt)\n r[\"values\"] = u\n if return_inverse:\n r[\"inverse\"] = np.arange(len(r), dtype=np.intp)\n if return_index or return_counts:\n for i, v in enumerate(r[\"values\"]):\n m = ar == v\n if return_index:\n indices[m].min(keepdims=True, out=r[\"indices\"][i : i + 1])\n if return_counts:\n counts[m].sum(keepdims=True, out=r[\"counts\"][i : i + 1])\n\n return r\n\n\ndef unique_no_structured_arr(\n ar, return_index=False, return_inverse=False, return_counts=False\n):\n # A simplified version of `unique`, that allows computing unique for array\n # types that don't support structured arrays (such as cupy.ndarray), but\n # can only compute values at the moment.\n\n if (\n return_index is not False\n or return_inverse is not False\n or return_counts is not False\n ):\n raise ValueError(\n \"dask.array.unique does not support `return_index`, `return_inverse` \"\n \"or `return_counts` with array types that don't support structured \"\n \"arrays.\"\n )\n\n ar = ar.ravel()\n\n args = [ar, \"i\"]\n meta = meta_from_array(ar)\n\n out = blockwise(np.unique, \"i\", *args, meta=meta)\n out._chunks = tuple((np.nan,) * len(c) for c in out.chunks)\n\n out_parts = [out]\n\n name = \"unique-aggregate-\" + out.name\n dsk = {\n (name, 0): (\n (np.unique,)\n + tuple(\n (np.concatenate, o.__dask_keys__())\n if hasattr(o, \"__dask_keys__\")\n else o\n for o in out_parts\n )\n )\n }\n\n dependencies = [o for o in out_parts if hasattr(o, \"__dask_keys__\")]\n graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)\n chunks = ((np.nan,),)\n out = Array(graph, name, chunks, meta=meta)\n\n result = [out]\n\n if len(result) == 1:\n result = result[0]\n else:\n result = tuple(result)\n\n return result\n\n\n@derived_from(np)\ndef unique(ar, return_index=False, return_inverse=False, return_counts=False):\n # Test whether the downstream library supports structured arrays. If the\n # `np.empty_like` call raises a `TypeError`, the downstream library (e.g.,\n # CuPy) doesn't support it. In that case we return the\n # `unique_no_structured_arr` implementation, otherwise (e.g., NumPy) just\n # continue as normal.\n try:\n meta = meta_from_array(ar)\n np.empty_like(meta, dtype=[(\"a\", int), (\"b\", float)])\n except TypeError:\n return unique_no_structured_arr(\n ar,\n return_index=return_index,\n return_inverse=return_inverse,\n return_counts=return_counts,\n )\n\n ar = ar.ravel()\n\n # Run unique on each chunk and collect results in a Dask Array of\n # unknown size.\n\n args = [ar, \"i\"]\n out_dtype = [(\"values\", ar.dtype)]\n if return_index:\n args.extend([arange(ar.shape[0], dtype=np.intp, chunks=ar.chunks[0]), \"i\"])\n out_dtype.append((\"indices\", np.intp))\n else:\n args.extend([None, None])\n if return_counts:\n args.extend([ones((ar.shape[0],), dtype=np.intp, chunks=ar.chunks[0]), \"i\"])\n out_dtype.append((\"counts\", np.intp))\n else:\n args.extend([None, None])\n\n out = blockwise(_unique_internal, \"i\", *args, dtype=out_dtype, return_inverse=False)\n out._chunks = tuple((np.nan,) * len(c) for c in out.chunks)\n\n # Take the results from the unique chunks and do the following.\n #\n # 1. Collect all results as arguments.\n # 2. Concatenate each result into one big array.\n # 3. Pass all results as arguments to the internal unique again.\n #\n # TODO: This should be replaced with a tree reduction using this strategy.\n # xref: https://github.com/dask/dask/issues/2851\n\n out_parts = [out[\"values\"]]\n if return_index:\n out_parts.append(out[\"indices\"])\n else:\n out_parts.append(None)\n if return_counts:\n out_parts.append(out[\"counts\"])\n else:\n out_parts.append(None)\n\n name = \"unique-aggregate-\" + out.name\n dsk = {\n (name, 0): (\n (_unique_internal,)\n + tuple(\n (np.concatenate, o.__dask_keys__())\n if hasattr(o, \"__dask_keys__\")\n else o\n for o in out_parts\n )\n + (return_inverse,)\n )\n }\n out_dtype = [(\"values\", ar.dtype)]\n if return_index:\n out_dtype.append((\"indices\", np.intp))\n if return_inverse:\n out_dtype.append((\"inverse\", np.intp))\n if return_counts:\n out_dtype.append((\"counts\", np.intp))\n\n dependencies = [o for o in out_parts if hasattr(o, \"__dask_keys__\")]\n graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies)\n chunks = ((np.nan,),)\n out = Array(graph, name, chunks, out_dtype)\n\n # Split out all results to return to the user.\n\n result = [out[\"values\"]]\n if return_index:\n result.append(out[\"indices\"])\n if return_inverse:\n # Using the returned unique values and arange of unknown length, find\n # each value matching a unique value and replace it with its\n # corresponding index or `0`. There should be only one entry for this\n # index in axis `1` (the one of unknown length). Reduce axis `1`\n # through summing to get an array with known dimensionality and the\n # mapping of the original values.\n mtches = (ar[:, None] == out[\"values\"][None, :]).astype(np.intp)\n result.append((mtches * out[\"inverse\"]).sum(axis=1))\n if return_counts:\n result.append(out[\"counts\"])\n\n if len(result) == 1:\n result = result[0]\n else:\n result = tuple(result)\n\n return result\n\n\ndef _isin_kernel(element, test_elements, assume_unique=False):\n values = np.in1d(element.ravel(), test_elements, assume_unique=assume_unique)\n return values.reshape(element.shape + (1,) * test_elements.ndim)\n\n\n@safe_wraps(getattr(np, \"isin\", None))\ndef isin(element, test_elements, assume_unique=False, invert=False):\n element = asarray(element)\n test_elements = asarray(test_elements)\n element_axes = tuple(range(element.ndim))\n test_axes = tuple(i + element.ndim for i in range(test_elements.ndim))\n mapped = blockwise(\n _isin_kernel,\n element_axes + test_axes,\n element,\n element_axes,\n test_elements,\n test_axes,\n adjust_chunks={axis: lambda _: 1 for axis in test_axes},\n dtype=bool,\n assume_unique=assume_unique,\n )\n\n result = mapped.any(axis=test_axes)\n if invert:\n result = ~result\n return result\n\n\n@derived_from(np)\ndef roll(array, shift, axis=None):\n result = array\n\n if axis is None:\n result = ravel(result)\n\n if not isinstance(shift, Integral):\n raise TypeError(\n \"Expect `shift` to be an instance of Integral when `axis` is None.\"\n )\n\n shift = (shift,)\n axis = (0,)\n else:\n try:\n len(shift)\n except TypeError:\n shift = (shift,)\n try:\n len(axis)\n except TypeError:\n axis = (axis,)\n\n if len(shift) != len(axis):\n raise ValueError(\"Must have the same number of shifts as axes.\")\n\n for i, s in zip(axis, shift):\n s = -s\n s %= result.shape[i]\n\n sl1 = result.ndim * [slice(None)]\n sl2 = result.ndim * [slice(None)]\n\n sl1[i] = slice(s, None)\n sl2[i] = slice(None, s)\n\n sl1 = tuple(sl1)\n sl2 = tuple(sl2)\n\n result = concatenate([result[sl1], result[sl2]], axis=i)\n\n result = result.reshape(array.shape)\n # Ensure that the output is always a new array object\n result = result.copy() if result is array else result\n\n return result\n\n\n@derived_from(np)\ndef shape(array):\n return array.shape\n\n\n@derived_from(np)\ndef union1d(ar1, ar2):\n return unique(concatenate((ar1.ravel(), ar2.ravel())))\n\n\n@derived_from(np)\ndef ravel(array_like):\n return asanyarray(array_like).reshape((-1,))\n\n\n@derived_from(np)\ndef expand_dims(a, axis):\n if type(axis) not in (tuple, list):\n axis = (axis,)\n\n out_ndim = len(axis) + a.ndim\n axis = validate_axis(axis, out_ndim)\n\n shape_it = iter(a.shape)\n shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]\n\n return a.reshape(shape)\n\n\n@derived_from(np)\ndef squeeze(a, axis=None):\n if axis is None:\n axis = tuple(i for i, d in enumerate(a.shape) if d == 1)\n elif not isinstance(axis, tuple):\n axis = (axis,)\n\n if any(a.shape[i] != 1 for i in axis):\n raise ValueError(\"cannot squeeze axis with size other than one\")\n\n axis = validate_axis(axis, a.ndim)\n\n sl = tuple(0 if i in axis else slice(None) for i, s in enumerate(a.shape))\n\n a = a[sl]\n\n return a\n\n\n@derived_from(np)\ndef compress(condition, a, axis=None):\n\n if not is_arraylike(condition):\n # Allow `condition` to be anything array-like, otherwise ensure `condition`\n # is a numpy array.\n condition = np.asarray(condition)\n condition = condition.astype(bool)\n a = asarray(a)\n\n if condition.ndim != 1:\n raise ValueError(\"Condition must be one dimensional\")\n\n if axis is None:\n a = a.ravel()\n axis = 0\n axis = validate_axis(axis, a.ndim)\n\n # Treat `condition` as filled with `False` (if it is too short)\n a = a[\n tuple(\n slice(None, len(condition)) if i == axis else slice(None)\n for i in range(a.ndim)\n )\n ]\n\n # Use `condition` to select along 1 dimension\n a = a[tuple(condition if i == axis else slice(None) for i in range(a.ndim))]\n\n return a\n\n\n@derived_from(np)\ndef extract(condition, arr):\n condition = asarray(condition).astype(bool)\n arr = asarray(arr)\n return compress(condition.ravel(), arr.ravel())\n\n\n@derived_from(np)\ndef take(a, indices, axis=0):\n axis = validate_axis(axis, a.ndim)\n\n if isinstance(a, np.ndarray) and isinstance(indices, Array):\n return _take_dask_array_from_numpy(a, indices, axis)\n else:\n return a[(slice(None),) * axis + (indices,)]\n\n\ndef _take_dask_array_from_numpy(a, indices, axis):\n assert isinstance(a, np.ndarray)\n assert isinstance(indices, Array)\n\n return indices.map_blocks(\n lambda block: np.take(a, block, axis), chunks=indices.chunks, dtype=a.dtype\n )\n\n\n@derived_from(np)\ndef around(x, decimals=0):\n return map_blocks(partial(np.around, decimals=decimals), x, dtype=x.dtype)\n\n\ndef _asarray_isnull(values):\n import pandas as pd\n\n return np.asarray(pd.isnull(values))\n\n\ndef isnull(values):\n \"\"\"pandas.isnull for dask arrays\"\"\"\n # eagerly raise ImportError, if pandas isn't available\n import pandas as pd # noqa\n\n return elemwise(_asarray_isnull, values, dtype=\"bool\")\n\n\ndef notnull(values):\n \"\"\"pandas.notnull for dask arrays\"\"\"\n return ~isnull(values)\n\n\n@derived_from(np)\ndef isclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):\n func = partial(np.isclose, rtol=rtol, atol=atol, equal_nan=equal_nan)\n return elemwise(func, arr1, arr2, dtype=\"bool\")\n\n\n@derived_from(np)\ndef allclose(arr1, arr2, rtol=1e-5, atol=1e-8, equal_nan=False):\n return isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=equal_nan).all()\n\n\ndef variadic_choose(a, *choices):\n return np.choose(a, choices)\n\n\n@derived_from(np)\ndef choose(a, choices):\n return elemwise(variadic_choose, a, *choices)\n\n\ndef _isnonzero_vec(v):\n return bool(np.count_nonzero(v))\n\n\n_isnonzero_vec = np.vectorize(_isnonzero_vec, otypes=[bool])\n\n\ndef isnonzero(a):\n if a.dtype.kind in {\"U\", \"S\"}:\n # NumPy treats all-whitespace strings as falsy (like in `np.nonzero`).\n # but not in `.astype(bool)`. To match the behavior of numpy at least until\n # 1.19, we use `_isnonzero_vec`. When NumPy changes behavior, we should just\n # use the try block below.\n # https://github.com/numpy/numpy/issues/9875\n return a.map_blocks(_isnonzero_vec, dtype=bool)\n try:\n np.zeros(tuple(), dtype=a.dtype).astype(bool)\n except ValueError:\n ######################################################\n # Handle special cases where conversion to bool does #\n # not work correctly. #\n # #\n # xref: https://github.com/numpy/numpy/issues/9479 #\n ######################################################\n return a.map_blocks(_isnonzero_vec, dtype=bool)\n else:\n return a.astype(bool)\n\n\n@derived_from(np)\ndef argwhere(a):\n a = asarray(a)\n\n nz = isnonzero(a).flatten()\n\n ind = indices(a.shape, dtype=np.intp, chunks=a.chunks)\n if ind.ndim > 1:\n ind = stack([ind[i].ravel() for i in range(len(ind))], axis=1)\n ind = compress(nz, ind, axis=0)\n\n return ind\n\n\n@derived_from(np)\ndef where(condition, x=None, y=None):\n if (x is None) != (y is None):\n raise ValueError(\"either both or neither of x and y should be given\")\n if (x is None) and (y is None):\n return nonzero(condition)\n\n if np.isscalar(condition):\n dtype = result_type(x, y)\n x = asarray(x)\n y = asarray(y)\n\n shape = broadcast_shapes(x.shape, y.shape)\n out = x if condition else y\n\n return broadcast_to(out, shape).astype(dtype)\n else:\n return elemwise(np.where, condition, x, y)\n\n\n@derived_from(np)\ndef count_nonzero(a, axis=None):\n return isnonzero(asarray(a)).astype(np.intp).sum(axis=axis)\n\n\n@derived_from(np)\ndef flatnonzero(a):\n return argwhere(asarray(a).ravel())[:, 0]\n\n\n@derived_from(np)\ndef nonzero(a):\n ind = argwhere(a)\n if ind.ndim > 1:\n return tuple(ind[:, i] for i in range(ind.shape[1]))\n else:\n return (ind,)\n\n\ndef _unravel_index_kernel(indices, func_kwargs):\n return np.stack(np.unravel_index(indices, **func_kwargs))\n\n\n@derived_from(np)\ndef unravel_index(indices, shape, order=\"C\"):\n if shape and indices.size:\n unraveled_indices = tuple(\n indices.map_blocks(\n _unravel_index_kernel,\n dtype=np.intp,\n chunks=(((len(shape),),) + indices.chunks),\n new_axis=0,\n func_kwargs={\"shape\": shape, \"order\": order},\n )\n )\n else:\n unraveled_indices = tuple(empty((0,), dtype=np.intp, chunks=1) for i in shape)\n\n return unraveled_indices\n\n\n@wraps(np.ravel_multi_index)\ndef ravel_multi_index(multi_index, dims, mode=\"raise\", order=\"C\"):\n if np.isscalar(dims):\n dims = (dims,)\n if is_dask_collection(dims) or any(is_dask_collection(d) for d in dims):\n raise NotImplementedError(\n f\"Dask types are not supported in the `dims` argument: {dims!r}\"\n )\n\n if is_arraylike(multi_index):\n index_stack = asarray(multi_index)\n else:\n multi_index_arrs = broadcast_arrays(*multi_index)\n index_stack = stack(multi_index_arrs)\n\n if not np.isnan(index_stack.shape).any() and len(index_stack) != len(dims):\n raise ValueError(\n f\"parameter multi_index must be a sequence of length {len(dims)}\"\n )\n if not np.issubdtype(index_stack.dtype, np.signedinteger):\n raise TypeError(\"only int indices permitted\")\n return index_stack.map_blocks(\n np.ravel_multi_index,\n dtype=np.intp,\n chunks=index_stack.chunks[1:],\n drop_axis=0,\n dims=dims,\n mode=mode,\n order=order,\n )\n\n\ndef _int_piecewise(x, *condlist, **kwargs):\n return np.piecewise(\n x, list(condlist), kwargs[\"funclist\"], *kwargs[\"func_args\"], **kwargs[\"func_kw\"]\n )\n\n\n@derived_from(np)\ndef piecewise(x, condlist, funclist, *args, **kw):\n return map_blocks(\n _int_piecewise,\n x,\n *condlist,\n dtype=x.dtype,\n name=\"piecewise\",\n funclist=funclist,\n func_args=args,\n func_kw=kw,\n )\n\n\ndef _select(*args, **kwargs):\n \"\"\"\n This is a version of :func:`numpy.select` that acceptes an arbitrary number of arguments and\n splits them in half to create ``condlist`` and ``choicelist`` params.\n \"\"\"\n split_at = len(args) // 2\n condlist = args[:split_at]\n choicelist = args[split_at:]\n return np.select(condlist, choicelist, **kwargs)\n\n\n@derived_from(np)\ndef select(condlist, choicelist, default=0):\n # Making the same checks that np.select\n # Check the size of condlist and choicelist are the same, or abort.\n if len(condlist) != len(choicelist):\n raise ValueError(\"list of cases must be same length as list of conditions\")\n\n if len(condlist) == 0:\n raise ValueError(\"select with an empty condition list is not possible\")\n\n choicelist = [asarray(choice) for choice in choicelist]\n\n try:\n intermediate_dtype = result_type(*choicelist)\n except TypeError as e:\n msg = \"Choicelist elements do not have a common dtype.\"\n raise TypeError(msg) from e\n\n blockwise_shape = tuple(range(choicelist[0].ndim))\n\n condargs = [arg for elem in condlist for arg in (elem, blockwise_shape)]\n choiceargs = [arg for elem in choicelist for arg in (elem, blockwise_shape)]\n\n return blockwise(\n _select,\n blockwise_shape,\n *condargs,\n *choiceargs,\n dtype=intermediate_dtype,\n name=\"select\",\n default=default,\n )\n\n\ndef _partition(total: int, divisor: int) -> tuple[tuple[int, ...], tuple[int, ...]]:\n \"\"\"Given a total and a divisor, return two tuples: A tuple containing `divisor`\n repeated the number of times it divides `total`, and length-1 or empty tuple\n containing the remainder when `total` is divided by `divisor`. If `divisor` factors\n `total`, i.e. if the remainder is 0, then `remainder` is empty.\n \"\"\"\n multiples = (divisor,) * (total // divisor)\n remainder = (total % divisor,) if total % divisor else ()\n return multiples, remainder\n\n\ndef aligned_coarsen_chunks(chunks: list[int], multiple: int) -> tuple[int, ...]:\n \"\"\"\n Returns a new chunking aligned with the coarsening multiple.\n Any excess is at the end of the array.\n\n Examples\n --------\n >>> aligned_coarsen_chunks(chunks=(1, 2, 3), multiple=4)\n (4, 2)\n >>> aligned_coarsen_chunks(chunks=(1, 20, 3, 4), multiple=4)\n (4, 20, 4)\n >>> aligned_coarsen_chunks(chunks=(20, 10, 15, 23, 24), multiple=10)\n (20, 10, 20, 20, 20, 2)\n \"\"\"\n overflow = np.array(chunks) % multiple\n excess = overflow.sum()\n new_chunks = np.array(chunks) - overflow\n # valid chunks are those that are already factorizable by `multiple`\n chunk_validity = new_chunks == chunks\n valid_inds, invalid_inds = np.where(chunk_validity)[0], np.where(~chunk_validity)[0]\n # sort the invalid chunks by size (ascending), then concatenate the results of\n # sorting the valid chunks by size (ascending)\n chunk_modification_order = [\n *invalid_inds[np.argsort(new_chunks[invalid_inds])],\n *valid_inds[np.argsort(new_chunks[valid_inds])],\n ]\n partitioned_excess, remainder = _partition(excess, multiple)\n # add elements the partitioned excess to the smallest invalid chunks,\n # then smallest valid chunks if needed.\n for idx, extra in enumerate(partitioned_excess):\n new_chunks[chunk_modification_order[idx]] += extra\n # create excess chunk with remainder, if any remainder exists\n new_chunks = np.array([*new_chunks, *remainder])\n # remove 0-sized chunks\n new_chunks = new_chunks[new_chunks > 0]\n return tuple(new_chunks)\n\n\n@wraps(chunk.coarsen)\ndef coarsen(reduction, x, axes, trim_excess=False, **kwargs):\n if not trim_excess and not all(x.shape[i] % div == 0 for i, div in axes.items()):\n msg = f\"Coarsening factors {axes} do not align with array shape {x.shape}.\"\n raise ValueError(msg)\n\n if reduction.__module__.startswith(\"dask.\"):\n reduction = getattr(np, reduction.__name__)\n\n new_chunks = {}\n for i, div in axes.items():\n aligned = aligned_coarsen_chunks(x.chunks[i], div)\n if aligned != x.chunks[i]:\n new_chunks[i] = aligned\n if new_chunks:\n x = x.rechunk(new_chunks)\n\n name = \"coarsen-\" + tokenize(reduction, x, axes, trim_excess)\n dsk = {\n (name,)\n + key[1:]: (apply, chunk.coarsen, [reduction, key, axes, trim_excess], kwargs)\n for key in flatten(x.__dask_keys__())\n }\n chunks = tuple(\n tuple(int(bd // axes.get(i, 1)) for bd in bds) for i, bds in enumerate(x.chunks)\n )\n\n meta = reduction(np.empty((1,) * x.ndim, dtype=x.dtype), **kwargs)\n graph = HighLevelGraph.from_collections(name, dsk, dependencies=[x])\n return Array(graph, name, chunks, meta=meta)\n\n\ndef split_at_breaks(array, breaks, axis=0):\n \"\"\"Split an array into a list of arrays (using slices) at the given breaks\n\n >>> split_at_breaks(np.arange(6), [3, 5])\n [array([0, 1, 2]), array([3, 4]), array([5])]\n \"\"\"\n padded_breaks = concat([[None], breaks, [None]])\n slices = [slice(i, j) for i, j in sliding_window(2, padded_breaks)]\n preslice = (slice(None),) * axis\n split_array = [array[preslice + (s,)] for s in slices]\n return split_array\n\n\n@derived_from(np)\ndef insert(arr, obj, values, axis):\n # axis is a required argument here to avoid needing to deal with the numpy\n # default case (which reshapes the array to make it flat)\n axis = validate_axis(axis, arr.ndim)\n\n if isinstance(obj, slice):\n obj = np.arange(*obj.indices(arr.shape[axis]))\n obj = np.asarray(obj)\n scalar_obj = obj.ndim == 0\n if scalar_obj:\n obj = np.atleast_1d(obj)\n\n obj = np.where(obj < 0, obj + arr.shape[axis], obj)\n if (np.diff(obj) < 0).any():\n raise NotImplementedError(\n \"da.insert only implemented for monotonic ``obj`` argument\"\n )\n\n split_arr = split_at_breaks(arr, np.unique(obj), axis)\n\n if getattr(values, \"ndim\", 0) == 0:\n # we need to turn values into a dask array\n name = \"values-\" + tokenize(values)\n dtype = getattr(values, \"dtype\", type(values))\n values = Array({(name,): values}, name, chunks=(), dtype=dtype)\n\n values_shape = tuple(\n len(obj) if axis == n else s for n, s in enumerate(arr.shape)\n )\n values = broadcast_to(values, values_shape)\n elif scalar_obj:\n values = values[(slice(None),) * axis + (None,)]\n\n values_chunks = tuple(\n values_bd if axis == n else arr_bd\n for n, (arr_bd, values_bd) in enumerate(zip(arr.chunks, values.chunks))\n )\n values = values.rechunk(values_chunks)\n\n counts = np.bincount(obj)[:-1]\n values_breaks = np.cumsum(counts[counts > 0])\n split_values = split_at_breaks(values, values_breaks, axis)\n\n interleaved = list(interleave([split_arr, split_values]))\n interleaved = [i for i in interleaved if i.nbytes]\n return concatenate(interleaved, axis=axis)\n\n\n@derived_from(np)\ndef delete(arr, obj, axis):\n \"\"\"\n NOTE: If ``obj`` is a dask array it is implicitly computed when this function\n is called.\n \"\"\"\n # axis is a required argument here to avoid needing to deal with the numpy\n # default case (which reshapes the array to make it flat)\n axis = validate_axis(axis, arr.ndim)\n\n if isinstance(obj, slice):\n tmp = np.arange(*obj.indices(arr.shape[axis]))\n obj = tmp[::-1] if obj.step and obj.step < 0 else tmp\n else:\n obj = np.asarray(obj)\n obj = np.where(obj < 0, obj + arr.shape[axis], obj)\n obj = np.unique(obj)\n\n target_arr = split_at_breaks(arr, obj, axis)\n\n target_arr = [\n arr[\n tuple(slice(1, None) if axis == n else slice(None) for n in range(arr.ndim))\n ]\n if i != 0\n else arr\n for i, arr in enumerate(target_arr)\n ]\n return concatenate(target_arr, axis=axis)\n\n\n@derived_from(np)\ndef append(arr, values, axis=None):\n # based on numpy.append\n arr = asanyarray(arr)\n if axis is None:\n if arr.ndim != 1:\n arr = arr.ravel()\n values = ravel(asanyarray(values))\n axis = arr.ndim - 1\n return concatenate((arr, values), axis=axis)\n\n\ndef _average(a, axis=None, weights=None, returned=False, is_masked=False):\n # This was minimally modified from numpy.average\n # See numpy license at https://github.com/numpy/numpy/blob/master/LICENSE.txt\n # or NUMPY_LICENSE.txt within this directory\n # Wrapper used by da.average or da.ma.average.\n a = asanyarray(a)\n\n if weights is None:\n avg = a.mean(axis)\n scl = avg.dtype.type(a.size / avg.size)\n else:\n wgt = asanyarray(weights)\n\n if issubclass(a.dtype.type, (np.integer, np.bool_)):\n result_dtype = result_type(a.dtype, wgt.dtype, \"f8\")\n else:\n result_dtype = result_type(a.dtype, wgt.dtype)\n\n # Sanity checks\n if a.shape != wgt.shape:\n if axis is None:\n raise TypeError(\n \"Axis must be specified when shapes of a and weights differ.\"\n )\n if wgt.ndim != 1:\n raise TypeError(\n \"1D weights expected when shapes of a and weights differ.\"\n )\n if wgt.shape[0] != a.shape[axis]:\n raise ValueError(\n \"Length of weights not compatible with specified axis.\"\n )\n\n # setup wgt to broadcast along axis\n wgt = broadcast_to(wgt, (a.ndim - 1) * (1,) + wgt.shape)\n wgt = wgt.swapaxes(-1, axis)\n if is_masked:\n from dask.array.ma import getmaskarray\n\n wgt = wgt * (~getmaskarray(a))\n scl = wgt.sum(axis=axis, dtype=result_dtype)\n avg = multiply(a, wgt, dtype=result_dtype).sum(axis) / scl\n\n if returned:\n if scl.shape != avg.shape:\n scl = broadcast_to(scl, avg.shape).copy()\n return avg, scl\n else:\n return avg\n\n\n@derived_from(np)\ndef average(a, axis=None, weights=None, returned=False):\n return _average(a, axis, weights, returned, is_masked=False)\n\n\n@derived_from(np)\ndef tril(m, k=0):\n m = asarray_safe(m, like=m)\n mask = tri(\n *m.shape[-2:],\n k=k,\n dtype=bool,\n chunks=m.chunks[-2:],\n like=meta_from_array(m) if _numpy_120 else None,\n )\n\n return where(mask, m, np.zeros_like(m, shape=(1,)))\n\n\n@derived_from(np)\ndef triu(m, k=0):\n m = asarray_safe(m, like=m)\n mask = tri(\n *m.shape[-2:],\n k=k - 1,\n dtype=bool,\n chunks=m.chunks[-2:],\n like=meta_from_array(m) if _numpy_120 else None,\n )\n\n return where(mask, np.zeros_like(m, shape=(1,)), m)\n\n\n@derived_from(np)\ndef tril_indices(n, k=0, m=None, chunks=\"auto\"):\n return nonzero(tri(n, m, k=k, dtype=bool, chunks=chunks))\n\n\n@derived_from(np)\ndef tril_indices_from(arr, k=0):\n if arr.ndim != 2:\n raise ValueError(\"input array must be 2-d\")\n return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1], chunks=arr.chunks)\n\n\n@derived_from(np)\ndef triu_indices(n, k=0, m=None, chunks=\"auto\"):\n return nonzero(~tri(n, m, k=k - 1, dtype=bool, chunks=chunks))\n\n\n@derived_from(np)\ndef triu_indices_from(arr, k=0):\n if arr.ndim != 2:\n raise ValueError(\"input array must be 2-d\")\n return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1], chunks=arr.chunks)\n" ]
[ [ "numpy.take", "numpy.linspace", "numpy.asarray", "numpy.issubdtype", "numpy.promote_types", "numpy.cumsum", "numpy.zeros_like", "numpy.searchsorted", "numpy.select", "numpy.where", "numpy.histogram", "numpy.unique", "numpy.empty_like", "numpy.atleast_1d", "numpy.apply_along_axis", "numpy.choose", "numpy.diff", "numpy.count_nonzero", "numpy.unravel_index", "numpy.zeros", "numpy.min", "numpy.isnan", "numpy.ndim", "numpy.argsort", "numpy.array", "numpy.absolute", "pandas.isnull", "numpy.gradient", "numpy.histogramdd", "numpy.ones", "numpy.result_type", "numpy.vectorize", "numpy.bincount", "numpy.isscalar", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
mujtahidalam/pandas
[ "526468c8fe6fc5157aaf2fce327c5ab2a3350f49", "ae6538f5df987aa382ec1499679982aaff1bfd86", "526468c8fe6fc5157aaf2fce327c5ab2a3350f49", "526468c8fe6fc5157aaf2fce327c5ab2a3350f49" ]
[ "pandas/tests/indexes/ranges/test_range.py", "pandas/io/sas/sas_xport.py", "pandas/core/arraylike.py", "pandas/tests/extension/json/array.py" ]
[ "import numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import ensure_platform_int\n\nimport pandas as pd\nfrom pandas import (\n Float64Index,\n Index,\n Int64Index,\n RangeIndex,\n)\nimport pandas._testing as tm\nfrom pandas.tests.indexes.test_numeric import Numeric\n\n# aliases to make some tests easier to read\nRI = RangeIndex\nI64 = Int64Index\nF64 = Float64Index\nOI = Index\n\n\nclass TestRangeIndex(Numeric):\n _index_cls = RangeIndex\n\n @pytest.fixture\n def simple_index(self) -> Index:\n return self._index_cls(start=0, stop=20, step=2)\n\n @pytest.fixture(\n params=[\n RangeIndex(start=0, stop=20, step=2, name=\"foo\"),\n RangeIndex(start=18, stop=-1, step=-2, name=\"bar\"),\n ],\n ids=[\"index_inc\", \"index_dec\"],\n )\n def index(self, request):\n return request.param\n\n def test_can_hold_identifiers(self, simple_index):\n idx = simple_index\n key = idx[0]\n assert idx._can_hold_identifiers_and_holds_name(key) is False\n\n def test_too_many_names(self, simple_index):\n index = simple_index\n with pytest.raises(ValueError, match=\"^Length\"):\n index.names = [\"roger\", \"harold\"]\n\n @pytest.mark.parametrize(\n \"index, start, stop, step\",\n [\n (RangeIndex(5), 0, 5, 1),\n (RangeIndex(0, 5), 0, 5, 1),\n (RangeIndex(5, step=2), 0, 5, 2),\n (RangeIndex(1, 5, 2), 1, 5, 2),\n ],\n )\n def test_start_stop_step_attrs(self, index, start, stop, step):\n # GH 25710\n assert index.start == start\n assert index.stop == stop\n assert index.step == step\n\n @pytest.mark.parametrize(\"attr_name\", [\"_start\", \"_stop\", \"_step\"])\n def test_deprecated_start_stop_step_attrs(self, attr_name, simple_index):\n # GH 26581\n idx = simple_index\n with tm.assert_produces_warning(FutureWarning):\n getattr(idx, attr_name)\n\n def test_copy(self):\n i = RangeIndex(5, name=\"Foo\")\n i_copy = i.copy()\n assert i_copy is not i\n assert i_copy.identical(i)\n assert i_copy._range == range(0, 5, 1)\n assert i_copy.name == \"Foo\"\n\n def test_repr(self):\n i = RangeIndex(5, name=\"Foo\")\n result = repr(i)\n expected = \"RangeIndex(start=0, stop=5, step=1, name='Foo')\"\n assert result == expected\n\n result = eval(result)\n tm.assert_index_equal(result, i, exact=True)\n\n i = RangeIndex(5, 0, -1)\n result = repr(i)\n expected = \"RangeIndex(start=5, stop=0, step=-1)\"\n assert result == expected\n\n result = eval(result)\n tm.assert_index_equal(result, i, exact=True)\n\n def test_insert(self):\n\n idx = RangeIndex(5, name=\"Foo\")\n result = idx[1:4]\n\n # test 0th element\n tm.assert_index_equal(idx[0:4], result.insert(0, idx[0]))\n\n # GH 18295 (test missing)\n expected = Float64Index([0, np.nan, 1, 2, 3, 4])\n for na in [np.nan, None, pd.NA]:\n result = RangeIndex(5).insert(1, na)\n tm.assert_index_equal(result, expected)\n\n result = RangeIndex(5).insert(1, pd.NaT)\n expected = Index([0, pd.NaT, 1, 2, 3, 4], dtype=object)\n tm.assert_index_equal(result, expected)\n\n def test_delete(self):\n\n idx = RangeIndex(5, name=\"Foo\")\n expected = idx[1:].astype(int)\n result = idx.delete(0)\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n\n expected = idx[:-1].astype(int)\n result = idx.delete(-1)\n tm.assert_index_equal(result, expected)\n assert result.name == expected.name\n\n msg = \"index 5 is out of bounds for axis 0 with size 5\"\n with pytest.raises((IndexError, ValueError), match=msg):\n # either depending on numpy version\n result = idx.delete(len(idx))\n\n def test_view(self):\n i = RangeIndex(0, name=\"Foo\")\n i_view = i.view()\n assert i_view.name == \"Foo\"\n\n i_view = i.view(\"i8\")\n tm.assert_numpy_array_equal(i.values, i_view)\n\n i_view = i.view(RangeIndex)\n tm.assert_index_equal(i, i_view)\n\n def test_dtype(self, simple_index):\n index = simple_index\n assert index.dtype == np.int64\n\n def test_cache(self):\n # GH 26565, GH26617, GH35432\n # This test checks whether _cache has been set.\n # Calling RangeIndex._cache[\"_data\"] creates an int64 array of the same length\n # as the RangeIndex and stores it in _cache.\n idx = RangeIndex(0, 100, 10)\n\n assert idx._cache == {}\n\n repr(idx)\n assert idx._cache == {}\n\n str(idx)\n assert idx._cache == {}\n\n idx.get_loc(20)\n assert idx._cache == {}\n\n 90 in idx # True\n assert idx._cache == {}\n\n 91 in idx # False\n assert idx._cache == {}\n\n idx.all()\n assert idx._cache == {}\n\n idx.any()\n assert idx._cache == {}\n\n for _ in idx:\n pass\n assert idx._cache == {}\n\n idx.format()\n assert idx._cache == {}\n\n df = pd.DataFrame({\"a\": range(10)}, index=idx)\n\n str(df)\n assert idx._cache == {}\n\n df.loc[50]\n assert idx._cache == {}\n\n with pytest.raises(KeyError, match=\"51\"):\n df.loc[51]\n assert idx._cache == {}\n\n df.loc[10:50]\n assert idx._cache == {}\n\n df.iloc[5:10]\n assert idx._cache == {}\n\n # idx._cache should contain a _data entry after call to idx._data\n idx._data\n assert isinstance(idx._data, np.ndarray)\n assert idx._data is idx._data # check cached value is reused\n assert len(idx._cache) == 1\n expected = np.arange(0, 100, 10, dtype=\"int64\")\n tm.assert_numpy_array_equal(idx._cache[\"_data\"], expected)\n\n def test_is_monotonic(self):\n index = RangeIndex(0, 20, 2)\n assert index.is_monotonic is True\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_decreasing is False\n assert index._is_strictly_monotonic_increasing is True\n assert index._is_strictly_monotonic_decreasing is False\n\n index = RangeIndex(4, 0, -1)\n assert index.is_monotonic is False\n assert index._is_strictly_monotonic_increasing is False\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_decreasing is True\n\n index = RangeIndex(1, 2)\n assert index.is_monotonic is True\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index._is_strictly_monotonic_decreasing is True\n\n index = RangeIndex(2, 1)\n assert index.is_monotonic is True\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index._is_strictly_monotonic_decreasing is True\n\n index = RangeIndex(1, 1)\n assert index.is_monotonic is True\n assert index.is_monotonic_increasing is True\n assert index.is_monotonic_decreasing is True\n assert index._is_strictly_monotonic_increasing is True\n assert index._is_strictly_monotonic_decreasing is True\n\n def test_equals_range(self):\n equiv_pairs = [\n (RangeIndex(0, 9, 2), RangeIndex(0, 10, 2)),\n (RangeIndex(0), RangeIndex(1, -1, 3)),\n (RangeIndex(1, 2, 3), RangeIndex(1, 3, 4)),\n (RangeIndex(0, -9, -2), RangeIndex(0, -10, -2)),\n ]\n for left, right in equiv_pairs:\n assert left.equals(right)\n assert right.equals(left)\n\n def test_logical_compat(self, simple_index):\n idx = simple_index\n assert idx.all() == idx.values.all()\n assert idx.any() == idx.values.any()\n\n def test_identical(self, simple_index):\n index = simple_index\n i = Index(index.copy())\n assert i.identical(index)\n\n # we don't allow object dtype for RangeIndex\n if isinstance(index, RangeIndex):\n return\n\n same_values_different_type = Index(i, dtype=object)\n assert not i.identical(same_values_different_type)\n\n i = index.copy(dtype=object)\n i = i.rename(\"foo\")\n same_values = Index(i, dtype=object)\n assert same_values.identical(index.copy(dtype=object))\n\n assert not i.identical(index)\n assert Index(same_values, name=\"foo\", dtype=object).identical(i)\n\n assert not index.copy(dtype=object).identical(index.copy(dtype=\"int64\"))\n\n def test_nbytes(self):\n\n # memory savings vs int index\n i = RangeIndex(0, 1000)\n assert i.nbytes < i._int64index.nbytes / 10\n\n # constant memory usage\n i2 = RangeIndex(0, 10)\n assert i.nbytes == i2.nbytes\n\n @pytest.mark.parametrize(\n \"start,stop,step\",\n [\n # can't\n (\"foo\", \"bar\", \"baz\"),\n # shouldn't\n (\"0\", \"1\", \"2\"),\n ],\n )\n def test_cant_or_shouldnt_cast(self, start, stop, step):\n msg = f\"Wrong type {type(start)} for value {start}\"\n with pytest.raises(TypeError, match=msg):\n RangeIndex(start, stop, step)\n\n def test_view_index(self, simple_index):\n index = simple_index\n index.view(Index)\n\n def test_prevent_casting(self, simple_index):\n index = simple_index\n result = index.astype(\"O\")\n assert result.dtype == np.object_\n\n def test_repr_roundtrip(self, simple_index):\n index = simple_index\n tm.assert_index_equal(eval(repr(index)), index)\n\n def test_slice_keep_name(self):\n idx = RangeIndex(1, 2, name=\"asdf\")\n assert idx.name == idx[1:].name\n\n def test_has_duplicates(self, index):\n assert index.is_unique\n assert not index.has_duplicates\n\n def test_extended_gcd(self, simple_index):\n index = simple_index\n result = index._extended_gcd(6, 10)\n assert result[0] == result[1] * 6 + result[2] * 10\n assert 2 == result[0]\n\n result = index._extended_gcd(10, 6)\n assert 2 == result[1] * 10 + result[2] * 6\n assert 2 == result[0]\n\n def test_min_fitting_element(self):\n result = RangeIndex(0, 20, 2)._min_fitting_element(1)\n assert 2 == result\n\n result = RangeIndex(1, 6)._min_fitting_element(1)\n assert 1 == result\n\n result = RangeIndex(18, -2, -2)._min_fitting_element(1)\n assert 2 == result\n\n result = RangeIndex(5, 0, -1)._min_fitting_element(1)\n assert 1 == result\n\n big_num = 500000000000000000000000\n\n result = RangeIndex(5, big_num * 2, 1)._min_fitting_element(big_num)\n assert big_num == result\n\n def test_max_fitting_element(self):\n result = RangeIndex(0, 20, 2)._max_fitting_element(17)\n assert 16 == result\n\n result = RangeIndex(1, 6)._max_fitting_element(4)\n assert 4 == result\n\n result = RangeIndex(18, -2, -2)._max_fitting_element(17)\n assert 16 == result\n\n result = RangeIndex(5, 0, -1)._max_fitting_element(4)\n assert 4 == result\n\n big_num = 500000000000000000000000\n\n result = RangeIndex(5, big_num * 2, 1)._max_fitting_element(big_num)\n assert big_num == result\n\n def test_pickle_compat_construction(self):\n # RangeIndex() is a valid constructor\n pass\n\n def test_slice_specialised(self, simple_index):\n index = simple_index\n index.name = \"foo\"\n\n # scalar indexing\n res = index[1]\n expected = 2\n assert res == expected\n\n res = index[-1]\n expected = 18\n assert res == expected\n\n # slicing\n # slice value completion\n index_slice = index[:]\n expected = index\n tm.assert_index_equal(index_slice, expected)\n\n # positive slice values\n index_slice = index[7:10:2]\n expected = Index(np.array([14, 18]), name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n # negative slice values\n index_slice = index[-1:-5:-2]\n expected = Index(np.array([18, 14]), name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n # stop overshoot\n index_slice = index[2:100:4]\n expected = Index(np.array([4, 12]), name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n # reverse\n index_slice = index[::-1]\n expected = Index(index.values[::-1], name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n index_slice = index[-8::-1]\n expected = Index(np.array([4, 2, 0]), name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n index_slice = index[-40::-1]\n expected = Index(np.array([], dtype=np.int64), name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n index_slice = index[40::-1]\n expected = Index(index.values[40::-1], name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n index_slice = index[10::-1]\n expected = Index(index.values[::-1], name=\"foo\")\n tm.assert_index_equal(index_slice, expected)\n\n @pytest.mark.parametrize(\"step\", set(range(-5, 6)) - {0})\n def test_len_specialised(self, step):\n # make sure that our len is the same as np.arange calc\n start, stop = (0, 5) if step > 0 else (5, 0)\n\n arr = np.arange(start, stop, step)\n index = RangeIndex(start, stop, step)\n assert len(index) == len(arr)\n\n index = RangeIndex(stop, start, step)\n assert len(index) == 0\n\n @pytest.fixture(\n params=[\n ([RI(1, 12, 5)], RI(1, 12, 5)),\n ([RI(0, 6, 4)], RI(0, 6, 4)),\n ([RI(1, 3), RI(3, 7)], RI(1, 7)),\n ([RI(1, 5, 2), RI(5, 6)], RI(1, 6, 2)),\n ([RI(1, 3, 2), RI(4, 7, 3)], RI(1, 7, 3)),\n ([RI(-4, 3, 2), RI(4, 7, 2)], RI(-4, 7, 2)),\n ([RI(-4, -8), RI(-8, -12)], RI(0, 0)),\n ([RI(-4, -8), RI(3, -4)], RI(0, 0)),\n ([RI(-4, -8), RI(3, 5)], RI(3, 5)),\n ([RI(-4, -2), RI(3, 5)], I64([-4, -3, 3, 4])),\n ([RI(-2), RI(3, 5)], RI(3, 5)),\n ([RI(2), RI(2)], I64([0, 1, 0, 1])),\n ([RI(2), RI(2, 5), RI(5, 8, 4)], RI(0, 6)),\n ([RI(2), RI(3, 5), RI(5, 8, 4)], I64([0, 1, 3, 4, 5])),\n ([RI(-2, 2), RI(2, 5), RI(5, 8, 4)], RI(-2, 6)),\n ([RI(3), I64([-1, 3, 15])], I64([0, 1, 2, -1, 3, 15])),\n ([RI(3), F64([-1, 3.1, 15.0])], F64([0, 1, 2, -1, 3.1, 15.0])),\n ([RI(3), OI([\"a\", None, 14])], OI([0, 1, 2, \"a\", None, 14])),\n ([RI(3, 1), OI([\"a\", None, 14])], OI([\"a\", None, 14])),\n ]\n )\n def appends(self, request):\n \"\"\"Inputs and expected outputs for RangeIndex.append test\"\"\"\n return request.param\n\n def test_append(self, appends):\n # GH16212\n\n indices, expected = appends\n\n result = indices[0].append(indices[1:])\n tm.assert_index_equal(result, expected, exact=True)\n\n if len(indices) == 2:\n # Append single item rather than list\n result2 = indices[0].append(indices[1])\n tm.assert_index_equal(result2, expected, exact=True)\n\n def test_engineless_lookup(self):\n # GH 16685\n # Standard lookup on RangeIndex should not require the engine to be\n # created\n idx = RangeIndex(2, 10, 3)\n\n assert idx.get_loc(5) == 1\n tm.assert_numpy_array_equal(\n idx.get_indexer([2, 8]), ensure_platform_int(np.array([0, 2]))\n )\n with pytest.raises(KeyError, match=\"3\"):\n idx.get_loc(3)\n\n assert \"_engine\" not in idx._cache\n\n # Different types of scalars can be excluded immediately, no need to\n # use the _engine\n with pytest.raises(KeyError, match=\"'a'\"):\n idx.get_loc(\"a\")\n\n assert \"_engine\" not in idx._cache\n\n def test_format_empty(self):\n # GH35712\n empty_idx = self._index_cls(0)\n assert empty_idx.format() == []\n assert empty_idx.format(name=True) == [\"\"]\n\n @pytest.mark.parametrize(\n \"RI\",\n [\n RangeIndex(0, -1, -1),\n RangeIndex(0, 1, 1),\n RangeIndex(1, 3, 2),\n RangeIndex(0, -1, -2),\n RangeIndex(-3, -5, -2),\n ],\n )\n def test_append_len_one(self, RI):\n # GH39401\n result = RI.append([])\n tm.assert_index_equal(result, RI, exact=True)\n\n @pytest.mark.parametrize(\"base\", [RangeIndex(0, 2), Index([0, 1])])\n def test_isin_range(self, base):\n # GH#41151\n values = RangeIndex(0, 1)\n result = base.isin(values)\n expected = np.array([True, False])\n tm.assert_numpy_array_equal(result, expected)\n", "\"\"\"\nRead a SAS XPort format file into a Pandas DataFrame.\n\nBased on code from Jack Cushman (github.com/jcushman/xport).\n\nThe file format is defined here:\n\nhttps://support.sas.com/techsup/technote/ts140.pdf\n\"\"\"\nfrom collections import abc\nfrom datetime import datetime\nimport struct\nfrom typing import (\n IO,\n cast,\n)\nimport warnings\n\nimport numpy as np\n\nfrom pandas.util._decorators import Appender\n\nimport pandas as pd\n\nfrom pandas.io.common import get_handle\nfrom pandas.io.sas.sasreader import ReaderBase\n\n_correct_line1 = (\n \"HEADER RECORD*******LIBRARY HEADER RECORD!!!!!!!\"\n \"000000000000000000000000000000 \"\n)\n_correct_header1 = (\n \"HEADER RECORD*******MEMBER HEADER RECORD!!!!!!!000000000000000001600000000\"\n)\n_correct_header2 = (\n \"HEADER RECORD*******DSCRPTR HEADER RECORD!!!!!!!\"\n \"000000000000000000000000000000 \"\n)\n_correct_obs_header = (\n \"HEADER RECORD*******OBS HEADER RECORD!!!!!!!\"\n \"000000000000000000000000000000 \"\n)\n_fieldkeys = [\n \"ntype\",\n \"nhfun\",\n \"field_length\",\n \"nvar0\",\n \"name\",\n \"label\",\n \"nform\",\n \"nfl\",\n \"num_decimals\",\n \"nfj\",\n \"nfill\",\n \"niform\",\n \"nifl\",\n \"nifd\",\n \"npos\",\n \"_\",\n]\n\n\n_base_params_doc = \"\"\"\\\nParameters\n----------\nfilepath_or_buffer : str or file-like object\n Path to SAS file or object implementing binary read method.\"\"\"\n\n_params2_doc = \"\"\"\\\nindex : identifier of index column\n Identifier of column that should be used as index of the DataFrame.\nencoding : str\n Encoding for text data.\nchunksize : int\n Read file `chunksize` lines at a time, returns iterator.\"\"\"\n\n_format_params_doc = \"\"\"\\\nformat : str\n File format, only `xport` is currently supported.\"\"\"\n\n_iterator_doc = \"\"\"\\\niterator : bool, default False\n Return XportReader object for reading file incrementally.\"\"\"\n\n\n_read_sas_doc = f\"\"\"Read a SAS file into a DataFrame.\n\n{_base_params_doc}\n{_format_params_doc}\n{_params2_doc}\n{_iterator_doc}\n\nReturns\n-------\nDataFrame or XportReader\n\nExamples\n--------\nRead a SAS Xport file:\n\n>>> df = pd.read_sas('filename.XPT')\n\nRead a Xport file in 10,000 line chunks:\n\n>>> itr = pd.read_sas('filename.XPT', chunksize=10000)\n>>> for chunk in itr:\n>>> do_something(chunk)\n\n\"\"\"\n\n_xport_reader_doc = f\"\"\"\\\nClass for reading SAS Xport files.\n\n{_base_params_doc}\n{_params2_doc}\n\nAttributes\n----------\nmember_info : list\n Contains information about the file\nfields : list\n Contains information about the variables in the file\n\"\"\"\n\n_read_method_doc = \"\"\"\\\nRead observations from SAS Xport file, returning as data frame.\n\nParameters\n----------\nnrows : int\n Number of rows to read from data file; if None, read whole\n file.\n\nReturns\n-------\nA DataFrame.\n\"\"\"\n\n\ndef _parse_date(datestr: str) -> datetime:\n \"\"\" Given a date in xport format, return Python date. \"\"\"\n try:\n # e.g. \"16FEB11:10:07:55\"\n return datetime.strptime(datestr, \"%d%b%y:%H:%M:%S\")\n except ValueError:\n return pd.NaT\n\n\ndef _split_line(s: str, parts):\n \"\"\"\n Parameters\n ----------\n s: str\n Fixed-length string to split\n parts: list of (name, length) pairs\n Used to break up string, name '_' will be filtered from output.\n\n Returns\n -------\n Dict of name:contents of string at given location.\n \"\"\"\n out = {}\n start = 0\n for name, length in parts:\n out[name] = s[start : start + length].strip()\n start += length\n del out[\"_\"]\n return out\n\n\ndef _handle_truncated_float_vec(vec, nbytes):\n # This feature is not well documented, but some SAS XPORT files\n # have 2-7 byte \"truncated\" floats. To read these truncated\n # floats, pad them with zeros on the right to make 8 byte floats.\n #\n # References:\n # https://github.com/jcushman/xport/pull/3\n # The R \"foreign\" library\n\n if nbytes != 8:\n vec1 = np.zeros(len(vec), np.dtype(\"S8\"))\n dtype = np.dtype(f\"S{nbytes},S{8 - nbytes}\")\n vec2 = vec1.view(dtype=dtype)\n vec2[\"f0\"] = vec\n return vec2\n\n return vec\n\n\ndef _parse_float_vec(vec):\n \"\"\"\n Parse a vector of float values representing IBM 8 byte floats into\n native 8 byte floats.\n \"\"\"\n dtype = np.dtype(\">u4,>u4\")\n vec1 = vec.view(dtype=dtype)\n xport1 = vec1[\"f0\"]\n xport2 = vec1[\"f1\"]\n\n # Start by setting first half of ieee number to first half of IBM\n # number sans exponent\n ieee1 = xport1 & 0x00FFFFFF\n\n # The fraction bit to the left of the binary point in the ieee\n # format was set and the number was shifted 0, 1, 2, or 3\n # places. This will tell us how to adjust the ibm exponent to be a\n # power of 2 ieee exponent and how to shift the fraction bits to\n # restore the correct magnitude.\n shift = np.zeros(len(vec), dtype=np.uint8)\n shift[np.where(xport1 & 0x00200000)] = 1\n shift[np.where(xport1 & 0x00400000)] = 2\n shift[np.where(xport1 & 0x00800000)] = 3\n\n # shift the ieee number down the correct number of places then\n # set the second half of the ieee number to be the second half\n # of the ibm number shifted appropriately, ored with the bits\n # from the first half that would have been shifted in if we\n # could shift a double. All we are worried about are the low\n # order 3 bits of the first half since we're only shifting by\n # 1, 2, or 3.\n ieee1 >>= shift\n ieee2 = (xport2 >> shift) | ((xport1 & 0x00000007) << (29 + (3 - shift)))\n\n # clear the 1 bit to the left of the binary point\n ieee1 &= 0xFFEFFFFF\n\n # set the exponent of the ieee number to be the actual exponent\n # plus the shift count + 1023. Or this into the first half of the\n # ieee number. The ibm exponent is excess 64 but is adjusted by 65\n # since during conversion to ibm format the exponent is\n # incremented by 1 and the fraction bits left 4 positions to the\n # right of the radix point. (had to add >> 24 because C treats &\n # 0x7f as 0x7f000000 and Python doesn't)\n ieee1 |= ((((((xport1 >> 24) & 0x7F) - 65) << 2) + shift + 1023) << 20) | (\n xport1 & 0x80000000\n )\n\n ieee = np.empty((len(ieee1),), dtype=\">u4,>u4\")\n ieee[\"f0\"] = ieee1\n ieee[\"f1\"] = ieee2\n ieee = ieee.view(dtype=\">f8\")\n ieee = ieee.astype(\"f8\")\n\n return ieee\n\n\nclass XportReader(ReaderBase, abc.Iterator):\n __doc__ = _xport_reader_doc\n\n def __init__(\n self, filepath_or_buffer, index=None, encoding=\"ISO-8859-1\", chunksize=None\n ):\n\n self._encoding = encoding\n self._lines_read = 0\n self._index = index\n self._chunksize = chunksize\n\n self.handles = get_handle(\n filepath_or_buffer, \"rb\", encoding=encoding, is_text=False\n )\n self.filepath_or_buffer = cast(IO[bytes], self.handles.handle)\n\n try:\n self._read_header()\n except Exception:\n self.close()\n raise\n\n def close(self):\n self.handles.close()\n\n def _get_row(self):\n return self.filepath_or_buffer.read(80).decode()\n\n def _read_header(self):\n self.filepath_or_buffer.seek(0)\n\n # read file header\n line1 = self._get_row()\n if line1 != _correct_line1:\n raise ValueError(\"Header record is not an XPORT file.\")\n\n line2 = self._get_row()\n fif = [[\"prefix\", 24], [\"version\", 8], [\"OS\", 8], [\"_\", 24], [\"created\", 16]]\n file_info = _split_line(line2, fif)\n if file_info[\"prefix\"] != \"SAS SAS SASLIB\":\n raise ValueError(\"Header record has invalid prefix.\")\n file_info[\"created\"] = _parse_date(file_info[\"created\"])\n self.file_info = file_info\n\n line3 = self._get_row()\n file_info[\"modified\"] = _parse_date(line3[:16])\n\n # read member header\n header1 = self._get_row()\n header2 = self._get_row()\n headflag1 = header1.startswith(_correct_header1)\n headflag2 = header2 == _correct_header2\n if not (headflag1 and headflag2):\n raise ValueError(\"Member header not found\")\n # usually 140, could be 135\n fieldnamelength = int(header1[-5:-2])\n\n # member info\n mem = [\n [\"prefix\", 8],\n [\"set_name\", 8],\n [\"sasdata\", 8],\n [\"version\", 8],\n [\"OS\", 8],\n [\"_\", 24],\n [\"created\", 16],\n ]\n member_info = _split_line(self._get_row(), mem)\n mem = [[\"modified\", 16], [\"_\", 16], [\"label\", 40], [\"type\", 8]]\n member_info.update(_split_line(self._get_row(), mem))\n member_info[\"modified\"] = _parse_date(member_info[\"modified\"])\n member_info[\"created\"] = _parse_date(member_info[\"created\"])\n self.member_info = member_info\n\n # read field names\n types = {1: \"numeric\", 2: \"char\"}\n fieldcount = int(self._get_row()[54:58])\n datalength = fieldnamelength * fieldcount\n # round up to nearest 80\n if datalength % 80:\n datalength += 80 - datalength % 80\n fielddata = self.filepath_or_buffer.read(datalength)\n fields = []\n obs_length = 0\n while len(fielddata) >= fieldnamelength:\n # pull data for one field\n fieldbytes, fielddata = (\n fielddata[:fieldnamelength],\n fielddata[fieldnamelength:],\n )\n\n # rest at end gets ignored, so if field is short, pad out\n # to match struct pattern below\n fieldbytes = fieldbytes.ljust(140)\n\n fieldstruct = struct.unpack(\">hhhh8s40s8shhh2s8shhl52s\", fieldbytes)\n field = dict(zip(_fieldkeys, fieldstruct))\n del field[\"_\"]\n field[\"ntype\"] = types[field[\"ntype\"]]\n fl = field[\"field_length\"]\n if field[\"ntype\"] == \"numeric\" and ((fl < 2) or (fl > 8)):\n msg = f\"Floating field width {fl} is not between 2 and 8.\"\n raise TypeError(msg)\n\n for k, v in field.items():\n try:\n field[k] = v.strip()\n except AttributeError:\n pass\n\n obs_length += field[\"field_length\"]\n fields += [field]\n\n header = self._get_row()\n if not header == _correct_obs_header:\n raise ValueError(\"Observation header not found.\")\n\n self.fields = fields\n self.record_length = obs_length\n self.record_start = self.filepath_or_buffer.tell()\n\n self.nobs = self._record_count()\n self.columns = [x[\"name\"].decode() for x in self.fields]\n\n # Setup the dtype.\n dtypel = [\n (\"s\" + str(i), \"S\" + str(field[\"field_length\"]))\n for i, field in enumerate(self.fields)\n ]\n dtype = np.dtype(dtypel)\n self._dtype = dtype\n\n def __next__(self):\n return self.read(nrows=self._chunksize or 1)\n\n def _record_count(self) -> int:\n \"\"\"\n Get number of records in file.\n\n This is maybe suboptimal because we have to seek to the end of\n the file.\n\n Side effect: returns file position to record_start.\n \"\"\"\n self.filepath_or_buffer.seek(0, 2)\n total_records_length = self.filepath_or_buffer.tell() - self.record_start\n\n if total_records_length % 80 != 0:\n warnings.warn(\"xport file may be corrupted\")\n\n if self.record_length > 80:\n self.filepath_or_buffer.seek(self.record_start)\n return total_records_length // self.record_length\n\n self.filepath_or_buffer.seek(-80, 2)\n last_card_bytes = self.filepath_or_buffer.read(80)\n last_card = np.frombuffer(last_card_bytes, dtype=np.uint64)\n\n # 8 byte blank\n ix = np.flatnonzero(last_card == 2314885530818453536)\n\n if len(ix) == 0:\n tail_pad = 0\n else:\n tail_pad = 8 * len(ix)\n\n self.filepath_or_buffer.seek(self.record_start)\n\n return (total_records_length - tail_pad) // self.record_length\n\n def get_chunk(self, size=None):\n \"\"\"\n Reads lines from Xport file and returns as dataframe\n\n Parameters\n ----------\n size : int, defaults to None\n Number of lines to read. If None, reads whole file.\n\n Returns\n -------\n DataFrame\n \"\"\"\n if size is None:\n size = self._chunksize\n return self.read(nrows=size)\n\n def _missing_double(self, vec):\n v = vec.view(dtype=\"u1,u1,u2,u4\")\n miss = (v[\"f1\"] == 0) & (v[\"f2\"] == 0) & (v[\"f3\"] == 0)\n miss1 = (\n ((v[\"f0\"] >= 0x41) & (v[\"f0\"] <= 0x5A))\n | (v[\"f0\"] == 0x5F)\n | (v[\"f0\"] == 0x2E)\n )\n miss &= miss1\n return miss\n\n @Appender(_read_method_doc)\n def read(self, nrows=None):\n\n if nrows is None:\n nrows = self.nobs\n\n read_lines = min(nrows, self.nobs - self._lines_read)\n read_len = read_lines * self.record_length\n if read_len <= 0:\n self.close()\n raise StopIteration\n raw = self.filepath_or_buffer.read(read_len)\n data = np.frombuffer(raw, dtype=self._dtype, count=read_lines)\n\n df = pd.DataFrame(index=range(read_lines))\n for j, x in enumerate(self.columns):\n vec = data[\"s\" + str(j)]\n ntype = self.fields[j][\"ntype\"]\n if ntype == \"numeric\":\n vec = _handle_truncated_float_vec(vec, self.fields[j][\"field_length\"])\n miss = self._missing_double(vec)\n v = _parse_float_vec(vec)\n v[miss] = np.nan\n elif self.fields[j][\"ntype\"] == \"char\":\n v = [y.rstrip() for y in vec]\n\n if self._encoding is not None:\n v = [y.decode(self._encoding) for y in v]\n\n df[x] = v\n\n if self._index is None:\n df.index = pd.Index(range(self._lines_read, self._lines_read + read_lines))\n else:\n df = df.set_index(self._index)\n\n self._lines_read += read_lines\n\n return df\n", "\"\"\"\nMethods that can be shared by many array-like classes or subclasses:\n Series\n Index\n ExtensionArray\n\"\"\"\nimport operator\nfrom typing import Any\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import lib\n\nfrom pandas.core.construction import extract_array\nfrom pandas.core.ops import (\n maybe_dispatch_ufunc_to_dunder_op,\n roperator,\n)\nfrom pandas.core.ops.common import unpack_zerodim_and_defer\n\n\nclass OpsMixin:\n # -------------------------------------------------------------\n # Comparisons\n\n def _cmp_method(self, other, op):\n return NotImplemented\n\n @unpack_zerodim_and_defer(\"__eq__\")\n def __eq__(self, other):\n return self._cmp_method(other, operator.eq)\n\n @unpack_zerodim_and_defer(\"__ne__\")\n def __ne__(self, other):\n return self._cmp_method(other, operator.ne)\n\n @unpack_zerodim_and_defer(\"__lt__\")\n def __lt__(self, other):\n return self._cmp_method(other, operator.lt)\n\n @unpack_zerodim_and_defer(\"__le__\")\n def __le__(self, other):\n return self._cmp_method(other, operator.le)\n\n @unpack_zerodim_and_defer(\"__gt__\")\n def __gt__(self, other):\n return self._cmp_method(other, operator.gt)\n\n @unpack_zerodim_and_defer(\"__ge__\")\n def __ge__(self, other):\n return self._cmp_method(other, operator.ge)\n\n # -------------------------------------------------------------\n # Logical Methods\n\n def _logical_method(self, other, op):\n return NotImplemented\n\n @unpack_zerodim_and_defer(\"__and__\")\n def __and__(self, other):\n return self._logical_method(other, operator.and_)\n\n @unpack_zerodim_and_defer(\"__rand__\")\n def __rand__(self, other):\n return self._logical_method(other, roperator.rand_)\n\n @unpack_zerodim_and_defer(\"__or__\")\n def __or__(self, other):\n return self._logical_method(other, operator.or_)\n\n @unpack_zerodim_and_defer(\"__ror__\")\n def __ror__(self, other):\n return self._logical_method(other, roperator.ror_)\n\n @unpack_zerodim_and_defer(\"__xor__\")\n def __xor__(self, other):\n return self._logical_method(other, operator.xor)\n\n @unpack_zerodim_and_defer(\"__rxor__\")\n def __rxor__(self, other):\n return self._logical_method(other, roperator.rxor)\n\n # -------------------------------------------------------------\n # Arithmetic Methods\n\n def _arith_method(self, other, op):\n return NotImplemented\n\n @unpack_zerodim_and_defer(\"__add__\")\n def __add__(self, other):\n return self._arith_method(other, operator.add)\n\n @unpack_zerodim_and_defer(\"__radd__\")\n def __radd__(self, other):\n return self._arith_method(other, roperator.radd)\n\n @unpack_zerodim_and_defer(\"__sub__\")\n def __sub__(self, other):\n return self._arith_method(other, operator.sub)\n\n @unpack_zerodim_and_defer(\"__rsub__\")\n def __rsub__(self, other):\n return self._arith_method(other, roperator.rsub)\n\n @unpack_zerodim_and_defer(\"__mul__\")\n def __mul__(self, other):\n return self._arith_method(other, operator.mul)\n\n @unpack_zerodim_and_defer(\"__rmul__\")\n def __rmul__(self, other):\n return self._arith_method(other, roperator.rmul)\n\n @unpack_zerodim_and_defer(\"__truediv__\")\n def __truediv__(self, other):\n return self._arith_method(other, operator.truediv)\n\n @unpack_zerodim_and_defer(\"__rtruediv__\")\n def __rtruediv__(self, other):\n return self._arith_method(other, roperator.rtruediv)\n\n @unpack_zerodim_and_defer(\"__floordiv__\")\n def __floordiv__(self, other):\n return self._arith_method(other, operator.floordiv)\n\n @unpack_zerodim_and_defer(\"__rfloordiv\")\n def __rfloordiv__(self, other):\n return self._arith_method(other, roperator.rfloordiv)\n\n @unpack_zerodim_and_defer(\"__mod__\")\n def __mod__(self, other):\n return self._arith_method(other, operator.mod)\n\n @unpack_zerodim_and_defer(\"__rmod__\")\n def __rmod__(self, other):\n return self._arith_method(other, roperator.rmod)\n\n @unpack_zerodim_and_defer(\"__divmod__\")\n def __divmod__(self, other):\n return self._arith_method(other, divmod)\n\n @unpack_zerodim_and_defer(\"__rdivmod__\")\n def __rdivmod__(self, other):\n return self._arith_method(other, roperator.rdivmod)\n\n @unpack_zerodim_and_defer(\"__pow__\")\n def __pow__(self, other):\n return self._arith_method(other, operator.pow)\n\n @unpack_zerodim_and_defer(\"__rpow__\")\n def __rpow__(self, other):\n return self._arith_method(other, roperator.rpow)\n\n\n# -----------------------------------------------------------------------------\n# Helpers to implement __array_ufunc__\n\n\ndef _is_aligned(frame, other):\n \"\"\"\n Helper to check if a DataFrame is aligned with another DataFrame or Series.\n \"\"\"\n from pandas import DataFrame\n\n if isinstance(other, DataFrame):\n return frame._indexed_same(other)\n else:\n # Series -> match index\n return frame.columns.equals(other.index)\n\n\ndef _maybe_fallback(ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any):\n \"\"\"\n In the future DataFrame, inputs to ufuncs will be aligned before applying\n the ufunc, but for now we ignore the index but raise a warning if behaviour\n would change in the future.\n This helper detects the case where a warning is needed and then fallbacks\n to applying the ufunc on arrays to avoid alignment.\n\n See https://github.com/pandas-dev/pandas/pull/39239\n \"\"\"\n from pandas import DataFrame\n from pandas.core.generic import NDFrame\n\n n_alignable = sum(isinstance(x, NDFrame) for x in inputs)\n n_frames = sum(isinstance(x, DataFrame) for x in inputs)\n\n if n_alignable >= 2 and n_frames >= 1:\n # if there are 2 alignable inputs (Series or DataFrame), of which at least 1\n # is a DataFrame -> we would have had no alignment before -> warn that this\n # will align in the future\n\n # the first frame is what determines the output index/columns in pandas < 1.2\n first_frame = next(x for x in inputs if isinstance(x, DataFrame))\n\n # check if the objects are aligned or not\n non_aligned = sum(\n not _is_aligned(first_frame, x) for x in inputs if isinstance(x, NDFrame)\n )\n\n # if at least one is not aligned -> warn and fallback to array behaviour\n if non_aligned:\n warnings.warn(\n \"Calling a ufunc on non-aligned DataFrames (or DataFrame/Series \"\n \"combination). Currently, the indices are ignored and the result \"\n \"takes the index/columns of the first DataFrame. In the future , \"\n \"the DataFrames/Series will be aligned before applying the ufunc.\\n\"\n \"Convert one of the arguments to a NumPy array \"\n \"(eg 'ufunc(df1, np.asarray(df2)') to keep the current behaviour, \"\n \"or align manually (eg 'df1, df2 = df1.align(df2)') before passing to \"\n \"the ufunc to obtain the future behaviour and silence this warning.\",\n FutureWarning,\n stacklevel=4,\n )\n\n # keep the first dataframe of the inputs, other DataFrame/Series is\n # converted to array for fallback behaviour\n new_inputs = []\n for x in inputs:\n if x is first_frame:\n new_inputs.append(x)\n elif isinstance(x, NDFrame):\n new_inputs.append(np.asarray(x))\n else:\n new_inputs.append(x)\n\n # call the ufunc on those transformed inputs\n return getattr(ufunc, method)(*new_inputs, **kwargs)\n\n # signal that we didn't fallback / execute the ufunc yet\n return NotImplemented\n\n\ndef array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any):\n \"\"\"\n Compatibility with numpy ufuncs.\n\n See also\n --------\n numpy.org/doc/stable/reference/arrays.classes.html#numpy.class.__array_ufunc__\n \"\"\"\n from pandas.core.generic import NDFrame\n from pandas.core.internals import BlockManager\n\n cls = type(self)\n\n # for backwards compatibility check and potentially fallback for non-aligned frames\n result = _maybe_fallback(ufunc, method, *inputs, **kwargs)\n if result is not NotImplemented:\n return result\n\n # for binary ops, use our custom dunder methods\n result = maybe_dispatch_ufunc_to_dunder_op(self, ufunc, method, *inputs, **kwargs)\n if result is not NotImplemented:\n return result\n\n # Determine if we should defer.\n\n # error: \"Type[ndarray]\" has no attribute \"__array_ufunc__\"\n no_defer = (\n np.ndarray.__array_ufunc__, # type: ignore[attr-defined]\n cls.__array_ufunc__,\n )\n\n for item in inputs:\n higher_priority = (\n hasattr(item, \"__array_priority__\")\n and item.__array_priority__ > self.__array_priority__\n )\n has_array_ufunc = (\n hasattr(item, \"__array_ufunc__\")\n and type(item).__array_ufunc__ not in no_defer\n and not isinstance(item, self._HANDLED_TYPES)\n )\n if higher_priority or has_array_ufunc:\n return NotImplemented\n\n # align all the inputs.\n types = tuple(type(x) for x in inputs)\n alignable = [x for x, t in zip(inputs, types) if issubclass(t, NDFrame)]\n\n if len(alignable) > 1:\n # This triggers alignment.\n # At the moment, there aren't any ufuncs with more than two inputs\n # so this ends up just being x1.index | x2.index, but we write\n # it to handle *args.\n\n if len(set(types)) > 1:\n # We currently don't handle ufunc(DataFrame, Series)\n # well. Previously this raised an internal ValueError. We might\n # support it someday, so raise a NotImplementedError.\n raise NotImplementedError(\n \"Cannot apply ufunc {} to mixed DataFrame and Series \"\n \"inputs.\".format(ufunc)\n )\n axes = self.axes\n for obj in alignable[1:]:\n # this relies on the fact that we aren't handling mixed\n # series / frame ufuncs.\n for i, (ax1, ax2) in enumerate(zip(axes, obj.axes)):\n axes[i] = ax1.union(ax2)\n\n reconstruct_axes = dict(zip(self._AXIS_ORDERS, axes))\n inputs = tuple(\n x.reindex(**reconstruct_axes) if issubclass(t, NDFrame) else x\n for x, t in zip(inputs, types)\n )\n else:\n reconstruct_axes = dict(zip(self._AXIS_ORDERS, self.axes))\n\n if self.ndim == 1:\n names = [getattr(x, \"name\") for x in inputs if hasattr(x, \"name\")]\n name = names[0] if len(set(names)) == 1 else None\n reconstruct_kwargs = {\"name\": name}\n else:\n reconstruct_kwargs = {}\n\n def reconstruct(result):\n if lib.is_scalar(result):\n return result\n if result.ndim != self.ndim:\n if method == \"outer\":\n if self.ndim == 2:\n # we already deprecated for Series\n msg = (\n \"outer method for ufunc {} is not implemented on \"\n \"pandas objects. Returning an ndarray, but in the \"\n \"future this will raise a 'NotImplementedError'. \"\n \"Consider explicitly converting the DataFrame \"\n \"to an array with '.to_numpy()' first.\"\n )\n warnings.warn(msg.format(ufunc), FutureWarning, stacklevel=4)\n return result\n raise NotImplementedError\n return result\n if isinstance(result, BlockManager):\n # we went through BlockManager.apply\n result = self._constructor(result, **reconstruct_kwargs, copy=False)\n else:\n # we converted an array, lost our axes\n result = self._constructor(\n result, **reconstruct_axes, **reconstruct_kwargs, copy=False\n )\n # TODO: When we support multiple values in __finalize__, this\n # should pass alignable to `__fianlize__` instead of self.\n # Then `np.add(a, b)` would consider attrs from both a and b\n # when a and b are NDFrames.\n if len(alignable) == 1:\n result = result.__finalize__(self)\n return result\n\n if self.ndim > 1 and (len(inputs) > 1 or ufunc.nout > 1):\n # Just give up on preserving types in the complex case.\n # In theory we could preserve them for them.\n # * nout>1 is doable if BlockManager.apply took nout and\n # returned a Tuple[BlockManager].\n # * len(inputs) > 1 is doable when we know that we have\n # aligned blocks / dtypes.\n inputs = tuple(np.asarray(x) for x in inputs)\n result = getattr(ufunc, method)(*inputs, **kwargs)\n elif self.ndim == 1:\n # ufunc(series, ...)\n inputs = tuple(extract_array(x, extract_numpy=True) for x in inputs)\n result = getattr(ufunc, method)(*inputs, **kwargs)\n else:\n # ufunc(dataframe)\n if method == \"__call__\" and not kwargs:\n # for np.<ufunc>(..) calls\n # kwargs cannot necessarily be handled block-by-block, so only\n # take this path if there are no kwargs\n mgr = inputs[0]._mgr\n result = mgr.apply(getattr(ufunc, method))\n else:\n # otherwise specific ufunc methods (eg np.<ufunc>.accumulate(..))\n # Those can have an axis keyword and thus can't be called block-by-block\n result = getattr(ufunc, method)(np.asarray(inputs[0]), **kwargs)\n\n if ufunc.nout > 1:\n result = tuple(reconstruct(x) for x in result)\n else:\n result = reconstruct(result)\n return result\n", "\"\"\"\nTest extension array for storing nested data in a pandas container.\n\nThe JSONArray stores lists of dictionaries. The storage mechanism is a list,\nnot an ndarray.\n\nNote\n----\nWe currently store lists of UserDicts. Pandas has a few places\ninternally that specifically check for dicts, and does non-scalar things\nin that case. We *want* the dictionaries to be treated as scalars, so we\nhack around pandas by using UserDicts.\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections import (\n UserDict,\n abc,\n)\nimport itertools\nimport numbers\nimport random\nimport string\nimport sys\nfrom typing import (\n Any,\n Mapping,\n)\n\nimport numpy as np\n\nfrom pandas._typing import type_t\n\nfrom pandas.core.dtypes.cast import construct_1d_object_array_from_listlike\nfrom pandas.core.dtypes.common import pandas_dtype\n\nimport pandas as pd\nfrom pandas.api.extensions import (\n ExtensionArray,\n ExtensionDtype,\n)\nfrom pandas.api.types import is_bool_dtype\nfrom pandas.core.arrays.string_arrow import ArrowStringDtype\n\n\nclass JSONDtype(ExtensionDtype):\n type = abc.Mapping\n name = \"json\"\n na_value: Mapping[str, Any] = UserDict()\n\n @classmethod\n def construct_array_type(cls) -> type_t[JSONArray]:\n \"\"\"\n Return the array type associated with this dtype.\n\n Returns\n -------\n type\n \"\"\"\n return JSONArray\n\n\nclass JSONArray(ExtensionArray):\n dtype = JSONDtype()\n __array_priority__ = 1000\n\n def __init__(self, values, dtype=None, copy=False):\n for val in values:\n if not isinstance(val, self.dtype.type):\n raise TypeError(\"All values must be of type \" + str(self.dtype.type))\n self.data = values\n\n # Some aliases for common attribute names to ensure pandas supports\n # these\n self._items = self._data = self.data\n # those aliases are currently not working due to assumptions\n # in internal code (GH-20735)\n # self._values = self.values = self.data\n\n @classmethod\n def _from_sequence(cls, scalars, dtype=None, copy=False):\n return cls(scalars)\n\n @classmethod\n def _from_factorized(cls, values, original):\n return cls([UserDict(x) for x in values if x != ()])\n\n def __getitem__(self, item):\n if isinstance(item, tuple):\n if len(item) > 1:\n if item[0] is Ellipsis:\n item = item[1:]\n elif item[-1] is Ellipsis:\n item = item[:-1]\n if len(item) > 1:\n raise IndexError(\"too many indices for array.\")\n item = item[0]\n\n if isinstance(item, numbers.Integral):\n return self.data[item]\n elif isinstance(item, slice) and item == slice(None):\n # Make sure we get a view\n return type(self)(self.data)\n elif isinstance(item, slice):\n # slice\n return type(self)(self.data[item])\n else:\n item = pd.api.indexers.check_array_indexer(self, item)\n if is_bool_dtype(item.dtype):\n return self._from_sequence([x for x, m in zip(self, item) if m])\n # integer\n return type(self)([self.data[i] for i in item])\n\n def __setitem__(self, key, value):\n if isinstance(key, numbers.Integral):\n self.data[key] = value\n else:\n if not isinstance(value, (type(self), abc.Sequence)):\n # broadcast value\n value = itertools.cycle([value])\n\n if isinstance(key, np.ndarray) and key.dtype == \"bool\":\n # masking\n for i, (k, v) in enumerate(zip(key, value)):\n if k:\n assert isinstance(v, self.dtype.type)\n self.data[i] = v\n else:\n for k, v in zip(key, value):\n assert isinstance(v, self.dtype.type)\n self.data[k] = v\n\n def __len__(self) -> int:\n return len(self.data)\n\n def __eq__(self, other):\n return NotImplemented\n\n def __ne__(self, other):\n return NotImplemented\n\n def __array__(self, dtype=None):\n if dtype is None:\n dtype = object\n return np.asarray(self.data, dtype=dtype)\n\n @property\n def nbytes(self) -> int:\n return sys.getsizeof(self.data)\n\n def isna(self):\n return np.array([x == self.dtype.na_value for x in self.data], dtype=bool)\n\n def take(self, indexer, allow_fill=False, fill_value=None):\n # re-implement here, since NumPy has trouble setting\n # sized objects like UserDicts into scalar slots of\n # an ndarary.\n indexer = np.asarray(indexer)\n msg = (\n \"Index is out of bounds or cannot do a \"\n \"non-empty take from an empty array.\"\n )\n\n if allow_fill:\n if fill_value is None:\n fill_value = self.dtype.na_value\n # bounds check\n if (indexer < -1).any():\n raise ValueError\n try:\n output = [\n self.data[loc] if loc != -1 else fill_value for loc in indexer\n ]\n except IndexError as err:\n raise IndexError(msg) from err\n else:\n try:\n output = [self.data[loc] for loc in indexer]\n except IndexError as err:\n raise IndexError(msg) from err\n\n return self._from_sequence(output)\n\n def copy(self):\n return type(self)(self.data[:])\n\n def astype(self, dtype, copy=True):\n # NumPy has issues when all the dicts are the same length.\n # np.array([UserDict(...), UserDict(...)]) fails,\n # but np.array([{...}, {...}]) works, so cast.\n from pandas.core.arrays.string_ import StringDtype\n\n dtype = pandas_dtype(dtype)\n # needed to add this check for the Series constructor\n if isinstance(dtype, type(self.dtype)) and dtype == self.dtype:\n if copy:\n return self.copy()\n return self\n elif isinstance(dtype, (StringDtype, ArrowStringDtype)):\n value = self.astype(str) # numpy doesn'y like nested dicts\n return dtype.construct_array_type()._from_sequence(value, copy=False)\n\n return np.array([dict(x) for x in self], dtype=dtype, copy=copy)\n\n def unique(self):\n # Parent method doesn't work since np.array will try to infer\n # a 2-dim object.\n return type(self)([dict(x) for x in {tuple(d.items()) for d in self.data}])\n\n @classmethod\n def _concat_same_type(cls, to_concat):\n data = list(itertools.chain.from_iterable(x.data for x in to_concat))\n return cls(data)\n\n def _values_for_factorize(self):\n frozen = self._values_for_argsort()\n if len(frozen) == 0:\n # factorize_array expects 1-d array, this is a len-0 2-d array.\n frozen = frozen.ravel()\n return frozen, ()\n\n def _values_for_argsort(self):\n # Bypass NumPy's shape inference to get a (N,) array of tuples.\n frozen = [tuple(x.items()) for x in self]\n return construct_1d_object_array_from_listlike(frozen)\n\n\ndef make_data():\n # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer\n return [\n UserDict(\n [\n (random.choice(string.ascii_letters), random.randint(0, 100))\n for _ in range(random.randint(0, 10))\n ]\n )\n for _ in range(100)\n ]\n" ]
[ [ "pandas._testing.assert_produces_warning", "pandas._testing.assert_numpy_array_equal", "pandas.RangeIndex", "numpy.arange", "pandas.Index", "pandas.Float64Index", "numpy.array", "pandas._testing.assert_index_equal" ], [ "pandas.util._decorators.Appender", "pandas.io.common.get_handle", "numpy.dtype", "numpy.flatnonzero", "numpy.frombuffer", "numpy.where" ], [ "numpy.asarray", "pandas._libs.lib.is_scalar", "pandas.core.ops.maybe_dispatch_ufunc_to_dunder_op", "pandas.core.construction.extract_array", "pandas.core.ops.common.unpack_zerodim_and_defer" ], [ "numpy.asarray", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.dtypes.cast.construct_1d_object_array_from_listlike", "pandas.api.indexers.check_array_indexer", "numpy.array", "pandas.api.types.is_bool_dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.0", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.0", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.0", "1.3" ], "scipy": [], "tensorflow": [] } ]
ggould256/twentyfortyeight
[ "7d2b88023077ba4c64b65617d493039c0a9998c3" ]
[ "twentyfortyeight/strategy/nn/data.py" ]
[ "#!/usr/bin/env python3\n\n\"\"\"Classes and functions related to dataset generation for learning Q\nfunctions. Datasets in this sense are mappings from board positions\n(represented as flattened arrays of tile numbers) to score values.\n\"\"\"\n\nimport argparse\nimport sys\n\nimport numpy as np\n\nfrom game.common import *\nfrom game.board import Board\nfrom game.game import Game\n\nEXAMPLE_WIDTH = Board.vector_width()\nMAX_BATCH_SIZE = 4096 # numpy arrays get slow to update beyond this size.\n\nclass Dataset(object):\n \"\"\"A set of training data (held as matrices whose rows are examples) and a\n column vector of the example scores..\"\"\"\n\n def __init__(self):\n \"\"\"Creates a new empty dataset.\"\"\"\n self._num_examples = 0\n self._example_batches = [np.zeros((0, EXAMPLE_WIDTH))]\n self._score_batches = [np.zeros((0, 1))]\n\n def add_game(self, player_strategy, rnd, starting_game_position=None):\n \"\"\"Runs a game with the given strategy and randomness source, then\n enrolls the outcome in the dataset.\n\n If @p starting_position is a Game object, start from that position.\n\n Returns the number of examples (moves) added.\n \"\"\"\n states = np.zeros((1, EXAMPLE_WIDTH))\n num_moves = 0\n game = starting_game_position or Game(rnd=rnd)\n running = True\n while running:\n intermediate_board, turn_outcome = (\n game.do_turn_and_retrieve_intermediate(\n player_strategy.get_move(game.board(), game.score())))\n running = (turn_outcome != GAMEOVER)\n num_moves += (turn_outcome != ILLEGAL)\n if turn_outcome == OK:\n states = np.append(states,\n Board.as_vector(intermediate_board),\n axis=0)\n self._num_examples += 1\n player_strategy.notify_outcome(game.board(), game.score())\n\n scores = Dataset.evaluate_states(states, game.board(), game.score)\n assert(len(states) == len(scores))\n batch_size_so_far = self._example_batches[-1].shape[0]\n if len(states) + batch_size_so_far > MAX_BATCH_SIZE:\n self._example_batches.append(np.zeros((0, EXAMPLE_WIDTH)))\n self._score_batches.append(np.zeros((0, 1)))\n self._example_batches[-1] = \\\n np.append(self._example_batches[-1], states, axis=0)\n self._score_batches[-1] = np.append(self._score_batches[-1], scores)\n return len(states)\n\n @staticmethod\n def evaluate_states(states, end_board, end_score):\n \"\"\"Associate a Q score with each state of the current game. There are\n many possible designs here, ranging from applying the ultimate score or\n highest attained tile to all of the states to scoring each state with\n the number of moves remaining in its game. The correct function is\n not obvious; the current implementation is moves-remaining.\"\"\"\n del end_board, end_score\n return np.array(list(range(len(states), 0, -1)))\n\n def add_n_examples(self, strategy, rnd, n,\n starting_positions_dataset=None):\n \"\"\"Runs games and adds them to the dataset until at least @p n\n examples have been added. Returns the number of examples added.\n\n If @p starting_positions_dataset is set, games will be started from\n a randomly selected position from that dataset rather than from a\n blank board.\"\"\"\n print(\"Adding\", n, \"examples to dataset.\")\n added = 0\n while added < n:\n starting_game = None\n if starting_positions_dataset:\n random_position = starting_positions_dataset.nth_example(\n rnd.randint(0,\n starting_positions_dataset.num_examples() - 1))\n starting_game = Game(Board.from_vector(random_position))\n if not starting_game.board().can_move():\n continue\n num_added = self.add_game(strategy, rnd, starting_game)\n if (added // 10000) != ((num_added + added) // 10000):\n print(\"Added %d so far...\" % (num_added + added))\n added += num_added\n return added\n\n def num_batches(self):\n return len(self._example_batches)\n\n def num_examples(self):\n return self._num_examples\n\n def example_batches(self):\n return self._example_batches\n\n def nth_example(self, n):\n counter = n\n for batch in self._example_batches:\n size = batch.shape[0]\n if counter < size:\n return batch[counter, :]\n else:\n counter -= size\n return None\n\n def nth_score(self, n):\n counter = n\n for batch in self._score_batches:\n size = batch.shape[0]\n if counter < size:\n return batch[counter]\n else:\n counter -= size\n return None\n\n def score_batches(self):\n return self._score_batches\n\n def collapse(self):\n \"\"\"Collapses all of the batches down to a single, very large batch.\"\"\"\n self._score_batches = [np.concatenate(self._score_batches)]\n self._example_batches = [np.concatenate(self._example_batches)]\n\n def save(self, filename):\n assert(filename.endswith(\".npz\"))\n num_batches = len(self._example_batches)\n examples_dict = {\"examples_%s\" % i: self._example_batches[i]\n for i in range(num_batches)}\n scores_dict = {\"scores_%s\" % i: self._score_batches[i]\n for i in range(num_batches)}\n unified_dict = {**examples_dict, **scores_dict}\n with open(filename, \"wb\") as f:\n np.savez(f, **unified_dict)\n\n @staticmethod\n def load(filename):\n assert(filename.endswith(\".npz\"))\n with open(filename, \"rb\") as f:\n npz_data = np.load(f)\n data = Dataset()\n data._example_batches = []\n data._score_batches = []\n num_batches = len(npz_data.files) // 2\n for i in range(num_batches):\n data._example_batches.append(\n npz_data[\"examples_%s\" % i])\n data._score_batches.append(\n npz_data[\"scores_%s\" % i])\n data._num_examples = sum(array.shape[0]\n for array in data._example_batches)\n return data\n\n\ndef main(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--num_examples', metavar='N', type=int,\n help=\"Number of examples (at minimum) to generate\")\n parser.add_argument('--output_file', metavar='FILENAME', type=str,\n help=\"npz file into which to write example data\")\n parser.add_argument('--strategy', metavar='FILE_OR_NAME', type=str,\n help=\"name of strategy or filename of model\",\n default=\"random\")\n parser.add_argument('--starting_positions', metavar='FILENAME', type=str,\n default=None,\n help=(\"If set, start some or all games from positions\"\n \"drawn from this dataset\"))\n parser.add_argument('--new_start_fraction', metavar='FRACTION', type=float,\n default=1.,\n help=(\"If --starting_positions is set, start this \"\n \"fraction of games from a new game position\"))\n args = parser.parse_args(argv[1:])\n\n import random\n from strategy.basic import RandomStrategy, SpinnyStrategy\n from strategy.nn.nn_strategy import ModelStrategy\n\n if args.strategy == \"spinny\":\n strategy = SpinnyStrategy()\n elif args.strategy == \"random\":\n strategy = RandomStrategy()\n else:\n strategy = ModelStrategy(args.strategy)\n\n start_positions_dataset = None\n if args.starting_positions:\n start_positions_dataset = Dataset.load(args.starting_positions)\n\n dataset = Dataset()\n num_added = dataset.add_n_examples(\n strategy, random, args.num_examples * args.new_start_fraction)\n if args.new_start_fraction < 1:\n assert start_positions_dataset, \\\n \"--new_start_fraction requires --starting_positions\"\n num_added = dataset.add_n_examples(\n strategy, random, args.num_examples * (1 - args.new_start_fraction),\n starting_positions_dataset=start_positions_dataset)\n print(\"Added\", num_added, \"examples\")\n print(\"saving...\")\n dataset.save(args.output_file)\n print(\"...saved.\")\n print(\"checking output file validity...\")\n check_data = Dataset.load(args.output_file)\n assert dataset.num_batches() == check_data.num_batches(), \\\n (\"original batch number %s does not equal output batch number %s\"\n % (dataset.num_batches(), check_data.num_batches()))\n check_data.collapse()\n print(\"...output is valid.\")\n\n\nif __name__ == '__main__':\n main(sys.argv)\n" ]
[ [ "numpy.savez", "numpy.concatenate", "numpy.append", "numpy.load", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rtu715/NAS-Bench-360
[ "d075006848c664371855c34082b0a00cda62be67", "d075006848c664371855c34082b0a00cda62be67", "d075006848c664371855c34082b0a00cda62be67", "d075006848c664371855c34082b0a00cda62be67", "d075006848c664371855c34082b0a00cda62be67" ]
[ "backbone/model_audio.py", "expert/Satellite/mlp.py", "AMBER/amber/architect/commonOps.py", "old/bananas/darts/cnn/train_class.py", "docs/point.py" ]
[ "'''\nDetermined model def example:\nhttps://github.com/determined-ai/determined/tree/master/examples/computer_vision/cifar10_pytorch\n'''\nimport tempfile\nfrom typing import Any, Dict, Sequence, Tuple, Union, cast\nfrom functools import partial\n\nimport os\nimport boto3\nimport numpy as np\nfrom sklearn.metrics import average_precision_score\n\nimport torch\nfrom torch import nn\n\nfrom determined.pytorch import DataLoader, PyTorchTrial, PyTorchTrialContext, LRScheduler\nfrom backbone_pt import Backbone_Pt, Backbone_Audio\n\nimport utils_pt\n\nfrom data_utils.load_data import load_data\nfrom data_utils.download_data import download_from_s3\n\nfrom data_utils.audio_dataset import *\nfrom data_utils.audio_dataset import _collate_fn, _collate_fn_eval\n\n# Constants about the dataset here (need to modify)\n\nTorchData = Union[Dict[str, torch.Tensor], Sequence[torch.Tensor], torch.Tensor]\n\n\ndef accuracy_rate(predictions: torch.Tensor, labels: torch.Tensor) -> float:\n \"\"\"Return the accuracy rate based on dense predictions and sparse labels.\"\"\"\n assert len(predictions) == len(labels), \"Predictions and labels must have the same length.\"\n assert len(labels.shape) == 1, \"Labels must be a column vector.\"\n\n return ( # type: ignore\n float((predictions.argmax(1) == labels.to(torch.long)).sum()) / predictions.shape[0]\n )\n\n\nclass AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\n\nclass BackboneTrial(PyTorchTrial):\n def __init__(self, trial_context: PyTorchTrialContext) -> None:\n self.context = trial_context\n self.hparams = AttrDict(trial_context.get_hparams())\n self.last_epoch = 0\n\n self.download_directory = self.download_data_from_s3()\n #self.results = {\"loss\": float(\"inf\"), \"top1_accuracy\": 0, \"top5_accuracy\": 0, \"test_loss\": float(\"inf\"),\n # \"test_top1_accuracy\": 0, \"test_top5_accuracy\": 0}\n\n dataset_hypers = {'sEMG': (7, 1), 'ninapro': (18, 1), 'cifar10': (10, 3),\n 'smnist': (10, 1), 'cifar100':(100, 3), 'scifar100': (100, 3),\n 'audio': (200, 1)}\n\n n_classes, in_channels = dataset_hypers[self.hparams.task]\n print('task: ', self.hparams.task, 'in_channels: ', in_channels, 'classes: ', n_classes)\n # Changing our backbone\n depth = list(map(int, self.hparams.backbone.split(',')))[0]\n width = list(map(int, self.hparams.backbone.split(',')))[1]\n\n #for audio, use multilabel loss\n if self.hparams.task == 'audio':\n # where is the weights file?\n self.criterion = nn.BCEWithLogitsLoss().cuda()\n self.backbone = Backbone_Audio(depth, n_classes, width,\n dropRate=self.hparams.droprate, in_channels=in_channels)\n else:\n self.criterion = nn.CrossEntropyLoss().cuda()\n self.backbone = Backbone_Pt(\n depth,\n n_classes,\n width,\n dropRate=self.hparams.droprate,\n in_channels=in_channels,\n )\n\n\n total_params = sum(p.numel() for p in self.backbone.parameters() if p.requires_grad)/ 1e6\n print('Parameter size in MB(backbone): ', total_params)\n \n \n self.model = self.context.wrap_model(self.backbone)\n self.last_eval = 0\n '''\n Definition of optimizer \n '''\n nesterov = self.hparams.nesterov if self.hparams.momentum else False\n\n self.opt = self.context.wrap_optimizer(torch.optim.SGD(\n self.model.parameters(),\n lr=self.hparams.learning_rate,\n momentum=self.hparams.momentum,\n weight_decay=self.hparams.weight_decay,\n nesterov=nesterov)\n )\n\n self.lr_scheduler = self.context.wrap_lr_scheduler(\n lr_scheduler=torch.optim.lr_scheduler.LambdaLR(\n self.opt,\n lr_lambda=self.weight_sched,\n last_epoch=self.hparams.start_epoch - 1\n ),\n step_mode=LRScheduler.StepMode.STEP_EVERY_EPOCH,\n )\n\n\n def weight_sched(self, epoch) -> Any:\n if self.hparams.epochs != 200:\n return 0.2 ** (epoch >= int(0.3 * self.hparams.epochs)) * 0.2 ** (epoch > int(0.6 * self.hparams.epochs)) * 0.2 ** (epoch > int(0.8 * self.hparams.epochs))\n #print('using original weight schedule') \n return 0.2 ** (epoch >= 60) * 0.2 ** (epoch >= 120) * 0.2 ** (epoch >=160)\n\n\n def download_data_from_s3(self):\n '''Download data from s3 to store in temp directory'''\n\n s3_bucket = self.context.get_data_config()[\"bucket\"]\n #download_directory = f\"/tmp/data-rank{self.context.distributed.get_rank()}\"\n #download_directory = \"/tmp/data\"\n download_directory = os.getcwd()\n s3 = boto3.client(\"s3\")\n #os.makedirs(download_directory, exist_ok=True)\n\n download_from_s3(s3_bucket, self.hparams.task, download_directory)\n\n if self.hparams.train:\n self.train_data, self.val_data, self.test_data = load_data(self.hparams.task, download_directory, True, self.hparams.permute) \n self.build_test_data_loader(download_directory)\n \n else:\n self.train_data, _, self.val_data = load_data(self.hparams.task, download_directory, False, self.hparams.permute)\n\n return download_directory\n\n def build_training_data_loader(self) -> DataLoader:\n\n trainset = self.train_data\n print(len(trainset))\n train_loader = DataLoader(trainset, num_workers=4, batch_size=self.context.get_per_slot_batch_size(),\n shuffle=True, sampler=None, collate_fn=_collate_fn,\n pin_memory=False, drop_last=True)\n print(len(train_loader))\n return train_loader\n\n\n def build_validation_data_loader(self) -> DataLoader:\n\n valset = self.val_data\n print(len(valset))\n\n return DataLoader(valset, sampler=None, num_workers=4,\n collate_fn=_collate_fn_eval,\n shuffle=False, batch_size=1,\n pin_memory=False\n )\n\n def build_test_data_loader(self, download_directory):\n\n testset = self.test_data\n print(len(testset))\n #self.test_loader = torch.utils.data.DataLoader(testset, batch_size=self.context.get_per_slot_batch_size(),\n # shuffle=False, num_workers=2)\n return\n \n '''\n Train and Evaluate Methods\n '''\n\n def train_batch(self, batch: TorchData, epoch_idx: int, batch_idx: int\n ) -> Dict[str, torch.Tensor]:\n\n x_train, _, y_train = batch\n self.model.train()\n output = self.model(x_train)\n loss = self.criterion(output, y_train)\n\n self.context.backward(loss)\n self.context.step_optimizer(self.opt)\n\n return {\n 'loss': loss,\n }\n \n def evaluate_full_dataset(\n self, data_loader: torch.utils.data.DataLoader,\n ) -> Dict[str, Any]:\n\n if not self.hparams.train and self.hparams.task == 'audio':\n return self.evaluate_audio_testset(self.val_data)\n\n loss_avg = utils_pt.AverageMeter()\n val_predictions = []\n val_gts = []\n with torch.no_grad():\n for batch in data_loader:\n batch = self.context.to_device(batch)\n input, target = batch\n n = input.size(0)\n logits = self.model(input)\n logits = logits.mean(0).unsqueeze(0)\n loss = self.criterion(logits, target)\n #top1, top5 = utils_pt.accuracy(logits, target, topk=(1, 5))\n #acc_top1.update(top1.item(), n)\n #acc_top5.update(top5.item(), n)\n loss_avg.update(loss, n)\n logits_sigmoid = torch.sigmoid(logits)\n val_predictions.append(logits_sigmoid.detach().cpu().numpy()[0])\n val_gts.append(target.detach().cpu().numpy()[0])\n\n val_preds = np.asarray(val_predictions).astype('float32')\n val_gts = np.asarray(val_gts).astype('int32')\n map_value = average_precision_score(val_gts, val_preds, average=\"macro\")\n\n results = {\n \"loss\": loss_avg.avg,\n \"val_mAP\": map_value,\n }\n\n\n '''\n if self.hparams.train:\n test_acc_top1 = utils_pt.AverageMeter()\n test_acc_top5 = utils_pt.AverageMeter()\n test_loss = utils_pt.AverageMeter()\n with torch.no_grad():\n for batch in self.test_loader:\n batch = self.context.to_device(batch)\n input, target = batch\n n = input.size(0)\n logits = self.model(input)\n loss = self.criterion(logits, target)\n top1, top5 = utils_pt.accuracy(logits, target, topk=(1, 5))\n test_acc_top1.update(top1.item(), n)\n test_acc_top5.update(top5.item(), n)\n test_loss.update(loss, n)\n\n results2 = {\n \"test_loss\": test_loss.avg,\n \"test_top1_accuracy\": test_acc_top1.avg,\n \"test_top5_accuracy\": test_acc_top5.avg,\n }\n\n results.update(results2)\n '''\n if self.hparams.task == 'audio' and self.last_eval % 20 == 0:\n results.update(self.evaluate_audio_testset(self.test_data))\n\n self.last_eval += 1\n\n return results\n\n def evaluate_audio_testset(self, testset) -> Dict[str, torch.Tensor]:\n cnt = 0\n test_predictions = []\n test_gts = []\n for ix in range(testset.len):\n with torch.no_grad():\n batch = testset[ix]\n x, y = batch\n x = x.cuda()\n y_pred = self.model(x)\n y_pred = y_pred.mean(0).unsqueeze(0)\n sigmoid_preds = torch.sigmoid(y_pred)\n test_predictions.append(sigmoid_preds.detach().cpu().numpy()[0])\n test_gts.append(y.detach().cpu().numpy()[0]) # drop batch axis\n test_predictions = np.asarray(test_predictions).astype('float32')\n test_gts = np.asarray(test_gts).astype('int32')\n\n stats = calculate_stats(test_predictions, test_gts)\n mAP = np.mean([stat['AP'] for stat in stats])\n mAUC = np.mean([stat['auc'] for stat in stats])\n\n results = {\n \"test_mAUC\": mAUC,\n \"test_mAP\": mAP,\n }\n\n return results\n", "import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport numpy as np\nimport os\nimport torch.utils.data as data_utils\nfrom torch.utils.data import Dataset\n\ntorch.manual_seed(1)\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# Hyper-parameters\ninput_size = 46\nhidden_size_1 = 40\nhidden_size_2 = 30\nnum_classes = 24\nnum_epochs = 200\nbatch_size = 1024\nlearning_rate = 0.001\n\n\ndef load_satellite_data(path):\n train_file = os.path.join(path, 'satellite_train.npy')\n test_file = os.path.join(path, 'satellite_test.npy')\n\n all_train_data, all_train_labels = np.load(train_file, allow_pickle=True)[()]['data'], np.load(train_file,allow_pickle=True)[()]['label']\n test_data, test_labels = np.load(test_file, allow_pickle=True)[()]['data'], np.load(test_file, allow_pickle=True)[()]['label']\n\n #rerange labels to 0-23\n all_train_labels = all_train_labels - 1\n test_labels = test_labels - 1\n\n #normalize data\n all_train_data = (all_train_data - all_train_data.mean(axis=1, keepdims=True))/all_train_data.std(axis=1, keepdims=True)\n test_data = (test_data - test_data.mean(axis=1, keepdims=True))/test_data.std(axis=1, keepdims=True)\n\n #convert to tensor/longtensor\n all_train_tensors, all_train_labeltensor = torch.from_numpy(all_train_data).type(torch.FloatTensor), \\\n torch.from_numpy(all_train_labels).type(torch.LongTensor)\n\n test_tensors, test_labeltensor = torch.from_numpy(test_data).type(torch.FloatTensor), torch.from_numpy(test_labels).type(torch.LongTensor)\n testset = data_utils.TensorDataset(test_tensors, test_labeltensor)\n\n trainset = data_utils.TensorDataset(all_train_tensors, all_train_labeltensor)\n\n return trainset, None, testset\n\ntrain_dataset, _, test_dataset = load_satellite_data('.')\n\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\n# Fully connected neural network with one hidden layer\n\n\nclass NeuralNet(nn.Module):\n def __init__(self, input_size, hidden_size_1, hidden_size_2, num_classes):\n super(NeuralNet, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_size_1)\n self.relu = nn.ReLU()\n self.fc2 = nn.Linear(hidden_size_1, hidden_size_2)\n self.fc3 = nn.Linear(hidden_size_2, num_classes)\n\n def forward(self, x):\n out = self.fc1(x)\n out = self.relu(out)\n out = self.fc2(out)\n out = self.relu(out)\n out = self.fc3(out)\n return out\n\n\nmodel = NeuralNet(input_size, hidden_size_1, hidden_size_2, num_classes).to(device)\n\n# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n # Move tensors to the configured device\n images = images.reshape(-1, 46).to(device)\n labels = labels.to(device)\n\n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1) % 100 == 0:\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n\n# Test the model\n# In test phase, we don't need to compute gradients (for memory efficiency)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, 46).to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Accuracy of the network on the test images: {} %'.format(\n 100 * correct / total))\n\n# Save the model checkpoint\ntorch.save(model.state_dict(), 'model.ckpt')\n", "import warnings\n\nimport keras.backend as K\nimport numpy as np\nimport tensorflow as tf\nif tf.__version__.startswith(\"2\"):\n tf.compat.v1.disable_eager_execution()\n import tensorflow.compat.v1 as tf\nfrom tensorflow.python.training import moving_averages\n\n\ndef unpack_data(data, unroll_generator_x=False, unroll_generator_y=False, callable_kwargs=None):\n is_generator = False\n unroll_generator = unroll_generator_x or unroll_generator_y\n if type(data) in (tuple, list):\n x, y = data[0], data[1]\n elif isinstance(data, tf.keras.utils.Sequence):\n x = data\n y = None\n is_generator = True\n elif hasattr(data, '__next__'):\n x = data\n y = None\n is_generator = True\n elif callable(data):\n callable_kwargs = callable_kwargs or {}\n x, y = unpack_data(data=data(**callable_kwargs),\n unroll_generator_x=unroll_generator_x,\n unroll_generator_y=unroll_generator_y)\n else:\n raise Exception(\"cannot unpack data of type: %s\"%type(data))\n if is_generator and unroll_generator:\n gen = data if hasattr(data, '__next__') else iter(data)\n d_ = [d for d in zip(*gen)]\n if unroll_generator_x ^ unroll_generator_y:\n if hasattr(data, \"shuffle\"):\n assert data.shuffle == False\n x = np.concatenate(d_[0], axis=0) if unroll_generator_x else data\n y = np.concatenate(d_[1], axis=0) if unroll_generator_y else None\n return x, y\n\n\ndef batchify(x, y=None, batch_size=None, shuffle=True, drop_remainder=True):\n if not type(x) is list: x = [x]\n if y is not None and type(y) is not list: y = [y]\n # assuming batch_size is axis=0\n n = len(x[0])\n idx = np.arange(n)\n if batch_size is None:\n batch_size = n\n if shuffle:\n idx = np.random.choice(idx, n, replace=False)\n while True:\n for i in range(0, n, batch_size):\n tmp_x = [x_[idx[i:i + batch_size]] for x_ in x]\n if drop_remainder and tmp_x[0].shape[0] != batch_size:\n continue\n if y is not None:\n tmp_y = [y_[idx[i:i + batch_size]] for y_ in y]\n yield tmp_x, tmp_y\n else:\n yield tmp_x\n\n\ndef batchify_infer(x, y=None, batch_size=None, shuffle=True, drop_remainder=True):\n if not type(x) is list: x = [x]\n if y is not None and type(y) is not list: y = [y]\n # assuming batch_size is axis=0\n n = len(x[0])\n idx = np.arange(n)\n if batch_size is None:\n batch_size = n\n if shuffle:\n idx = np.random.choice(idx, n, replace=False)\n for i in range(0, n, batch_size):\n tmp_x = [x_[idx[i:i + batch_size]] for x_ in x]\n if drop_remainder and tmp_x[0].shape[0] != batch_size:\n continue\n if y is not None:\n tmp_y = [y_[idx[i:i + batch_size]] for y_ in y]\n yield tmp_x, tmp_y\n else:\n yield tmp_x\n\ndef numpy_shuffle_in_unison(List):\n rng_state = np.random.get_state()\n for x in List:\n np.random.set_state(rng_state)\n np.random.shuffle(x)\n\n\ndef get_tf_loss(loss, y_true, y_pred):\n loss = loss.lower()\n if loss == 'mse' or loss == 'mean_squared_error':\n loss_ = tf.reduce_mean(tf.square(y_true - y_pred))\n elif loss == 'categorical_crossentropy':\n loss_ = tf.reduce_mean(tf.keras.losses.categorical_crossentropy(y_true, y_pred))\n elif loss == 'binary_crossentropy':\n loss_ = tf.reduce_mean(tf.keras.losses.binary_crossentropy(y_true, y_pred))\n else:\n raise Exception(\"cannot understand string loss: %s\" % loss)\n return loss_\n\n\ndef get_tf_metrics(m):\n if callable(m):\n return m\n elif m.lower() == 'mae':\n return tf.keras.metrics.MAE\n elif m.lower() == 'mse':\n return tf.keras.metrics.MSE\n elif m.lower() == 'acc':\n def acc(y_true, y_pred):\n return tf.reduce_mean(y_true)\n\n # return tf.keras.metrics.Accuracy\n return acc\n elif m.lower() == 'auc':\n return tf.keras.metrics.AUC\n else:\n raise Exception(\"cannot understand metric type: %s\" % m)\n\n\ndef get_tf_layer(fn_str):\n fn_str = fn_str.lower()\n if fn_str == \"relu\":\n return tf.nn.relu\n elif fn_str == \"linear\":\n return lambda x: x\n elif fn_str == \"softmax\":\n return tf.nn.softmax\n elif fn_str == \"sigmoid\":\n return tf.nn.sigmoid\n elif fn_str == 'leaky_relu':\n return tf.nn.leaky_relu\n elif fn_str == 'elu':\n return tf.nn.elu\n elif fn_str == 'tanh':\n return tf.nn.tanh\n else:\n raise Exception(\"cannot get tensorflow layer for: %s\" % fn_str)\n\n\ndef create_weight(name, shape, initializer=None, trainable=True, seed=None):\n if initializer is None:\n try:\n initializer = tf.contrib.keras.initializers.he_normal(seed=seed)\n except AttributeError:\n initializer = tf.keras.initializers.he_normal(seed=seed)\n return tf.get_variable(name, shape, initializer=initializer, trainable=trainable)\n\n\ndef create_bias(name, shape, initializer=None):\n if initializer is None:\n initializer = tf.constant_initializer(0.0, dtype=tf.float32)\n return tf.get_variable(name, shape, initializer=initializer)\n\n\ndef batch_norm1d(x, is_training, name=\"bn\", decay=0.9, epsilon=1e-5,\n data_format=\"NWC\"):\n if data_format == \"NWC\":\n shape = [x.get_shape()[-1]]\n x = tf.expand_dims(x, axis=1) # NHWC\n sq_dim = 1\n elif data_format == \"NCW\":\n shape = [x.get_shape()[1]]\n x = tf.expand_dims(x, axis=2) # NCHW\n sq_dim = 2\n else:\n raise NotImplementedError(\"Unknown data_format {}\".format(data_format))\n\n with tf.variable_scope(name, reuse=False if is_training else True):\n offset = tf.get_variable(\n \"offset\", shape,\n initializer=tf.constant_initializer(0.0, dtype=tf.float32))\n scale = tf.get_variable(\n \"scale\", shape,\n initializer=tf.constant_initializer(1.0, dtype=tf.float32))\n moving_mean = tf.get_variable(\n \"moving_mean\", shape, trainable=False,\n initializer=tf.constant_initializer(0.0, dtype=tf.float32))\n moving_variance = tf.get_variable(\n \"moving_variance\", shape, trainable=False,\n initializer=tf.constant_initializer(1.0, dtype=tf.float32))\n\n if is_training:\n x, mean, variance = tf.nn.fused_batch_norm(\n x, scale, offset, epsilon=epsilon,\n is_training=True)\n update_mean = moving_averages.assign_moving_average(\n moving_mean, mean, decay)\n update_variance = moving_averages.assign_moving_average(\n moving_variance, variance, decay)\n with tf.control_dependencies([update_mean, update_variance]):\n x = tf.identity(x)\n else:\n x, _, _ = tf.nn.fused_batch_norm(\n x, scale, offset, mean=moving_mean,\n variance=moving_variance,\n epsilon=epsilon,\n is_training=False)\n x = tf.squeeze(x, axis=sq_dim)\n return x\n\n\ndef get_keras_train_ops(loss, tf_variables, optim_algo, **kwargs):\n assert K.backend() == 'tensorflow'\n # TODO: change to TF.keras\n from keras.optimizers import get as get_opt\n opt = get_opt(optim_algo)\n grads = tf.gradients(loss, tf_variables)\n grad_var = []\n no_grad_var = []\n for g, v in zip(grads, tf_variables):\n if g is None:\n # get sub-scope name; if is optimizer-related, ignore\n if 'compile' in v.name.split('/'):\n continue\n no_grad_var.append(v)\n else:\n grad_var.append(v)\n if no_grad_var:\n warnings.warn(\n \"\\n\" + \"=\" * 80 + \"\\nWarning: the following tf.variables have no gradients\"\n \" and have been discarded: \\n %s\" % no_grad_var, stacklevel=2)\n train_op = opt.get_updates(loss, grad_var)\n try:\n config = opt.get_config()\n except NotImplementedError: # if cannot get learning-rate when eager-execution is disableed\n config = {'lr':None}\n try:\n learning_rate = config['lr']\n except: # for newer version of keras\n learning_rate = config['learning_rate']\n return train_op, learning_rate, None, opt\n\n\ndef count_model_params(tf_variables):\n num_vars = 0\n for var in tf_variables:\n num_vars += np.prod([dim.value for dim in var.get_shape()])\n return num_vars\n\n\ndef proximal_policy_optimization_loss(curr_prediction, curr_onehot, old_prediction, old_onehotpred, rewards, advantage, clip_val, beta=None):\n rewards_ = tf.squeeze(rewards, axis=1)\n advantage_ = tf.squeeze(advantage, axis=1)\n\n entropy = 0\n r = 1\n for t, (p, onehot, old_p, old_onehot) in \\\n enumerate(zip(curr_prediction, curr_onehot, old_prediction, old_onehotpred)):\n # print(t)\n # print(\"p\", p)\n # print(\"old_p\", old_p)\n # print(\"old_onehot\", old_onehot)\n ll_t = tf.log(tf.reduce_sum(old_onehot * p))\n ll_0 = tf.log(tf.reduce_sum(old_onehot * old_p))\n r_t = tf.exp(ll_t - ll_0)\n r = r * r_t\n # approx entropy\n entropy += -tf.reduce_mean(tf.log(tf.reduce_sum(onehot * p, axis=1)))\n\n surr_obj = tf.reduce_mean(tf.abs(1 / (rewards_ + 1e-8)) *\n tf.minimum(r * advantage_,\n tf.clip_by_value(r,\n clip_value_min=1 - clip_val,\n clip_value_max=1 + clip_val) * advantage_)\n )\n if beta:\n # maximize surr_obj for learning and entropy for regularization\n return - surr_obj + beta * (- entropy)\n else:\n return - surr_obj\n\n\ndef get_kl_divergence_n_entropy(curr_prediction, curr_onehot, old_prediction, old_onehotpred):\n \"\"\"compute approx\n return kl, ent\n \"\"\"\n kl = []\n ent = []\n for t, (p, onehot, old_p, old_onehot) in \\\n enumerate(zip(curr_prediction, curr_onehot, old_prediction, old_onehotpred)):\n # print(t, old_p, old_onehot, p, onehot)\n kl.append(tf.reshape(tf.keras.metrics.kullback_leibler_divergence(old_p, p), [-1]))\n ent.append(tf.reshape(tf.keras.backend.binary_crossentropy(onehot, p), [-1]))\n return tf.reduce_mean(tf.concat(kl, axis=0)), tf.reduce_mean(tf.concat(ent, axis=0))\n\n\ndef lstm(x, prev_c, prev_h, w):\n ifog = tf.matmul(tf.concat([x, prev_h], axis=1), w)\n i, f, o, g = tf.split(ifog, 4, axis=1)\n i = tf.sigmoid(i)\n f = tf.sigmoid(f)\n o = tf.sigmoid(o)\n g = tf.tanh(g)\n next_c = i * g + f * prev_c\n next_h = o * tf.tanh(next_c)\n return next_c, next_h\n\n\ndef stack_lstm(x, prev_c, prev_h, w):\n next_c, next_h = [], []\n for layer_id, (_c, _h, _w) in enumerate(zip(prev_c, prev_h, w)):\n inputs = x if layer_id == 0 else next_h[-1]\n curr_c, curr_h = lstm(inputs, _c, _h, _w)\n next_c.append(curr_c)\n next_h.append(curr_h)\n return next_c, next_h\n", "import os\nimport sys\nimport time\nimport glob\nimport numpy as np\nimport random\nimport torch\nimport utils\nimport utils_data\nimport logging\nimport argparse\nimport torch.nn as nn\nimport genotypes\nimport torch.utils\nimport torchvision.datasets as dset\nimport torch.backends.cudnn as cudnn\nfrom collections import namedtuple\n\nfrom torch.autograd import Variable\nfrom model import NetworkCIFAR as Network\n\nclass Train:\n\n def __init__(self):\n\n self.data='../data'\n self.batch_size= 32\n self.learning_rate= 0.025\n self.momentum= 0.9\n self.weight_decay = 3e-4\n self.load_weights = 0\n self.report_freq = 50\n self.gpu = 0\n self.epochs = 600\n self.init_channels = 36\n self.layers = 20\n self.model_path = 'saved_models'\n self.auxiliary = False\n self.auxiliary_weight = 0.4\n self.cutout = False\n self.cutout_length = 16\n self.drop_path_prob = 0.2\n self.save = 'EXP'\n self.seed = 0\n self.arch = 'BANANAS'\n self.grad_clip = 5\n self.train_portion = 0.7\n self.validation_set = True\n self.CIFAR_CLASSES = 10\n self.sEMG_classes = 7\n self.in_channels=3\n\n\n def main(self, arch, epochs=600, gpu=0, load_weights=False, train_portion=0.7, seed=0, save='EXP'):\n\n # Set up save file and logging\n self.save = 'eval-{}-{}'.format(save, time.strftime(\"%Y%m%d-%H%M%S\"))\n utils.create_exp_dir(self.save, scripts_to_save=glob.glob('*.py'))\n log_format = '%(asctime)s %(message)s'\n logging.basicConfig(stream=sys.stdout, level=logging.INFO,\n format=log_format, datefmt='%m/%d %I:%M:%S %p')\n fh = logging.FileHandler(os.path.join(self.save, 'log.txt'))\n fh.setFormatter(logging.Formatter(log_format))\n logging.getLogger().addHandler(fh)\n\n self.arch = arch\n self.epochs = epochs\n self.load_weights = load_weights\n self.gpu = gpu\n self.train_portion = train_portion\n if self.train_portion == 1:\n self.validation_set = False\n self.seed = seed\n\n print('Train class params')\n print('arch: {}, epochs: {}, gpu: {}, load_weights: {}, train_portion: {}'\n .format(arch, epochs, gpu, load_weights, train_portion))\n\n # cpu-gpu switch\n if not torch.cuda.is_available():\n logging.info('no gpu device available')\n torch.manual_seed(self.seed)\n device = torch.device('cpu')\n\n else: \n torch.cuda.manual_seed_all(self.seed)\n random.seed(self.seed)\n torch.manual_seed(self.seed)\n device = torch.device(self.gpu)\n cudnn.benchmark = False\n cudnn.enabled=True\n cudnn.deterministic=True\n logging.info('gpu device = %d' % self.gpu)\n\n Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')\n genotype = eval(self.convert_to_genotype(arch))\n model = Network(self.init_channels, self.CIFAR_CLASSES, self.layers, self.auxiliary, genotype, self.in_channels)\n model = model.to(device)\n\n logging.info(\"param size = %fMB\", utils.count_parameters_in_MB(model))\n total_params = sum(x.data.nelement() for x in model.parameters())\n logging.info('Model total parameters: {}'.format(total_params))\n\n criterion = nn.CrossEntropyLoss()\n criterion = criterion.to(device)\n optimizer = torch.optim.SGD(\n model.parameters(),\n self.learning_rate,\n momentum=self.momentum,\n weight_decay=self.weight_decay\n )\n\n train_transform, test_transform = utils._data_transforms_cifar10(self.cutout, self.cutout_length)\n \n #modify loaders\n train_data = dset.CIFAR10(root=self.data, train=True, download=True, transform=train_transform)\n test_data = dset.CIFAR10(root=self.data, train=False, download=True, transform=test_transform)\n #train_data, test_data = utils_data.load_spherical_data()\n #train_data = utils_data.load_sEMG_train_data()\n #test_data = utils_data.load_sEMG_val_data()\n\n num_train = len(train_data)\n indices = list(range(num_train))\n if self.validation_set:\n split = int(np.floor(self.train_portion * num_train))\n else:\n split = num_train\n\n train_queue = torch.utils.data.DataLoader(\n train_data, batch_size=self.batch_size,\n sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[:split]),\n pin_memory=True, num_workers=0)\n\n if self.validation_set:\n valid_queue = torch.utils.data.DataLoader(\n train_data, batch_size=self.batch_size // 2,\n sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:num_train]),\n pin_memory=True, num_workers=0) \n\n test_queue = torch.utils.data.DataLoader(\n test_data, batch_size=self.batch_size // 2, shuffle=False, pin_memory=True, num_workers=0)\n\n if self.load_weights:\n logging.info('loading saved weights')\n ml = 'cuda:{}'.format(self.gpu) if torch.cuda.is_available() else 'cpu'\n model.load_state_dict(torch.load('weights.pt', map_location = ml))\n logging.info('loaded saved weights')\n \n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(self.epochs))\n\n valid_accs = []\n test_accs = []\n\n for epoch in range(self.epochs):\n scheduler.step()\n logging.info('epoch %d lr %e', epoch, scheduler.get_lr()[0])\n model.drop_path_prob = self.drop_path_prob * epoch / self.epochs\n\n train_acc, train_obj = self.train(train_queue, model, criterion, optimizer)\n logging.info('train_acc %f', train_acc)\n\n if self.validation_set:\n valid_acc, valid_obj = self.infer(valid_queue, model, criterion)\n logging.info('valid_acc %f', valid_acc)\n else:\n valid_acc, valid_obj = 0, 0\n\n test_acc, test_obj = self.infer(test_queue, model, criterion, test_data=True)\n logging.info('test_acc %f', test_acc)\n\n utils.save(model, os.path.join(self.save, 'weights-new.pt'))\n\n if epoch in list(range(max(0, epochs - 5), epochs)):\n valid_accs.append((epoch, valid_acc))\n test_accs.append((epoch, test_acc))\n\n return valid_accs, test_accs\n\n\n def convert_to_genotype(self, arch):\n\n Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')\n op_dict = {\n 0: 'none',\n 1: 'max_pool_3x3',\n 2: 'avg_pool_3x3',\n 3: 'skip_connect',\n 4: 'sep_conv_3x3',\n 5: 'sep_conv_5x5',\n 6: 'dil_conv_3x3',\n 7: 'dil_conv_5x5'\n }\n\n darts_arch = [[], []]\n i=0\n for cell in arch:\n for n in cell:\n darts_arch[i].append((op_dict[n[1]], n[0]))\n i += 1\n geno = Genotype(normal=darts_arch[0], normal_concat=[2,3,4,5], reduce=darts_arch[1], reduce_concat=[2,3,4,5])\n print(str(geno))\n return str(geno)\n\n\n def train(self, train_queue, model, criterion, optimizer):\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n model.train()\n\n for step, (input, target) in enumerate(train_queue):\n device = torch.device('cuda:{}'.format(self.gpu) if torch.cuda.is_available() else 'cpu')\n input = Variable(input).to(device)\n target = Variable(target).to(device)\n\n optimizer.zero_grad()\n logits, logits_aux = model(input)\n #print(input.shape)\n #print(logits.shape)\n loss = criterion(logits, target)\n if self.auxiliary:\n loss_aux = criterion(logits_aux, target)\n loss += self.auxiliary_weight*loss_aux\n loss.backward()\n nn.utils.clip_grad_norm(model.parameters(), self.grad_clip)\n optimizer.step()\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n\n objs.update(loss.item(), n)\n top1.update(prec1.item(), n)\n top5.update(prec5.item(), n) \n\n if step % self.report_freq == 0:\n logging.info('train %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)\n\n return top1.avg, objs.avg\n\n\n def infer(self, valid_queue, model, criterion, test_data=False):\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n model.eval()\n device = torch.device('cuda:{}'.format(self.gpu) if torch.cuda.is_available() else 'cpu')\n \n for step, (input, target) in enumerate(valid_queue):\n input = Variable(input, volatile=True).to(device)\n target = Variable(target, volatile=True).to(device)\n\n logits, _ = model(input)\n loss = criterion(logits, target)\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n\n objs.update(loss.item(), n)\n top1.update(prec1.item(), n)\n top5.update(prec5.item(), n) \n\n if step % self.report_freq == 0:\n if not test_data:\n logging.info('valid %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)\n else:\n logging.info('test %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)\n\n return top1.avg, objs.avg\n\n\n\n", "import os\nimport numpy as np\nimport torch\nimport shutil\nfrom torch.autograd import Variable\nimport math\nimport gzip\nimport pickle\nfrom torch import nn\n\nimport torch.utils.data as data_utils\n\nimport torchvision\nfrom torchvision import transforms\n\n\ndef load_data(task, path, train=True, permute=False):\n '''use train=True to have validation split, otherwise set to false'''\n\n\n if task == 'scifar100':\n return load_scifar100_data(path, 0.2, train)\n\n elif task == 'ninapro':\n return load_ninapro_data(path, train)\n\n elif task == 'cifar100':\n trainset, valset = load_cifar100_train_data(path, permute, 0.2, train)\n testset = load_cifar100_test_data(path, permute)\n return trainset, valset, testset\n\n else:\n raise NotImplementedError\n\n\n\n'''\nStandard and Permuted CIFAR-100 related\n'''\ndef bitreversal_permutation(n):\n log_n = int(math.log2(n))\n assert n == 1 << log_n, 'n must be a power of 2'\n perm = np.arange(n).reshape(n, 1)\n for i in range(log_n):\n n1 = perm.shape[0] // 2\n perm = np.hstack((perm[:n1], perm[n1:]))\n perm = perm.squeeze(0)\n return torch.tensor(perm)\n\nclass RowColPermute(nn.Module):\n\n def __init__(self):\n super().__init__()\n #self.rowperm = torch.randperm(row) if type(row) == int else row\n #self.colperm = torch.randperm(col) if type(col) == int else col\n self.rowperm = bitreversal_permutation(32)\n self.colperm = bitreversal_permutation(32)\n \n def forward(self, tensor):\n return tensor[:, self.rowperm][:, :, self.colperm]\n\n\n\ndef load_cifar100_train_data(path, permute=False, val_split=0.2, train=True):\n #We could include cutout in transforms\n CIFAR_MEAN = [0.5071, 0.4867, 0.4408]\n CIFAR_STD = [0.2675, 0.2565, 0.2761]\n normalize = transforms.Normalize(CIFAR_MEAN,\n CIFAR_STD)\n\n if permute:\n permute_op = RowColPermute()\n transform = transforms.Compose([transforms.ToTensor(), permute_op, normalize])\n\n else:\n transform = transforms.Compose(\n [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(),\n normalize]\n )\n\n all_trainset = torchvision.datasets.CIFAR100(\n root=path, train=True, download=True, transform=transform\n )\n\n if val_split==0.0 or not train:\n return all_trainset, None\n\n n_train = int((1-val_split) * len(all_trainset))\n train_ind = torch.arange(n_train)\n val_ind = torch.arange(n_train, len(all_trainset))\n trainset = data_utils.Subset(all_trainset, train_ind)\n valset = data_utils.Subset(all_trainset, val_ind)\n\n return trainset, valset\n\ndef load_cifar100_test_data(path, permute=False):\n CIFAR_MEAN = [0.5071, 0.4867, 0.4408]\n CIFAR_STD = [0.2675, 0.2565, 0.2761]\n\n normalize = transforms.Normalize(CIFAR_MEAN,\n CIFAR_STD)\n if permute:\n permute_op = RowColPermute()\n transform = transforms.Compose([transforms.ToTensor(), permute_op, normalize])\n\n else:\n transform = transforms.Compose(\n [transforms.ToTensor(), normalize]\n )\n\n testset = torchvision.datasets.CIFAR100(\n root=path, train=False, download=True, transform=transform\n )\n\n return testset\n\n'''\nSpherical CIFAR-100 related\n'''\ndef load_scifar100_data(path, val_split=0.2, train=True):\n\n data_file = os.path.join(path, 's2_cifar100.gz')\n with gzip.open(data_file, 'rb') as f:\n dataset = pickle.load(f)\n\n train_data = torch.from_numpy(\n dataset[\"train\"][\"images\"][:, :, :, :].astype(np.float32))\n train_labels = torch.from_numpy(\n dataset[\"train\"][\"labels\"].astype(np.int64))\n\n\n all_train_dataset = data_utils.TensorDataset(train_data, train_labels)\n print(len(all_train_dataset))\n if val_split == 0.0 or not train:\n val_dataset = None\n train_dataset = all_train_dataset\n else:\n ntrain = int((1-val_split) * len(all_train_dataset))\n train_dataset = data_utils.TensorDataset(train_data[:ntrain], train_labels[:ntrain])\n val_dataset = data_utils.TensorDataset(train_data[ntrain:], train_labels[ntrain:])\n\n print(len(train_dataset))\n test_data = torch.from_numpy(\n dataset[\"test\"][\"images\"][:, :, :, :].astype(np.float32))\n test_labels = torch.from_numpy(\n dataset[\"test\"][\"labels\"].astype(np.int64))\n\n test_dataset = data_utils.TensorDataset(test_data, test_labels)\n\n return train_dataset, val_dataset, test_dataset\n\n\n\n'''\nsEMG Ninapro DB5 related\n'''\ndef load_ninapro_data(path, train=True):\n\n trainset = load_ninapro(path, 'train')\n valset = load_ninapro(path, 'val')\n testset = load_ninapro(path, 'test')\n\n if train:\n return trainset, valset, testset\n\n else:\n trainset = data_utils.ConcatDataset([trainset, valset])\n\n return trainset, None, testset\n\ndef load_ninapro(path, whichset):\n data_str = 'ninapro_' + whichset + '.npy'\n label_str = 'label_' + whichset + '.npy'\n\n data = np.load(os.path.join(path, data_str),\n encoding=\"bytes\", allow_pickle=True)\n labels = np.load(os.path.join(path, label_str), encoding=\"bytes\", allow_pickle=True)\n\n data = np.transpose(data, (0, 2, 1))\n data = data[:, None, :, :]\n print(data.shape)\n print(labels.shape)\n data = torch.from_numpy(data.astype(np.float32))\n labels = torch.from_numpy(labels.astype(np.int64))\n\n all_data = data_utils.TensorDataset(data, labels)\n return all_data\n\n\n" ]
[ [ "torch.sigmoid", "torch.optim.lr_scheduler.LambdaLR", "torch.nn.CrossEntropyLoss", "numpy.asarray", "torch.nn.BCEWithLogitsLoss", "torch.no_grad", "numpy.mean", "sklearn.metrics.average_precision_score" ], [ "torch.nn.CrossEntropyLoss", "torch.max", "torch.manual_seed", "torch.utils.data.TensorDataset", "torch.utils.data.DataLoader", "torch.from_numpy", "torch.nn.Linear", "torch.no_grad", "torch.cuda.is_available", "numpy.load", "torch.nn.ReLU" ], [ "tensorflow.compat.v1.keras.metrics.kullback_leibler_divergence", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.gradients", "numpy.concatenate", "tensorflow.compat.v1.contrib.keras.initializers.he_normal", "tensorflow.compat.v1.compat.v1.disable_eager_execution", "tensorflow.compat.v1.identity", "tensorflow.python.training.moving_averages.assign_moving_average", "numpy.arange", "tensorflow.compat.v1.abs", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.sigmoid", "tensorflow.compat.v1.constant_initializer", "numpy.random.set_state", "tensorflow.compat.v1.variable_scope", "tensorflow.compat.v1.square", "tensorflow.compat.v1.exp", "numpy.random.choice", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.get_variable", "tensorflow.compat.v1.keras.initializers.he_normal", "tensorflow.compat.v1.split", "tensorflow.compat.v1.tanh", "tensorflow.compat.v1.keras.losses.binary_crossentropy", "tensorflow.compat.v1.clip_by_value", "tensorflow.compat.v1.nn.fused_batch_norm", "numpy.random.get_state", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.control_dependencies", "numpy.random.shuffle", "tensorflow.compat.v1.keras.backend.binary_crossentropy", "tensorflow.compat.v1.__version__.startswith", "tensorflow.compat.v1.squeeze", "tensorflow.compat.v1.keras.losses.categorical_crossentropy" ], [ "torch.nn.CrossEntropyLoss", "torch.load", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.utils.data.sampler.SubsetRandomSampler", "torch.cuda.is_available", "torch.cuda.manual_seed_all", "torch.device", "numpy.floor", "torch.autograd.Variable" ], [ "numpy.hstack", "numpy.arange", "torch.utils.data.TensorDataset", "numpy.transpose", "torch.tensor", "torch.utils.data.ConcatDataset", "torch.arange", "torch.utils.data.Subset" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
reeechart/ricommender
[ "c5cdf1cb9db27b9fc4a2553aee2b705b9ad0b95a" ]
[ "music_extractor.py" ]
[ "import csv\nimport eyed3\nimport librosa\nimport numpy as np\nimport sys\n\ndef load_editorial_metadata(audiofile):\n '''Loads an audio file and extract its editorial metadata\n\n Args:\n audiofile (string): audio file to be extracted.\n\n Returns:\n title (string): title of the mp3 file\n artist (string): artist/singer of the song in mp3 file\n album (string): name of album of the mp3 file\n '''\n audio = eyed3.load(audiofile)\n\n return audio.tag.title, audio.tag.artist, audio.tag.album\n\ndef get_reformatted_music_file_directory(file):\n '''Returns a reformatted music file directory\n\n Args:\n file (string): audio file directory to be reformatted\n\n Returns:\n directory (string): reformatted music file directory\n '''\n\n splitted_dir = file.split('\\\\')\n directory = '/'.join(splitted_dir[-2:])\n \n return directory\n\ndef extract_music_content(directory):\n '''Extracts mp3 metadata from a specified directory\n\n Args:\n directory (string): directory that contains the mp3 files\n\n Returns:\n metadata ([string]): list of mp3 metadata with a structure of \n (file, title, artist, album, mfcc, zcr, tempo, chroma_stft)\n '''\n all_metadata = [['id', 'file', 'title', 'artist', 'album', 'mfcc', 'zcr', 'tempo', 'pitch', 'chroma', 'num_frames']]\n\n files = librosa.util.find_files(directory, ext='mp3')\n\n for idx, file in enumerate(files):\n print('Extracting ', file, '...')\n music_metadata = []\n\n music_metadata.append(idx)\n\n title, artist, album = load_editorial_metadata(file)\n \n music_metadata.append(get_reformatted_music_file_directory(file))\n music_metadata.append(title)\n music_metadata.append(artist)\n music_metadata.append(album)\n\n wf, sr = librosa.load(file)\n\n mfcc = librosa.feature.mfcc(y=wf, sr=sr)\n music_metadata.append(np.mean(mfcc))\n\n zcr = librosa.feature.zero_crossing_rate(y=wf)\n music_metadata.append(np.mean(zcr))\n\n tempo = librosa.beat.tempo(y=wf, sr=sr)\n music_metadata.append(tempo[0])\n\n # Get pitches array and its corresponding power (magnitude)\n pitches, magnitudes = librosa.piptrack(y=wf, sr=sr)\n\n # Select pitches with high energy (bigger than its median)\n pitches = pitches[magnitudes > np.median(magnitudes)]\n pitch = librosa.pitch_tuning(pitches)\n music_metadata.append(pitch)\n\n chroma_stft = librosa.feature.chroma_stft(y=wf, sr=sr)\n music_metadata.append(np.mean(chroma_stft))\n music_metadata.append(len(mfcc[0]))\n\n all_metadata.append(music_metadata)\n \n return all_metadata\n\ndef extract_music_frames(directory):\n '''Extracts mp3 metadata by frame\n\n Args:\n directory (string): directory that contains mp3 files\n\n Returns:\n metadata ([string]): all frames metadata\n '''\n all_metadata = [['id', 'mean_thirteen_first_mfcc', 'zcr', 'max_chroma']]\n\n files = librosa.util.find_files(directory, ext='mp3')\n\n for idx, file in enumerate(files):\n print('Extracting ', file, '...')\n\n title, artist, _ = load_editorial_metadata(file)\n\n wf, sr = librosa.load(file)\n\n mfcc = librosa.feature.mfcc(y=wf, sr=sr)\n mfcc = np.mean(mfcc[:13], axis=0) # take the first 13 mfcc values\n\n zcr = librosa.feature.zero_crossing_rate(y=wf)\n zcr = np.mean(zcr, axis=0)\n\n chroma_stft = librosa.feature.chroma_stft(y=wf, sr=sr)\n chroma_stft_max = np.argmax(chroma_stft, axis=0)\n\n for i in range(len(mfcc)):\n music_frame_metadata = []\n music_frame_metadata.append(idx)\n music_frame_metadata.append(mfcc[i])\n music_frame_metadata.append(zcr[i])\n music_frame_metadata.append(chroma_stft_max[i])\n\n all_metadata.append(music_frame_metadata)\n \n return all_metadata\n\ndef save_to_csv(data, csv_file):\n '''Saves data (list) to a csv file\n\n Args:\n data ([object]): list of metadata to be saved\n '''\n print('Saving metadata to ', csv_file, '...')\n with open(csv_file, 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(data)\n\ndef exit_with_msg(msg):\n '''Exit with a custom message\n\n Args:\n msg (string): exit message\n '''\n print(msg)\n sys.exit()\n\ndef check_arguments(argv):\n '''Check arguments when running the program\n\n Args:\n argv ([string]): list of arguments\n '''\n if (len(argv) != 4):\n exit_with_msg('Need 4 arguments to continue')\n else:\n extraction_type = sys.argv[1]\n music_folder = sys.argv[2]\n csv_file = sys.argv[3]\n return extraction_type, music_folder, csv_file\n\n# Main program\nif __name__ == '__main__':\n extraction_type, music_folder, csv_file = check_arguments(sys.argv)\n if (extraction_type == 'extract_music'):\n metadata = extract_music_content(music_folder)\n save_to_csv(metadata, csv_file)\n elif (extraction_type == 'extract_music_frame'):\n metadata = extract_music_frames(music_folder)\n save_to_csv(metadata, csv_file)\n else:\n exit_with_msg('Extraction type invalid, please use only \\'extract_music\\' or \\'extract_music_frame\\'')\n" ]
[ [ "numpy.median", "numpy.argmax", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
basarane/model-based-rl
[ "af7ba84c272054d1de0b8cf9cc91b571abe91c3d" ]
[ "src/old_code/utils_old.py" ]
[ "import keras.backend as K\nimport numpy as np\nfrom PIL import Image, ImageDraw\n\ndef get_activations(model, model_inputs, print_shape_only=False, layer_name=None):\n\tprint('----- activations -----')\n\tactivations = []\n\tinp = model.input\n\n\tmodel_multi_inputs_cond = True\n\tif not isinstance(inp, list):\n\t\t# only one input! let's wrap it in a list.\n\t\tinp = [inp]\n\t\tmodel_multi_inputs_cond = False\n\n\t#from pprint import pprint\n\t#pprint(vars(model.layers[3]))\n\n\tfor layer in model.layers:\n\t\tprint(layer.name, len(layer.outbound_nodes), len(layer.inbound_nodes))\n\t\tfor I in range(len(layer.inbound_nodes)):\n\t\t\to1 = layer.get_output_at(I)\n\t\t\tprint(o1.name, o1.shape)\n\t\t\t\n\toutputs = [[layer.get_output_at(I) for I in range(len(layer.inbound_nodes))] for layer in model.layers if (layer.name == layer_name or layer_name is None)]\n\toutputs = [item for sublist in outputs for item in sublist]\n\t#outputs.extend([])\n\n\tfuncs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs] # evaluation functions\n\n\tif model_multi_inputs_cond:\n\t\tlist_inputs = []\n\t\tlist_inputs.extend(model_inputs)\n\t\tlist_inputs.append(0.)\n\telse:\n\t\tlist_inputs = [model_inputs, 0.]\n\n\tprint(\"model_multi_inputs_cond\", model_multi_inputs_cond, len(list_inputs))\n\t# Learning phase. 0 = Test mode (no dropout or batch normalization)\n\t# layer_outputs = [func([model_inputs, 0.])[0] for func in funcs]\n\tlayer_outputs = [func(list_inputs)[0] for func in funcs]\n\tfor layer_activations in layer_outputs:\n\t\tactivations.append(layer_activations)\n\t\tif print_shape_only:\n\t\t\tprint(layer_activations.shape)\n\t\telse:\n\t\t\tprint(layer_activations)\n\treturn activations\n\ndef toRGBImage(x):\n\tim = Image.fromarray(x)\n\tim = im.convert('RGB') \n\treturn np.array(im, dtype='uint8')\n\ndef\tprediction_to_image(prediction, meanImage):\n\tpredOutput = np.array(prediction)*255.0\n\tpredOutput = predOutput + meanImage\n\tpredOutput[predOutput<0] = 0\n\tpredOutput[predOutput>255] = 255\n\tpredOutput = np.array(predOutput, dtype=\"uint8\")\n\tpredImage = np.squeeze(predOutput)\n\treturn predImage\n\t\ndef draw_reward(predImage, reward):\n\tim = Image.fromarray(predImage)\n\tdraw = ImageDraw.Draw(im)\n\tw = 100\n\tx = 57\n\tdraw.rectangle([x,196,x+int(w*reward),208], \"#fff\", None)\n\tdraw.rectangle([x,196,x+w,208], None, \"#f00\")\n\tpredImage = np.array(im)\n\treturn predImage\n\ndef get_obs_input(lastFramesOrig, meanImage):\n\tnetin = np.array(lastFramesOrig, dtype='f')/255.0\n\tnetin = np.squeeze(netin)\n\tnetin = np.transpose(netin, (0,3,1,2))\n\tnetin = np.reshape(netin, (12, 210,160))\n\tnetin = netin - np.tile(np.transpose(meanImage/255.0, (2,0,1)), (4,1,1))\n\tnetin = np.reshape(netin, (1, 12, 210,160))\n\treturn netin\n\t" ]
[ [ "numpy.reshape", "numpy.squeeze", "numpy.array", "numpy.transpose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EmmaRenauld/dwi_ml
[ "f2f776199dd886509d15520aa68099a8c870a233", "f2f776199dd886509d15520aa68099a8c870a233" ]
[ "dwi_ml/models/utils/fisher_von_mises.py", "dwi_ml/models/utils/gaussians.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport torch\n\n\"\"\"\nThe complete formulas and explanations are available in our doc:\nhttps://dwi-ml.readthedocs.io/en/latest/formulas.html\n\"\"\"\n\n\ndef fisher_von_mises_log_prob_vector(mus, kappa, targets):\n log_c = np.log(kappa) - np.log(2 * np.pi) - np.log(np.exp(kappa) -\n np.exp(-kappa))\n log_prob = log_c + (kappa * (mus * targets).sum(axis=-1))\n return log_prob\n\n\ndef fisher_von_mises_log_prob(mus, kappa, targets, eps=1e-6):\n log_2pi = np.log(2 * np.pi).astype(np.float32)\n\n # Add an epsilon in case kappa is too small (i.e. a uniform\n # distribution)\n log_diff_exp_kappa = torch.log(torch.exp(kappa) - torch.exp(-kappa) + eps)\n log_c = torch.log(kappa) - log_2pi - log_diff_exp_kappa\n\n batch_dot_product = torch.sum(mus * targets, dim=1)\n\n log_prob = log_c + (kappa * batch_dot_product)\n\n return log_prob\n", "# -*- coding: utf-8 -*-\n\nimport numpy as np\n\n\"\"\"\nThe complete formulas and explanations are available in our doc:\nhttps://dwi-ml.readthedocs.io/en/latest/formulas.html\n\"\"\"\nd = 3\n\n\ndef independent_gaussian_log_prob(targets, mus, sigmas):\n \"\"\"\n This function computes the log likelihood for **individual** multivariate\n Gaussians, computed from tensors.\n\n If K>1 (the number of Gaussians), then the variables mu and sigma contain\n the information for many Gaussians, and log likelihoods for each Gaussian\n are returned.\n\n Parameters\n ----------\n targets: torch.tensor\n The variable, of shape [batch_size, none, d], d=3.\n mus: torch.tensor\n The mean, of size [batch_size, n, d], d=3.\n sigmas: torch.tensor\n The standard deviation\n \"\"\"\n log_2pi = np.log(2 * np.pi).astype(np.float32)\n squared_m = ((targets - mus) / sigmas).pow(2).sum(dim=-1)\n log_det = sigmas.log().sum(dim=-1)\n\n gaussians_log_prob = -0.5 * (d * log_2pi + squared_m) - log_det\n\n return gaussians_log_prob\n" ]
[ [ "numpy.log", "torch.sum", "torch.exp", "torch.log", "numpy.exp" ], [ "numpy.log" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
quattro/numpyro
[ "b7b6e937297ea47c55760446134f84fc82936a9d", "b7b6e937297ea47c55760446134f84fc82936a9d", "b7b6e937297ea47c55760446134f84fc82936a9d" ]
[ "examples/annotation.py", "numpyro/infer/util.py", "examples/covtype.py" ]
[ "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nExample: Bayesian Models of Annotation\n======================================\n\nIn this example, we run MCMC for various crowdsourced annotation models in [1].\n\nAll models have discrete latent variables. Under the hood, we enumerate over\n(marginalize out) those discrete latent sites in inference. Those models have different\ncomplexity so they are great refererences for those who are new to Pyro/NumPyro\nenumeration mechanism. We recommend readers compare the implementations with the\ncorresponding plate diagrams in [1] to see how concise a Pyro/NumPyro program is.\n\nThe interested readers can also refer to [3] for more explanation about enumeration.\n\nThe data is taken from Table 1 of reference [2].\n\nCurrently, this example does not include postprocessing steps to deal with \"Label\nSwitching\" issue (mentioned in section 6.2 of [1]).\n\n**References:**\n\n 1. Paun, S., Carpenter, B., Chamberlain, J., Hovy, D., Kruschwitz, U.,\n and Poesio, M. (2018). \"Comparing bayesian models of annotation\"\n (https://www.aclweb.org/anthology/Q18-1040/)\n 2. Dawid, A. P., and Skene, A. M. (1979).\n \"Maximum likelihood estimation of observer error‐rates using the EM algorithm\"\n 3. \"Inference with Discrete Latent Variables\"\n (http://pyro.ai/examples/enumeration.html)\n\n\"\"\"\n\nimport argparse\nimport os\n\nimport numpy as np\n\nfrom jax import nn, random, vmap\nimport jax.numpy as jnp\n\nimport numpyro\nfrom numpyro import handlers\nfrom numpyro.contrib.indexing import Vindex\nimport numpyro.distributions as dist\nfrom numpyro.infer import MCMC, NUTS, Predictive\nfrom numpyro.infer.reparam import LocScaleReparam\n\n\ndef get_data():\n \"\"\"\n :return: a tuple of annotator indices and class indices. The first term has shape\n `num_positions` whose entries take values from `0` to `num_annotators - 1`.\n The second term has shape `num_items x num_positions` whose entries take values\n from `0` to `num_classes - 1`.\n \"\"\"\n # NB: the first annotator assessed each item 3 times\n positions = np.array([1, 1, 1, 2, 3, 4, 5])\n annotations = np.array(\n [\n [1, 1, 1, 1, 1, 1, 1],\n [3, 3, 3, 4, 3, 3, 4],\n [1, 1, 2, 2, 1, 2, 2],\n [2, 2, 2, 3, 1, 2, 1],\n [2, 2, 2, 3, 2, 2, 2],\n [2, 2, 2, 3, 3, 2, 2],\n [1, 2, 2, 2, 1, 1, 1],\n [3, 3, 3, 3, 4, 3, 3],\n [2, 2, 2, 2, 2, 2, 3],\n [2, 3, 2, 2, 2, 2, 3],\n [4, 4, 4, 4, 4, 4, 4],\n [2, 2, 2, 3, 3, 4, 3],\n [1, 1, 1, 1, 1, 1, 1],\n [2, 2, 2, 3, 2, 1, 2],\n [1, 2, 1, 1, 1, 1, 1],\n [1, 1, 1, 2, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [2, 2, 2, 2, 2, 2, 1],\n [2, 2, 2, 1, 3, 2, 2],\n [2, 2, 2, 2, 2, 2, 2],\n [2, 2, 2, 2, 2, 2, 1],\n [2, 2, 2, 3, 2, 2, 2],\n [2, 2, 1, 2, 2, 2, 2],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [2, 3, 2, 2, 2, 2, 2],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 2, 1, 1, 2, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [3, 3, 3, 3, 2, 3, 3],\n [1, 1, 1, 1, 1, 1, 1],\n [2, 2, 2, 2, 2, 2, 2],\n [2, 2, 2, 3, 2, 3, 2],\n [4, 3, 3, 4, 3, 4, 3],\n [2, 2, 1, 2, 2, 3, 2],\n [2, 3, 2, 3, 2, 3, 3],\n [3, 3, 3, 3, 4, 3, 2],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 2, 1, 2, 1, 1, 1],\n [2, 3, 2, 2, 2, 2, 2],\n [1, 2, 1, 1, 1, 1, 1],\n [2, 2, 2, 2, 2, 2, 2],\n ]\n )\n # we minus 1 because in Python, the first index is 0\n return positions - 1, annotations - 1\n\n\ndef multinomial(annotations):\n \"\"\"\n This model corresponds to the plate diagram in Figure 1 of reference [1].\n \"\"\"\n num_classes = int(np.max(annotations)) + 1\n num_items, num_positions = annotations.shape\n\n with numpyro.plate(\"class\", num_classes):\n zeta = numpyro.sample(\"zeta\", dist.Dirichlet(jnp.ones(num_classes)))\n\n pi = numpyro.sample(\"pi\", dist.Dirichlet(jnp.ones(num_classes)))\n\n with numpyro.plate(\"item\", num_items, dim=-2):\n c = numpyro.sample(\"c\", dist.Categorical(pi))\n\n with numpyro.plate(\"position\", num_positions):\n numpyro.sample(\"y\", dist.Categorical(zeta[c]), obs=annotations)\n\n\ndef dawid_skene(positions, annotations):\n \"\"\"\n This model corresponds to the plate diagram in Figure 2 of reference [1].\n \"\"\"\n num_annotators = int(np.max(positions)) + 1\n num_classes = int(np.max(annotations)) + 1\n num_items, num_positions = annotations.shape\n\n with numpyro.plate(\"annotator\", num_annotators, dim=-2):\n with numpyro.plate(\"class\", num_classes):\n beta = numpyro.sample(\"beta\", dist.Dirichlet(jnp.ones(num_classes)))\n\n pi = numpyro.sample(\"pi\", dist.Dirichlet(jnp.ones(num_classes)))\n\n with numpyro.plate(\"item\", num_items, dim=-2):\n c = numpyro.sample(\"c\", dist.Categorical(pi))\n\n # here we use Vindex to allow broadcasting for the second index `c`\n # ref: http://num.pyro.ai/en/latest/utilities.html#numpyro.contrib.indexing.vindex\n with numpyro.plate(\"position\", num_positions):\n numpyro.sample(\n \"y\", dist.Categorical(Vindex(beta)[positions, c, :]), obs=annotations\n )\n\n\ndef mace(positions, annotations):\n \"\"\"\n This model corresponds to the plate diagram in Figure 3 of reference [1].\n \"\"\"\n num_annotators = int(np.max(positions)) + 1\n num_classes = int(np.max(annotations)) + 1\n num_items, num_positions = annotations.shape\n\n with numpyro.plate(\"annotator\", num_annotators):\n epsilon = numpyro.sample(\"epsilon\", dist.Dirichlet(jnp.full(num_classes, 10)))\n theta = numpyro.sample(\"theta\", dist.Beta(0.5, 0.5))\n\n with numpyro.plate(\"item\", num_items, dim=-2):\n # NB: using constant logits for discrete uniform prior\n # (NumPyro does not have DiscreteUniform distribution yet)\n c = numpyro.sample(\"c\", dist.Categorical(logits=jnp.zeros(num_classes)))\n\n with numpyro.plate(\"position\", num_positions):\n s = numpyro.sample(\"s\", dist.Bernoulli(1 - theta[positions]))\n probs = jnp.where(\n s[..., None] == 0, nn.one_hot(c, num_classes), epsilon[positions]\n )\n numpyro.sample(\"y\", dist.Categorical(probs), obs=annotations)\n\n\ndef hierarchical_dawid_skene(positions, annotations):\n \"\"\"\n This model corresponds to the plate diagram in Figure 4 of reference [1].\n \"\"\"\n num_annotators = int(np.max(positions)) + 1\n num_classes = int(np.max(annotations)) + 1\n num_items, num_positions = annotations.shape\n\n with numpyro.plate(\"class\", num_classes):\n # NB: we define `beta` as the `logits` of `y` likelihood; but `logits` is\n # invariant up to a constant, so we'll follow [1]: fix the last term of `beta`\n # to 0 and only define hyperpriors for the first `num_classes - 1` terms.\n zeta = numpyro.sample(\n \"zeta\", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)\n )\n omega = numpyro.sample(\n \"Omega\", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)\n )\n\n with numpyro.plate(\"annotator\", num_annotators, dim=-2):\n with numpyro.plate(\"class\", num_classes):\n # non-centered parameterization\n with handlers.reparam(config={\"beta\": LocScaleReparam(0)}):\n beta = numpyro.sample(\"beta\", dist.Normal(zeta, omega).to_event(1))\n # pad 0 to the last item\n beta = jnp.pad(beta, [(0, 0)] * (jnp.ndim(beta) - 1) + [(0, 1)])\n\n pi = numpyro.sample(\"pi\", dist.Dirichlet(jnp.ones(num_classes)))\n\n with numpyro.plate(\"item\", num_items, dim=-2):\n c = numpyro.sample(\"c\", dist.Categorical(pi))\n\n with numpyro.plate(\"position\", num_positions):\n logits = Vindex(beta)[positions, c, :]\n numpyro.sample(\"y\", dist.Categorical(logits=logits), obs=annotations)\n\n\ndef item_difficulty(annotations):\n \"\"\"\n This model corresponds to the plate diagram in Figure 5 of reference [1].\n \"\"\"\n num_classes = int(np.max(annotations)) + 1\n num_items, num_positions = annotations.shape\n\n with numpyro.plate(\"class\", num_classes):\n eta = numpyro.sample(\n \"eta\", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)\n )\n chi = numpyro.sample(\n \"Chi\", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)\n )\n\n pi = numpyro.sample(\"pi\", dist.Dirichlet(jnp.ones(num_classes)))\n\n with numpyro.plate(\"item\", num_items, dim=-2):\n c = numpyro.sample(\"c\", dist.Categorical(pi))\n\n with handlers.reparam(config={\"theta\": LocScaleReparam(0)}):\n theta = numpyro.sample(\"theta\", dist.Normal(eta[c], chi[c]).to_event(1))\n theta = jnp.pad(theta, [(0, 0)] * (jnp.ndim(theta) - 1) + [(0, 1)])\n\n with numpyro.plate(\"position\", annotations.shape[-1]):\n numpyro.sample(\"y\", dist.Categorical(logits=theta), obs=annotations)\n\n\ndef logistic_random_effects(positions, annotations):\n \"\"\"\n This model corresponds to the plate diagram in Figure 5 of reference [1].\n \"\"\"\n num_annotators = int(np.max(positions)) + 1\n num_classes = int(np.max(annotations)) + 1\n num_items, num_positions = annotations.shape\n\n with numpyro.plate(\"class\", num_classes):\n zeta = numpyro.sample(\n \"zeta\", dist.Normal(0, 1).expand([num_classes - 1]).to_event(1)\n )\n omega = numpyro.sample(\n \"Omega\", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)\n )\n chi = numpyro.sample(\n \"Chi\", dist.HalfNormal(1).expand([num_classes - 1]).to_event(1)\n )\n\n with numpyro.plate(\"annotator\", num_annotators, dim=-2):\n with numpyro.plate(\"class\", num_classes):\n with handlers.reparam(config={\"beta\": LocScaleReparam(0)}):\n beta = numpyro.sample(\"beta\", dist.Normal(zeta, omega).to_event(1))\n beta = jnp.pad(beta, [(0, 0)] * (jnp.ndim(beta) - 1) + [(0, 1)])\n\n pi = numpyro.sample(\"pi\", dist.Dirichlet(jnp.ones(num_classes)))\n\n with numpyro.plate(\"item\", num_items, dim=-2):\n c = numpyro.sample(\"c\", dist.Categorical(pi))\n\n with handlers.reparam(config={\"theta\": LocScaleReparam(0)}):\n theta = numpyro.sample(\"theta\", dist.Normal(0, chi[c]).to_event(1))\n theta = jnp.pad(theta, [(0, 0)] * (jnp.ndim(theta) - 1) + [(0, 1)])\n\n with numpyro.plate(\"position\", num_positions):\n logits = Vindex(beta)[positions, c, :] - theta\n numpyro.sample(\"y\", dist.Categorical(logits=logits), obs=annotations)\n\n\nNAME_TO_MODEL = {\n \"mn\": multinomial,\n \"ds\": dawid_skene,\n \"mace\": mace,\n \"hds\": hierarchical_dawid_skene,\n \"id\": item_difficulty,\n \"lre\": logistic_random_effects,\n}\n\n\ndef main(args):\n annotators, annotations = get_data()\n model = NAME_TO_MODEL[args.model]\n data = (\n (annotations,)\n if model in [multinomial, item_difficulty]\n else (annotators, annotations)\n )\n\n mcmc = MCMC(\n NUTS(model),\n num_warmup=args.num_warmup,\n num_samples=args.num_samples,\n num_chains=args.num_chains,\n progress_bar=False if \"NUMPYRO_SPHINXBUILD\" in os.environ else True,\n )\n mcmc.run(random.PRNGKey(0), *data)\n mcmc.print_summary()\n\n posterior_samples = mcmc.get_samples()\n predictive = Predictive(model, posterior_samples, infer_discrete=True)\n discrete_samples = predictive(random.PRNGKey(1), *data)\n\n item_class = vmap(lambda x: jnp.bincount(x, length=4), in_axes=1)(\n discrete_samples[\"c\"].squeeze(-1)\n )\n print(\"Histogram of the predicted class of each item:\")\n row_format = \"{:>10}\" * 5\n print(row_format.format(\"\", *[\"c={}\".format(i) for i in range(4)]))\n for i, row in enumerate(item_class):\n print(row_format.format(f\"item[{i}]\", *row))\n\n\nif __name__ == \"__main__\":\n assert numpyro.__version__.startswith(\"0.7.2\")\n parser = argparse.ArgumentParser(description=\"Bayesian Models of Annotation\")\n parser.add_argument(\"-n\", \"--num-samples\", nargs=\"?\", default=1000, type=int)\n parser.add_argument(\"--num-warmup\", nargs=\"?\", default=1000, type=int)\n parser.add_argument(\"--num-chains\", nargs=\"?\", default=1, type=int)\n parser.add_argument(\n \"--model\",\n nargs=\"?\",\n default=\"ds\",\n help='one of \"mn\" (multinomial), \"ds\" (dawid_skene), \"mace\",'\n ' \"hds\" (hierarchical_dawid_skene),'\n ' \"id\" (item_difficulty), \"lre\" (logistic_random_effects)',\n )\n parser.add_argument(\"--device\", default=\"cpu\", type=str, help='use \"cpu\" or \"gpu\".')\n args = parser.parse_args()\n\n numpyro.set_platform(args.device)\n numpyro.set_host_device_count(args.num_chains)\n\n main(args)\n", "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom functools import partial\nimport warnings\n\nimport numpy as np\n\nfrom jax import device_get, jacfwd, lax, random, value_and_grad\nfrom jax.flatten_util import ravel_pytree\nimport jax.numpy as jnp\nfrom jax.tree_util import tree_map\n\nimport numpyro\nfrom numpyro.distributions import constraints\nfrom numpyro.distributions.transforms import biject_to\nfrom numpyro.distributions.util import is_identically_one, sum_rightmost\nfrom numpyro.handlers import condition, replay, seed, substitute, trace\nfrom numpyro.infer.initialization import init_to_uniform, init_to_value\nfrom numpyro.util import not_jax_tracer, soft_vmap, while_loop\n\n__all__ = [\n \"find_valid_initial_params\",\n \"get_potential_fn\",\n \"log_density\",\n \"log_likelihood\",\n \"potential_energy\",\n \"initialize_model\",\n \"Predictive\",\n]\n\nModelInfo = namedtuple(\n \"ModelInfo\", [\"param_info\", \"potential_fn\", \"postprocess_fn\", \"model_trace\"]\n)\nParamInfo = namedtuple(\"ParamInfo\", [\"z\", \"potential_energy\", \"z_grad\"])\n\n\ndef log_density(model, model_args, model_kwargs, params):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Computes log of joint density for the model given\n latent values ``params``.\n\n :param model: Python callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: dictionary of current parameter values keyed by site\n name.\n :return: log of joint density and a corresponding model trace\n \"\"\"\n model = substitute(model, data=params)\n model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n log_joint = jnp.zeros(())\n for site in model_trace.values():\n if site[\"type\"] == \"sample\":\n value = site[\"value\"]\n intermediates = site[\"intermediates\"]\n scale = site[\"scale\"]\n if intermediates:\n log_prob = site[\"fn\"].log_prob(value, intermediates)\n else:\n log_prob = site[\"fn\"].log_prob(value)\n\n if (scale is not None) and (not is_identically_one(scale)):\n log_prob = scale * log_prob\n\n log_prob = jnp.sum(log_prob)\n log_joint = log_joint + log_prob\n return log_joint, model_trace\n\n\nclass _without_rsample_stop_gradient(numpyro.primitives.Messenger):\n \"\"\"\n Stop gradient for samples at latent sample sites for which has_rsample=False.\n \"\"\"\n\n def postprocess_message(self, msg):\n if (\n msg[\"type\"] == \"sample\"\n and (not msg[\"is_observed\"])\n and (not msg[\"fn\"].has_rsample)\n ):\n msg[\"value\"] = lax.stop_gradient(msg[\"value\"])\n # TODO: reconsider this logic\n # here we clear all the cached value so that gradients of log_prob(value) w.r.t.\n # all parameters of the transformed distributions match the behavior of\n # TransformedDistribution(d, transform) in Pyro with transform.cache_size == 0\n msg[\"intermediates\"] = None\n\n\ndef get_importance_trace(model, guide, args, kwargs, params):\n \"\"\"\n (EXPERIMENTAL) Returns traces from the guide and the model that is run against it.\n The returned traces also store the log probability at each site.\n\n .. note:: Gradients are blocked at latent sites which do not have reparametrized samplers.\n \"\"\"\n guide = substitute(guide, data=params)\n with _without_rsample_stop_gradient():\n guide_trace = trace(guide).get_trace(*args, **kwargs)\n model = substitute(replay(model, guide_trace), data=params)\n model_trace = trace(model).get_trace(*args, **kwargs)\n for tr in (guide_trace, model_trace):\n for site in tr.values():\n if site[\"type\"] == \"sample\":\n if \"log_prob\" not in site:\n value = site[\"value\"]\n intermediates = site[\"intermediates\"]\n scale = site[\"scale\"]\n if intermediates:\n log_prob = site[\"fn\"].log_prob(value, intermediates)\n else:\n log_prob = site[\"fn\"].log_prob(value)\n\n if (scale is not None) and (not is_identically_one(scale)):\n log_prob = scale * log_prob\n site[\"log_prob\"] = log_prob\n return model_trace, guide_trace\n\n\ndef transform_fn(transforms, params, invert=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Callable that applies a transformation from the `transforms`\n dict to values in the `params` dict and returns the transformed values keyed on\n the same names.\n\n :param transforms: Dictionary of transforms keyed by names. Names in\n `transforms` and `params` should align.\n :param params: Dictionary of arrays keyed by names.\n :param invert: Whether to apply the inverse of the transforms.\n :return: `dict` of transformed params.\n \"\"\"\n if invert:\n transforms = {k: v.inv for k, v in transforms.items()}\n return {k: transforms[k](v) if k in transforms else v for k, v in params.items()}\n\n\ndef constrain_fn(model, model_args, model_kwargs, params, return_deterministic=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Gets value at each latent site in `model` given\n unconstrained parameters `params`. The `transforms` is used to transform these\n unconstrained parameters to base values of the corresponding priors in `model`.\n If a prior is a transformed distribution, the corresponding base value lies in\n the support of base distribution. Otherwise, the base value lies in the support\n of the distribution.\n\n :param model: a callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: dictionary of unconstrained values keyed by site\n names.\n :param bool return_deterministic: whether to return the value of `deterministic`\n sites from the model. Defaults to `False`.\n :return: `dict` of transformed params.\n \"\"\"\n\n def substitute_fn(site):\n if site[\"name\"] in params:\n if site[\"type\"] == \"sample\":\n with helpful_support_errors(site):\n return biject_to(site[\"fn\"].support)(params[site[\"name\"]])\n else:\n return params[site[\"name\"]]\n\n substituted_model = substitute(model, substitute_fn=substitute_fn)\n model_trace = trace(substituted_model).get_trace(*model_args, **model_kwargs)\n return {\n k: v[\"value\"]\n for k, v in model_trace.items()\n if (k in params) or (return_deterministic and (v[\"type\"] == \"deterministic\"))\n }\n\n\ndef _unconstrain_reparam(params, site):\n name = site[\"name\"]\n if name in params:\n p = params[name]\n support = site[\"fn\"].support\n with helpful_support_errors(site):\n t = biject_to(support)\n # in scan, we might only want to substitute an item at index i, rather than the whole sequence\n i = site[\"infer\"].get(\"_scan_current_index\", None)\n if i is not None:\n event_dim_shift = t.codomain.event_dim - t.domain.event_dim\n expected_unconstrained_dim = len(site[\"fn\"].shape()) - event_dim_shift\n # check if p has additional time dimension\n if jnp.ndim(p) > expected_unconstrained_dim:\n p = p[i]\n\n if support in [constraints.real, constraints.real_vector]:\n return p\n value = t(p)\n\n log_det = t.log_abs_det_jacobian(p, value)\n log_det = sum_rightmost(\n log_det, jnp.ndim(log_det) - jnp.ndim(value) + len(site[\"fn\"].event_shape)\n )\n if site[\"scale\"] is not None:\n log_det = site[\"scale\"] * log_det\n numpyro.factor(\"_{}_log_det\".format(name), log_det)\n return value\n\n\ndef potential_energy(model, model_args, model_kwargs, params, enum=False):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Computes potential energy of a model given unconstrained params.\n Under the hood, we will transform these unconstrained parameters to the values\n belong to the supports of the corresponding priors in `model`.\n\n :param model: a callable containing NumPyro primitives.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict params: unconstrained parameters of `model`.\n :param bool enum: whether to enumerate over discrete latent sites.\n :return: potential energy given unconstrained parameters.\n \"\"\"\n if enum:\n from numpyro.contrib.funsor import log_density as log_density_\n else:\n log_density_ = log_density\n\n substituted_model = substitute(\n model, substitute_fn=partial(_unconstrain_reparam, params)\n )\n # no param is needed for log_density computation because we already substitute\n log_joint, model_trace = log_density_(\n substituted_model, model_args, model_kwargs, {}\n )\n return -log_joint\n\n\ndef _init_to_unconstrained_value(site=None, values={}):\n if site is None:\n return partial(_init_to_unconstrained_value, values=values)\n\n\ndef find_valid_initial_params(\n rng_key,\n model,\n *,\n init_strategy=init_to_uniform,\n enum=False,\n model_args=(),\n model_kwargs=None,\n prototype_params=None,\n forward_mode_differentiation=False,\n validate_grad=True,\n):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns an initial\n valid unconstrained value for all the parameters. This function also returns\n the corresponding potential energy, the gradients, and an\n `is_valid` flag to say whether the initial parameters are valid. Parameter values\n are considered valid if the values and the gradients for the log density have\n finite values.\n\n :param jax.random.PRNGKey rng_key: random number generator seed to\n sample from the prior. The returned `init_params` will have the\n batch shape ``rng_key.shape[:-1]``.\n :param model: Python callable containing Pyro primitives.\n :param callable init_strategy: a per-site initialization function.\n :param bool enum: whether to enumerate over discrete latent sites.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param dict prototype_params: an optional prototype parameters, which is used\n to define the shape for initial parameters.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. Defaults to False.\n :param bool validate_grad: whether to validate gradient of the initial params.\n Defaults to True.\n :return: tuple of `init_params_info` and `is_valid`, where `init_params_info` is the tuple\n containing the initial params, their potential energy, and their gradients.\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n init_strategy = (\n init_strategy if isinstance(init_strategy, partial) else init_strategy()\n )\n # handle those init strategies differently to save computation\n if init_strategy.func is init_to_uniform:\n radius = init_strategy.keywords.get(\"radius\")\n init_values = {}\n elif init_strategy.func is _init_to_unconstrained_value:\n radius = 2\n init_values = init_strategy.keywords.get(\"values\")\n else:\n radius = None\n\n def cond_fn(state):\n i, _, _, is_valid = state\n return (i < 100) & (~is_valid)\n\n def body_fn(state):\n i, key, _, _ = state\n key, subkey = random.split(key)\n\n if radius is None or prototype_params is None:\n # XXX: we don't want to apply enum to draw latent samples\n model_ = model\n if enum:\n from numpyro.contrib.funsor import enum as enum_handler\n\n if isinstance(model, substitute) and isinstance(model.fn, enum_handler):\n model_ = substitute(model.fn.fn, data=model.data)\n elif isinstance(model, enum_handler):\n model_ = model.fn\n\n # Wrap model in a `substitute` handler to initialize from `init_loc_fn`.\n seeded_model = substitute(seed(model_, subkey), substitute_fn=init_strategy)\n model_trace = trace(seeded_model).get_trace(*model_args, **model_kwargs)\n constrained_values, inv_transforms = {}, {}\n for k, v in model_trace.items():\n if (\n v[\"type\"] == \"sample\"\n and not v[\"is_observed\"]\n and not v[\"fn\"].is_discrete\n ):\n constrained_values[k] = v[\"value\"]\n with helpful_support_errors(v):\n inv_transforms[k] = biject_to(v[\"fn\"].support)\n params = transform_fn(\n inv_transforms,\n {k: v for k, v in constrained_values.items()},\n invert=True,\n )\n else: # this branch doesn't require tracing the model\n params = {}\n for k, v in prototype_params.items():\n if k in init_values:\n params[k] = init_values[k]\n else:\n params[k] = random.uniform(\n subkey, jnp.shape(v), minval=-radius, maxval=radius\n )\n key, subkey = random.split(key)\n\n potential_fn = partial(\n potential_energy, model, model_args, model_kwargs, enum=enum\n )\n if validate_grad:\n if forward_mode_differentiation:\n pe = potential_fn(params)\n z_grad = jacfwd(potential_fn)(params)\n else:\n pe, z_grad = value_and_grad(potential_fn)(params)\n z_grad_flat = ravel_pytree(z_grad)[0]\n is_valid = jnp.isfinite(pe) & jnp.all(jnp.isfinite(z_grad_flat))\n else:\n pe = potential_fn(params)\n is_valid = jnp.isfinite(pe)\n z_grad = None\n\n return i + 1, key, (params, pe, z_grad), is_valid\n\n def _find_valid_params(rng_key, exit_early=False):\n init_state = (0, rng_key, (prototype_params, 0.0, prototype_params), False)\n if exit_early and not_jax_tracer(rng_key):\n # Early return if valid params found. This is only helpful for single chain,\n # where we can avoid compiling body_fn in while_loop.\n _, _, (init_params, pe, z_grad), is_valid = init_state = body_fn(init_state)\n if not_jax_tracer(is_valid):\n if device_get(is_valid):\n return (init_params, pe, z_grad), is_valid\n\n # XXX: this requires compiling the model, so for multi-chain, we trace the model 2-times\n # even if the init_state is a valid result\n _, _, (init_params, pe, z_grad), is_valid = while_loop(\n cond_fn, body_fn, init_state\n )\n return (init_params, pe, z_grad), is_valid\n\n # Handle possible vectorization\n if rng_key.ndim == 1:\n (init_params, pe, z_grad), is_valid = _find_valid_params(\n rng_key, exit_early=True\n )\n else:\n (init_params, pe, z_grad), is_valid = lax.map(_find_valid_params, rng_key)\n return (init_params, pe, z_grad), is_valid\n\n\ndef _get_model_transforms(model, model_args=(), model_kwargs=None):\n model_kwargs = {} if model_kwargs is None else model_kwargs\n model_trace = trace(model).get_trace(*model_args, **model_kwargs)\n inv_transforms = {}\n # model code may need to be replayed in the presence of deterministic sites\n replay_model = False\n has_enumerate_support = False\n for k, v in model_trace.items():\n if v[\"type\"] == \"sample\" and not v[\"is_observed\"]:\n if v[\"fn\"].is_discrete:\n has_enumerate_support = True\n if not v[\"fn\"].has_enumerate_support:\n raise RuntimeError(\n \"MCMC only supports continuous sites or discrete sites \"\n f\"with enumerate support, but got {type(v['fn']).__name__}.\"\n )\n else:\n support = v[\"fn\"].support\n with helpful_support_errors(v, raise_warnings=True):\n inv_transforms[k] = biject_to(support)\n # XXX: the following code filters out most situations with dynamic supports\n args = ()\n if isinstance(support, constraints._GreaterThan):\n args = (\"lower_bound\",)\n elif isinstance(support, constraints._Interval):\n args = (\"lower_bound\", \"upper_bound\")\n for arg in args:\n if not isinstance(getattr(support, arg), (int, float)):\n replay_model = True\n elif v[\"type\"] == \"deterministic\":\n replay_model = True\n return inv_transforms, replay_model, has_enumerate_support, model_trace\n\n\ndef get_potential_fn(\n model,\n inv_transforms,\n *,\n enum=False,\n replay_model=False,\n dynamic_args=False,\n model_args=(),\n model_kwargs=None,\n):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Given a model with Pyro primitives, returns a\n function which, given unconstrained parameters, evaluates the potential\n energy (negative log joint density). In addition, this returns a\n function to transform unconstrained values at sample sites to constrained\n values within their respective support.\n\n :param model: Python callable containing Pyro primitives.\n :param dict inv_transforms: dictionary of transforms keyed by names.\n :param bool enum: whether to enumerate over discrete latent sites.\n :param bool replay_model: whether we need to replay model in\n `postprocess_fn` to obtain `deterministic` sites.\n :param bool dynamic_args: if `True`, the `potential_fn` and\n `constraints_fn` are themselves dependent on model arguments.\n When provided a `*model_args, **model_kwargs`, they return\n `potential_fn` and `constraints_fn` callables, respectively.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :return: tuple of (`potential_fn`, `postprocess_fn`). The latter is used\n to constrain unconstrained samples (e.g. those returned by HMC)\n to values that lie within the site's support, and return values at\n `deterministic` sites in the model.\n \"\"\"\n if dynamic_args:\n\n def potential_fn(*args, **kwargs):\n return partial(potential_energy, model, args, kwargs, enum=enum)\n\n def postprocess_fn(*args, **kwargs):\n if replay_model:\n # XXX: we seed to sample discrete sites (but not collect them)\n model_ = seed(model.fn, 0) if enum else model\n return partial(\n constrain_fn, model_, args, kwargs, return_deterministic=True\n )\n else:\n return partial(transform_fn, inv_transforms)\n\n else:\n model_kwargs = {} if model_kwargs is None else model_kwargs\n potential_fn = partial(\n potential_energy, model, model_args, model_kwargs, enum=enum\n )\n if replay_model:\n model_ = seed(model.fn, 0) if enum else model\n postprocess_fn = partial(\n constrain_fn,\n model_,\n model_args,\n model_kwargs,\n return_deterministic=True,\n )\n else:\n postprocess_fn = partial(transform_fn, inv_transforms)\n\n return potential_fn, postprocess_fn\n\n\ndef _guess_max_plate_nesting(model_trace):\n \"\"\"\n Guesses max_plate_nesting by using model trace.\n This optimistically assumes static model\n structure.\n \"\"\"\n sites = [site for site in model_trace.values() if site[\"type\"] == \"sample\"]\n\n dims = [\n frame.dim\n for site in sites\n for frame in site[\"cond_indep_stack\"]\n if frame.dim is not None\n ]\n max_plate_nesting = -min(dims) if dims else 0\n return max_plate_nesting\n\n\n# TODO: follow pyro.util.check_site_shape logics for more complete validation\ndef _validate_model(model_trace):\n # XXX: this validates plate statements under `enum`\n sites = [site for site in model_trace.values() if site[\"type\"] == \"sample\"]\n\n for site in sites:\n batch_dims = len(site[\"fn\"].batch_shape)\n if site.get(\"_control_flow_done\", False):\n batch_dims = batch_dims - 1 # remove time dimension under scan\n plate_dims = -min([0] + [frame.dim for frame in site[\"cond_indep_stack\"]])\n assert (\n plate_dims >= batch_dims\n ), \"Missing plate statement for batch dimensions at site {}\".format(\n site[\"name\"]\n )\n\n\ndef initialize_model(\n rng_key,\n model,\n *,\n init_strategy=init_to_uniform,\n dynamic_args=False,\n model_args=(),\n model_kwargs=None,\n forward_mode_differentiation=False,\n validate_grad=True,\n):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Helper function that calls :func:`~numpyro.infer.util.get_potential_fn`\n and :func:`~numpyro.infer.util.find_valid_initial_params` under the hood\n to return a tuple of (`init_params_info`, `potential_fn`, `postprocess_fn`, `model_trace`).\n\n :param jax.random.PRNGKey rng_key: random number generator seed to\n sample from the prior. The returned `init_params` will have the\n batch shape ``rng_key.shape[:-1]``.\n :param model: Python callable containing Pyro primitives.\n :param callable init_strategy: a per-site initialization function.\n See :ref:`init_strategy` section for available functions.\n :param bool dynamic_args: if `True`, the `potential_fn` and\n `constraints_fn` are themselves dependent on model arguments.\n When provided a `*model_args, **model_kwargs`, they return\n `potential_fn` and `constraints_fn` callables, respectively.\n :param tuple model_args: args provided to the model.\n :param dict model_kwargs: kwargs provided to the model.\n :param bool forward_mode_differentiation: whether to use forward-mode differentiation\n or reverse-mode differentiation. By default, we use reverse mode but the forward\n mode can be useful in some cases to improve the performance. In addition, some\n control flow utility on JAX such as `jax.lax.while_loop` or `jax.lax.fori_loop`\n only supports forward-mode differentiation. See\n `JAX's The Autodiff Cookbook <https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html>`_\n for more information.\n :param bool validate_grad: whether to validate gradient of the initial params.\n Defaults to True.\n :return: a namedtupe `ModelInfo` which contains the fields\n (`param_info`, `potential_fn`, `postprocess_fn`, `model_trace`), where\n `param_info` is a namedtuple `ParamInfo` containing values from the prior\n used to initiate MCMC, their corresponding potential energy, and their gradients;\n `postprocess_fn` is a callable that uses inverse transforms\n to convert unconstrained HMC samples to constrained values that\n lie within the site's support, in addition to returning values\n at `deterministic` sites in the model.\n \"\"\"\n model_kwargs = {} if model_kwargs is None else model_kwargs\n substituted_model = substitute(\n seed(model, rng_key if jnp.ndim(rng_key) == 1 else rng_key[0]),\n substitute_fn=init_strategy,\n )\n (\n inv_transforms,\n replay_model,\n has_enumerate_support,\n model_trace,\n ) = _get_model_transforms(substituted_model, model_args, model_kwargs)\n # substitute param sites from model_trace to model so\n # we don't need to generate again parameters of `numpyro.module`\n model = substitute(\n model,\n data={\n k: site[\"value\"]\n for k, site in model_trace.items()\n if site[\"type\"] in [\"param\"]\n },\n )\n constrained_values = {\n k: v[\"value\"]\n for k, v in model_trace.items()\n if v[\"type\"] == \"sample\" and not v[\"is_observed\"] and not v[\"fn\"].is_discrete\n }\n\n if has_enumerate_support:\n from numpyro.contrib.funsor import config_enumerate, enum\n\n if not isinstance(model, enum):\n max_plate_nesting = _guess_max_plate_nesting(model_trace)\n _validate_model(model_trace)\n model = enum(config_enumerate(model), -max_plate_nesting - 1)\n\n potential_fn, postprocess_fn = get_potential_fn(\n model,\n inv_transforms,\n replay_model=replay_model,\n enum=has_enumerate_support,\n dynamic_args=dynamic_args,\n model_args=model_args,\n model_kwargs=model_kwargs,\n )\n\n init_strategy = (\n init_strategy if isinstance(init_strategy, partial) else init_strategy()\n )\n if (init_strategy.func is init_to_value) and not replay_model:\n init_values = init_strategy.keywords.get(\"values\")\n unconstrained_values = transform_fn(inv_transforms, init_values, invert=True)\n init_strategy = _init_to_unconstrained_value(values=unconstrained_values)\n prototype_params = transform_fn(inv_transforms, constrained_values, invert=True)\n (init_params, pe, grad), is_valid = find_valid_initial_params(\n rng_key,\n substitute(\n model,\n data={\n k: site[\"value\"]\n for k, site in model_trace.items()\n if site[\"type\"] in [\"plate\"]\n },\n ),\n init_strategy=init_strategy,\n enum=has_enumerate_support,\n model_args=model_args,\n model_kwargs=model_kwargs,\n prototype_params=prototype_params,\n forward_mode_differentiation=forward_mode_differentiation,\n validate_grad=validate_grad,\n )\n\n if not_jax_tracer(is_valid):\n if device_get(~jnp.all(is_valid)):\n with numpyro.validation_enabled(), trace() as tr:\n # validate parameters\n substituted_model(*model_args, **model_kwargs)\n # validate values\n for site in tr.values():\n if site[\"type\"] == \"sample\":\n with warnings.catch_warnings(record=True) as ws:\n site[\"fn\"]._validate_sample(site[\"value\"])\n if len(ws) > 0:\n for w in ws:\n # at site information to the warning message\n w.message.args = (\n \"Site {}: {}\".format(\n site[\"name\"], w.message.args[0]\n ),\n ) + w.message.args[1:]\n warnings.showwarning(\n w.message,\n w.category,\n w.filename,\n w.lineno,\n file=w.file,\n line=w.line,\n )\n raise RuntimeError(\n \"Cannot find valid initial parameters. Please check your model again.\"\n )\n return ModelInfo(\n ParamInfo(init_params, pe, grad), potential_fn, postprocess_fn, model_trace\n )\n\n\ndef _predictive(\n rng_key,\n model,\n posterior_samples,\n batch_shape,\n return_sites=None,\n infer_discrete=False,\n parallel=True,\n model_args=(),\n model_kwargs={},\n):\n masked_model = numpyro.handlers.mask(model, mask=False)\n if infer_discrete:\n # inspect the model to get some structure\n rng_key, subkey = random.split(rng_key)\n batch_ndim = len(batch_shape)\n prototype_sample = tree_map(\n lambda x: jnp.reshape(x, (-1,) + jnp.shape(x)[batch_ndim:])[0],\n posterior_samples,\n )\n prototype_trace = trace(\n seed(substitute(masked_model, prototype_sample), subkey)\n ).get_trace(*model_args, **model_kwargs)\n first_available_dim = -_guess_max_plate_nesting(prototype_trace) - 1\n\n def single_prediction(val):\n rng_key, samples = val\n if infer_discrete:\n from numpyro.contrib.funsor import config_enumerate\n from numpyro.contrib.funsor.discrete import _sample_posterior\n\n model_trace = prototype_trace\n temperature = 1\n pred_samples = _sample_posterior(\n config_enumerate(condition(model, samples)),\n first_available_dim,\n temperature,\n rng_key,\n *model_args,\n **model_kwargs,\n )\n else:\n model_trace = trace(\n seed(substitute(masked_model, samples), rng_key)\n ).get_trace(*model_args, **model_kwargs)\n pred_samples = {name: site[\"value\"] for name, site in model_trace.items()}\n\n if return_sites is not None:\n if return_sites == \"\":\n sites = {\n k for k, site in model_trace.items() if site[\"type\"] != \"plate\"\n }\n else:\n sites = return_sites\n else:\n sites = {\n k\n for k, site in model_trace.items()\n if (site[\"type\"] == \"sample\" and k not in samples)\n or (site[\"type\"] == \"deterministic\")\n }\n return {name: value for name, value in pred_samples.items() if name in sites}\n\n num_samples = int(np.prod(batch_shape))\n if num_samples > 1:\n rng_key = random.split(rng_key, num_samples)\n rng_key = rng_key.reshape(batch_shape + (2,))\n chunk_size = num_samples if parallel else 1\n return soft_vmap(\n single_prediction, (rng_key, posterior_samples), len(batch_shape), chunk_size\n )\n\n\nclass Predictive(object):\n \"\"\"\n This class is used to construct predictive distribution. The predictive distribution is obtained\n by running model conditioned on latent samples from `posterior_samples`.\n\n .. warning::\n The interface for the `Predictive` class is experimental, and\n might change in the future.\n\n :param model: Python callable containing Pyro primitives.\n :param dict posterior_samples: dictionary of samples from the posterior.\n :param callable guide: optional guide to get posterior samples of sites not present\n in `posterior_samples`.\n :param dict params: dictionary of values for param sites of model/guide.\n :param int num_samples: number of samples\n :param list return_sites: sites to return; by default only sample sites not present\n in `posterior_samples` are returned.\n :param bool infer_discrete: whether or not to sample discrete sites from the\n posterior, conditioned on observations and other latent values in\n ``posterior_samples``. Under the hood, those sites will be marked with\n ``site[\"infer\"][\"enumerate\"] = \"parallel\"``. See how `infer_discrete` works at\n the `Pyro enumeration tutorial <https://pyro.ai/examples/enumeration.html>`_.\n Note that this requires ``funsor`` installation.\n :param bool parallel: whether to predict in parallel using JAX vectorized map :func:`jax.vmap`.\n Defaults to False.\n :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n + set `batch_ndims=0` to get prediction for 1 single sample\n\n + set `batch_ndims=1` to get prediction for `posterior_samples`\n with shapes `(num_samples x ...)`\n\n + set `batch_ndims=2` to get prediction for `posterior_samples`\n with shapes `(num_chains x N x ...)`. Note that if `num_samples`\n argument is not None, its value should be equal to `num_chains x N`.\n\n :return: dict of samples from the predictive distribution.\n\n **Example:**\n\n Given a model::\n\n def model(X, y=None):\n ...\n return numpyro.sample(\"obs\", likelihood, obs=y)\n\n you can sample from the prior predictive::\n\n predictive = Predictive(model, num_samples=1000)\n y_pred = predictive(rng_key, X)[\"obs\"]\n\n If you also have posterior samples, you can sample from the posterior predictive::\n\n predictive = Predictive(model, posterior_samples=posterior_samples)\n y_pred = predictive(rng_key, X)[\"obs\"]\n\n See docstrings for :class:`~numpyro.infer.svi.SVI` and :class:`~numpyro.infer.mcmc.MCMCKernel`\n to see example code of this in context.\n \"\"\"\n\n def __init__(\n self,\n model,\n posterior_samples=None,\n *,\n guide=None,\n params=None,\n num_samples=None,\n return_sites=None,\n infer_discrete=False,\n parallel=False,\n batch_ndims=1,\n ):\n if posterior_samples is None and num_samples is None:\n raise ValueError(\n \"Either posterior_samples or num_samples must be specified.\"\n )\n\n posterior_samples = {} if posterior_samples is None else posterior_samples\n\n prototype_site = batch_shape = batch_size = None\n for name, sample in posterior_samples.items():\n if batch_shape is not None and sample.shape[:batch_ndims] != batch_shape:\n raise ValueError(\n f\"Batch shapes at site {name} and {prototype_site} \"\n f\"should be the same, but got \"\n f\"{sample.shape[:batch_ndims]} and {batch_shape}\"\n )\n else:\n prototype_site = name\n batch_shape = sample.shape[:batch_ndims]\n batch_size = int(np.prod(batch_shape))\n if (num_samples is not None) and (num_samples != batch_size):\n warnings.warn(\n \"Sample's batch dimension size {} is different from the \"\n \"provided {} num_samples argument. Defaulting to {}.\".format(\n batch_size, num_samples, batch_size\n ),\n UserWarning,\n )\n num_samples = batch_size\n\n if num_samples is None:\n raise ValueError(\n \"No sample sites in posterior samples to infer `num_samples`.\"\n )\n\n if batch_shape is None:\n batch_shape = (1,) * (batch_ndims - 1) + (num_samples,)\n\n if return_sites is not None:\n assert isinstance(return_sites, (list, tuple, set))\n\n self.model = model\n self.posterior_samples = {} if posterior_samples is None else posterior_samples\n self.num_samples = num_samples\n self.guide = guide\n self.params = {} if params is None else params\n self.infer_discrete = infer_discrete\n self.return_sites = return_sites\n self.parallel = parallel\n self.batch_ndims = batch_ndims\n self._batch_shape = batch_shape\n\n def __call__(self, rng_key, *args, **kwargs):\n \"\"\"\n Returns dict of samples from the predictive distribution. By default, only sample sites not\n contained in `posterior_samples` are returned. This can be modified by changing the\n `return_sites` keyword argument of this :class:`Predictive` instance.\n\n :param jax.random.PRNGKey rng_key: random key to draw samples.\n :param args: model arguments.\n :param kwargs: model kwargs.\n \"\"\"\n posterior_samples = self.posterior_samples\n if self.guide is not None:\n rng_key, guide_rng_key = random.split(rng_key)\n # use return_sites='' as a special signal to return all sites\n guide = substitute(self.guide, self.params)\n posterior_samples = _predictive(\n guide_rng_key,\n guide,\n posterior_samples,\n self._batch_shape,\n return_sites=\"\",\n parallel=self.parallel,\n model_args=args,\n model_kwargs=kwargs,\n )\n model = substitute(self.model, self.params)\n return _predictive(\n rng_key,\n model,\n posterior_samples,\n self._batch_shape,\n return_sites=self.return_sites,\n infer_discrete=self.infer_discrete,\n parallel=self.parallel,\n model_args=args,\n model_kwargs=kwargs,\n )\n\n\ndef log_likelihood(\n model, posterior_samples, *args, parallel=False, batch_ndims=1, **kwargs\n):\n \"\"\"\n (EXPERIMENTAL INTERFACE) Returns log likelihood at observation nodes of model,\n given samples of all latent variables.\n\n :param model: Python callable containing Pyro primitives.\n :param dict posterior_samples: dictionary of samples from the posterior.\n :param args: model arguments.\n :param batch_ndims: the number of batch dimensions in posterior samples. Some usages:\n\n + set `batch_ndims=0` to get log likelihoods for 1 single sample\n\n + set `batch_ndims=1` to get log likelihoods for `posterior_samples`\n with shapes `(num_samples x ...)`\n\n + set `batch_ndims=2` to get log likelihoods for `posterior_samples`\n with shapes `(num_chains x num_samples x ...)`\n\n :param kwargs: model kwargs.\n :return: dict of log likelihoods at observation sites.\n \"\"\"\n\n def single_loglik(samples):\n substituted_model = (\n substitute(model, samples) if isinstance(samples, dict) else model\n )\n model_trace = trace(substituted_model).get_trace(*args, **kwargs)\n return {\n name: site[\"fn\"].log_prob(site[\"value\"])\n for name, site in model_trace.items()\n if site[\"type\"] == \"sample\" and site[\"is_observed\"]\n }\n\n prototype_site = batch_shape = None\n for name, sample in posterior_samples.items():\n if batch_shape is not None and jnp.shape(sample)[:batch_ndims] != batch_shape:\n raise ValueError(\n f\"Batch shapes at site {name} and {prototype_site} \"\n f\"should be the same, but got \"\n f\"{sample.shape[:batch_ndims]} and {batch_shape}\"\n )\n else:\n prototype_site = name\n batch_shape = jnp.shape(sample)[:batch_ndims]\n\n if batch_shape is None: # posterior_samples is an empty dict\n batch_shape = (1,) * batch_ndims\n posterior_samples = np.zeros(batch_shape)\n\n batch_size = int(np.prod(batch_shape))\n chunk_size = batch_size if parallel else 1\n return soft_vmap(single_loglik, posterior_samples, len(batch_shape), chunk_size)\n\n\n@contextmanager\ndef helpful_support_errors(site, raise_warnings=False):\n name = site[\"name\"]\n support = getattr(site[\"fn\"], \"support\", None)\n if isinstance(support, constraints.independent):\n support = support.base_constraint\n\n # Warnings\n if raise_warnings:\n if support is constraints.circular:\n msg = (\n f\"Continuous inference poorly handles circular sample site '{name}'. \"\n + \"Consider using VonMises distribution together with \"\n + \"a reparameterizer, e.g. \"\n + f\"numpyro.handlers.reparam(config={{'{name}': CircularReparam()}}).\"\n )\n warnings.warn(msg, UserWarning)\n\n # Exceptions\n try:\n yield\n except NotImplementedError as e:\n support_name = repr(support).lower()\n if \"integer\" in support_name or \"boolean\" in support_name:\n # TODO: mention enumeration when it is supported in SVI\n raise ValueError(\n f\"Continuous inference cannot handle discrete sample site '{name}'.\"\n )\n if \"sphere\" in support_name:\n raise ValueError(\n f\"Continuous inference cannot handle spherical sample site '{name}'. \"\n \"Consider using ProjectedNormal distribution together with \"\n \"a reparameterizer, e.g. \"\n f\"numpyro.handlers.reparam(config={{'{name}': ProjectedNormalReparam()}}).\"\n )\n raise e from None\n", "# Copyright Contributors to the Pyro project.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nExample: MCMC Methods for Tall Data\n===================================\n\nThis example illustrates the usages of various MCMC methods which are suitable for tall data:\n\n - `algo=\"SA\"` uses the sample adaptive MCMC method in [1]\n - `algo=\"HMCECS\"` uses the energy conserving subsampling method in [2]\n - `algo=\"FlowHMCECS\"` utilizes a normalizing flow to neutralize the posterior\n geometry into a Gaussian-like one. Then HMCECS is used to draw the posterior\n samples. Currently, this method gives the best mixing rate among those methods.\n\n**References:**\n\n 1. *Sample Adaptive MCMC*,\n Michael Zhu (2019)\n 2. *Hamiltonian Monte Carlo with energy conserving subsampling*,\n Dang, K. D., Quiroz, M., Kohn, R., Minh-Ngoc, T., & Villani, M. (2019)\n 3. *NeuTra-lizing Bad Geometry in Hamiltonian Monte Carlo Using Neural Transport*,\n Hoffman, M. et al. (2019)\n\n\"\"\"\n\nimport argparse\nimport time\n\nimport matplotlib.pyplot as plt\n\nfrom jax import random\nimport jax.numpy as jnp\n\nimport numpyro\nimport numpyro.distributions as dist\nfrom numpyro.examples.datasets import COVTYPE, load_dataset\nfrom numpyro.infer import HMC, HMCECS, MCMC, NUTS, SA, SVI, Trace_ELBO, init_to_value\nfrom numpyro.infer.autoguide import AutoBNAFNormal\nfrom numpyro.infer.reparam import NeuTraReparam\n\n\ndef _load_dataset():\n _, fetch = load_dataset(COVTYPE, shuffle=False)\n features, labels = fetch()\n\n # normalize features and add intercept\n features = (features - features.mean(0)) / features.std(0)\n features = jnp.hstack([features, jnp.ones((features.shape[0], 1))])\n\n # make binary feature\n _, counts = jnp.unique(labels, return_counts=True)\n specific_category = jnp.argmax(counts)\n labels = labels == specific_category\n\n N, dim = features.shape\n print(\"Data shape:\", features.shape)\n print(\n \"Label distribution: {} has label 1, {} has label 0\".format(\n labels.sum(), N - labels.sum()\n )\n )\n return features, labels\n\n\ndef model(data, labels, subsample_size=None):\n dim = data.shape[1]\n coefs = numpyro.sample(\"coefs\", dist.Normal(jnp.zeros(dim), jnp.ones(dim)))\n with numpyro.plate(\"N\", data.shape[0], subsample_size=subsample_size) as idx:\n logits = jnp.dot(data[idx], coefs)\n return numpyro.sample(\"obs\", dist.Bernoulli(logits=logits), obs=labels[idx])\n\n\ndef benchmark_hmc(args, features, labels):\n rng_key = random.PRNGKey(1)\n start = time.time()\n # a MAP estimate at the following source\n # https://github.com/google/edward2/blob/master/examples/no_u_turn_sampler/logistic_regression.py#L117\n ref_params = {\n \"coefs\": jnp.array(\n [\n +2.03420663e00,\n -3.53567265e-02,\n -1.49223924e-01,\n -3.07049364e-01,\n -1.00028366e-01,\n -1.46827862e-01,\n -1.64167881e-01,\n -4.20344204e-01,\n +9.47479829e-02,\n -1.12681836e-02,\n +2.64442056e-01,\n -1.22087866e-01,\n -6.00568838e-02,\n -3.79419506e-01,\n -1.06668741e-01,\n -2.97053963e-01,\n -2.05253899e-01,\n -4.69537191e-02,\n -2.78072730e-02,\n -1.43250525e-01,\n -6.77954629e-02,\n -4.34899796e-03,\n +5.90927452e-02,\n +7.23133609e-02,\n +1.38526391e-02,\n -1.24497898e-01,\n -1.50733739e-02,\n -2.68872194e-02,\n -1.80925727e-02,\n +3.47936489e-02,\n +4.03552800e-02,\n -9.98773426e-03,\n +6.20188080e-02,\n +1.15002751e-01,\n +1.32145107e-01,\n +2.69109547e-01,\n +2.45785132e-01,\n +1.19035013e-01,\n -2.59744357e-02,\n +9.94279515e-04,\n +3.39266285e-02,\n -1.44057125e-02,\n -6.95222765e-02,\n -7.52013028e-02,\n +1.21171586e-01,\n +2.29205526e-02,\n +1.47308692e-01,\n -8.34354162e-02,\n -9.34122875e-02,\n -2.97472421e-02,\n -3.03937674e-01,\n -1.70958012e-01,\n -1.59496680e-01,\n -1.88516974e-01,\n -1.20889175e00,\n ]\n )\n }\n if args.algo == \"HMC\":\n step_size = jnp.sqrt(0.5 / features.shape[0])\n trajectory_length = step_size * args.num_steps\n kernel = HMC(\n model,\n step_size=step_size,\n trajectory_length=trajectory_length,\n adapt_step_size=False,\n dense_mass=args.dense_mass,\n )\n subsample_size = None\n elif args.algo == \"NUTS\":\n kernel = NUTS(model, dense_mass=args.dense_mass)\n subsample_size = None\n elif args.algo == \"HMCECS\":\n subsample_size = 1000\n inner_kernel = NUTS(\n model,\n init_strategy=init_to_value(values=ref_params),\n dense_mass=args.dense_mass,\n )\n # note: if num_blocks=100, we'll update 10 index at each MCMC step\n # so it took 50000 MCMC steps to iterative the whole dataset\n kernel = HMCECS(\n inner_kernel, num_blocks=100, proxy=HMCECS.taylor_proxy(ref_params)\n )\n elif args.algo == \"SA\":\n # NB: this kernel requires large num_warmup and num_samples\n # and running on GPU is much faster than on CPU\n kernel = SA(\n model, adapt_state_size=1000, init_strategy=init_to_value(values=ref_params)\n )\n subsample_size = None\n elif args.algo == \"FlowHMCECS\":\n subsample_size = 1000\n guide = AutoBNAFNormal(model, num_flows=1, hidden_factors=[8])\n svi = SVI(model, guide, numpyro.optim.Adam(0.01), Trace_ELBO())\n svi_result = svi.run(random.PRNGKey(2), 2000, features, labels)\n params, losses = svi_result.params, svi_result.losses\n plt.plot(losses)\n plt.show()\n\n neutra = NeuTraReparam(guide, params)\n neutra_model = neutra.reparam(model)\n neutra_ref_params = {\"auto_shared_latent\": jnp.zeros(55)}\n # no need to adapt mass matrix if the flow does a good job\n inner_kernel = NUTS(\n neutra_model,\n init_strategy=init_to_value(values=neutra_ref_params),\n adapt_mass_matrix=False,\n )\n kernel = HMCECS(\n inner_kernel, num_blocks=100, proxy=HMCECS.taylor_proxy(neutra_ref_params)\n )\n else:\n raise ValueError(\"Invalid algorithm, either 'HMC', 'NUTS', or 'HMCECS'.\")\n mcmc = MCMC(kernel, num_warmup=args.num_warmup, num_samples=args.num_samples)\n mcmc.run(rng_key, features, labels, subsample_size, extra_fields=(\"accept_prob\",))\n print(\"Mean accept prob:\", jnp.mean(mcmc.get_extra_fields()[\"accept_prob\"]))\n mcmc.print_summary(exclude_deterministic=False)\n print(\"\\nMCMC elapsed time:\", time.time() - start)\n\n\ndef main(args):\n features, labels = _load_dataset()\n benchmark_hmc(args, features, labels)\n\n\nif __name__ == \"__main__\":\n assert numpyro.__version__.startswith(\"0.7.2\")\n parser = argparse.ArgumentParser(description=\"parse args\")\n parser.add_argument(\n \"-n\", \"--num-samples\", default=1000, type=int, help=\"number of samples\"\n )\n parser.add_argument(\n \"--num-warmup\", default=1000, type=int, help=\"number of warmup steps\"\n )\n parser.add_argument(\n \"--num-steps\", default=10, type=int, help='number of steps (for \"HMC\")'\n )\n parser.add_argument(\"--num-chains\", nargs=\"?\", default=1, type=int)\n parser.add_argument(\n \"--algo\",\n default=\"HMCECS\",\n type=str,\n help='whether to run \"HMC\", \"NUTS\", \"HMCECS\", \"SA\" or \"FlowHMCECS\"',\n )\n parser.add_argument(\"--dense-mass\", action=\"store_true\")\n parser.add_argument(\"--x64\", action=\"store_true\")\n parser.add_argument(\"--device\", default=\"cpu\", type=str, help='use \"cpu\" or \"gpu\".')\n args = parser.parse_args()\n\n numpyro.set_platform(args.device)\n numpyro.set_host_device_count(args.num_chains)\n if args.x64:\n numpyro.enable_x64()\n\n main(args)\n" ]
[ [ "numpy.max", "numpy.array" ], [ "numpy.zeros", "numpy.prod" ], [ "matplotlib.pyplot.plot", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
listato/Logarithmic-Quantization-of-Parameters-in-Neural-Networks
[ "dbc6a48ab5e0bf4361be459a45598523f2344371" ]
[ "utils/logquant_v1.py" ]
[ "\"\"\"\nAuthor: CAI JINGYONG @ BeatCraft, Inc & Tokyo University of Agriculture and Technology\n\nplaceholder\n\ninput: numpy array\noutput: numpy array\n\"\"\"\nimport numpy\n\nclass LogQuant:\n def __init__(self,layer,bitwidth):\n self.layer_data = layer\n self.width = bitwidth\n self.maxima = numpy.amax(layer)\n self.minima = numpy.amin(layer)\n self.fsr = self.maxima - self.minima\n self.sign = numpy.sign(layer)\n pass\n\n def __clip(self, x):\n # min = self.fsr-(2**self.width)\n min = 4 - (2**self.width)\n if(x <= min):\n return 0\n elif(x >= 4):\n return 4 - 1\n else:\n return x\n\n def __round(self,x):\n bridge = numpy.sqrt(2)-1\n decimalpart, intpart = numpy.modf(x)\n if decimalpart >= bridge:\n return numpy.ceil(x)\n else:\n return numpy.floor(x)\n\n @property\n def log_quantize(self):\n round = numpy.vectorize(self.__round)\n clip = numpy.vectorize(self.__clip)\n # numpy.log2(0) -> -infinity == float(\"-inf\") which will be used in clip method\n return numpy.array(clip(round(numpy.log2(abs(self.layer_data)))),dtype=numpy.int8)\n\n @property\n def de_quantize(self):\n x = numpy.power(2.0, self.log_quantized)\n return x * self.sign\n" ]
[ [ "numpy.amax", "numpy.sqrt", "numpy.power", "numpy.amin", "numpy.modf", "numpy.sign", "numpy.ceil", "numpy.vectorize", "numpy.floor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sa-y-an/open-source-autonomous-vehicle-controller
[ "b959a4fefa1d44d052436ff9129af386e15e0455", "0cc415fb141d1b66ac45a7bf6b50add6814728fb" ]
[ "path-finding/yolo-v5/utils/datasets.py", "python/generate_points.py" ]
[ "# Dataset utils and dataloaders\n\nimport glob\nimport hashlib\nimport json\nimport logging\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool, Pool\nfrom pathlib import Path\nfrom threading import Thread\n\nimport cv2\nimport math\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport yaml\nfrom PIL import Image, ExifTags\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom utils.general import check_requirements, check_file, check_dataset, xywh2xyxy, xywhn2xyxy, xyxy2xywhn, \\\n xyn2xy, segment2box, segments2boxes, resample_segments, clean_str\nfrom utils.metrics import bbox_ioa\nfrom utils.torch_utils import torch_distributed_zero_first\n\n# Parameters\nhelp_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'\nimg_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes\nvid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes\nnum_threads = min(8, os.cpu_count()) # number of multiprocessing threads\nlogger = logging.getLogger(__name__)\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n if ExifTags.TAGS[orientation] == 'Orientation':\n break\n\n\ndef get_hash(paths):\n # Returns a single hash value of a list of paths (files or dirs)\n size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes\n h = hashlib.md5(str(size).encode()) # hash sizes\n h.update(''.join(paths).encode()) # hash paths\n return h.hexdigest() # return hash\n\n\ndef exif_size(img):\n # Returns exif-corrected PIL size\n s = img.size # (width, height)\n try:\n rotation = dict(img._getexif().items())[orientation]\n if rotation == 6: # rotation 270\n s = (s[1], s[0])\n elif rotation == 8: # rotation 90\n s = (s[1], s[0])\n except:\n pass\n\n return s\n\n\ndef exif_transpose(image):\n \"\"\"\n Transpose a PIL image accordingly if it has an EXIF Orientation tag.\n From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py\n\n :param image: The image to transpose.\n :return: An image.\n \"\"\"\n exif = image.getexif()\n orientation = exif.get(0x0112, 1) # default 1\n if orientation > 1:\n method = {2: Image.FLIP_LEFT_RIGHT,\n 3: Image.ROTATE_180,\n 4: Image.FLIP_TOP_BOTTOM,\n 5: Image.TRANSPOSE,\n 6: Image.ROTATE_270,\n 7: Image.TRANSVERSE,\n 8: Image.ROTATE_90,\n }.get(orientation)\n if method is not None:\n image = image.transpose(method)\n del exif[0x0112]\n image.info[\"exif\"] = exif.tobytes()\n return image\n\n\ndef create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,\n rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix=''):\n # Make sure only the first process in DDP process the dataset first, and the following others can use the cache\n with torch_distributed_zero_first(rank):\n dataset = LoadImagesAndLabels(path, imgsz, batch_size,\n augment=augment, # augment images\n hyp=hyp, # augmentation hyperparameters\n rect=rect, # rectangular training\n cache_images=cache,\n single_cls=single_cls,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix)\n\n batch_size = min(batch_size, len(dataset))\n nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None\n loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader\n # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()\n dataloader = loader(dataset,\n batch_size=batch_size,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)\n return dataloader, dataset\n\n\nclass InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):\n \"\"\" Dataloader that reuses workers\n\n Uses same syntax as vanilla DataLoader\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n self.iterator = super().__iter__()\n\n def __len__(self):\n return len(self.batch_sampler.sampler)\n\n def __iter__(self):\n for i in range(len(self)):\n yield next(self.iterator)\n\n\nclass _RepeatSampler(object):\n \"\"\" Sampler that repeats forever\n\n Args:\n sampler (Sampler)\n \"\"\"\n\n def __init__(self, sampler):\n self.sampler = sampler\n\n def __iter__(self):\n while True:\n yield from iter(self.sampler)\n\n\nclass LoadImages: # for inference\n def __init__(self, path, img_size=640, stride=32):\n p = str(Path(path).absolute()) # os-agnostic absolute path\n if '*' in p:\n files = sorted(glob.glob(p, recursive=True)) # glob\n elif os.path.isdir(p):\n files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir\n elif os.path.isfile(p):\n files = [p] # files\n else:\n raise Exception(f'ERROR: {p} does not exist')\n\n images = [x for x in files if x.split('.')[-1].lower() in img_formats]\n videos = [x for x in files if x.split('.')[-1].lower() in vid_formats]\n ni, nv = len(images), len(videos)\n\n self.img_size = img_size\n self.stride = stride\n self.files = images + videos\n self.nf = ni + nv # number of files\n self.video_flag = [False] * ni + [True] * nv\n self.mode = 'image'\n if any(videos):\n self.new_video(videos[0]) # new video\n else:\n self.cap = None\n assert self.nf > 0, f'No images or videos found in {p}. ' \\\n f'Supported formats are:\\nimages: {img_formats}\\nvideos: {vid_formats}'\n\n def __iter__(self):\n self.count = 0\n return self\n\n def __next__(self):\n if self.count == self.nf:\n raise StopIteration\n path = self.files[self.count]\n\n if self.video_flag[self.count]:\n # Read video\n self.mode = 'video'\n ret_val, img0 = self.cap.read()\n if not ret_val:\n self.count += 1\n self.cap.release()\n if self.count == self.nf: # last video\n raise StopIteration\n else:\n path = self.files[self.count]\n self.new_video(path)\n ret_val, img0 = self.cap.read()\n\n self.frame += 1\n print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='')\n\n else:\n # Read image\n self.count += 1\n img0 = cv2.imread(path) # BGR\n assert img0 is not None, 'Image Not Found ' + path\n print(f'image {self.count}/{self.nf} {path}: ', end='')\n\n # Padded resize\n img = letterbox(img0, self.img_size, stride=self.stride)[0]\n\n # Convert\n img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB and HWC to CHW\n img = np.ascontiguousarray(img)\n\n return path, img, img0, self.cap\n\n def new_video(self, path):\n self.frame = 0\n self.cap = cv2.VideoCapture(path)\n self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n def __len__(self):\n return self.nf # number of files\n\n\nclass LoadWebcam: # for inference\n def __init__(self, pipe='0', img_size=640, stride=32):\n self.img_size = img_size\n self.stride = stride\n self.pipe = eval(pipe) if pipe.isnumeric() else pipe\n self.cap = cv2.VideoCapture(self.pipe) # video capture object\n self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size\n\n def __iter__(self):\n self.count = -1\n return self\n\n def __next__(self):\n self.count += 1\n if cv2.waitKey(1) == ord('q'): # q to quit\n self.cap.release()\n cv2.destroyAllWindows()\n raise StopIteration\n\n # Read frame\n ret_val, img0 = self.cap.read()\n img0 = cv2.flip(img0, 1) # flip left-right\n\n # Print\n assert ret_val, f'Camera Error {self.pipe}'\n img_path = 'webcam.jpg'\n print(f'webcam {self.count}: ', end='')\n\n # Padded resize\n img = letterbox(img0, self.img_size, stride=self.stride)[0]\n\n # Convert\n img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB and HWC to CHW\n img = np.ascontiguousarray(img)\n\n return img_path, img, img0, None\n\n def __len__(self):\n return 0\n\n\nclass LoadStreams: # multiple IP or RTSP cameras\n def __init__(self, sources='streams.txt', img_size=640, stride=32):\n self.mode = 'stream'\n self.img_size = img_size\n self.stride = stride\n\n if os.path.isfile(sources):\n with open(sources, 'r') as f:\n sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]\n else:\n sources = [sources]\n\n n = len(sources)\n self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n self.sources = [clean_str(x) for x in sources] # clean source names for later\n for i, s in enumerate(sources): # index, source\n # Start thread to read frames from video stream\n print(f'{i + 1}/{n}: {s}... ', end='')\n if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video\n check_requirements(('pafy', 'youtube_dl'))\n import pafy\n s = pafy.new(s).getbest(preftype=\"mp4\").url # YouTube URL\n s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam\n cap = cv2.VideoCapture(s)\n assert cap.isOpened(), f'Failed to open {s}'\n w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback\n self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback\n\n _, self.imgs[i] = cap.read() # guarantee first frame\n self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True)\n print(f\" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)\")\n self.threads[i].start()\n print('') # newline\n\n # check for common shapes\n s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes\n self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal\n if not self.rect:\n print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')\n\n def update(self, i, cap):\n # Read stream `i` frames in daemon thread\n n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame\n while cap.isOpened() and n < f:\n n += 1\n # _, self.imgs[index] = cap.read()\n cap.grab()\n if n % read == 0:\n success, im = cap.retrieve()\n self.imgs[i] = im if success else self.imgs[i] * 0\n time.sleep(1 / self.fps[i]) # wait time\n\n def __iter__(self):\n self.count = -1\n return self\n\n def __next__(self):\n self.count += 1\n if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit\n cv2.destroyAllWindows()\n raise StopIteration\n\n # Letterbox\n img0 = self.imgs.copy()\n img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]\n\n # Stack\n img = np.stack(img, 0)\n\n # Convert\n img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB and BHWC to BCHW\n img = np.ascontiguousarray(img)\n\n return self.sources, img, img0, None\n\n def __len__(self):\n return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\ndef img2label_paths(img_paths):\n # Define label paths as a function of image paths\n sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings\n return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\nclass LoadImagesAndLabels(Dataset): # for training/testing\n def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,\n cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):\n self.img_size = img_size\n self.augment = augment\n self.hyp = hyp\n self.image_weights = image_weights\n self.rect = False if image_weights else rect\n self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)\n self.mosaic_border = [-img_size // 2, -img_size // 2]\n self.stride = stride\n self.path = path\n\n try:\n f = [] # image files\n for p in path if isinstance(path, list) else [path]:\n p = Path(p) # os-agnostic\n if p.is_dir(): # dir\n f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n # f = list(p.rglob('**/*.*')) # pathlib\n elif p.is_file(): # file\n with open(p, 'r') as t:\n t = t.read().strip().splitlines()\n parent = str(p.parent) + os.sep\n f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path\n # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)\n else:\n raise Exception(f'{prefix}{p} does not exist')\n self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats])\n # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib\n assert self.img_files, f'{prefix}No images found'\n except Exception as e:\n raise Exception(f'{prefix}Error loading data from {path}: {e}\\nSee {help_url}')\n\n # Check cache\n self.label_files = img2label_paths(self.img_files) # labels\n cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels\n if cache_path.is_file():\n cache, exists = torch.load(cache_path), True # load\n if cache.get('version') != 0.3 or cache.get('hash') != get_hash(self.label_files + self.img_files):\n cache, exists = self.cache_labels(cache_path, prefix), False # re-cache\n else:\n cache, exists = self.cache_labels(cache_path, prefix), False # cache\n\n # Display cache\n nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total\n if exists:\n d = f\"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results\n if cache['msgs']:\n logging.info('\\n'.join(cache['msgs'])) # display warnings\n assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'\n\n # Read cache\n [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items\n labels, shapes, self.segments = zip(*cache.values())\n self.labels = list(labels)\n self.shapes = np.array(shapes, dtype=np.float64)\n self.img_files = list(cache.keys()) # update\n self.label_files = img2label_paths(cache.keys()) # update\n if single_cls:\n for x in self.labels:\n x[:, 0] = 0\n\n n = len(shapes) # number of images\n bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index\n nb = bi[-1] + 1 # number of batches\n self.batch = bi # batch index of image\n self.n = n\n self.indices = range(n)\n\n # Rectangular Training\n if self.rect:\n # Sort by aspect ratio\n s = self.shapes # wh\n ar = s[:, 1] / s[:, 0] # aspect ratio\n irect = ar.argsort()\n self.img_files = [self.img_files[i] for i in irect]\n self.label_files = [self.label_files[i] for i in irect]\n self.labels = [self.labels[i] for i in irect]\n self.shapes = s[irect] # wh\n ar = ar[irect]\n\n # Set training image shapes\n shapes = [[1, 1]] * nb\n for i in range(nb):\n ari = ar[bi == i]\n mini, maxi = ari.min(), ari.max()\n if maxi < 1:\n shapes[i] = [maxi, 1]\n elif mini > 1:\n shapes[i] = [1, 1 / mini]\n\n self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride\n\n # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)\n self.imgs = [None] * n\n if cache_images:\n gb = 0 # Gigabytes of cached images\n self.img_hw0, self.img_hw = [None] * n, [None] * n\n results = ThreadPool(num_threads).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))\n pbar = tqdm(enumerate(results), total=n)\n for i, x in pbar:\n self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i)\n gb += self.imgs[i].nbytes\n pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'\n pbar.close()\n\n def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n # Cache dataset labels, check images and read shapes\n x = {} # dict\n nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages\n desc = f\"{prefix}Scanning '{path.parent / path.stem}' images and labels...\"\n with Pool(num_threads) as pool:\n pbar = tqdm(pool.imap_unordered(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),\n desc=desc, total=len(self.img_files))\n for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n nm += nm_f\n nf += nf_f\n ne += ne_f\n nc += nc_f\n if im_file:\n x[im_file] = [l, shape, segments]\n if msg:\n msgs.append(msg)\n pbar.desc = f\"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n\n pbar.close()\n if msgs:\n logging.info('\\n'.join(msgs))\n if nf == 0:\n logging.info(f'{prefix}WARNING: No labels found in {path}. See {help_url}')\n x['hash'] = get_hash(self.label_files + self.img_files)\n x['results'] = nf, nm, ne, nc, len(self.img_files)\n x['msgs'] = msgs # warnings\n x['version'] = 0.3 # cache version\n try:\n torch.save(x, path) # save cache for next time\n logging.info(f'{prefix}New cache created: {path}')\n except Exception as e:\n logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable\n return x\n\n def __len__(self):\n return len(self.img_files)\n\n # def __iter__(self):\n # self.count = -1\n # print('ran dataset iter')\n # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)\n # return self\n\n def __getitem__(self, index):\n index = self.indices[index] # linear, shuffled, or image_weights\n\n hyp = self.hyp\n mosaic = self.mosaic and random.random() < hyp['mosaic']\n if mosaic:\n # Load mosaic\n img, labels = load_mosaic(self, index)\n shapes = None\n\n # MixUp https://arxiv.org/pdf/1710.09412.pdf\n if random.random() < hyp['mixup']:\n img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))\n r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0\n img = (img * r + img2 * (1 - r)).astype(np.uint8)\n labels = np.concatenate((labels, labels2), 0)\n\n else:\n # Load image\n img, (h0, w0), (h, w) = load_image(self, index)\n\n # Letterbox\n shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape\n img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling\n\n labels = self.labels[index].copy()\n if labels.size: # normalized xywh to pixel xyxy format\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n if self.augment:\n # Augment imagespace\n if not mosaic:\n img, labels = random_perspective(img, labels,\n degrees=hyp['degrees'],\n translate=hyp['translate'],\n scale=hyp['scale'],\n shear=hyp['shear'],\n perspective=hyp['perspective'])\n\n # Augment colorspace\n augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n # Apply cutouts\n # if random.random() < 0.9:\n # labels = cutout(img, labels)\n\n nL = len(labels) # number of labels\n if nL:\n labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0]) # xyxy to xywh normalized\n\n if self.augment:\n # flip up-down\n if random.random() < hyp['flipud']:\n img = np.flipud(img)\n if nL:\n labels[:, 2] = 1 - labels[:, 2]\n\n # flip left-right\n if random.random() < hyp['fliplr']:\n img = np.fliplr(img)\n if nL:\n labels[:, 1] = 1 - labels[:, 1]\n\n labels_out = torch.zeros((nL, 6))\n if nL:\n labels_out[:, 1:] = torch.from_numpy(labels)\n\n # Convert\n img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3 x img_height x img_width\n img = np.ascontiguousarray(img)\n\n return torch.from_numpy(img), labels_out, self.img_files[index], shapes\n\n @staticmethod\n def collate_fn(batch):\n img, label, path, shapes = zip(*batch) # transposed\n for i, l in enumerate(label):\n l[:, 0] = i # add target image index for build_targets()\n return torch.stack(img, 0), torch.cat(label, 0), path, shapes\n\n @staticmethod\n def collate_fn4(batch):\n img, label, path, shapes = zip(*batch) # transposed\n n = len(shapes) // 4\n img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]\n\n ho = torch.tensor([[0., 0, 0, 1, 0, 0]])\n wo = torch.tensor([[0., 0, 1, 0, 0, 0]])\n s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale\n for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW\n i *= 4\n if random.random() < 0.5:\n im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[\n 0].type(img[i].type())\n l = label[i]\n else:\n im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)\n l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s\n img4.append(im)\n label4.append(l)\n\n for i, l in enumerate(label4):\n l[:, 0] = i # add target image index for build_targets()\n\n return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef load_image(self, index):\n # loads 1 image from dataset, returns img, original hw, resized hw\n img = self.imgs[index]\n if img is None: # not cached\n path = self.img_files[index]\n img = cv2.imread(path) # BGR\n assert img is not None, 'Image Not Found ' + path\n h0, w0 = img.shape[:2] # orig hw\n r = self.img_size / max(h0, w0) # ratio\n if r != 1: # if sizes are not equal\n img = cv2.resize(img, (int(w0 * r), int(h0 * r)),\n interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)\n return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized\n else:\n return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized\n\n\ndef augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):\n if hgain or sgain or vgain:\n r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains\n hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))\n dtype = img.dtype # uint8\n\n x = np.arange(0, 256, dtype=r.dtype)\n lut_hue = ((x * r[0]) % 180).astype(dtype)\n lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\n cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed\n\n\ndef hist_equalize(img, clahe=True, bgr=False):\n # Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255\n yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)\n if clahe:\n c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n yuv[:, :, 0] = c.apply(yuv[:, :, 0])\n else:\n yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram\n return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB\n\n\ndef load_mosaic(self, index):\n # loads images in a 4-mosaic\n\n labels4, segments4 = [], []\n s = self.img_size\n yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y\n indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices\n for i, index in enumerate(indices):\n # Load image\n img, _, (h, w) = load_image(self, index)\n\n # place img in img4\n if i == 0: # top left\n img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles\n x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)\n x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)\n elif i == 1: # top right\n x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n elif i == 2: # bottom left\n x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n elif i == 3: # bottom right\n x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]\n padw = x1a - x1b\n padh = y1a - y1b\n\n # Labels\n labels, segments = self.labels[index].copy(), self.segments[index].copy()\n if labels.size:\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format\n segments = [xyn2xy(x, w, h, padw, padh) for x in segments]\n labels4.append(labels)\n segments4.extend(segments)\n\n # Concat/clip labels\n labels4 = np.concatenate(labels4, 0)\n for x in (labels4[:, 1:], *segments4):\n np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()\n # img4, labels4 = replicate(img4, labels4) # replicate\n\n # Augment\n img4, labels4, segments4 = copy_paste(img4, labels4, segments4, probability=self.hyp['copy_paste'])\n img4, labels4 = random_perspective(img4, labels4, segments4,\n degrees=self.hyp['degrees'],\n translate=self.hyp['translate'],\n scale=self.hyp['scale'],\n shear=self.hyp['shear'],\n perspective=self.hyp['perspective'],\n border=self.mosaic_border) # border to remove\n\n return img4, labels4\n\n\ndef load_mosaic9(self, index):\n # loads images in a 9-mosaic\n\n labels9, segments9 = [], []\n s = self.img_size\n indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices\n for i, index in enumerate(indices):\n # Load image\n img, _, (h, w) = load_image(self, index)\n\n # place img in img9\n if i == 0: # center\n img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles\n h0, w0 = h, w\n c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates\n elif i == 1: # top\n c = s, s - h, s + w, s\n elif i == 2: # top right\n c = s + wp, s - h, s + wp + w, s\n elif i == 3: # right\n c = s + w0, s, s + w0 + w, s + h\n elif i == 4: # bottom right\n c = s + w0, s + hp, s + w0 + w, s + hp + h\n elif i == 5: # bottom\n c = s + w0 - w, s + h0, s + w0, s + h0 + h\n elif i == 6: # bottom left\n c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n elif i == 7: # left\n c = s - w, s + h0 - h, s, s + h0\n elif i == 8: # top left\n c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n padx, pady = c[:2]\n x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords\n\n # Labels\n labels, segments = self.labels[index].copy(), self.segments[index].copy()\n if labels.size:\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format\n segments = [xyn2xy(x, w, h, padx, pady) for x in segments]\n labels9.append(labels)\n segments9.extend(segments)\n\n # Image\n img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]\n hp, wp = h, w # height, width previous\n\n # Offset\n yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y\n img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]\n\n # Concat/clip labels\n labels9 = np.concatenate(labels9, 0)\n labels9[:, [1, 3]] -= xc\n labels9[:, [2, 4]] -= yc\n c = np.array([xc, yc]) # centers\n segments9 = [x - c for x in segments9]\n\n for x in (labels9[:, 1:], *segments9):\n np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()\n # img9, labels9 = replicate(img9, labels9) # replicate\n\n # Augment\n img9, labels9 = random_perspective(img9, labels9, segments9,\n degrees=self.hyp['degrees'],\n translate=self.hyp['translate'],\n scale=self.hyp['scale'],\n shear=self.hyp['shear'],\n perspective=self.hyp['perspective'],\n border=self.mosaic_border) # border to remove\n\n return img9, labels9\n\n\ndef replicate(img, labels):\n # Replicate labels\n h, w = img.shape[:2]\n boxes = labels[:, 1:].astype(int)\n x1, y1, x2, y2 = boxes.T\n s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)\n for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices\n x1b, y1b, x2b, y2b = boxes[i]\n bh, bw = y2b - y1b, x2b - x1b\n yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y\n x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]\n img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]\n labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)\n\n return img, labels\n\n\ndef letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):\n # Resize and pad image while meeting stride-multiple constraints\n shape = img.shape[:2] # current shape [height, width]\n if isinstance(new_shape, int):\n new_shape = (new_shape, new_shape)\n\n # Scale ratio (new / old)\n r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n if not scaleup: # only scale down, do not scale up (for better test mAP)\n r = min(r, 1.0)\n\n # Compute padding\n ratio = r, r # width, height ratios\n new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding\n if auto: # minimum rectangle\n dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding\n elif scaleFill: # stretch\n dw, dh = 0.0, 0.0\n new_unpad = (new_shape[1], new_shape[0])\n ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios\n\n dw /= 2 # divide padding into 2 sides\n dh /= 2\n\n if shape[::-1] != new_unpad: # resize\n img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border\n return img, ratio, (dw, dh)\n\n\ndef random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,\n border=(0, 0)):\n # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))\n # targets = [cls, xyxy]\n\n height = img.shape[0] + border[0] * 2 # shape(h,w,c)\n width = img.shape[1] + border[1] * 2\n\n # Center\n C = np.eye(3)\n C[0, 2] = -img.shape[1] / 2 # x translation (pixels)\n C[1, 2] = -img.shape[0] / 2 # y translation (pixels)\n\n # Perspective\n P = np.eye(3)\n P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)\n P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)\n\n # Rotation and Scale\n R = np.eye(3)\n a = random.uniform(-degrees, degrees)\n # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations\n s = random.uniform(1 - scale, 1 + scale)\n # s = 2 ** random.uniform(-scale, scale)\n R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n # Shear\n S = np.eye(3)\n S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)\n S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)\n\n # Translation\n T = np.eye(3)\n T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)\n T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)\n\n # Combined rotation matrix\n M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT\n if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed\n if perspective:\n img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))\n else: # affine\n img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))\n\n # Visualize\n # import matplotlib.pyplot as plt\n # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()\n # ax[0].imshow(img[:, :, ::-1]) # base\n # ax[1].imshow(img2[:, :, ::-1]) # warped\n\n # Transform label coordinates\n n = len(targets)\n if n:\n use_segments = any(x.any() for x in segments)\n new = np.zeros((n, 4))\n if use_segments: # warp segments\n segments = resample_segments(segments) # upsample\n for i, segment in enumerate(segments):\n xy = np.ones((len(segment), 3))\n xy[:, :2] = segment\n xy = xy @ M.T # transform\n xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine\n\n # clip\n new[i] = segment2box(xy, width, height)\n\n else: # warp boxes\n xy = np.ones((n * 4, 3))\n xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1\n xy = xy @ M.T # transform\n xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine\n\n # create new boxes\n x = xy[:, [0, 2, 4, 6]]\n y = xy[:, [1, 3, 5, 7]]\n new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n # clip\n new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)\n new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)\n\n # filter candidates\n i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)\n targets = targets[i]\n targets[:, 1:5] = new[i]\n\n return img, targets\n\n\ndef copy_paste(img, labels, segments, probability=0.5):\n # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)\n n = len(segments)\n if probability and n:\n h, w, c = img.shape # height, width, channels\n im_new = np.zeros(img.shape, np.uint8)\n for j in random.sample(range(n), k=round(probability * n)):\n l, s = labels[j], segments[j]\n box = w - l[3], l[2], w - l[1], l[4]\n ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area\n if (ioa < 0.30).all(): # allow 30% obscuration of existing labels\n labels = np.concatenate((labels, [[l[0], *box]]), 0)\n segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))\n cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)\n\n result = cv2.bitwise_and(src1=img, src2=im_new)\n result = cv2.flip(result, 1) # augment segments (flip left-right)\n i = result > 0 # pixels to replace\n # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch\n img[i] = result[i] # cv2.imwrite('debug.jpg', img) # debug\n\n return img, labels, segments\n\n\ndef box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)\n # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio\n return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates\n\n\ndef cutout(image, labels):\n # Applies image cutout augmentation https://arxiv.org/abs/1708.04552\n h, w = image.shape[:2]\n\n # create random masks\n scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction\n for s in scales:\n mask_h = random.randint(1, int(h * s))\n mask_w = random.randint(1, int(w * s))\n\n # box\n xmin = max(0, random.randint(0, w) - mask_w // 2)\n ymin = max(0, random.randint(0, h) - mask_h // 2)\n xmax = min(w, xmin + mask_w)\n ymax = min(h, ymin + mask_h)\n\n # apply random color mask\n image[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]\n\n # return unobscured labels\n if len(labels) and s > 0.03:\n box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)\n ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area\n labels = labels[ioa < 0.60] # remove >60% obscured labels\n\n return labels\n\n\ndef create_folder(path='./new'):\n # Create folder\n if os.path.exists(path):\n shutil.rmtree(path) # delete output folder\n os.makedirs(path) # make new output folder\n\n\ndef flatten_recursive(path='../datasets/coco128'):\n # Flatten a recursive directory by bringing all files to top level\n new_path = Path(path + '_flat')\n create_folder(new_path)\n for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):\n shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes()\n # Convert detection dataset into classification dataset, with one directory per class\n\n path = Path(path) # images dir\n shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing\n files = list(path.rglob('*.*'))\n n = len(files) # number of files\n for im_file in tqdm(files, total=n):\n if im_file.suffix[1:] in img_formats:\n # image\n im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB\n h, w = im.shape[:2]\n\n # labels\n lb_file = Path(img2label_paths([str(im_file)])[0])\n if Path(lb_file).exists():\n with open(lb_file, 'r') as f:\n lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels\n\n for j, x in enumerate(lb):\n c = int(x[0]) # class\n f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename\n if not f.parent.is_dir():\n f.parent.mkdir(parents=True)\n\n b = x[1:] * [w, h, w, h] # box\n # b[2:] = b[2:].max() # rectangle to square\n b[2:] = b[2:] * 1.2 + 3 # pad\n b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)\n\n b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image\n b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):\n \"\"\" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n Usage: from utils.datasets import *; autosplit()\n Arguments\n path: Path to images directory\n weights: Train, val, test weights (list, tuple)\n annotated_only: Only use images with an annotated txt file\n \"\"\"\n path = Path(path) # images dir\n files = sum([list(path.rglob(f\"*.{img_ext}\")) for img_ext in img_formats], []) # image files only\n n = len(files) # number of files\n random.seed(0) # for reproducibility\n indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split\n\n txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files\n [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing\n\n print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)\n for i, img in tqdm(zip(indices, files), total=n):\n if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label\n with open(path.parent / txt[i], 'a') as f:\n f.write('./' + img.relative_to(path.parent).as_posix() + '\\n') # add image to txt file\n\n\ndef verify_image_label(args):\n # Verify one image-label pair\n im_file, lb_file, prefix = args\n nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, corrupt\n try:\n # verify images\n im = Image.open(im_file)\n im.verify() # PIL verify\n shape = exif_size(im) # image size\n assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n assert im.format.lower() in img_formats, f'invalid image format {im.format}'\n if im.format.lower() in ('jpg', 'jpeg'):\n with open(im_file, 'rb') as f:\n f.seek(-2, 2)\n assert f.read() == b'\\xff\\xd9', 'corrupted JPEG'\n\n # verify labels\n segments = [] # instance segments\n if os.path.isfile(lb_file):\n nf = 1 # label found\n with open(lb_file, 'r') as f:\n l = [x.split() for x in f.read().strip().splitlines() if len(x)]\n if any([len(x) > 8 for x in l]): # is segment\n classes = np.array([x[0] for x in l], dtype=np.float32)\n segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)\n l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)\n l = np.array(l, dtype=np.float32)\n if len(l):\n assert l.shape[1] == 5, 'labels require 5 columns each'\n assert (l >= 0).all(), 'negative labels'\n assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'\n else:\n ne = 1 # label empty\n l = np.zeros((0, 5), dtype=np.float32)\n else:\n nm = 1 # label missing\n l = np.zeros((0, 5), dtype=np.float32)\n return im_file, l, shape, segments, nm, nf, ne, nc, ''\n except Exception as e:\n nc = 1\n msg = f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}'\n return [None, None, None, None, nm, nf, ne, nc, msg]\n\n\ndef dataset_stats(path='coco128.yaml', autodownload=False, verbose=False):\n \"\"\" Return dataset statistics dictionary with images and instances counts per split per class\n Usage: from utils.datasets import *; dataset_stats('coco128.yaml', verbose=True)\n Arguments\n path: Path to data.yaml\n autodownload: Attempt to download dataset if not found locally\n verbose: Print stats dictionary\n \"\"\"\n\n def round_labels(labels):\n # Update labels to integer class and 6 decimal place floats\n return [[int(c), *[round(x, 6) for x in points]] for c, *points in labels]\n\n with open(check_file(path)) as f:\n data = yaml.safe_load(f) # data dict\n check_dataset(data, autodownload) # download dataset if missing\n nc = data['nc'] # number of classes\n stats = {'nc': nc, 'names': data['names']} # statistics dictionary\n for split in 'train', 'val', 'test':\n if data.get(split) is None:\n stats[split] = None # i.e. no test set\n continue\n x = []\n dataset = LoadImagesAndLabels(data[split], augment=False, rect=True) # load dataset\n if split == 'train':\n cache_path = Path(dataset.label_files[0]).parent.with_suffix('.cache') # *.cache path\n for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):\n x.append(np.bincount(label[:, 0].astype(int), minlength=nc))\n x = np.array(x) # shape(128x80)\n stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},\n 'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),\n 'per_class': (x > 0).sum(0).tolist()},\n 'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in\n zip(dataset.img_files, dataset.labels)]}\n\n # Save, print and return\n with open(cache_path.with_suffix('.json'), 'w') as f:\n json.dump(stats, f) # save stats *.json\n if verbose:\n print(json.dumps(stats, indent=2, sort_keys=False))\n # print(yaml.dump([stats], sort_keys=False, default_flow_style=False))\n return stats\n", "import numpy as np\nimport pandas as pd\nimport datetime\n\n\n#x = AX+B\n\n#Calib matrix\n# scales = [0.984, 1.07, 0.995]\n# rot = [[0.9716406, 0.1448620, 0.1868945],\\\n# \t\t[-0.1410913, 0.9894332, -0.0333945],\\\n# \t\t[-0.1897572, 0.0060782, 0.9818122]] #EulerXYZ: 0.034, 0.188, -0.148\n# skews = np.eye(3)\n\n# A = np.matmul(rot, np.diag(scales))\n# A = np.matmul(skews, A)\nA = np.array([[1.3, 0.03, 0.04],[0.026, 1.56, 0.0],[0.011, 0.12, 0.8]])\n\nprint(A)\n\n#Bias\nB = np.array([[-0.0568], [0.055], [0.109]])\nprint(B)\n\n#Variance\nvar = 0.1\n\n#Generate points\nnum_points = 2_000\nr =1\n\npoints = []\nfor i in range(num_points):\n\ttheta = np.random.rand()*2*np.pi\n\tphi = np.random.rand()*2*np.pi\n\tx = r*np.sin(phi)*np.cos(theta)\n\ty = r*np.sin(phi)*np.sin(theta)\n\tz = r*np.cos(phi)\n\tpoints.append([x,y,z])\n\ndf_calib = pd.DataFrame(points)\n\n\n#Simulate Drift (1. sudden-drift)\nsimulate_drift = False\n\nif simulate_drift:\n\tscale_drift = np.diag(np.random.randn(3)*0.1 +1)\n\trot_drift = np.random.randn(3,3)*0.002\n\tz = (scale_drift==0)*rot_drift + scale_drift\n\tbias_drift = np.random.randn(3,1)*0.2\n\n\t#A = z@A\n\tB = B+bias_drift\n\tprint('\\n Drifted params:\\n')\n\tprint(A)\n\tprint(B)\n\n#Corrupt\npoints_raw = []\nfor p in points:\n\tp_ = np.matmul(A,p)+B.T\n\tp_ += np.random.randn(3)*var\n\tpoints_raw.append(*(p_.tolist()))\n\nassert(len(points_raw)==len(points))\n\ndf_raw = pd.DataFrame(points_raw)\n\n\n#Save CSVs\nstamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n\ndf_calib.to_csv('points_calib__'+stamp+'.csv', header=False, index=False)\ndf_raw.to_csv('points_raw__'+stamp+'.csv', header=False, index=False)\n\n" ]
[ [ "torch.zeros", "torch.cat", "torch.load", "numpy.flipud", "numpy.concatenate", "numpy.all", "torch.save", "numpy.random.beta", "torch.utils.data.distributed.DistributedSampler", "numpy.clip", "numpy.fliplr", "numpy.arange", "numpy.eye", "numpy.unique", "torch.from_numpy", "numpy.stack", "torch.tensor", "numpy.full", "numpy.zeros", "numpy.ascontiguousarray", "numpy.append", "torch.stack", "numpy.array", "numpy.maximum", "numpy.ones", "numpy.mod", "numpy.random.uniform" ], [ "numpy.matmul", "numpy.cos", "pandas.DataFrame", "numpy.sin", "numpy.random.randn", "numpy.random.rand", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Leyan529/ImageClassificationPL
[ "a4be75f4525828100d8d278e46ff5dccd829af1a" ]
[ "extra/face.py" ]
[ "import torch\r\nimport matplotlib.image as img \r\n\r\nimport cv2\r\nimport dlib\r\nfrom imutils.face_utils import *\r\n\r\nimport numpy as np\r\n\r\n# image = img.imread(\"extra//test.jpg\")\r\n# image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) # opencvImage\r\ndlib_path = 'extra//shape_predictor_68_face_landmarks.dat'\r\n\r\ndef get_face(img):\r\n global detector, landmark_predictor\r\n # 宣告臉部偵測器,以及載入預訓練的臉部特徵點模型\r\n detector = dlib.get_frontal_face_detector()\r\n landmark_predictor = dlib.shape_predictor(dlib_path)\r\n # 產生臉部識別\r\n face_rects = detector(img, 1) \r\n for i, d in enumerate(face_rects):\r\n # 讀取框左上右下座標\r\n x1 = d.left()\r\n y1 = d.top()\r\n x2 = d.right()\r\n y2 = d.bottom()\r\n # 根據此座標範圍讀取臉部特徵點\r\n shape = landmark_predictor(img, d)\r\n # 將特徵點轉為numpy\r\n shape = shape_to_np(shape) # (68,2)\r\n # 透過dlib挖取臉孔部分,將臉孔圖片縮放至256*256的大小,並存放於pickle檔中\r\n # 人臉圖像部分呢。很簡單,只要根據畫框的位置切取即可crop_img = img[y1:y2, x1:x2, :]\r\n crop_img = img[y1:y2, x1:x2, :]\r\n try:\r\n resize_img = cv2.resize(crop_img, (512, 512))\r\n # cv2.imshow(\"OpenCV\",resize_img) \r\n # cv2.waitKey()\r\n return resize_img\r\n except:\r\n return np.array([0])\r\n return np.array([0])\r\n\r\ndef predict_image(logger, image, model):\r\n try:\r\n face = get_face(image) # predict target\r\n face = torch.tensor(face, dtype=torch.float32)/255 # normalize\r\n face = face.permute(2, 0, 1).unsqueeze(0).cuda()\r\n # model = torch.load('run\\SCUT\\pre_googlenet\\experiment_6\\pre_googlenet.pkl')\r\n # model.load_state_dict(torch.load('run\\SCUT\\pre_googlenet\\experiment_6\\checkpoint.pth.tar')['state_dict'])\r\n outputs = model(face) # [bsz, c, h, w]\r\n _, predicted = torch.max(outputs.data, 1)\r\n score = int(predicted.item()) * 20\r\n# logger.info(\"Predict Score : {}\".format(score))\r\n return score\r\n except Exception as e:\r\n # print(e)\r\n return 0 " ]
[ [ "numpy.array", "torch.max", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
washcycle/mlflow
[ "5a60ab34a4cecfe0b9636f6df77c087faa8b6959" ]
[ "mlflow/pyfunc/__init__.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"\nThe ``mlflow.pyfunc`` module defines a generic :ref:`filesystem format <pyfunc-filesystem-format>`\nfor Python models and provides utilities for saving to and loading from this format. The format is\nself contained in the sense that it includes all necessary information for anyone to load it and\nuse it. Dependencies are either stored directly with the model or referenced via a Conda\nenvironment.\n\nThe ``mlflow.pyfunc`` module also defines utilities for creating custom ``pyfunc`` models\nusing frameworks and inference logic that may not be natively included in MLflow. See\n:ref:`pyfunc-create-custom`.\n\n.. _pyfunc-filesystem-format:\n\n*****************\nFilesystem format\n*****************\n\nThe Pyfunc format is defined as a directory structure containing all required data, code, and\nconfiguration::\n\n ./dst-path/\n ./MLmodel: configuration\n <code>: code packaged with the model (specified in the MLmodel file)\n <data>: data packaged with the model (specified in the MLmodel file)\n <env>: Conda environment definition (specified in the MLmodel file)\n\nThe directory structure may contain additional contents that can be referenced by the ``MLmodel``\nconfiguration.\n\n.. _pyfunc-model-config:\n\nMLModel configuration\n#####################\n\nA Python model contains an ``MLmodel`` file in **python_function** format in its root with the\nfollowing parameters:\n\n- loader_module [required]:\n Python module that can load the model. Expected as module identifier\n e.g. ``mlflow.sklearn``, it will be imported using ``importlib.import_module``.\n The imported module must contain a function with the following signature::\n\n _load_pyfunc(path: string) -> <pyfunc model>\n\n The path argument is specified by the ``data`` parameter and may refer to a file or\n directory.\n\n- code [optional]:\n Relative path to a directory containing the code packaged with this model.\n All files and directories inside this directory are added to the Python path\n prior to importing the model loader.\n\n- data [optional]:\n Relative path to a file or directory containing model data.\n The path is passed to the model loader.\n\n- env [optional]:\n Relative path to an exported Conda environment. If present this environment\n should be activated prior to running the model.\n\n- Optionally, any additional parameters necessary for interpreting the serialized model in\n ``pyfunc`` format.\n\n.. rubric:: Example\n\n>>> tree example/sklearn_iris/mlruns/run1/outputs/linear-lr\n\n::\n\n ├── MLmodel\n ├── code\n │   ├── sklearn_iris.py\n │  \n ├── data\n │   └── model.pkl\n └── mlflow_env.yml\n\n>>> cat example/sklearn_iris/mlruns/run1/outputs/linear-lr/MLmodel\n\n::\n\n python_function:\n code: code\n data: data/model.pkl\n loader_module: mlflow.sklearn\n env: mlflow_env.yml\n main: sklearn_iris\n\n.. _pyfunc-inference-api:\n\n*************\nInference API\n*************\n\nThe convention for pyfunc models is to have a ``predict`` method or function with the following\nsignature::\n\n predict(model_input: pandas.DataFrame) -> [numpy.ndarray | pandas.Series | pandas.DataFrame]\n\nThis convention is relied on by other MLflow components.\n\n.. _pyfunc-create-custom:\n\n******************************\nCreating custom Pyfunc models\n******************************\n\nMLflow's persistence modules provide convenience functions for creating models with the\n``pyfunc`` flavor in a variety of machine learning frameworks (scikit-learn, Keras, Pytorch, and\nmore); however, they do not cover every use case. For example, you may want to create an MLflow\nmodel with the ``pyfunc`` flavor using a framework that MLflow does not natively support.\nAlternatively, you may want to build an MLflow model that executes custom logic when evaluating\nqueries, such as preprocessing and postprocessing routines. Therefore, ``mlflow.pyfunc``\nprovides utilities for creating ``pyfunc`` models from arbitrary code and model data.\n\nThe :meth:`save_model()` and :meth:`log_model()` methods are designed to support multiple workflows\nfor creating custom ``pyfunc`` models that incorporate custom inference logic and artifacts\nthat the logic may require.\n\nAn `artifact` is a file or directory, such as a serialized model or a CSV. For example, a\nserialized TensorFlow graph is an artifact. An MLflow model directory is also an artifact.\n\n.. _pyfunc-create-custom-workflows:\n\nWorkflows\n#########\n\n:meth:`save_model()` and :meth:`log_model()` support the following workflows:\n\n1. Programmatically defining a new MLflow model, including its attributes and artifacts.\n\n Given a set of artifact URIs, :meth:`save_model()` and :meth:`log_model()` can\n automatically download artifacts from their URIs and create an MLflow model directory.\n\n In this case, you must define a Python class which inherits from :class:`~PythonModel`,\n defining ``predict()`` and, optionally, ``load_context()``. An instance of this class is\n specified via the ``python_model`` parameter; it is automatically serialized and deserialized\n as a Python class, including all of its attributes.\n\n2. Interpreting pre-existing data as an MLflow model.\n\n If you already have a directory containing model data, :meth:`save_model()` and\n :meth:`log_model()` can import the data as an MLflow model. The ``data_path`` parameter\n specifies the local filesystem path to the directory containing model data.\n\n In this case, you must provide a Python module, called a `loader module`. The\n loader module defines a ``_load_pyfunc()`` method that performs the following tasks:\n\n - Load data from the specified ``data_path``. For example, this process may include\n deserializing pickled Python objects or models or parsing CSV files.\n\n - Construct and return a pyfunc-compatible model wrapper. As in the first\n use case, this wrapper must define a ``predict()`` method that is used to evaluate\n queries. ``predict()`` must adhere to the :ref:`pyfunc-inference-api`.\n\n The ``loader_module`` parameter specifies the name of your loader module.\n\n For an example loader module implementation, refer to the `loader module\n implementation in mlflow.keras <https://github.com/mlflow/mlflow/blob/\n 74d75109aaf2975f5026104d6125bb30f4e3f744/mlflow/keras.py#L157-L187>`_.\n\n.. _pyfunc-create-custom-selecting-workflow:\n\nWhich workflow is right for my use case?\n########################################\n\nWe consider the first workflow to be more user-friendly and generally recommend it for the\nfollowing reasons:\n\n- It automatically resolves and collects specified model artifacts.\n\n- It automatically serializes and deserializes the ``python_model`` instance and all of\n its attributes, reducing the amount of user logic that is required to load the model\n\n- You can create Models using logic that is defined in the ``__main__`` scope. This allows\n custom models to be constructed in interactive environments, such as notebooks and the Python\n REPL.\n\nYou may prefer the second, lower-level workflow for the following reasons:\n\n- Inference logic is always persisted as code, rather than a Python object. This makes logic\n easier to inspect and modify later.\n\n- If you have already collected all of your model data in a single location, the second\n workflow allows it to be saved in MLflow format directly, without enumerating constituent\n artifacts.\n\"\"\"\n\nimport importlib\nimport logging\nimport numpy as np\nimport os\nimport pandas\nimport shutil\nfrom copy import deepcopy\n\nimport mlflow\nimport mlflow.pyfunc.model\nimport mlflow.pyfunc.utils\nfrom mlflow.models import Model\nfrom mlflow.pyfunc.model import PythonModel, PythonModelContext, get_default_conda_env\nfrom mlflow.tracking.artifact_utils import _download_artifact_from_uri\nfrom mlflow.utils import PYTHON_VERSION, deprecated, get_major_minor_py_version\nfrom mlflow.utils.file_utils import TempDir, _copy_file_or_tree\nfrom mlflow.utils.model_utils import _get_flavor_configuration\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE, RESOURCE_ALREADY_EXISTS\n\nFLAVOR_NAME = \"python_function\"\nMAIN = \"loader_module\"\nCODE = \"code\"\nDATA = \"data\"\nENV = \"env\"\nPY_VERSION = \"python_version\"\n\n_logger = logging.getLogger(__name__)\n\n\ndef add_to_model(model, loader_module, data=None, code=None, env=None, **kwargs):\n \"\"\"\n Add a ``pyfunc`` spec to the model configuration.\n\n Defines ``pyfunc`` configuration schema. Caller can use this to create a valid ``pyfunc`` model\n flavor out of an existing directory structure. For example, other model flavors can use this to\n specify how to use their output as a ``pyfunc``.\n\n NOTE:\n\n All paths are relative to the exported model root directory.\n\n :param model: Existing model.\n :param loader_module: The module to be used to load the model.\n :param data: Path to the model data.\n :param code: Path to the code dependencies.\n :param env: Conda environment.\n :param kwargs: Additional key-value pairs to include in the ``pyfunc`` flavor specification.\n Values must be YAML-serializable.\n :return: Updated model configuration.\n \"\"\"\n parms = deepcopy(kwargs)\n parms[MAIN] = loader_module\n parms[PY_VERSION] = PYTHON_VERSION\n if code:\n parms[CODE] = code\n if data:\n parms[DATA] = data\n if env:\n parms[ENV] = env\n return model.add_flavor(FLAVOR_NAME, **parms)\n\n\ndef _load_model_env(path):\n \"\"\"\n Get ENV file string from a model configuration stored in Python Function format.\n Returned value is a model-relative path to a Conda Environment file,\n or None if none was specified at model save time\n \"\"\"\n return _get_flavor_configuration(model_path=path, flavor_name=FLAVOR_NAME).get(ENV, None)\n\n\ndef load_model(model_uri, suppress_warnings=False):\n \"\"\"\n Load a model stored in Python function format.\n\n :param model_uri: The location, in URI format, of the MLflow model. For example:\n\n - ``/Users/me/path/to/local/model``\n - ``relative/path/to/local/model``\n - ``s3://my_bucket/path/to/model``\n - ``runs:/<mlflow_run_id>/run-relative/path/to/model``\n\n For more information about supported URI schemes, see\n `Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#\n artifact-locations>`_.\n :param suppress_warnings: If ``True``, non-fatal warning messages associated with the model\n loading process will be suppressed. If ``False``, these warning\n messages will be emitted.\n \"\"\"\n return load_pyfunc(model_uri, suppress_warnings)\n\n\n@deprecated(\"pyfunc.load_model\", 1.0)\ndef load_pyfunc(model_uri, suppress_warnings=False):\n \"\"\"\n Load a model stored in Python function format.\n\n :param model_uri: The location, in URI format, of the MLflow model. For example:\n\n - ``/Users/me/path/to/local/model``\n - ``relative/path/to/local/model``\n - ``s3://my_bucket/path/to/model``\n - ``runs:/<mlflow_run_id>/run-relative/path/to/model``\n\n For more information about supported URI schemes, see\n `Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#\n artifact-locations>`_.\n\n :param suppress_warnings: If ``True``, non-fatal warning messages associated with the model\n loading process will be suppressed. If ``False``, these warning\n messages will be emitted.\n \"\"\"\n local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)\n conf = _get_flavor_configuration(model_path=local_model_path, flavor_name=FLAVOR_NAME)\n model_py_version = conf.get(PY_VERSION)\n if not suppress_warnings:\n _warn_potentially_incompatible_py_version_if_necessary(model_py_version=model_py_version)\n if CODE in conf and conf[CODE]:\n code_path = os.path.join(local_model_path, conf[CODE])\n mlflow.pyfunc.utils._add_code_to_system_path(code_path=code_path)\n data_path = os.path.join(local_model_path, conf[DATA]) if (DATA in conf) else local_model_path\n return importlib.import_module(conf[MAIN])._load_pyfunc(data_path)\n\n\ndef _warn_potentially_incompatible_py_version_if_necessary(model_py_version=None):\n \"\"\"\n Compares the version of Python that was used to save a given model with the version\n of Python that is currently running. If a major or minor version difference is detected,\n logs an appropriate warning.\n \"\"\"\n if model_py_version is None:\n _logger.warning(\n \"The specified model does not have a specified Python version. It may be\"\n \" incompatible with the version of Python that is currently running: Python %s\",\n PYTHON_VERSION)\n elif get_major_minor_py_version(model_py_version) != get_major_minor_py_version(PYTHON_VERSION):\n _logger.warning(\n \"The version of Python that the model was saved in, `Python %s`, differs\"\n \" from the version of Python that is currently running, `Python %s`,\"\n \" and may be incompatible\",\n model_py_version, PYTHON_VERSION)\n\n\ndef spark_udf(spark, model_uri, result_type=\"double\"):\n \"\"\"\n A Spark UDF that can be used to invoke the Python function formatted model.\n\n Parameters passed to the UDF are forwarded to the model as a DataFrame where the names are\n ordinals (0, 1, ...).\n\n The predictions are filtered to contain only the columns that can be represented as the\n ``result_type``. If the ``result_type`` is string or array of strings, all predictions are\n converted to string. If the result type is not an array type, the left most column with\n matching type is returned.\n\n >>> predict = mlflow.pyfunc.spark_udf(spark, \"/my/local/model\")\n >>> df.withColumn(\"prediction\", predict(\"name\", \"age\")).show()\n\n :param spark: A SparkSession object.\n :param model_uri: The location, in URI format, of the MLflow model with the\n :py:mod:`mlflow.pyfunc` flavor. For example:\n\n - ``/Users/me/path/to/local/model``\n - ``relative/path/to/local/model``\n - ``s3://my_bucket/path/to/model``\n - ``runs:/<mlflow_run_id>/run-relative/path/to/model``\n\n For more information about supported URI schemes, see\n `Referencing Artifacts <https://www.mlflow.org/docs/latest/tracking.html#\n artifact-locations>`_.\n\n :param result_type: the return type of the user-defined function. The value can be either a\n :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. Only a primitive\n type or an array ``pyspark.sql.types.ArrayType`` of primitive type are allowed.\n The following classes of result type are supported:\n\n - \"int\" or ``pyspark.sql.types.IntegerType``: The leftmost integer that can fit in an\n ``int32`` or an exception if there is none.\n\n - \"long\" or ``pyspark.sql.types.LongType``: The leftmost long integer that can fit in an\n ``int64`` or an exception if there is none.\n\n - ``ArrayType(IntegerType|LongType)``: All integer columns that can fit into the requested\n size.\n\n - \"float\" or ``pyspark.sql.types.FloatType``: The leftmost numeric result cast to\n ``float32`` or an exception if there is none.\n\n - \"double\" or ``pyspark.sql.types.DoubleType``: The leftmost numeric result cast to\n ``double`` or an exception if there is none.\n\n - ``ArrayType(FloatType|DoubleType)``: All numeric columns cast to the requested type or\n an exception if there are no numeric columns.\n\n - \"string\" or ``pyspark.sql.types.StringType``: The leftmost column converted to ``string``.\n\n - ``ArrayType(StringType)``: All columns converted to ``string``.\n\n :return: Spark UDF that applies the model's ``predict`` method to the data and returns a\n type specified by ``result_type``, which by default is a double.\n \"\"\"\n\n # Scope Spark import to this method so users don't need pyspark to use non-Spark-related\n # functionality.\n from mlflow.pyfunc.spark_model_cache import SparkModelCache\n from pyspark.sql.functions import pandas_udf\n from pyspark.sql.types import _parse_datatype_string\n from pyspark.sql.types import ArrayType, DataType\n from pyspark.sql.types import DoubleType, IntegerType, FloatType, LongType, StringType\n\n if not isinstance(result_type, DataType):\n result_type = _parse_datatype_string(result_type)\n\n elem_type = result_type\n if isinstance(elem_type, ArrayType):\n elem_type = elem_type.elementType\n\n supported_types = [IntegerType, LongType, FloatType, DoubleType, StringType]\n\n if not any([isinstance(elem_type, x) for x in supported_types]):\n raise MlflowException(\n message=\"Invalid result_type '{}'. Result type can only be one of or an array of one \"\n \"of the following types types: {}\".format(str(elem_type), str(supported_types)),\n error_code=INVALID_PARAMETER_VALUE)\n\n local_model_path = _download_artifact_from_uri(artifact_uri=model_uri)\n archive_path = SparkModelCache.add_local_model(spark, local_model_path)\n\n def predict(*args):\n model = SparkModelCache.get_or_load(archive_path)\n schema = {str(i): arg for i, arg in enumerate(args)}\n # Explicitly pass order of columns to avoid lexicographic ordering (i.e., 10 < 2)\n columns = [str(i) for i, _ in enumerate(args)]\n pdf = pandas.DataFrame(schema, columns=columns)\n result = model.predict(pdf)\n if not isinstance(result, pandas.DataFrame):\n result = pandas.DataFrame(data=result)\n\n elif type(elem_type) == IntegerType:\n result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort,\n np.int32]).astype(np.int32)\n\n elif type(elem_type) == LongType:\n result = result.select_dtypes([np.byte, np.ubyte, np.short, np.ushort, np.int, np.long])\n\n elif type(elem_type) == FloatType:\n result = result.select_dtypes(include=(np.number,)).astype(np.float32)\n\n elif type(elem_type) == DoubleType:\n result = result.select_dtypes(include=(np.number,)).astype(np.float64)\n\n if len(result.columns) == 0:\n raise MlflowException(\n message=\"The the model did not produce any values compatible with the requested \"\n \"type '{}'. Consider requesting udf with StringType or \"\n \"Arraytype(StringType).\".format(str(elem_type)),\n error_code=INVALID_PARAMETER_VALUE)\n\n if type(elem_type) == StringType:\n result = result.applymap(str)\n\n if type(result_type) == ArrayType:\n return pandas.Series([row[1].values for row in result.iterrows()])\n else:\n return result[result.columns[0]]\n\n return pandas_udf(predict, result_type)\n\n\ndef save_model(path, loader_module=None, data_path=None, code_path=None, conda_env=None,\n mlflow_model=Model(), python_model=None, artifacts=None, **kwargs):\n \"\"\"\n save_model(path, loader_module=None, data_path=None, code_path=None, conda_env=None,\\\n mlflow_model=Model(), python_model=None, artifacts=None)\n\n Save a Pyfunc model with custom inference logic and optional data dependencies to a path on the\n local filesystem.\n\n For information about the workflows that this method supports, please see :ref:`\"workflows for\n creating custom pyfunc models\" <pyfunc-create-custom-workflows>` and\n :ref:`\"which workflow is right for my use case?\" <pyfunc-create-custom-selecting-workflow>`.\n Note that the parameters for the first workflow: ``loader_module``, ``data_path`` and the\n parameters for the second workflow: ``python_model``, ``artifacts``, cannot be\n specified together.\n\n :param path: The path to which to save the Python model.\n :param loader_module: The name of the Python module that is used to load the model\n from ``data_path``. This module must define a method with the prototype\n ``_load_pyfunc(data_path)``. If not ``None``, this module and its\n dependencies must be included in one of the following locations:\n\n - The MLflow library.\n - Package(s) listed in the model's Conda environment, specified by\n the ``conda_env`` parameter.\n - One or more of the files specified by the ``code_path`` parameter.\n\n :param data_path: Path to a file or directory containing model data.\n :param code_path: A list of local filesystem paths to Python file dependencies (or directories\n containing file dependencies). These files are *prepended* to the system\n path before the model is loaded.\n :param conda_env: Either a dictionary representation of a Conda environment or the path to a\n Conda environment yaml file. This decribes the environment this model should\n be run in. If ``python_model`` is not ``None``, the Conda environment must\n at least specify the dependencies contained in\n :func:`get_default_conda_env()`. If ``None``, the default\n :func:`get_default_conda_env()` environment is added to the\n model. The following is an *example* dictionary representation of a Conda\n environment::\n\n {\n 'name': 'mlflow-env',\n 'channels': ['defaults'],\n 'dependencies': [\n 'python=3.7.0',\n 'cloudpickle==0.5.8'\n ]\n }\n :param mlflow_model: :py:mod:`mlflow.models.Model` configuration to which to add the\n **python_function** flavor.\n :param python_model: An instance of a subclass of :class:`~PythonModel`. This class is\n serialized using the CloudPickle library. Any dependencies of the class\n should be included in one of the following locations:\n\n - The MLflow library.\n - Package(s) listed in the model's Conda environment, specified by\n the ``conda_env`` parameter.\n - One or more of the files specified by the ``code_path`` parameter.\n\n Note: If the class is imported from another module, as opposed to being\n defined in the ``__main__`` scope, the defining module should also be\n included in one of the listed locations.\n :param artifacts: A dictionary containing ``<name, artifact_uri>`` entries. Remote artifact URIs\n are resolved to absolute filesystem paths, producing a dictionary of\n ``<name, absolute_path>`` entries. ``python_model`` can reference these\n resolved entries as the ``artifacts`` property of the ``context`` parameter\n in :func:`PythonModel.load_context() <mlflow.pyfunc.PythonModel.load_context>`\n and :func:`PythonModel.predict() <mlflow.pyfunc.PythonModel.predict>`.\n For example, consider the following ``artifacts`` dictionary::\n\n {\n \"my_file\": \"s3://my-bucket/path/to/my/file\"\n }\n\n In this case, the ``\"my_file\"`` artifact is downloaded from S3. The\n ``python_model`` can then refer to ``\"my_file\"`` as an absolute filesystem\n path via ``context.artifacts[\"my_file\"]``.\n\n If ``None``, no artifacts are added to the model.\n \"\"\"\n mlflow_model = kwargs.pop('model', mlflow_model)\n if len(kwargs) > 0:\n raise TypeError(\"save_model() got unexpected keyword arguments: {}\".format(kwargs))\n first_argument_set = {\n \"loader_module\": loader_module,\n \"data_path\": data_path,\n }\n second_argument_set = {\n \"artifacts\": artifacts,\n \"python_model\": python_model,\n }\n first_argument_set_specified = any([item is not None for item in first_argument_set.values()])\n second_argument_set_specified = any([item is not None for item in second_argument_set.values()])\n if first_argument_set_specified and second_argument_set_specified:\n raise MlflowException(\n message=(\n \"The following sets of parameters cannot be specified together: {first_set_keys}\"\n \" and {second_set_keys}. All parameters in one set must be `None`. Instead, found\"\n \" the following values: {first_set_entries} and {second_set_entries}\".format(\n first_set_keys=first_argument_set.keys(),\n second_set_keys=second_argument_set.keys(),\n first_set_entries=first_argument_set,\n second_set_entries=second_argument_set)),\n error_code=INVALID_PARAMETER_VALUE)\n elif (loader_module is None) and (python_model is None):\n raise MlflowException(\n message=\"Either `loader_module` or `python_model` must be specified!\",\n error_code=INVALID_PARAMETER_VALUE)\n\n if first_argument_set_specified:\n return _save_model_with_loader_module_and_data_path(\n path=path, loader_module=loader_module, data_path=data_path,\n code_paths=code_path, conda_env=conda_env, mlflow_model=mlflow_model)\n elif second_argument_set_specified:\n return mlflow.pyfunc.model._save_model_with_class_artifacts_params(\n path=path, python_model=python_model, artifacts=artifacts, conda_env=conda_env,\n code_paths=code_path, mlflow_model=mlflow_model)\n\n\ndef log_model(artifact_path, loader_module=None, data_path=None, code_path=None, conda_env=None,\n python_model=None, artifacts=None):\n \"\"\"\n Log a Pyfunc model with custom inference logic and optional data dependencies as an MLflow\n artifact for the current run.\n\n For information about the workflows that this method supports, see :ref:`Workflows for\n creating custom pyfunc models <pyfunc-create-custom-workflows>` and\n :ref:`Which workflow is right for my use case? <pyfunc-create-custom-selecting-workflow>`.\n You cannot specify the parameters for the first workflow: ``loader_module``, ``data_path``\n and the parameters for the second workflow: ``python_model``, ``artifacts`` together.\n\n :param artifact_path: The run-relative artifact path to which to log the Python model.\n :param loader_module: The name of the Python module that is used to load the model\n from ``data_path``. This module must define a method with the prototype\n ``_load_pyfunc(data_path)``. If not ``None``, this module and its\n dependencies must be included in one of the following locations:\n\n - The MLflow library.\n - Package(s) listed in the model's Conda environment, specified by\n the ``conda_env`` parameter.\n - One or more of the files specified by the ``code_path`` parameter.\n\n :param data_path: Path to a file or directory containing model data.\n :param code_path: A list of local filesystem paths to Python file dependencies (or directories\n containing file dependencies). These files are *prepended* to the system\n path before the model is loaded.\n :param conda_env: Either a dictionary representation of a Conda environment or the path to a\n Conda environment yaml file. This decribes the environment this model should\n be run in. If ``python_model`` is not ``None``, the Conda environment must\n at least specify the dependencies contained in\n :func:`get_default_conda_env()`. If `None`, the default\n :func:`get_default_conda_env()` environment is added to the\n model. The following is an *example* dictionary representation of a Conda\n environment::\n\n {\n 'name': 'mlflow-env',\n 'channels': ['defaults'],\n 'dependencies': [\n 'python=3.7.0',\n 'cloudpickle==0.5.8'\n ]\n }\n\n :param python_model: An instance of a subclass of :class:`~PythonModel`. This class is\n serialized using the CloudPickle library. Any dependencies of the class\n should be included in one of the following locations:\n\n - The MLflow library.\n - Package(s) listed in the model's Conda environment, specified by\n the ``conda_env`` parameter.\n - One or more of the files specified by the ``code_path`` parameter.\n\n Note: If the class is imported from another module, as opposed to being\n defined in the ``__main__`` scope, the defining module should also be\n included in one of the listed locations.\n :param artifacts: A dictionary containing ``<name, artifact_uri>`` entries. Remote artifact URIs\n are resolved to absolute filesystem paths, producing a dictionary of\n ``<name, absolute_path>`` entries. ``python_model`` can reference these\n resolved entries as the ``artifacts`` property of the ``context`` parameter\n in :func:`PythonModel.load_context() <mlflow.pyfunc.PythonModel.load_context>`\n and :func:`PythonModel.predict() <mlflow.pyfunc.PythonModel.predict>`.\n For example, consider the following ``artifacts`` dictionary::\n\n {\n \"my_file\": \"s3://my-bucket/path/to/my/file\"\n }\n\n In this case, the ``\"my_file\"`` artifact is downloaded from S3. The\n ``python_model`` can then refer to ``\"my_file\"`` as an absolute filesystem\n path via ``context.artifacts[\"my_file\"]``.\n\n If ``None``, no artifacts are added to the model.\n \"\"\"\n return Model.log(artifact_path=artifact_path,\n flavor=mlflow.pyfunc,\n loader_module=loader_module,\n data_path=data_path,\n code_path=code_path,\n python_model=python_model,\n artifacts=artifacts,\n conda_env=conda_env)\n\n\ndef _save_model_with_loader_module_and_data_path(path, loader_module, data_path=None,\n code_paths=None, conda_env=None,\n mlflow_model=Model()):\n \"\"\"\n Export model as a generic Python function model.\n :param path: The path to which to save the Python model.\n :param loader_module: The name of the Python module that is used to load the model\n from ``data_path``. This module must define a method with the prototype\n ``_load_pyfunc(data_path)``.\n :param data_path: Path to a file or directory containing model data.\n :param code_paths: A list of local filesystem paths to Python file dependencies (or directories\n containing file dependencies). These files are *prepended* to the system\n path before the model is loaded.\n :param conda_env: Either a dictionary representation of a Conda environment or the path to a\n Conda environment yaml file. If provided, this decribes the environment\n this model should be run in.\n :return: Model configuration containing model info.\n \"\"\"\n if os.path.exists(path):\n raise MlflowException(\n message=\"Path '{}' already exists\".format(path),\n error_code=RESOURCE_ALREADY_EXISTS)\n os.makedirs(path)\n\n code = None\n data = None\n env = None\n\n if data_path is not None:\n model_file = _copy_file_or_tree(src=data_path, dst=path, dst_dir=\"data\")\n data = model_file\n\n if code_paths is not None:\n for code_path in code_paths:\n _copy_file_or_tree(src=code_path, dst=path, dst_dir=\"code\")\n code = \"code\"\n\n if conda_env is not None:\n shutil.copy(src=conda_env, dst=os.path.join(path, \"mlflow_env.yml\"))\n env = \"mlflow_env.yml\"\n\n mlflow.pyfunc.add_to_model(\n mlflow_model, loader_module=loader_module, code=code, data=data, env=env)\n mlflow_model.save(os.path.join(path, 'MLmodel'))\n return mlflow_model\n\n\nloader_template = \"\"\"\n\nimport importlib\nimport os\nimport sys\n\ndef load_pyfunc():\n {update_path}return importlib.import_module('{main}')._load_pyfunc('{data_path}')\n\n\"\"\"\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
mattzakh/mattplotlib
[ "5e9bc779d8c1b7074549615ab6790a9f7163cd59", "5e9bc779d8c1b7074549615ab6790a9f7163cd59" ]
[ ".history/src/modules/test_plot/test_plot_20190927183934.py", ".history/src/modules/test_plot/test_plot_20190927183924.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\n# plt.style.use('../notebooks/test.mplstyle')\nimport seaborn as sns\n\nfrom logs import logDecorator as lD \nimport jsonref, pprint\n\nconfig = jsonref.load(open('../config/config.json'))\nlogBase = config['logging']['logBase'] + '.modules.test_plot.test_plot'\n\n\[email protected](logBase + '.doSomething')\ndef doSomething(logger):\n '''print a line\n \n This function simply prints a single line\n \n Parameters\n ----------\n logger : {logging.Logger}\n The logger used for logging error information\n '''\n\n with plt.style.context('../notebooks/test.mplstyle'):\n\n w = 7.2\n fig = plt.figure(figsize=(w, w/1.6)) #, edgecolor='k', linewidth=2)\n ax = {}\n ax[0] = plt.axes([0.10, 0.10, 0.35, 0.30])\n ax[1] = plt.axes([0.55, 0.10, 0.35, 0.30])\n ax[2] = plt.axes([0.10, 0.57, 0.35, 0.30])\n ax[3] = plt.axes([0.55, 0.57, 0.35, 0.30])\n\n [ax[0].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), marker='', label=f'line {i}') for i in range(4)]\n [ax[1].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), linestyle='', label=f'marker {i}') for i in range(4)]\n\n params = ((10, 10), (4, 12), (50, 12), (6, 55))\n for a, b in params:\n values = np.random.beta(a, b, size=10000)\n ax[2].hist(values, histtype=\"stepfilled\", bins=30,\n alpha=0.2, density=True)\n\n mean, cov = [0, 2], [(1, .5), (.5, 1)]\n x, y = np.random.multivariate_normal(mean, cov, size=50).T\n # ax[3] = sns.kdeplot(x, linestyle='-', marker='', label='hist')#, marker='')\n\n fig.suptitle('Times New Roman')\n\n [ax[i].set_title(f'ax{i} Title') for i in range(4)]\n [ax[i].set_xlabel(f'ax{i} xlabel') for i in range(4)]\n [ax[i].set_ylabel(f'ax{i} ylabel') for i in range(4)]\n [ax[i].legend(loc='upper right') for i in range(4)]\n\n ax[3].set_xlabel(r'ax3 $a_i \\sin(2\\pi fx_i)$ label');\n\n plt.savefig('test.svg')\n\n return\n\[email protected](logBase + '.main')\ndef main(logger, resultsDict):\n '''main function for module1\n \n This function finishes all the tasks for the\n main function. This is a way in which a \n particular module is going to be executed. \n \n Parameters\n ----------\n logger : {logging.Logger}\n The logger used for logging error information\n resultsDict: {dict}\n A dintionary containing information about the \n command line arguments. These can be used for\n overwriting command line arguments as needed.\n '''\n\n print('='*30)\n print('Main function of module 1')\n print('='*30)\n print('We get a copy of the result dictionary over here ...')\n\n\n doSomething()\n\n print('Getting out of Module 1')\n print('-'*30)\n\n return\n\n", "import numpy as np\nimport matplotlib.pyplot as plt\n# plt.style.use('../notebooks/test.mplstyle')\nimport seaborn as sns\n\nfrom logs import logDecorator as lD \nimport jsonref, pprint\n\nconfig = jsonref.load(open('../config/config.json'))\nlogBase = config['logging']['logBase'] + '.modules.test_plot.test_plot'\n\n\[email protected](logBase + '.doSomething')\ndef doSomething(logger):\n '''print a line\n \n This function simply prints a single line\n \n Parameters\n ----------\n logger : {logging.Logger}\n The logger used for logging error information\n '''\n\n with plt.style.context('../notebooks/test.mplstyle'):\n\n w = 7.2\n fig = plt.figure(figsize=(w, w/1.6)) #, edgecolor='k', linewidth=2)\n ax = {}\n ax[0] = plt.axes([0.10, 0.10, 0.35, 0.30])\n ax[1] = plt.axes([0.55, 0.10, 0.35, 0.30])\n ax[2] = plt.axes([0.10, 0.57, 0.35, 0.30])\n ax[3] = plt.axes([0.55, 0.57, 0.35, 0.30])\n\n [ax[0].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), marker='', label=f'line {i}') for i in range(4)]\n [ax[1].plot([1,2,3],np.random.randint([1,2,3],[10,9,8], size=3), linestyle='', label=f'marker {i}') for i in range(4)]\n\n params = ((10, 10), (4, 12), (50, 12), (6, 55))\n for a, b in params:\n values = np.random.beta(a, b, size=10000)\n ax[2].hist(values, histtype=\"stepfilled\", bins=30,\n alpha=0.2, density=True)\n\n mean, cov = [0, 2], [(1, .5), (.5, 1)]\n x, y = np.random.multivariate_normal(mean, cov, size=50).T\n # ax[3] = sns.kdeplot(x, linestyle='-', marker='', label='hist')#, marker='')\n\n fig.suptitle('Times New Roman')\n\n [ax[i].set_title(f'ax{i} Title') for i in range(4)]\n [ax[i].set_xlabel(f'ax{i} xlabel') for i in range(4)]\n [ax[i].set_ylabel(f'ax{i} ylabel') for i in range(4)]\n [ax[i].legend(loc='upper right') for i in range(4)]\n\n ax[3].set_xlabel(r'ax3 $a_i \\sin(2\\pi fx_i)$ label');\n\n plt.savefig('test.svg')\n\n return\n\[email protected](logBase + '.main')\ndef main(logger, resultsDict):\n '''main function for module1\n \n This function finishes all the tasks for the\n main function. This is a way in which a \n particular module is going to be executed. \n \n Parameters\n ----------\n logger : {logging.Logger}\n The logger used for logging error information\n resultsDict: {dict}\n A dintionary containing information about the \n command line arguments. These can be used for\n overwriting command line arguments as needed.\n '''\n\n print('='*30)\n print('Main function of module 1')\n print('='*30)\n print('We get a copy of the result dictionary over here ...')\n pprint.pprint(resultsDict)\n\n doSomething()\n\n print('Getting out of Module 1')\n print('-'*30)\n\n return\n\n" ]
[ [ "numpy.random.beta", "numpy.random.multivariate_normal", "matplotlib.pyplot.savefig", "matplotlib.pyplot.style.context", "matplotlib.pyplot.axes", "numpy.random.randint", "matplotlib.pyplot.figure" ], [ "numpy.random.beta", "numpy.random.multivariate_normal", "matplotlib.pyplot.savefig", "matplotlib.pyplot.style.context", "matplotlib.pyplot.axes", "numpy.random.randint", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tusharsarkar3/XBNet
[ "01e385f1c0a446eb38f4dd59ee9c510170bf096b" ]
[ "XBNet/main.py" ]
[ "from kivymd.app import MDApp\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.actionbar import ActionBar\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivymd.theming import ThemableBehavior\nfrom kivymd.uix.list import OneLineListItem, MDList, TwoLineListItem, ThreeLineListItem\nfrom kivymd.uix.list import MDList\nfrom kivymd.uix.textfield import MDTextField\nfrom kivy.uix.button import Button\nfrom kivy.lang import Builder\nfrom kivymd.toast import toast\nfrom kivy.uix.screenmanager import Screen, ScreenManager\nimport time\nfrom kivy.core.window import Window\nfrom kivymd.uix.label import MDLabel\nfrom kivy.uix.modalview import ModalView\nfrom kivymd.uix.filemanager import MDFileManager\nfrom kivymd.theming import ThemeManager\nimport requests\nfrom kivy.uix.popup import Popup\nimport os\nfrom xgboost import XGBClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom lightgbm import LGBMClassifier\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom XBNet.training_utils import training,predict\nfrom XBNet.models import XBNETClassifier\nfrom XBNet.run import run_XBNET\nfrom os import environ\nimport pickle\n\ndef suppress_qt_warnings():\n environ[\"QT_DEVICE_PIXEL_RATIO\"] = \"0\"\n environ[\"QT_AUTO_SCREEN_SCALE_FACTOR\"] = \"1\"\n environ[\"QT_SCREEN_SCALE_FACTORS\"] = \"1\"\n environ[\"QT_SCALE_FACTOR\"] = \"1\"\n\nLogin_Page = \"\"\"\nScreenManager:\n LoginPage\n ModelDetails\n FileManage\n\n<LoginPage>:\n name:\"Login\"\n MDFloatLayout:\n Image:\n id: imageView\n source: 'Untitled.png'\n allow_stretch: True\n halign: 'center'\n pos_hint: {\"center_x\":0.23, \"center_y\":0.5}\n\n MDRoundFlatIconButton:\n id: filemanage\n text: \"Select Dataset\"\n icon: \"folder\"\n pos_hint: {'center_x': .77, 'center_y': .85}\n on_release: root.manager.current = \"File\"\n \n \n MDTextField:\n id: modelname\n hint_text:\"Enter the model name: \"\n pos_hint:{\"center_x\":0.77,\"center_y\":0.7}\n current_hint_text_color:0,0,0,1\n size_hint_x:0.4\n required: True\n \n MDTextField:\n id: layers\n hint_text:\"Enter number of layers(For XBNet or NN): \"\n pos_hint:{\"center_x\":0.77,\"center_y\":0.55}\n current_hint_text_color:0,0,0,1\n size_hint_x:0.4\n \n MDTextField:\n id: target\n hint_text:\"Enter name of target feature: \"\n pos_hint:{\"center_x\":0.77,\"center_y\":0.40}\n current_hint_text_color:0,0,0,1\n size_hint_x:0.4\n required: True\n\n MDRaisedButton:\n text:\"Build model\"\n pos_hint:{\"center_x\":0.77,\"center_y\":0.25}\n size_hint_x:0.3\n on_release: root.manager.current = \"Model\"\n on_press: app.get_model(modelname.text,target.text,layers.text)\n theme_text_color:\"Custom\"\n text_color:0,0,0,1\n \n\n<ModelDetails>:\n name:\"Model\"\n MDFloatLayout: \n Image:\n id: imageView\n source: 'Untitled.png'\n allow_stretch: True\n halign: 'center'\n pos_hint: {\"center_x\":0.23, \"center_y\":0.5} \n \n MDRaisedButton:\n text:\"Train\"\n pos_hint:{\"center_x\":0.63,\"center_y\":0.15}\n size_hint_x:0.2\n # on_release: root.manager.current = \"Model\"\n on_press: app.get_layers()\n theme_text_color:\"Custom\"\n text_color:0,0,0,1\n \n MDRaisedButton:\n text:\"Predict\"\n pos_hint:{\"center_x\":0.88,\"center_y\":0.15}\n size_hint_x:0.2\n # on_release: root.manager.current = \"Model\"\n on_press: app.predict()\n theme_text_color:\"Custom\"\n text_color:0,0,0,1\n \n \n<FileManage>:\n name:\"File\"\n BoxLayout: \n FileChooserListView:\n canvas.before:\n Color:\n rgb: 0.1, 0.2, 0.5\n Rectangle:\n pos: self.pos\n size: self.size\n on_selection: app.get_path(*args) \n \n \"\"\"\n\nclass LoginPage(Screen):\n pass\n\nclass ModelDetails(Screen):\n pass\n\nclass CustomDropDown(BoxLayout):\n pass\n\nclass FileManage(Screen):\n pass\n\nsm = ScreenManager()\nsm.add_widget(LoginPage(name=\"Login\"))\nsm.add_widget(ModelDetails(name=\"Model\"))\nsm.add_widget(FileManage(name=\"File\"))\n\nclass XBNetGUI(MDApp):\n\n def __init__(self):\n super(XBNetGUI, self).__init__()\n self.predict_phase = False\n\n class ContentNavigationDrawer(BoxLayout):\n pass\n\n class DrawerList(ThemableBehavior, MDList):\n pass\n\n def build(self):\n self.theme_cls.primary_palette = \"Blue\"\n login_page = Builder.load_string(Login_Page)\n\n return login_page\n\n def get_layers(self):\n self.layers_dims = []\n if self.model == \"xbnet\" or self.model == \"neural network\":\n for i,j in self.fields.items():\n self.layers_dims.append(int(j.text))\n print(j.text)\n elif (self.model == \"xgboost\" or self.model == \"randomforest\"\n or self.model == \"decision tree\" or self.model == \"lightgbm\"):\n for i,j in self.fields.items():\n try:\n self.layers_dims.append(int(j.text))\n except:\n self.layers_dims.append(float(j.text))\n\n self.train()\n\n def process_input(self):\n suppress_qt_warnings()\n column_to_predict = self.target\n data = pd.read_csv(self.file_selected)\n n_df = len(data)\n label_encoded = {}\n imputations = {}\n for i in data.columns:\n imputations[i] = data[i].mode()\n if data[i].isnull().sum() / n_df >= 0.15:\n data.drop(i, axis=1, inplace=True)\n elif data[i].isnull().sum() / n_df < 0.15 and data[i].isnull().sum() / n_df > 0:\n data[i].fillna(data[i].mode(), inplace=True)\n imputations[i] = data[i].mode()\n columns_object = list(data.dtypes[data.dtypes == object].index)\n for i in columns_object:\n if i != column_to_predict:\n if data[i].nunique() / n_df < 0.4:\n le = LabelEncoder()\n data[i] = le.fit_transform(data[i])\n label_encoded[i] = le\n else:\n data.drop(i, axis=1, inplace=True)\n\n x_data = data.drop(column_to_predict, axis=1).to_numpy()\n self.columns_finally_used = data.drop(column_to_predict, axis=1).columns\n\n y_data = data[column_to_predict].to_numpy()\n self.label_y = False\n if y_data.dtype == object:\n self.label_y = True\n self.y_label_encoder = LabelEncoder()\n y_data = self.y_label_encoder.fit_transform(y_data)\n self.label_encoded = label_encoded\n self.imputations = imputations\n toast(\"Number of features are: \" + str(x_data.shape[1]) +\n \" classes are: \"+ str(len(np.unique(y_data))),duration=5)\n self.x_data = x_data\n self.y_data = y_data\n\n def train(self):\n X_train, X_test, y_train, y_test = train_test_split(self.x_data, self.y_data,\n test_size=0.3, random_state=0)\n if self.model == \"xbnet\" or self.model ==\"neural network\":\n print(self.layers_dims)\n m = self.model\n model = XBNETClassifier( X_train, y_train, self.layers,\n input_through_cmd=True, inputs_for_gui=self.layers_dims,\n num_layers_boosted=self.n_layers_boosted\n )\n criterion = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n self.model, self.acc, self.lo, self.val_ac, self.val_lo = run_XBNET(X_train, X_test, y_train, y_test, model, criterion, optimizer, 32, 10)\n model.save(m+\"_testAccuracy_\" +str(max(self.val_ac))[:4] +\"_trainAccuracy_\" +\n str(max(self.acc))[:4]+ \".pt\",)\n toast(\"Test Accuracy is: \" +str(max(self.val_ac))[:4] +\" and Training Accuracy is: \" +\n str(max(self.acc))[:4] + \" and model is saved.\",duration= 10)\n\n elif (self.model == \"xgboost\" or self.model == \"randomforest\"\n or self.model == \"decision tree\" or self.model == \"lightgbm\"):\n if self.model == \"xgboost\":\n self.model_tree = XGBClassifier(n_estimators=self.layers_dims[0],\n max_depth=self.layers_dims[1],\n learning_rate= self.layers_dims[2],\n subsample= self.layers_dims[3],\n colsample_bylevel = self.layers_dims[4],\n random_state=0,n_jobs=-1,\n )\n self.model_tree.fit(X_train, y_train,eval_metric=\"mlogloss\")\n training_acc = self.model_tree.score(X_train, y_train)\n testing_acc = self.model_tree.score(X_test,y_test)\n elif self.model == \"randomforest\":\n self.model_tree = RandomForestClassifier(n_estimators=self.layers_dims[0],\n max_depth=self.layers_dims[1],\n random_state=0,n_jobs=-1)\n self.model_tree.fit(X_train, y_train)\n training_acc = self.model_tree.score(X_train, y_train)\n testing_acc = self.model_tree.score(X_test,y_test)\n elif self.model == \"decision tree\":\n self.model_tree = DecisionTreeClassifier(max_depth=self.layers_dims[1],random_state=0)\n self.model_tree.fit(X_train, y_train)\n training_acc = self.model_tree.score(X_train, y_train)\n testing_acc = self.model_tree.score(X_test,y_test)\n elif self.model == \"lightgbm\":\n self.model_tree = LGBMClassifier(n_estimators=self.layers_dims[0],\n max_depth=self.layers_dims[1],\n learning_rate= self.layers_dims[2],\n subsample= self.layers_dims[3],\n colsample_bylevel = self.layers_dims[4],\n random_state=0,n_jobs=-1,)\n self.model_tree.fit(X_train, y_train,eval_metric=\"mlogloss\")\n training_acc = self.model_tree.score(X_train, y_train)\n testing_acc = self.model_tree.score(X_test,y_test)\n toast(text=\"Training and Testing accuracies are \"+str(training_acc*100)\n +\" \"+str(testing_acc*100) + \" respectively and model is stored\",duration=7)\n with open(self.model+\"_testAccuracy_\" +str(testing_acc)[:4] +\"_trainAccuracy_\" +\n str(training_acc)[:4]+ \".pkl\", 'wb') as outfile:\n pickle.dump(self.model_tree,outfile)\n\n def predict(self):\n self.predict_phase = True\n self.root.current = \"File\"\n\n def predict_results(self):\n df = pd.read_csv(self.file_selected)\n data = df[self.columns_finally_used]\n for i in data.columns:\n if data[i].isnull().sum() > 0:\n data[i].fillna(self.imputations[i], inplace=True)\n if i in self.label_encoded.keys():\n data[i] = self.label_encoded[i].transform(data[i])\n if (self.model == \"xgboost\" or self.model == \"randomforest\"\n or self.model == \"decision tree\" or self.model == \"lightgbm\"):\n predictions = self.model_tree.predict(data.to_numpy())\n else:\n predictions = predict(self.model, data.to_numpy())\n if self.label_y == True:\n df[self.target] = self.y_label_encoder.inverse_transform(predictions)\n else:\n df[self.target] = predictions\n df.to_csv(\"Predicted_Results.csv\",index=False)\n toast(text=\"Predicted_Results.csv in this directory has the results\",\n duration = 10)\n\n\n def get_model(self,model,target,layers):\n self.model = model.lower()\n if len(layers) > 0:\n self.layers = int(layers)\n self.target = target\n if self.model.lower() == \"xbnet\":\n self.n_layers_boosted = 1\n self.net_model()\n elif (self.model == \"xgboost\" or self.model == \"randomforest\"\n or self.model == \"decision tree\" or self.model == \"lightgbm\"):\n self.tree_model()\n elif self.model.lower() == \"neural network\":\n self.n_layers_boosted = 0\n self.net_model()\n\n self.process_input()\n\n def net_model(self):\n layout = self.root.get_screen('Model')\n gap = 1/(2*self.layers+2)\n counter = 1\n self.fields = {}\n for i in range(self.layers):\n lab1 = MDTextField(hint_text=\"Enter input dimensions of layer \"+ str(i+1) +\":\",\n pos_hint={\"center_x\":0.77,\"center_y\":1-gap*(counter)},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n\n counter+=1\n lab2 = MDTextField(hint_text=\"Enter output dimensions of layer \"+ str(i+1) +\":\",\n pos_hint={\"center_x\":0.77,\"center_y\":1-gap*(counter)},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n counter +=1\n layout.add_widget(lab1)\n layout.add_widget(lab2)\n self.fields[\"input_\"+str(i+1)] = lab1\n self.fields[\"output_\" + str(i+1)] = lab2\n\n def tree_model(self):\n layout = self.root.get_screen('Model')\n self.fields = {}\n lab1 = MDTextField(hint_text=\"Enter number of estimators: \",\n pos_hint={\"center_x\":0.77,\"center_y\":0.85},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n\n lab2 = MDTextField(hint_text=\"Enter depth of trees[default:6](Typical 3-10): \",\n pos_hint={\"center_x\":0.77,\"center_y\":0.7},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n\n lab3 = MDTextField(hint_text=\"Enter learning rate forr XGBoost(eta)[default:0.3]: \",\n pos_hint={\"center_x\":0.77,\"center_y\":0.55},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n\n lab4 = MDTextField(hint_text=\"Enter size of subsample[default:1](Typical 0.5-1): \",\n pos_hint={\"center_x\":0.77,\"center_y\":0.4},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n\n lab5 = MDTextField(hint_text=\"Enter size of colsample_bytree[default:1](Typical 0.5-1): \",\n pos_hint={\"center_x\":0.77,\"center_y\":0.25},\n size_hint_x=.4, current_hint_text_color=[0,0,0,1] )\n\n layout.add_widget(lab1)\n layout.add_widget(lab2)\n layout.add_widget(lab3)\n layout.add_widget(lab4)\n layout.add_widget(lab5)\n self.fields[\"no_trees\"] = lab1\n self.fields[\"depth\"] = lab2\n self.fields[\"learning_rate\"] = lab3\n self.fields[\"subsample\"] = lab4\n self.fields[\"colsample_bytree\"] = lab5\n\n def get_path(self,*args):\n print(args)\n self.file_selected = args[1][0]\n print(self.file_selected)\n if self.predict_phase:\n self.root.current = \"Model\"\n print(\"hellooo\")\n self.predict_results()\n else:\n self.root.current = \"Login\"\n\nif __name__ == \"__main__\":\n XBNetGUI().run()" ]
[ [ "torch.nn.CrossEntropyLoss", "pandas.read_csv", "sklearn.ensemble.RandomForestClassifier", "numpy.unique", "sklearn.model_selection.train_test_split", "sklearn.tree.DecisionTreeClassifier", "sklearn.preprocessing.LabelEncoder" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
DJRavinszkha/pykeen
[ "d79fe39f83bc2831137f22be6421b37568694cf4" ]
[ "src/pykeen/models/unimodal/trans_e.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"TransE.\"\"\"\n\nfrom typing import Any, ClassVar, Mapping, Optional\n\nimport torch\nimport torch.autograd\nfrom torch.nn import functional\n\nfrom ..base import EntityRelationEmbeddingModel\nfrom ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE\nfrom ...losses import Loss\nfrom ...nn.emb import EmbeddingSpecification\nfrom ...nn.init import xavier_uniform_, xavier_uniform_norm_\nfrom ...regularizers import Regularizer\nfrom ...triples import TriplesFactory\nfrom ...typing import Constrainer, DeviceHint, Hint, Initializer\n\n__all__ = [\n 'TransE',\n]\n\n\nclass TransE(EntityRelationEmbeddingModel):\n r\"\"\"An implementation of TransE [bordes2013]_.\n\n TransE models relations as a translation from head to tail entities in :math:`\\textbf{e}`:\n\n .. math::\n\n \\textbf{e}_h + \\textbf{e}_r \\approx \\textbf{e}_t\n\n This equation is rearranged and the :math:`l_p` norm is applied to create the TransE interaction function.\n\n .. math::\n\n f(h, r, t) = - \\|\\textbf{e}_h + \\textbf{e}_r - \\textbf{e}_t\\|_{p}\n\n While this formulation is computationally efficient, it inherently cannot model one-to-many, many-to-one, and\n many-to-many relationships. For triples :math:`(h,r,t_1), (h,r,t_2) \\in \\mathcal{K}` where :math:`t_1 \\neq t_2`,\n the model adapts the embeddings in order to ensure :math:`\\textbf{e}_h + \\textbf{e}_r \\approx \\textbf{e}_{t_1}`\n and :math:`\\textbf{e}_h + \\textbf{e}_r \\approx \\textbf{e}_{t_2}` which results in\n :math:`\\textbf{e}_{t_1} \\approx \\textbf{e}_{t_2}`.\n ---\n citation:\n author: Bordes\n year: 2013\n link: http://papers.nips.cc/paper/5071-translating-embeddings-for-modeling-multi-relational-data.pdf\n \"\"\"\n\n #: The default strategy for optimizing the model's hyper-parameters\n hpo_default: ClassVar[Mapping[str, Any]] = dict(\n embedding_dim=DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE,\n scoring_fct_norm=dict(type=int, low=1, high=2),\n )\n\n def __init__(\n self,\n triples_factory: TriplesFactory,\n embedding_dim: int = 50,\n scoring_fct_norm: int = 1,\n loss: Optional[Loss] = None,\n preferred_device: DeviceHint = None,\n random_seed: Optional[int] = None,\n regularizer: Optional[Regularizer] = None,\n entity_initializer: Hint[Initializer] = xavier_uniform_,\n entity_constrainer: Hint[Constrainer] = functional.normalize,\n relation_initializer: Hint[Initializer] = xavier_uniform_norm_,\n ) -> None:\n r\"\"\"Initialize TransE.\n\n :param embedding_dim: The entity embedding dimension $d$. Is usually $d \\in [50, 300]$.\n :param scoring_fct_norm: The :math:`l_p` norm applied in the interaction function. Is usually ``1`` or ``2.``.\n\n .. seealso::\n\n - OpenKE `implementation of TransE <https://github.com/thunlp/OpenKE/blob/OpenKE-PyTorch/models/TransE.py>`_\n \"\"\"\n super().__init__(\n triples_factory=triples_factory,\n loss=loss,\n preferred_device=preferred_device,\n random_seed=random_seed,\n regularizer=regularizer,\n entity_representations=EmbeddingSpecification(\n embedding_dim=embedding_dim,\n initializer=entity_initializer,\n constrainer=entity_constrainer,\n ),\n relation_representations=EmbeddingSpecification(\n embedding_dim=embedding_dim,\n initializer=relation_initializer,\n ),\n )\n self.scoring_fct_norm = scoring_fct_norm\n\n def score_hrt(self, hrt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102\n # Get embeddings\n h = self.entity_embeddings(indices=hrt_batch[:, 0])\n r = self.relation_embeddings(indices=hrt_batch[:, 1])\n t = self.entity_embeddings(indices=hrt_batch[:, 2])\n\n # TODO: Use torch.dist\n return -torch.norm(h + r - t, dim=-1, p=self.scoring_fct_norm, keepdim=True)\n\n def score_t(self, hr_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102\n # Get embeddings\n h = self.entity_embeddings(indices=hr_batch[:, 0])\n r = self.relation_embeddings(indices=hr_batch[:, 1])\n t = self.entity_embeddings(indices=None)\n\n # TODO: Use torch.cdist\n return -torch.norm(h[:, None, :] + r[:, None, :] - t[None, :, :], dim=-1, p=self.scoring_fct_norm)\n\n def score_h(self, rt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102\n # Get embeddings\n h = self.entity_embeddings(indices=None)\n r = self.relation_embeddings(indices=rt_batch[:, 0])\n t = self.entity_embeddings(indices=rt_batch[:, 1])\n\n # TODO: Use torch.cdist\n return -torch.norm(h[None, :, :] + r[:, None, :] - t[:, None, :], dim=-1, p=self.scoring_fct_norm)\n" ]
[ [ "torch.norm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jiaoml1996/mmaction2
[ "777546f27f8f5a3c83e10d966e2149be2fc9fa31", "777546f27f8f5a3c83e10d966e2149be2fc9fa31" ]
[ "mmaction/models/builder.py", "mmaction/core/evaluation/ava_utils.py" ]
[ "import warnings\n\nimport torch.nn as nn\nfrom mmcv.utils import Registry, build_from_cfg\n\nfrom .registry import BACKBONES, HEADS, LOCALIZERS, LOSSES, NECKS, RECOGNIZERS\n\ntry:\n from mmdet.models.builder import DETECTORS, build_detector\nexcept (ImportError, ModuleNotFoundError):\n warnings.warn('Please install mmdet to use DETECTORS, build_detector')\n\n # Define an empty registry and building func, so that can import\n DETECTORS = Registry('detector')\n\n def build_detector(cfg, train_cfg, test_cfg):\n pass\n\n\ndef build(cfg, registry, default_args=None):\n \"\"\"Build a module.\n\n Args:\n cfg (dict, list[dict]): The config of modules, it is either a dict\n or a list of configs.\n registry (:obj:`Registry`): A registry the module belongs to.\n default_args (dict, optional): Default arguments to build the module.\n Defaults to None.\n\n Returns:\n nn.Module: A built nn module.\n \"\"\"\n\n if isinstance(cfg, list):\n modules = [\n build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg\n ]\n return nn.Sequential(*modules)\n\n return build_from_cfg(cfg, registry, default_args)\n\n\ndef build_backbone(cfg):\n \"\"\"Build backbone.\"\"\"\n return build(cfg, BACKBONES)\n\n\ndef build_head(cfg):\n \"\"\"Build head.\"\"\"\n return build(cfg, HEADS)\n\n\ndef build_recognizer(cfg, train_cfg=None, test_cfg=None):\n \"\"\"Build recognizer.\"\"\"\n return build(cfg, RECOGNIZERS,\n dict(train_cfg=train_cfg, test_cfg=test_cfg))\n\n\ndef build_loss(cfg):\n \"\"\"Build loss.\"\"\"\n return build(cfg, LOSSES)\n\n\ndef build_localizer(cfg):\n \"\"\"Build localizer.\"\"\"\n return build(cfg, LOCALIZERS)\n\n\ndef build_model(cfg, train_cfg=None, test_cfg=None):\n \"\"\"Build model.\"\"\"\n args = cfg.copy()\n obj_type = args.pop('type')\n if obj_type in LOCALIZERS:\n return build_localizer(cfg)\n if obj_type in RECOGNIZERS:\n return build_recognizer(cfg, train_cfg, test_cfg)\n if obj_type in DETECTORS:\n return build_detector(cfg, train_cfg, test_cfg)\n raise ValueError(f'{obj_type} is not registered in '\n 'LOCALIZERS, RECOGNIZERS or DETECTORS')\n\n\ndef build_neck(cfg):\n \"\"\"Build neck.\"\"\"\n return build(cfg, NECKS)\n", "import csv\nimport heapq\nimport logging\nimport time\nfrom collections import defaultdict\n\nimport numpy as np\n\nfrom .ava_evaluation import object_detection_evaluation as det_eval\nfrom .ava_evaluation import standard_fields\nfrom .recall import eval_recalls\n\n\ndef det2csv(dataset, results):\n csv_results = []\n for idx in range(len(dataset)):\n video_id = dataset.video_infos[idx]['video_id']\n timestamp = dataset.video_infos[idx]['timestamp']\n result = results[idx]\n for label, _ in enumerate(result):\n for bbox in result[label]:\n bbox_ = tuple(bbox.tolist())\n csv_results.append((\n video_id,\n timestamp,\n ) + bbox_[:4] + (label + 1, ) + bbox_[4:])\n return csv_results\n\n\n# results is organized by class\ndef results2csv(dataset, results, out_file):\n if isinstance(results[0], list):\n csv_results = det2csv(dataset, results)\n\n # save space for float\n def tostr(item):\n if isinstance(item, float):\n return f'{item:.3f}'\n return str(item)\n\n with open(out_file, 'w') as f:\n for csv_result in csv_results:\n f.write(','.join(map(lambda x: tostr(x), csv_result)))\n f.write('\\n')\n\n\ndef print_time(message, start):\n print('==> %g seconds to %s' % (time.time() - start, message))\n\n\ndef make_image_key(video_id, timestamp):\n \"\"\"Returns a unique identifier for a video id & timestamp.\"\"\"\n return f'{video_id},{int(timestamp):04d}'\n\n\ndef read_csv(csv_file, class_whitelist=None, capacity=0):\n \"\"\"Loads boxes and class labels from a CSV file in the AVA format.\n\n CSV file format described at https://research.google.com/ava/download.html.\n\n Args:\n csv_file: A file object.\n class_whitelist: If provided, boxes corresponding to (integer) class\n labels not in this set are skipped.\n capacity: Maximum number of labeled boxes allowed for each example.\n Default is 0 where there is no limit.\n\n Returns:\n boxes: A dictionary mapping each unique image key (string) to a list of\n boxes, given as coordinates [y1, x1, y2, x2].\n labels: A dictionary mapping each unique image key (string) to a list\n of integer class lables, matching the corresponding box in `boxes`.\n scores: A dictionary mapping each unique image key (string) to a list\n of score values lables, matching the corresponding label in `labels`.\n If scores are not provided in the csv, then they will default to 1.0.\n \"\"\"\n start = time.time()\n entries = defaultdict(list)\n boxes = defaultdict(list)\n labels = defaultdict(list)\n scores = defaultdict(list)\n reader = csv.reader(csv_file)\n for row in reader:\n assert len(row) in [7, 8], 'Wrong number of columns: ' + row\n image_key = make_image_key(row[0], row[1])\n x1, y1, x2, y2 = [float(n) for n in row[2:6]]\n action_id = int(row[6])\n if class_whitelist and action_id not in class_whitelist:\n continue\n\n score = 1.0\n if len(row) == 8:\n score = float(row[7])\n if capacity < 1 or len(entries[image_key]) < capacity:\n heapq.heappush(entries[image_key],\n (score, action_id, y1, x1, y2, x2))\n elif score > entries[image_key][0][0]:\n heapq.heapreplace(entries[image_key],\n (score, action_id, y1, x1, y2, x2))\n for image_key in entries:\n # Evaluation API assumes boxes with descending scores\n entry = sorted(entries[image_key], key=lambda tup: -tup[0])\n for item in entry:\n score, action_id, y1, x1, y2, x2 = item\n boxes[image_key].append([y1, x1, y2, x2])\n labels[image_key].append(action_id)\n scores[image_key].append(score)\n print_time('read file ' + csv_file.name, start)\n return boxes, labels, scores\n\n\ndef read_exclusions(exclusions_file):\n \"\"\"Reads a CSV file of excluded timestamps.\n\n Args:\n exclusions_file: A file object containing a csv of video-id,timestamp.\n\n Returns:\n A set of strings containing excluded image keys, e.g.\n \"aaaaaaaaaaa,0904\",\n or an empty set if exclusions file is None.\n \"\"\"\n excluded = set()\n if exclusions_file:\n reader = csv.reader(exclusions_file)\n for row in reader:\n assert len(row) == 2, 'Expected only 2 columns, got: ' + row\n excluded.add(make_image_key(row[0], row[1]))\n return excluded\n\n\ndef read_labelmap(labelmap_file):\n \"\"\"Reads a labelmap without the dependency on protocol buffers.\n\n Args:\n labelmap_file: A file object containing a label map protocol buffer.\n\n Returns:\n labelmap: The label map in the form used by the\n object_detection_evaluation\n module - a list of {\"id\": integer, \"name\": classname } dicts.\n class_ids: A set containing all of the valid class id integers.\n \"\"\"\n labelmap = []\n class_ids = set()\n name = ''\n class_id = ''\n for line in labelmap_file:\n if line.startswith(' name:'):\n name = line.split('\"')[1]\n elif line.startswith(' id:') or line.startswith(' label_id:'):\n class_id = int(line.strip().split(' ')[-1])\n labelmap.append({'id': class_id, 'name': name})\n class_ids.add(class_id)\n return labelmap, class_ids\n\n\n# Seems there is at most 100 detections for each image\ndef ava_eval(result_file,\n result_type,\n label_file,\n ann_file,\n exclude_file,\n max_dets=(100, ),\n verbose=True):\n\n assert result_type in ['proposal', 'bbox']\n\n start = time.time()\n categories, class_whitelist = read_labelmap(open(label_file))\n\n # loading gt, do not need gt score\n gt_boxes, gt_labels, _ = read_csv(open(ann_file), class_whitelist, 0)\n if verbose:\n print_time('Reading detection results', start)\n\n if exclude_file is not None:\n excluded_keys = read_exclusions(open(exclude_file))\n else:\n excluded_keys = list()\n\n start = time.time()\n boxes, labels, scores = read_csv(open(result_file), class_whitelist, 0)\n if verbose:\n print_time('Reading detection results', start)\n\n if result_type == 'proposal':\n gts = [\n np.array(gt_boxes[image_key], dtype=float)\n for image_key in gt_boxes\n ]\n proposals = []\n for image_key in gt_boxes:\n if image_key in boxes:\n proposals.append(\n np.concatenate(\n (np.array(boxes[image_key], dtype=float),\n np.array(scores[image_key], dtype=float)[:, None]),\n axis=1))\n else:\n # if no corresponding proposal, add a fake one\n proposals.append(np.array([0, 0, 1, 1, 1]))\n\n # Proposals used here are with scores\n recalls = eval_recalls(gts, proposals, np.array(max_dets),\n np.arange(0.5, 0.96, 0.05))\n ar = recalls.mean(axis=1)\n ret = {}\n for i, num in enumerate(max_dets):\n print(f'[email protected]@{num}\\t={recalls[i, 0]:.4f}')\n print(f'AR@{num}\\t={ar[i]:.4f}')\n ret[f'[email protected]@{num}'] = recalls[i, 0]\n ret[f'AR@{num}'] = ar[i]\n return ret\n\n if result_type == 'bbox':\n pascal_evaluator = det_eval.PascalDetectionEvaluator(categories)\n\n start = time.time()\n for image_key in gt_boxes:\n if verbose and image_key in excluded_keys:\n logging.info(\n 'Found excluded timestamp in detections: %s.'\n 'It will be ignored.', image_key)\n continue\n pascal_evaluator.add_single_ground_truth_image_info(\n image_key, {\n standard_fields.InputDataFields.groundtruth_boxes:\n np.array(gt_boxes[image_key], dtype=float),\n standard_fields.InputDataFields.groundtruth_classes:\n np.array(gt_labels[image_key], dtype=int),\n standard_fields.InputDataFields.groundtruth_difficult:\n np.zeros(len(gt_boxes[image_key]), dtype=bool)\n })\n if verbose:\n print_time('Convert groundtruth', start)\n\n start = time.time()\n for image_key in boxes:\n if verbose and image_key in excluded_keys:\n logging.info(\n 'Found excluded timestamp in detections: %s.'\n 'It will be ignored.', image_key)\n continue\n pascal_evaluator.add_single_detected_image_info(\n image_key, {\n standard_fields.DetectionResultFields.detection_boxes:\n np.array(boxes[image_key], dtype=float),\n standard_fields.DetectionResultFields.detection_classes:\n np.array(labels[image_key], dtype=int),\n standard_fields.DetectionResultFields.detection_scores:\n np.array(scores[image_key], dtype=float)\n })\n if verbose:\n print_time('convert detections', start)\n\n start = time.time()\n metrics = pascal_evaluator.evaluate()\n if verbose:\n print_time('run_evaluator', start)\n for display_name in metrics:\n print(f'{display_name}=\\t{metrics[display_name]}')\n return {\n display_name: metrics[display_name]\n for display_name in metrics if 'ByCategory' not in display_name\n }\n" ]
[ [ "torch.nn.Sequential" ], [ "numpy.arange", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
IaaC/MACT21.22_Digital_tools_Big_Data_part_2
[ "f0c50a5f7ac147f6e9753545767d2d9998075ebb" ]
[ "iop_data_flow/footfall/01_footfall_clip.py" ]
[ "import os\n\nimport pandas as pd\nimport geopandas as gpd\n\n## Config\n\n# Number of rows to read\nnrows = 1000\n#nrows = 1000000\n#nrows = None\n\n# Output file path\nday_num = 1\ninput_csv_filepath = f'../../data/footfall/footfall_20210217/day{day_num}Bcntrakingotherdays.csv'\n\n# Clip mask file path\n#clip_mask_filepath = '../../data/studio/clip_area/clip_darea.shp'\nclip_mask_filepath = '../../data/footfall/aoi_glories.geojson'\n\n# Output file path\noutput_file = f'ff-day{day_num}-clipped.shp'\noutput_folder = '../../data/studio/footfall/01_clipped/'\n\n## Run\n\n# Load csv all spain footfall\nprint(f\"Load csv footfall : {input_csv_filepath}\")\ndf = pd.read_csv(input_csv_filepath,\n delimiter='|',\n nrows=nrows)\n\n# Convert it to geopandas\ngdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.LONGITUDE, df.LATITUDE), crs='epsg:4326')\nprint(f\"Footfall all: {len(gdf)} points\")\n\n# Load clip mask\nmask_gdf = gpd.read_file(clip_mask_filepath)\nmask_gdf = mask_gdf[mask_gdf['geometry'].notnull()]\n\n# Clip it to district\ngdf = gpd.clip(gdf, mask_gdf)\nprint(f\"Footfall clipped district: {len(gdf)} points\")\n\n# Create output directory if it doesn't exist\nif not os.path.exists(output_folder):\n os.mkdir(output_folder)\noutput_fullpath = os.path.join(output_folder, output_file)\n\n# Save clipped points\ngdf.to_file(output_fullpath)\nprint(f\"Saved shp footfall district: {output_fullpath}\")" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
zerogerc/rnn-autocomplete
[ "39dc8dd7c431cb8ac9e15016388ec823771388e4", "39dc8dd7c431cb8ac9e15016388ec823771388e4" ]
[ "zerogercrnn/experiments/ast_level/metrics.py", "zerogercrnn/lib/attn.py" ]
[ "import json\nimport os\n\nimport numpy as np\nimport torch\n\nfrom zerogercrnn.lib.constants import EMPTY_TOKEN_ID, UNKNOWN_TOKEN_ID\nfrom zerogercrnn.experiments.ast_level.utils import read_non_terminals\nfrom zerogercrnn.lib.constants import EMPTY_TOKEN_ID, UNKNOWN_TOKEN_ID, EOF_TOKEN\nfrom zerogercrnn.lib.metrics import Metrics, BaseAccuracyMetrics, IndexedAccuracyMetrics, MaxPredictionAccuracyMetrics, TopKAccuracy\n\n\nclass NonTerminalsMetricsWrapper(Metrics):\n \"\"\"Metrics that extract non-terminals from target and pass non-terminals tensor to base metrics.\"\"\"\n\n def __init__(self, base: Metrics):\n super().__init__()\n self.base = base\n\n def drop_state(self):\n self.base.drop_state()\n\n def report(self, prediction_target):\n prediction, target = prediction_target\n self.base.report((prediction, target.non_terminals))\n\n def get_current_value(self, should_print=False):\n return self.base.get_current_value(should_print)\n\n def decrease_hits(self, number):\n self.base.decrease_hits(number)\n\n\nclass SingleNonTerminalAccuracyMetrics(Metrics):\n \"\"\"Metrics that show accuracies per non-terminal. It should not be used for plotting, but to\n print results on console during model evaluation.\"\"\"\n\n def __init__(self, non_terminals_file, results_dir=None, group=False, dim=2):\n \"\"\"\n\n :param non_terminals_file: file with json of non-terminals\n :param results_dir: where to save json with accuracies per non-terminal\n :param dim: dimension to run max function on for predicted values\n \"\"\"\n super().__init__()\n print('SingleNonTerminalAccuracyMetrics created!')\n\n self.non_terminals = read_non_terminals(non_terminals_file)\n self.non_terminals_number = len(self.non_terminals)\n self.results_dir = results_dir\n self.group = group\n self.dim = dim\n\n self.accuracies = [IndexedAccuracyMetrics(label='ERROR') for _ in self.non_terminals]\n\n def drop_state(self):\n for accuracy in self.accuracies:\n accuracy.drop_state()\n\n def report(self, data):\n prediction, target = data\n if self.dim is None:\n predicted = prediction\n else:\n _, predicted = torch.max(prediction, dim=self.dim)\n predicted = predicted.view(-1)\n target = target.non_terminals.view(-1)\n\n for cur in range(len(self.non_terminals)):\n indices = (target == cur).nonzero().squeeze()\n self.accuracies[cur].report(predicted, target, indices)\n\n def get_current_value(self, should_print=False):\n result = []\n for cur in range(len(self.non_terminals)):\n cur_accuracy = self.accuracies[cur].get_current_value(should_print=False)\n result.append(cur_accuracy)\n # if should_print:\n # print('Accuracy on {} is {}'.format(self.non_terminals[cur], cur_accuracy))\n\n self.save_to_file(result)\n\n return 0 # this metrics if only for printing\n\n def save_to_file(self, result):\n if self.results_dir is not None:\n if self.group:\n nt, res = self.get_grouped_result()\n else:\n nt, res = self.non_terminals, result\n\n with open(os.path.join(self.results_dir, 'nt_acc.txt'), mode='w') as f:\n f.write(json.dumps(nt))\n f.write('\\n')\n f.write(json.dumps(res))\n\n def get_grouped_result(self):\n \"\"\"Calc accuracies ignoring last two bits of information.\"\"\"\n nt = set()\n hits = {}\n misses = {}\n for i in range(len(self.non_terminals)):\n base = self.non_terminals[i]\n if self.non_terminals[i] != EOF_TOKEN:\n base = base[:-2] # remove last two bits\n\n nt.add(base)\n\n if base not in hits:\n hits[base] = 0\n if base not in misses:\n misses[base] = 0\n\n hits[base] += self.accuracies[i].metrics.hits\n misses[base] += self.accuracies[i].metrics.misses\n\n nt = sorted(list(nt))\n result = []\n\n nt.remove('Program')\n nt.remove('AssignmentPattern')\n for cur in nt:\n if hits[cur] + misses[cur] == 0:\n result.append(0)\n else:\n result.append(float(hits[cur]) / (hits[cur] + misses[cur]))\n\n return nt, result\n\n\nclass TerminalAccuracyMetrics(Metrics):\n def __init__(self, dim=2):\n super().__init__()\n self.dim = dim\n self.general_accuracy = BaseAccuracyMetrics()\n self.empty_accuracy = IndexedAccuracyMetrics(\n label='Accuracy on terminals that ground truth is <empty>'\n )\n self.non_empty_accuracy = IndexedAccuracyMetrics(\n label='Accuracy on terminals that ground truth is not <empty>'\n )\n self.ground_not_unk_accuracy = IndexedAccuracyMetrics(\n label='Accuracy on terminals that ground truth is not <unk> (and ground truth is not <empty>)'\n )\n self.model_not_unk_accuracy = IndexedAccuracyMetrics(\n label='Accuracy on terminals that model predicted to non <unk> (and ground truth is not <empty>)'\n )\n\n def drop_state(self):\n self.general_accuracy.drop_state()\n self.empty_accuracy.drop_state()\n self.non_empty_accuracy.drop_state()\n self.ground_not_unk_accuracy.drop_state()\n self.model_not_unk_accuracy.drop_state()\n\n def report(self, prediction_target):\n prediction, target = prediction_target\n _, predicted = torch.max(prediction, dim=self.dim)\n predicted = predicted.view(-1)\n target = target.view(-1)\n\n self.general_accuracy.report((predicted, target))\n\n if not self.is_train:\n empty_indexes = torch.nonzero(target == 0).squeeze()\n self.empty_accuracy.report(predicted, target, empty_indexes)\n\n non_empty_indexes = torch.nonzero(target - EMPTY_TOKEN_ID).squeeze()\n self.non_empty_accuracy.report(predicted, target, non_empty_indexes)\n\n predicted = torch.index_select(predicted, 0, non_empty_indexes)\n target = torch.index_select(target, 0, non_empty_indexes)\n\n ground_not_unk_indexes = torch.nonzero(target - UNKNOWN_TOKEN_ID).squeeze()\n self.ground_not_unk_accuracy.report(predicted, target, ground_not_unk_indexes)\n\n model_not_unk_indexes = torch.nonzero(predicted - UNKNOWN_TOKEN_ID).squeeze()\n self.model_not_unk_accuracy.report(predicted, target, model_not_unk_indexes)\n\n def get_current_value(self, should_print=False):\n general_accuracy = self.general_accuracy.get_current_value(should_print=should_print)\n if (not self.is_train) and should_print:\n self.empty_accuracy.get_current_value(should_print=True)\n self.non_empty_accuracy.get_current_value(should_print=True)\n self.ground_not_unk_accuracy.get_current_value(should_print=True)\n self.model_not_unk_accuracy.get_current_value(should_print=True)\n return general_accuracy\n\n\nclass NonTerminalTerminalAccuracyMetrics(Metrics):\n\n def __init__(self):\n super().__init__()\n self.nt_accuracy = MaxPredictionAccuracyMetrics()\n self.t_accuracy = MaxPredictionAccuracyMetrics()\n\n def drop_state(self):\n self.nt_accuracy.drop_state()\n self.t_accuracy.drop_state()\n\n def report(self, data):\n nt_prediction, t_prediction, nt_target, t_target = data\n self.nt_accuracy.report((nt_prediction, nt_target))\n self.t_accuracy.report((t_prediction, t_target))\n\n def get_current_value(self, should_print=False):\n nt_value = self.nt_accuracy.get_current_value(should_print=False)\n t_value = self.t_accuracy.get_current_value(should_print=False)\n\n if should_print:\n print('Non terminals accuracy: {}'.format(nt_value))\n print('Terminals accuracy: {}'.format(t_value))\n\n return nt_value, t_value\n\n\nclass LayeredNodeDepthsAttentionMetrics(Metrics):\n \"\"\"Metrics that is able to visualize attention coefficient per node depths\"\"\"\n\n def __init__(self):\n super().__init__()\n self.per_depth_attention_sum = np.zeros((50, 50))\n self.per_depth_reports = np.zeros((50))\n\n def drop_state(self):\n pass\n\n def report(self, node_depths, attention_coefficients):\n for i in range(50):\n index = torch.nonzero((node_depths == i))\n if index.size()[0] == 0:\n continue\n selected_attention = torch.index_select(attention_coefficients, dim=0, index=index.squeeze())\n selected_attention = selected_attention.squeeze(2)\n to_report = torch.sum(selected_attention, dim=0).cpu().numpy()\n self.per_depth_attention_sum[i] += to_report\n self.per_depth_reports[i] += index.size()[0]\n\n def get_current_value(self, should_print=False):\n for i in range(50):\n if abs(self.per_depth_reports[i]) > 1e-6:\n self.per_depth_attention_sum[i] /= self.per_depth_reports[i]\n np.save('eval/temp/attention/per_depth_matrix', self.per_depth_attention_sum)\n return 0 # this metrics is only for saving results to file.\n\n\nclass PerNtAttentionMetrics(Metrics):\n def __init__(self):\n super().__init__()\n\n def report(self, current_input, attention_coefficients):\n nt_ids = torch.argmax(current_input, dim=-1)\n\n # for i in range(97): # TODO: check\n # index = torch.nonzero((nt_ids == i))\n # if index.size()[0] == 0:\n # continue\n # selected_attention = torch.index_select(attention_coefficients, dim=0, index=index.squeeze())\n # selected_attention = selected_attention.squeeze(2)\n # to_report = torch.sum(selected_attention, dim=0).cpu().numpy()\n # self.per_depth_attention_sum[i] += to_report\n # self.per_depth_reports[i] += index.size()[0]\n\n\n def drop_state(self):\n pass\n\n def get_current_value(self, should_print=False):\n pass\n\n\nclass EmptyNonEmptyWrapper(Metrics):\n def __init__(self, non_emp_base: Metrics, with_emp_base:Metrics):\n super().__init__()\n self.non_emp_base = non_emp_base\n self.with_emp_base = with_emp_base\n\n def drop_state(self):\n self.non_emp_base.drop_state()\n self.with_emp_base.drop_state()\n\n def report(self, prediction_target):\n prediction, target = prediction_target\n prediction = prediction.view(-1)\n target = target.view(-1)\n\n self.with_emp_base.report((prediction, target))\n\n non_emp_indices = (target != EMPTY_TOKEN_ID).nonzero().squeeze()\n prediction = torch.index_select(prediction, 0, non_emp_indices)\n target = torch.index_select(target, 0, non_emp_indices)\n self.non_emp_base.report((prediction, target))\n\n def get_current_value(self, should_print=False):\n print('Non Empty')\n self.non_emp_base.get_current_value(should_print=should_print)\n print('With Empty')\n self.with_emp_base.get_current_value(should_print=should_print)\n\n\nclass EmptyNonEmptyTerminalTopKAccuracyWrapper(Metrics):\n def __init__(self):\n super().__init__()\n self.non_emp_base = TopKAccuracy(k=5)\n self.with_emp_base = TopKAccuracy(k=5)\n\n def drop_state(self):\n self.non_emp_base.drop_state()\n self.with_emp_base.drop_state()\n\n def report(self, prediction_target):\n prediction, target = prediction_target\n prediction = prediction.view(-1, prediction.size()[-1])\n target = target.view(-1)\n\n self.with_emp_base.report((prediction, target))\n\n non_emp_indices = (target != EMPTY_TOKEN_ID).nonzero().squeeze()\n prediction = torch.index_select(prediction, 0, non_emp_indices)\n target = torch.index_select(target, 0, non_emp_indices)\n self.non_emp_base.report((prediction, target))\n\n def get_current_value(self, should_print=False):\n print('Non Empty')\n self.non_emp_base.get_current_value(should_print=should_print)\n print('With Empty')\n self.with_emp_base.get_current_value(should_print=should_print)\n\n\n# class AggregatedTerminalTopKMetrics(Metrics):\n#\n# def __init__(self, k):\n# super().__init__()\n# self.k = k\n# self.common = BaseAccuracyMetrics()\n# self.target_non_unk = Top\n# self.prediction_non_unk = IndexedAccuracyMetrics('Prediction not unk')\n#\n# def drop_state(self):\n# self.common.drop_state()\n# self.target_non_unk.drop_state()\n# self.prediction_non_unk.drop_state()\n#\n# def report(self, prediction_target):\n# prediction, target = prediction_target\n# prediction = prediction.view(-1)\n# target = target.view(-1)\n#\n# self.common.report((prediction, target))\n#\n# pred_non_unk_indices = (prediction != UNKNOWN_TOKEN_ID).nonzero().squeeze()\n# target_non_unk_indices = (target != UNKNOWN_TOKEN_ID).nonzero().squeeze()\n#\n# self.prediction_non_unk.report(prediction, target, pred_non_unk_indices)\n# self.target_non_unk.report(prediction, target, target_non_unk_indices)\n#\n# def get_current_value(self, should_print=False):\n# print('P(hat(t) == t) = {}'.format(self.common.get_current_value(False)))\n# print('P(hat(t) == t && hat(t) != unk) = {}'.format(self.prediction_non_unk.metrics.hits / (self.common.hits + self.common.misses)))\n# print('P(hat(t) == t | t != unk) = {}'.format(self.target_non_unk.get_current_value(False)))\n# print('P(hat(t) == t | hat(t) != unk) = {}'.format(self.prediction_non_unk.get_current_value(False)))\n\n\n\nclass AggregatedTerminalMetrics(Metrics):\n\n def __init__(self):\n super().__init__()\n self.common = BaseAccuracyMetrics()\n self.target_non_unk = IndexedAccuracyMetrics('Target not unk')\n self.prediction_non_unk = IndexedAccuracyMetrics('Prediction not unk')\n\n def drop_state(self):\n self.common.drop_state()\n self.target_non_unk.drop_state()\n self.prediction_non_unk.drop_state()\n\n def report(self, prediction_target):\n prediction, target = prediction_target\n prediction = prediction.view(-1)\n target = target.view(-1)\n\n self.common.report((prediction, target))\n\n pred_non_unk_indices = (prediction != UNKNOWN_TOKEN_ID).nonzero().squeeze()\n target_non_unk_indices = (target != UNKNOWN_TOKEN_ID).nonzero().squeeze()\n\n self.prediction_non_unk.report(prediction, target, pred_non_unk_indices)\n self.target_non_unk.report(prediction, target, target_non_unk_indices)\n\n def get_current_value(self, should_print=False):\n print('P(hat(t) == t) = {}'.format(self.common.get_current_value(False)))\n print('P(hat(t) == t && hat(t) != unk) = {}'.format(self.prediction_non_unk.metrics.hits / (self.common.hits + self.common.misses)))\n print('P(hat(t) == t | t != unk) = {}'.format(self.target_non_unk.get_current_value(False)))\n print('P(hat(t) == t | hat(t) != unk) = {}'.format(self.prediction_non_unk.get_current_value(False)))\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom zerogercrnn.lib.calculation import drop_matrix_rows_3d, calc_attention_combination\nfrom zerogercrnn.lib.core import BaseModule\nfrom zerogercrnn.lib.utils import init_layers_uniform, get_best_device\n\n\nclass CyclicBuffer:\n def __init__(self, buffer):\n self.buffer = buffer\n self.it = 0\n\n def add_vector(self, vector):\n self.buffer[:, self.it, :].copy_(vector) # TODO: general way\n self.it += 1\n if self.it >= self.buffer.size()[1]:\n self.it = 0\n\n def get(self):\n return self.buffer\n\n\nclass LastKBuffer:\n def __init__(self, window_len, buffer):\n assert window_len <= buffer.size()[1]\n self.buffer_size = buffer.size()[1]\n self.window_len = window_len\n self.buffer = buffer\n\n self.it = window_len\n\n def add_vector(self, vector):\n self.buffer[:, self.it, :].copy_(vector.detach()) # TODO: general way\n self.it += 1\n if self.it >= self.buffer_size:\n self.buffer.narrow(dim=1, start=0, length=self.window_len).copy_(\n self.buffer.narrow(dim=1, start=self.buffer_size - self.window_len, length=self.window_len)\n )\n self.it = self.window_len\n\n def get(self):\n return self.buffer.narrow(dim=1, start=self.it - self.window_len, length=self.window_len)\n\n\nclass Attn(BaseModule):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n\n self.method = method\n self.hidden_size = hidden_size\n\n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, self.hidden_size)\n init_layers_uniform(-0.05, 0.05, [self.attn])\n\n # elif self.method == 'concat':\n # self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n # self.other = nn.Parameter(torch.FloatTensor(1, hidden_size))\n # nn.init.uniform(self.attn.parameters(), -0.05, 0.05)\n # nn.init.uniform(self.other, -0.05, 0.05)\n\n def forward(self, main_vector, attn_vectors):\n \"\"\"\n :param main_vector: matrix of size [batch_size, N]\n :param attn_vectors: matrix of size [batch_size, seq_len, N]\n :return:\n \"\"\"\n seq_len = attn_vectors.size()[1]\n\n # Calculate energies for each encoder output\n attn_energies = self.score(main_vector, attn_vectors)\n\n return F.softmax(attn_energies, dim=1)\n\n def score(self, main_vector, attn_vectors):\n \"\"\"\n :param main_vector: matrix of size [batch_size, N]\n :param attn_vectors: matrix of size [batch_size, seq_len, N]\n :return: matrix with attention coefficients of size [batch_size, seq_len, 1]\n \"\"\"\n if self.method == 'dot':\n pass # all is ready\n elif self.method == 'general':\n attn_vectors = self.attn(attn_vectors)\n else:\n raise Exception('Unknown attention method: {}'.format(self.method))\n\n # main_vector [batch_size, N] -> [batch_size, 1, 1, N]\n main_vector = main_vector.unsqueeze(1).unsqueeze(1)\n # att_vectors [batch_size, seq_len, N, 1]\n attn_vectors = attn_vectors.unsqueeze(3)\n # after multiplication [batch_size, seq_len, 1, 1] -> [batch_size, seq_len, 1, 1]\n energy = main_vector.matmul(attn_vectors).squeeze(-1)\n return energy\n\n # TODO: implement concat\n # elif self.method == 'concat':\n # energy = self.attn(torch.cat((hidden, encoder_output), 1))\n # energy = self.other.dot(energy)\n # return energy\n\n\nclass ContextAttention(BaseModule):\n \"\"\"Attention layer that calculate attention of past seq_len reported inputs to the currently reported input.\"\"\"\n\n def __init__(self, context_len, hidden_size):\n super().__init__()\n self.seq_len = context_len\n self.hidden_size = hidden_size\n self.it = 0\n\n # Layer that applies attention to past self.cntx hidden states of contexts\n self.attn = Attn(method='general', hidden_size=self.hidden_size)\n\n # Matrix that will hold past seq_len contexts. No backprop will be computed\n # size: [batch_size, seq_len, hidden_size]\n self.context_buffer = None\n\n def init_hidden(self, batch_size):\n b_matrix = torch.FloatTensor(batch_size, 2 * self.seq_len, self.hidden_size).to(get_best_device())\n self.context_buffer = LastKBuffer(window_len=self.seq_len, buffer=b_matrix)\n\n def forget_context_partly(self, forget_vector):\n \"\"\"Method to drop context for programs that ended.\n :param forget_vector vector of size [batch_size, 1] with either 0 or 1\n \"\"\"\n drop_matrix_rows_3d(self.context_buffer.get(), forget_vector)\n\n def forward(self, h_t):\n \"\"\"\n :param h_t: current hidden state of size [batch_size, hidden_size]\n :return: hidden state with applied sum attention of size [batch_size, hidden_size]\n \"\"\"\n assert self.context_buffer is not None\n\n current_context = self.context_buffer.get()\n attn_weights = self.attn(h_t, current_context)\n\n # self.it += 1\n # if self.it % 10000 == 0:\n # print(attn_weights.data[0])\n\n # Calc current context vector as sum of previous contexts multiplied by attention coefficients\n cntx = calc_attention_combination(attn_weights, current_context)\n\n self.context_buffer.add_vector(h_t)\n return cntx\n" ]
[ [ "torch.max", "torch.sum", "numpy.save", "torch.nonzero", "torch.index_select", "numpy.zeros", "torch.argmax" ], [ "torch.nn.Linear", "torch.nn.functional.softmax", "torch.FloatTensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
PeterouZh/CIPS-3D
[ "9b8bfa0fb23f642af042e150ccd70408f9d137c6" ]
[ "exp/cips3d_inversion/models/generator_v2.py" ]
[ "from itertools import chain\nimport math\nimport logging\nimport collections\nfrom collections import OrderedDict\nimport tqdm\nimport random\nimport time\nfrom einops import rearrange, repeat\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.cuda.amp import autocast\n\nfrom tl2.proj.fvcore import MODEL_REGISTRY, build_model\n# from tl2.proj.stylegan2_ada import persistence\nfrom tl2.launch.launch_utils import global_cfg\nfrom tl2.proj.pytorch.pytorch_hook import VerboseModel\nfrom tl2.proj.pytorch import torch_utils\nfrom tl2.proj.pytorch import torch_utils, init_func\nfrom tl2 import tl2_utils\nfrom tl2.proj.pytorch.examples.nerf import cam_params\nfrom tl2.proj.pytorch.examples.nerf import volume_rendering\nfrom tl2.proj.pytorch.examples.networks import nerf_net\nfrom tl2.proj.pytorch.examples.networks import multi_head_mapping\nfrom tl2.proj.pytorch.examples.networks import cips_net\n\nfrom exp.pigan import pigan_utils\nfrom exp.dev.nerf_inr.models.generator_nerf_inr import INRNetwork\nfrom exp.dev.nerf_inr.models.generator_nerf_inr import GeneratorNerfINR as GeneratorNerfINR_base\nfrom exp.comm import comm_utils\nfrom exp.comm.models import nerf_network\nfrom exp.comm.models import inr_network\nfrom exp.comm.models import film_layer\nfrom exp.comm.models import mod_conv_fc\n# from exp.cips3d.models import multi_head_mapping\n\n\nclass SkipLayer(nn.Module):\n def __init__(self, ):\n super(SkipLayer, self).__init__()\n\n def forward(self, x0, x1):\n # out = (x0 + x1) / math.pi\n out = (x0 + x1)\n return out\n\n\n\nclass SinAct(nn.Module):\n def __init__(self, ):\n super(SinAct, self).__init__()\n\n def forward(self, x):\n return torch.sin(x)\n\n\nclass LinearSinAct(nn.Module):\n def __init__(self,\n in_features,\n out_features):\n super(LinearSinAct, self).__init__()\n\n self.linear = nn.Linear(in_features=in_features, out_features=out_features)\n self.sin = SinAct()\n pass\n\n def forward(self, x, *args, **kwargs):\n x = self.linear(x)\n x = self.sin(x)\n return x\n\n\nclass FiLMLayer(nn.Module):\n def __init__(self,\n in_dim,\n out_dim,\n style_dim,\n use_style_fc=True,\n which_linear=nn.Linear,\n **kwargs):\n super(FiLMLayer, self).__init__()\n\n self.in_dim = in_dim\n self.out_dim = out_dim\n self.style_dim = style_dim\n self.use_style_fc = use_style_fc\n\n self.linear = which_linear(in_dim, out_dim)\n # self.linear.apply(film_layer.frequency_init(25))\n\n # self.gain_scale = film_layer.LinearScale(scale=15, bias=30)\n self.gain_scale = nn.Identity()\n # Prepare gain and bias layers\n if use_style_fc:\n self.gain_fc = which_linear(style_dim, out_dim)\n self.bias_fc = which_linear(style_dim, out_dim)\n # self.gain_fc.weight.data.mul_(0.25)\n # self.bias_fc.weight.data.mul_(0.25)\n else:\n self.style_dim = out_dim * 2\n\n self.sin = SinAct()\n self.lrelu = nn.LeakyReLU(0.2, inplace=True)\n # self.register_buffer('stored_mean', torch.zeros(output_size))\n # self.register_buffer('stored_var', torch.ones(output_size))\n pass\n\n def forward(self,\n x,\n style):\n \"\"\"\n\n :param x: (b, c) or (b, n, c)\n :param style: (b, c)\n :return:\n \"\"\"\n\n if self.use_style_fc:\n gain = self.gain_fc(style)\n gain = self.gain_scale(gain)\n bias = self.bias_fc(style)\n else:\n style = rearrange(style, \"b (n c) -> b n c\", n=2)\n gain, bias = style.unbind(dim=1)\n gain = self.gain_scale(gain)\n\n if x.dim() == 3:\n gain = rearrange(gain, \"b c -> b 1 c\")\n bias = rearrange(bias, \"b c -> b 1 c\")\n elif x.dim() == 2:\n pass\n else:\n assert 0\n\n x = self.linear(x)\n\n x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-8)\n # out = self.sin(gain * x + bias)\n out = self.lrelu((gain + 1.) * x + bias)\n\n return out\n\n def __repr__(self):\n s = f'{self.__class__.__name__}(' \\\n f'in_dim={self.in_dim}, ' \\\n f'out_dim={self.out_dim}, ' \\\n f'style_dim={self.style_dim}, ' \\\n f'use_style_fc={self.use_style_fc}, ' \\\n f')'\n return s\n\n\nclass INRNetwork_Skip(nn.Module):\n def __repr__(self): return f\"{self.__class__.__name__}({self.repr})\"\n\n def __init__(self,\n input_dim,\n style_dim,\n hidden_layers,\n dim_scale=1,\n rgb_dim=3,\n device=None,\n name_prefix='inr',\n **kwargs):\n \"\"\"\n\n :param z_dim:\n :param hidden_dim:\n :param rgb_dim:\n :param device:\n :param kwargs:\n \"\"\"\n super().__init__()\n\n self.repr = f\"input_dim={input_dim}, \" \\\n f\"style_dim={style_dim}, \" \\\n f\"hidden_layers={hidden_layers}, \" \\\n f\"dim_scale={dim_scale}, \"\n\n self.device = device\n self.rgb_dim = rgb_dim\n self.hidden_layers = hidden_layers\n self.name_prefix = name_prefix\n\n self.channels = {\n 0: int(512 * dim_scale), # 4\n 1: int(512 * dim_scale), # 8\n 2: int(512 * dim_scale), # 16\n 3: int(512 * dim_scale), # 32\n 4: int(512 * dim_scale), # 64\n 5: int(128 * dim_scale), # 128\n 6: int(64 * dim_scale), # 256\n 7: int(32 * dim_scale), # 512\n 8: int(16 * dim_scale), # 1024\n }\n\n self.style_dim_dict = {}\n\n _out_dim = input_dim\n\n self.network = nn.ModuleList()\n self.to_rbgs = nn.ModuleList()\n for i in range(hidden_layers):\n _in_dim = _out_dim\n _out_dim = self.channels[i]\n\n _layer = film_layer.FiLMLayer(in_dim=_in_dim,\n out_dim=_out_dim,\n style_dim=style_dim)\n self.network.append(_layer)\n self.style_dim_dict[f'{name_prefix}_w{i}_0'] = _layer.style_dim\n\n _layer = film_layer.FiLMLayer(in_dim=_out_dim,\n out_dim=_out_dim,\n style_dim=style_dim)\n self.network.append(_layer)\n self.style_dim_dict[f'{name_prefix}_w{i}_1'] = _layer.style_dim\n\n to_rgb = inr_network.ToRGB(in_dim=_out_dim, dim_rgb=3)\n self.to_rbgs.append(to_rgb)\n\n self.tanh = nn.Sequential(\n # nn.Linear(hidden_dim, rgb_dim),\n nn.Tanh()\n )\n # self.to_rbg.apply(frequency_init(25))\n\n torch_utils.print_number_params(\n {\n 'network': self.network,\n 'to_rbgs': self.to_rbgs,\n 'inr_net': self\n })\n logging.getLogger('tl').info(self)\n pass\n\n def forward(self,\n input,\n style_dict,\n **kwargs):\n \"\"\"\n\n :param input: points xyz, (b, num_points, 3)\n :param style_dict:\n :param ray_directions: (b, num_points, 3)\n :param kwargs:\n :return:\n - out: (b, num_points, 4), rgb(3) + sigma(1)\n \"\"\"\n\n x = input\n rgb = 0\n for index in range(self.hidden_layers):\n\n _layer = self.network[index * 2]\n style = style_dict[f'{self.name_prefix}_w{index}_0']\n\n if global_cfg.tl_debug:\n VerboseModel.forward_verbose(_layer,\n inputs_args=(x, style),\n name_prefix=f\"{self.name_prefix}.network.{index}.0.\")\n x = _layer(x, style)\n\n _layer = self.network[index * 2 + 1]\n style = style_dict[f'{self.name_prefix}_w{index}_1']\n\n if global_cfg.tl_debug:\n VerboseModel.forward_verbose(_layer,\n inputs_args=(x, style),\n name_prefix=f\"{self.name_prefix}.network.{index}.1.\")\n x = _layer(x, style)\n\n if global_cfg.tl_debug:\n VerboseModel.forward_verbose(self.to_rbgs[index],\n inputs_args=(x, rgb),\n name_prefix=f'to_rgb.{index}')\n rgb = self.to_rbgs[index](x, skip=rgb)\n\n # if global_cfg.tl_debug:\n # VerboseModel.forward_verbose(self.to_rbg,\n # inputs_args=(x, ),\n # name_prefix='to_rgb.')\n # out = self.to_rbg(x)\n if global_cfg.tl_debug:\n VerboseModel.forward_verbose(self.tanh,\n inputs_args=(rgb, ),\n name_prefix='tanh.')\n out = self.tanh(rgb)\n return out\n\n\n\nclass ModSinLayer(nn.Module):\n def __repr__(self): return f\"{self.__class__.__name__}({self.repr})\"\n\n def __init__(self,\n in_dim,\n use_style_fc=False,\n style_dim=None,\n which_linear=nn.Linear,\n spectral_norm=False,\n eps=1e-5,\n freq=1,\n phase=0,\n **kwargs):\n super(ModSinLayer, self).__init__()\n\n self.repr = f\"in_dim={in_dim}, use_style_fc={use_style_fc}, style_dim={style_dim}, \" \\\n f\"freq={freq}, phase={phase}\"\n\n self.in_dim = in_dim\n self.use_style_fc = use_style_fc\n self.style_dim = style_dim\n self.freq = freq\n self.phase = phase\n\n self.spectral_norm = spectral_norm\n # Prepare gain and bias layers\n\n if use_style_fc:\n self.gain_fc = which_linear(style_dim, in_dim)\n self.bias_fc = which_linear(style_dim, in_dim)\n if spectral_norm:\n self.gain_fc = nn.utils.spectral_norm(self.gain_fc)\n self.bias_fc = nn.utils.spectral_norm(self.bias_fc)\n else:\n self.style_dim = in_dim * 2\n\n self.eps = eps\n\n self.lrelu = nn.LeakyReLU(0.2, inplace=True)\n # self.register_buffer('stored_mean', torch.zeros(output_size))\n # self.register_buffer('stored_var', torch.ones(output_size))\n pass\n\n def forward(self,\n x,\n style):\n \"\"\"\n Calculate class-conditional gains and biases.\n\n :param x: (b, c) or (b, n, c)\n :param style: (b, c)\n :return:\n \"\"\"\n assert style.shape[-1] == self.style_dim\n\n if self.use_style_fc:\n gain = self.gain_fc(style) + 1.\n bias = self.bias_fc(style)\n else:\n style = rearrange(style, \"b (n c) -> b n c\", n=2)\n gain, bias = style.unbind(dim=1)\n gain = gain + 1.\n\n if x.dim() == 3:\n gain = rearrange(gain, \"b c -> b 1 c\")\n bias = rearrange(bias, \"b c -> b 1 c\")\n elif x.dim() == 2:\n pass\n else:\n assert 0\n\n # x = torch.sin(self.freq * x + self.phase)\n # out = x * gain + bias\n\n x = x * torch.rsqrt(torch.mean(x ** 2, dim=-1, keepdim=True) + 1e-8)\n x = x * gain + bias\n\n out = self.lrelu(x)\n return out\n\n\nclass ModSinLayer_NoBias(nn.Module):\n def __repr__(self): return f\"{self.__class__.__name__}({self.repr})\"\n\n def __init__(self,\n in_dim,\n use_style_fc=False,\n style_dim=None,\n which_linear=nn.Linear,\n spectral_norm=False,\n eps=1e-5,\n freq=1,\n phase=0,\n **kwargs):\n super(ModSinLayer_NoBias, self).__init__()\n\n self.repr = f\"in_dim={in_dim}, use_style_fc={use_style_fc}, style_dim={style_dim}, \" \\\n f\"freq={freq}, phase={phase}\"\n\n self.in_dim = in_dim\n self.use_style_fc = use_style_fc\n self.style_dim = style_dim\n self.freq = freq\n self.phase = phase\n\n self.spectral_norm = spectral_norm\n # Prepare gain and bias layers\n\n if use_style_fc:\n self.gain_fc = which_linear(style_dim, in_dim)\n # self.bias_fc = which_linear(style_dim, in_dim)\n if spectral_norm:\n self.gain_fc = nn.utils.spectral_norm(self.gain_fc)\n # self.bias_fc = nn.utils.spectral_norm(self.bias_fc)\n else:\n self.style_dim = in_dim * 2\n\n self.eps = eps\n pass\n\n def forward(self,\n x,\n style):\n \"\"\"\n Calculate class-conditional gains and biases.\n\n :param x: (b, c) or (b, n, c)\n :param style: (b, c)\n :return:\n \"\"\"\n assert style.shape[-1] == self.style_dim\n\n if self.use_style_fc:\n gain = self.gain_fc(style) + 1.\n else:\n style = rearrange(style, \"b (n c) -> b n c\", n=2)\n gain, bias = style.unbind(dim=1)\n gain = gain + 1.\n\n if x.dim() == 3:\n gain = rearrange(gain, \"b c -> b 1 c\")\n elif x.dim() == 2:\n pass\n else:\n assert 0\n\n x = torch.sin(self.freq * x + self.phase)\n # out = x * gain + bias\n out = x * gain\n return out\n\n\nclass SinBlock(nn.Module):\n def __init__(self,\n in_dim,\n out_dim,\n style_dim,\n name_prefix,\n ):\n super().__init__()\n self.in_dim = in_dim\n self.out_dim = out_dim\n self.style_dim = style_dim\n self.name_prefix = name_prefix\n\n self.style_dim_dict = {}\n\n # self.mod1 = mod_conv_fc.Modulated_FC_Conv(in_channel=in_dim,\n # out_channel=out_dim,\n # style_dim=style_dim,\n # use_style_fc=True,\n # scale=1.,\n # # scale=None,\n # )\n self.mod1 = mod_conv_fc.SinStyleMod(in_channel=in_dim,\n out_channel=out_dim,\n style_dim=style_dim,\n use_style_fc=True,\n )\n self.style_dim_dict[f'{name_prefix}_0'] = self.mod1.style_dim\n self.act1 = nn.LeakyReLU(0.2, inplace=True)\n\n # self.mod2 = mod_conv_fc.Modulated_FC_Conv(in_channel=out_dim,\n # out_channel=out_dim,\n # style_dim=style_dim,\n # use_style_fc=True,\n # scale=1.,\n # # scale=None,\n # )\n self.mod2 = mod_conv_fc.SinStyleMod(in_channel=out_dim,\n out_channel=out_dim,\n style_dim=style_dim,\n use_style_fc=True,\n )\n self.style_dim_dict[f'{name_prefix}_1'] = self.mod2.style_dim\n self.act2 = nn.LeakyReLU(0.2, inplace=True)\n\n # self.linear1 = nn.Linear(in_dim, out_dim)\n # self.mod1 = ModSinLayer(in_dim=out_dim, use_style_fc=True, style_dim=style_dim)\n # self.style_dim_dict[f'{name_prefix}_0'] = self.mod1.style_dim\n\n # self.linear2 = nn.Linear(out_dim, out_dim)\n # self.mod2 = ModSinLayer(in_dim=out_dim, use_style_fc=True, style_dim=style_dim)\n # self.style_dim_dict[f'{name_prefix}_1'] = self.mod2.style_dim\n\n self.skip = SkipLayer()\n pass\n\n def forward(self,\n x,\n style_dict,\n skip=False):\n x_orig = x\n\n style = style_dict[f'{self.name_prefix}_0']\n x = self.mod1(x, style)\n x = self.act1(x)\n\n style = style_dict[f'{self.name_prefix}_1']\n x = self.mod2(x, style)\n out = self.act2(x)\n\n # x = self.linear1(x)\n # style = style_dict[f'{self.name_prefix}_0']\n # x = self.mod1(x, style)\n\n # x = self.linear2(x)\n # style = style_dict[f'{self.name_prefix}_1']\n # out = self.mod2(x, style)\n\n if skip and out.shape[-1] == x_orig.shape[-1]:\n # out = (out + x_orig) / 1.41421\n out = self.skip(out, x_orig)\n return out\n\n def __repr__(self):\n repr = f\"{self.__class__.__name__}(in_dim={self.in_dim}, \" \\\n f\"out_dim={self.out_dim}, \" \\\n f\"style_dim={self.style_dim})\"\n return repr\n\n\nclass ToRGB(nn.Module):\n def __init__(self,\n in_dim,\n dim_rgb=3,\n use_equal_fc=False):\n super().__init__()\n self.in_dim = in_dim\n self.dim_rgb = dim_rgb\n\n if use_equal_fc:\n self.linear = mod_conv_fc.EqualLinear(in_dim, dim_rgb, scale=1.)\n else:\n self.linear = nn.Linear(in_dim, dim_rgb)\n pass\n\n def forward(self,\n input,\n skip=None):\n\n out = self.linear(input)\n\n if skip is not None:\n out = out + skip\n return out\n\n\n@MODEL_REGISTRY.register(name_prefix=__name__)\n# class Generator_Diffcam(GeneratorNerfINR_base):\nclass Generator_Diffcam(nn.Module):\n\n def __repr__(self):\n return tl2_utils.get_class_repr(self)\n\n def __init__(self,\n nerf_cfg,\n mapping_shape_cfg,\n mapping_app_cfg,\n inr_cfg,\n mapping_inr_cfg,\n shape_block_end_index=None,\n app_block_end_index=None,\n inr_block_end_index=None,\n device='cuda',\n **kwargs):\n super(Generator_Diffcam, self).__init__()\n\n self.repr_str = tl2_utils.dict2string(dict_obj={\n 'nerf_cfg': nerf_cfg,\n 'mapping_shape_cfg': mapping_shape_cfg,\n 'mapping_app_cfg': mapping_app_cfg,\n 'inr_cfg': inr_cfg,\n 'mapping_inr_cfg': mapping_inr_cfg,\n 'shape_block_end_index': shape_block_end_index,\n 'app_block_end_index': app_block_end_index,\n 'inr_block_end_index': inr_block_end_index,\n })\n\n self.device = device\n self.inr_block_end_index = inr_block_end_index\n\n self.module_name_list = []\n\n # nerf_net\n self.nerf_net = nerf_net.NeRFNetwork_SIREN_skip(\n shape_block_end_index=shape_block_end_index,\n app_block_end_index=app_block_end_index,\n **nerf_cfg)\n self.module_name_list.append('nerf_net')\n\n # mapping shape\n self.mapping_shape = multi_head_mapping.MultiHeadMappingNetwork(**{\n **mapping_shape_cfg,\n 'head_dim_dict': self.nerf_net.style_dim_dict_shape\n })\n self.module_name_list.append('mapping_shape')\n\n # mapping appearance\n self.mapping_app = multi_head_mapping.MultiHeadMappingNetwork(**{\n **mapping_app_cfg,\n 'head_dim_dict': self.nerf_net.style_dim_dict_app\n })\n self.module_name_list.append('mapping_app')\n\n _in_dim = nerf_cfg.app_net_cfg.out_dim\n\n # inr_net\n self.inr_net = cips_net.CIPSNet(**{\n **inr_cfg,\n \"input_dim\": _in_dim,\n 'add_out_layer': True,\n })\n self.module_name_list.append('inr_net')\n\n self.mapping_inr = multi_head_mapping.MultiHeadMappingNetwork(**{\n **mapping_inr_cfg,\n 'head_dim_dict': self.inr_net.style_dim_dict\n })\n self.module_name_list.append('mapping_inr')\n\n\n self.aux_to_rbg = nn.Sequential(\n nn.Linear(_in_dim, 3),\n nn.Tanh()\n )\n self.aux_to_rbg.apply(nerf_network.frequency_init(25))\n self.module_name_list.append('aux_to_rbg')\n\n\n logger = logging.getLogger('tl')\n models_dict = {}\n for name in self.module_name_list:\n models_dict[name] = getattr(self, name)\n models_dict['G'] = self\n torch_utils.print_number_params(models_dict=models_dict, logger=logger)\n logger.info(self)\n\n pass\n\n def forward(self,\n zs,\n rays_o,\n rays_d,\n nerf_kwargs={},\n psi=1,\n return_aux_img=False,\n grad_points=None,\n forward_points=None, # disable gradients\n **kwargs):\n \"\"\"\n Generates images from a noise vector, rendering parameters, and camera distribution.\n Uses the hierarchical sampling scheme described in NeRF.\n\n :param zs: {k: (b, z_dim), ...}\n :param rays_o: (b, h, w, 3) in world space\n :param rays_d: (b, h, w, 3) in world space\n\n :return:\n - pixels: (b, 3, h, w)\n - pitch_yaw: (b, 2)\n \"\"\"\n\n # mapping network\n style_dict = self.mapping_network(**zs)\n\n if psi < 1:\n avg_styles = self.generate_avg_frequencies(device=self.device)\n style_dict = self.get_truncated_freq_phase(\n raw_style_dict=style_dict, avg_style_dict=avg_styles, raw_lambda=psi)\n\n b, h, w, c = rays_o.shape\n rays_o = rearrange(rays_o, \"b h w c -> b (h w) c\")\n rays_d = rearrange(rays_d, \"b h w c -> b (h w) c\")\n\n if grad_points is not None and grad_points < h * w:\n imgs, ret_maps = self.part_grad_forward(\n rays_o=rays_o,\n rays_d=rays_d,\n style_dict=style_dict,\n nerf_kwargs=nerf_kwargs,\n return_aux_img=return_aux_img,\n grad_points=grad_points)\n\n else:\n imgs, ret_maps = self.whole_grad_forward(\n rays_o=rays_o,\n rays_d=rays_d,\n style_dict=style_dict,\n nerf_kwargs=nerf_kwargs,\n return_aux_img=return_aux_img,\n forward_points=forward_points)\n\n imgs = rearrange(imgs, \"b (h w) c -> b c h w\", h=h, w=w)\n\n ret_imgs = {}\n for name, v_map in ret_maps.items():\n if v_map.dim() == 3:\n v_map = rearrange(v_map, \"b (h w) c -> b c h w\", h=h, w=w)\n elif v_map.dim() == 2:\n v_map = rearrange(v_map, \"b (h w) -> b h w\", h=h, w=w)\n ret_imgs[name] = v_map\n\n return imgs, ret_imgs\n\n def get_rays_axis_angle(self,\n R,\n t,\n fx,\n fy,\n H: int,\n W: int,\n N_rays: int = -1):\n \"\"\"\n\n :param R: (b, 3)\n :param t: (b, 3)\n :param fx:\n :param fy:\n :param H:\n :param W:\n :param N_rays:\n :return\n\n - rays_o: (b, H, W, 3)\n - rays_d: (b, H, W, 3)\n - select_inds: (b, H, W)\n \"\"\"\n\n rays_o, rays_d, select_inds = cam_params.get_rays(\n rot=R,\n trans=t,\n focal_x=fx,\n focal_y=fy,\n H=H,\n W=W,\n N_rays=N_rays,\n flatten=False)\n\n return rays_o, rays_d, select_inds\n\n def get_batch_style_dict(self, b, style_dict):\n ret_style_dict = {}\n for name, style in style_dict.items():\n ret_style_dict[name] = style[[b]]\n return ret_style_dict\n\n def whole_grad_forward(self,\n rays_o,\n rays_d,\n style_dict,\n nerf_kwargs,\n return_aux_img=True,\n forward_points=None,\n **kwargs):\n\n if forward_points is not None and forward_points < rays_o.shape[1]: # no gradients\n # stage forward\n with torch.no_grad():\n batch_size = rays_o.shape[0]\n num_points = rays_o.shape[1]\n\n near = nerf_kwargs['near']\n far = nerf_kwargs['far']\n N_samples = nerf_kwargs['N_samples']\n perturb = self.training\n z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,\n rays_d=rays_d,\n near=near,\n far=far,\n N_samples=N_samples,\n perturb=perturb)\n\n batch_image_ddict = collections.defaultdict(list)\n for b in range(batch_size):\n image_ddict = collections.defaultdict(list)\n\n head = 0\n while head < num_points:\n tail = head + forward_points\n cur_style_dict = self.get_batch_style_dict(b=b, style_dict=style_dict)\n\n cur_inr_img, cur_ret_maps = self.points_forward(\n rays_o=rays_o[[b], head:tail], # (b, hxw, 3)\n rays_d=rays_d[[b], head:tail], # (b, hxw, 3)\n points=points[[b], head:tail], # (b, hxw, Nsamples, 3)\n z_vals=z_vals[[b], head:tail], # (b, hxw, Nsamples)\n style_dict=cur_style_dict,\n nerf_kwargs=nerf_kwargs,\n return_aux_img=return_aux_img)\n\n image_ddict['inr_img'].append(cur_inr_img)\n for k, v in cur_ret_maps.items():\n image_ddict[k].append(v)\n head += forward_points\n for k, v in image_ddict.items():\n one_image = torch.cat(v, dim=1)\n batch_image_ddict[k].append(one_image)\n ret_maps = {}\n for k, v in batch_image_ddict.items():\n ret_maps[k] = torch.cat(v, dim=0)\n imgs = ret_maps.pop('inr_img')\n\n else:\n near = nerf_kwargs['near']\n far = nerf_kwargs['far']\n N_samples = nerf_kwargs['N_samples']\n perturb = self.training\n z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o,\n rays_d=rays_d,\n near=near,\n far=far,\n N_samples=N_samples,\n perturb=perturb)\n\n # transformed_points = rearrange(transformed_points, \"b (h w s) c -> b (h w) s c\", h=img_size, s=num_steps)\n # transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded,\n # \"b (h w s) c -> b (h w) s c\", h=img_size, s=num_steps)\n\n imgs, ret_maps = self.points_forward(\n rays_o=rays_o,\n rays_d=rays_d,\n points=points,\n z_vals=z_vals,\n style_dict=style_dict,\n nerf_kwargs=nerf_kwargs,\n return_aux_img=return_aux_img)\n\n return imgs, ret_maps\n\n def part_grad_forward(self,\n rays_o,\n rays_d,\n style_dict,\n nerf_kwargs,\n return_aux_img,\n grad_points):\n\n near = nerf_kwargs['near']\n far = nerf_kwargs['far']\n N_samples = nerf_kwargs['N_samples']\n perturb = self.training\n # z_vals: (b, hxw, Nsamples), points: (b, hxw, Nsamples, 3)\n z_vals, points = volume_rendering.ray_sample_points(rays_o=rays_o, # (b, hxw, 3)\n rays_d=rays_d, # (b, hxw, 3)\n near=near,\n far=far,\n N_samples=N_samples,\n perturb=perturb)\n\n # transformed_points = rearrange(transformed_points, \"b (h w s) c -> b (h w) s c\", h=img_size, s=num_steps)\n # transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded,\n # \"b (h w s) c -> b (h w) s c\", h=img_size, s=num_steps)\n\n batch_size = rays_o.shape[0]\n num_points = rays_o.shape[1]\n device = self.device\n assert num_points > grad_points\n idx_grad, idx_no_grad = torch_utils.batch_random_split_indices(bs=batch_size,\n num_points=num_points,\n grad_points=grad_points,\n device=device)\n # rand_idx = torch.randperm(num_points, device=device)\n # idx_grad = rand_idx[:grad_points]\n # idx_no_grad = rand_idx[grad_points:]\n\n inr_img_grad, ret_maps_grad = self.points_forward(\n rays_o=rays_o,\n rays_d=rays_d,\n points=points,\n z_vals=z_vals,\n style_dict=style_dict,\n nerf_kwargs=nerf_kwargs,\n return_aux_img=return_aux_img,\n idx_grad=idx_grad)\n\n with torch.no_grad():\n inr_img_no_grad, ret_maps_no_grad = self.points_forward(\n rays_o=rays_o,\n rays_d=rays_d,\n points=points,\n z_vals=z_vals,\n style_dict=style_dict,\n nerf_kwargs=nerf_kwargs,\n return_aux_img=return_aux_img,\n idx_grad=idx_no_grad)\n\n imgs = comm_utils.batch_scatter_points(idx_grad=idx_grad,\n points_grad=inr_img_grad,\n idx_no_grad=idx_no_grad,\n points_no_grad=inr_img_no_grad,\n num_points=num_points)\n ret_maps = {}\n for k in ret_maps_grad.keys():\n comp_map = comm_utils.batch_scatter_points(idx_grad=idx_grad,\n points_grad=ret_maps_grad[k],\n idx_no_grad=idx_no_grad,\n points_no_grad=ret_maps_no_grad[k],\n num_points=num_points)\n ret_maps[k] = comp_map\n return imgs, ret_maps\n\n def points_forward(self,\n rays_o,\n rays_d,\n points,\n z_vals,\n style_dict,\n nerf_kwargs,\n return_aux_img,\n idx_grad=None,\n **kwargs):\n \"\"\"\n\n :param rays_o: (b, hxw, 3)\n :param rays_d: (b, hxw, 3)\n :param points: (b, hxw, Nsamples, 3)\n :param z_vals: (b, hxw, Nsamples)\n :param style_dict:\n :param nerf_kwargs:\n :param return_aux_img:\n :param idx_grad: (b, N_grad, )\n :param kwargs:\n :return:\n \"\"\"\n\n device = points.device\n\n viewdirs = volume_rendering.get_viewdirs(rays_d=rays_d)\n # viewdirs = viewdirs[..., None, :].expand_as(points)\n N_samples = nerf_kwargs['N_samples']\n\n if idx_grad is not None:\n rays_o = comm_utils.batch_gather_points(points=rays_o, idx_grad=idx_grad)\n rays_d = comm_utils.batch_gather_points(points=rays_d, idx_grad=idx_grad)\n points = comm_utils.batch_gather_points(points=points, idx_grad=idx_grad)\n z_vals = comm_utils.batch_gather_points(points=z_vals, idx_grad=idx_grad)\n\n\n points = rearrange(points, \"b Nrays Nsamples c -> b (Nrays Nsamples) c\")\n coarse_viewdirs = repeat(viewdirs, \"b Nrays c -> b (Nrays Nsamples) c\", Nsamples=N_samples)\n\n # Model prediction on course points\n coarse_output = self.nerf_net(\n x=points, # b (Nrays Nsamples) c\n ray_directions=coarse_viewdirs, # b (Nrays Nsamples) c\n style_dict=style_dict)\n coarse_output = rearrange(\n coarse_output, \"b (Nrays Nsamples) rgb_sigma -> b Nrays Nsamples rgb_sigma\", Nsamples=N_samples)\n\n # Re-sample fine points alont camera rays, as described in NeRF\n if nerf_kwargs['N_importance'] > 0:\n\n with torch.no_grad():\n raw_sigma = coarse_output[..., -1]\n perturb = self.training\n fine_z_vals, fine_points = volume_rendering.get_fine_points(\n z_vals=z_vals,\n rays_o=rays_o,\n rays_d=rays_d,\n raw_sigma=raw_sigma,\n N_importance=nerf_kwargs['N_importance'],\n perturb=perturb,\n raw_noise_std=nerf_kwargs['raw_noise_std'],\n eps=nerf_kwargs['eps'])\n\n # Model prediction on re-sampled find points\n fine_points = rearrange(fine_points, \"b Nrays Nsamples c -> b (Nrays Nsamples) c\")\n fine_viewdirs = repeat(viewdirs, \"b Nrays c -> b (Nrays Nsamples) c\", Nsamples=nerf_kwargs['N_importance'])\n\n fine_output = self.nerf_net(\n x=fine_points, # b (Nrays Nsamples) c\n ray_directions=fine_viewdirs, # b (Nrays Nsamples) c\n style_dict=style_dict)\n fine_output = rearrange(\n fine_output, \"b (Nrays Nsamples) rgb_sigma -> b Nrays Nsamples rgb_sigma\", Nsamples=nerf_kwargs['N_importance'])\n\n # Combine course and fine points\n DIM_SAMPLES = 2\n all_z_vals = torch.cat([fine_z_vals, z_vals], dim=DIM_SAMPLES) # (b, N_rays, N_samples)\n _, indices = torch.sort(all_z_vals, dim=DIM_SAMPLES) # (b, N_rays, N_samples)\n # gather z_vals\n all_z_vals = torch.gather(all_z_vals, DIM_SAMPLES, indices) # (b, N_rays, N_samples)\n\n # (b, N_rays, N_samples, rgb_sigma)\n all_outputs = torch.cat([fine_output, coarse_output], dim=DIM_SAMPLES)\n view_shape = [*indices.shape, *(len(all_outputs.shape) - len(indices.shape)) * [1]]\n all_outputs = torch.gather(all_outputs, DIM_SAMPLES, indices.view(view_shape).expand_as(all_outputs))\n\n else:\n all_outputs = coarse_output\n all_z_vals = z_vals\n\n # Create images with NeRF\n all_raw_rgb = all_outputs[..., :-1]\n all_raw_sigma = all_outputs[..., -1]\n\n pixels_fea, ret_maps = volume_rendering.ray_integration(raw_rgb=all_raw_rgb,\n raw_sigma=all_raw_sigma,\n z_vals=all_z_vals,\n rays_d=rays_d,\n raw_noise_std=nerf_kwargs['raw_noise_std'],\n eps=nerf_kwargs['eps'])\n\n # inr_net\n inr_img = self.inr_net(pixels_fea, style_dict, block_end_index=self.inr_block_end_index)\n\n if return_aux_img:\n # aux rgb_branch\n aux_img = self.aux_to_rbg(pixels_fea)\n ret_maps['aux_img'] = aux_img\n\n return inr_img, ret_maps\n\n def z_sampler(self,\n shape,\n device,\n dist='gaussian'):\n if dist == 'gaussian':\n z = torch.randn(shape, device=device)\n elif dist == 'uniform':\n z = torch.rand(shape, device=device) * 2 - 1\n return z\n\n def get_zs(self,\n b,\n batch_split=1):\n z_shape = self.z_sampler(shape=(b, self.mapping_shape.z_dim), device=self.device)\n z_app = self.z_sampler(shape=(b, self.mapping_app.z_dim), device=self.device)\n z_inr = self.z_sampler(shape=(b, self.mapping_inr.z_dim), device=self.device)\n\n if batch_split > 1:\n zs_list = []\n z_shape_list = z_shape.split(b // batch_split)\n z_app_list = z_app.split(b // batch_split)\n z_inr_list = z_inr.split(b // batch_split)\n for z_shape_, z_app_, z_inr_ in zip(z_shape_list, z_app_list, z_inr_list):\n zs_ = {\n 'z_shape': z_shape_,\n 'z_app': z_app_,\n 'z_inr': z_inr_,\n }\n zs_list.append(zs_)\n return zs_list\n else:\n zs = {\n 'z_shape': z_shape,\n 'z_app': z_app,\n 'z_inr': z_inr,\n }\n return zs\n\n def mapping_network(self,\n z_shape,\n z_app,\n z_inr):\n if global_cfg.tl_debug:\n VerboseModel.forward_verbose(self.mapping_shape,\n inputs_args=(z_shape,),\n submodels=['base_net'],\n name_prefix='mapping_shape.')\n VerboseModel.forward_verbose(self.mapping_app,\n inputs_args=(z_app,),\n submodels=['base_net'],\n name_prefix='mapping_app.')\n VerboseModel.forward_verbose(self.mapping_inr,\n inputs_args=(z_inr,),\n submodels=['base_net', ],\n input_padding=50,\n name_prefix='mapping_inr.')\n\n style_dict = {}\n style_dict.update(self.mapping_shape(z_shape))\n style_dict.update(self.mapping_app(z_app))\n style_dict.update(self.mapping_inr(z_inr))\n\n return style_dict\n\n def get_truncated_freq_phase(self,\n raw_style_dict,\n avg_style_dict,\n raw_lambda):\n\n truncated_style_dict = {}\n for name, avg_style in avg_style_dict.items():\n raw_style = raw_style_dict[name]\n truncated_style = avg_style + raw_lambda * (raw_style - avg_style)\n truncated_style_dict[name] = truncated_style\n return truncated_style_dict\n\n def generate_avg_frequencies(self,\n num_samples=10000,\n device='cuda'):\n \"\"\"Calculates average frequencies and phase shifts\"\"\"\n\n # z = torch.randn((num_samples, self.z_dim), device=device)\n zs = self.get_zs(num_samples)\n with torch.no_grad():\n style_dict = self.mapping_network(**zs)\n\n avg_styles = {}\n for name, style in style_dict.items():\n avg_styles[name] = style.mean(0, keepdim=True)\n\n # self.avg_styles = avg_styles\n return avg_styles\n\n def staged_forward(self, *args, **kwargs):\n raise NotImplementedError\n\n def set_device(self, device):\n pass\n\n def forward_camera_pos_and_lookup(self,\n zs,\n img_size,\n fov,\n ray_start,\n ray_end,\n num_steps,\n h_stddev,\n v_stddev,\n h_mean,\n v_mean,\n hierarchical_sample,\n camera_pos,\n camera_lookup,\n psi=1,\n sample_dist=None,\n lock_view_dependence=False,\n clamp_mode='relu',\n nerf_noise=0.,\n white_back=False,\n last_back=False,\n return_aux_img=False,\n grad_points=None,\n forward_points=None,\n **kwargs):\n \"\"\"\n Generates images from a noise vector, rendering parameters, and camera distribution.\n Uses the hierarchical sampling scheme described in NeRF.\n\n :param z: (b, z_dim)\n :param img_size:\n :param fov: face: 12\n :param ray_start: face: 0.88\n :param ray_end: face: 1.12\n :param num_steps: face: 12\n :param h_stddev: face: 0.3\n :param v_stddev: face: 0.155\n :param h_mean: face: pi/2\n :param v_mean: face: pi/2\n :param hierarchical_sample: face: true\n :param camera_pos: (b, 3)\n :param camera_lookup: (b, 3)\n :param psi: [0, 1]\n :param sample_dist: mode for sample_camera_positions, face: 'gaussian'\n :param lock_view_dependence: face: false\n :param clamp_mode: face: 'relu'\n :param nerf_noise:\n :param last_back: face: false\n :param white_back: face: false\n :param kwargs:\n :return:\n - pixels: (b, 3, h, w)\n - pitch_yaw: (b, 2)\n \"\"\"\n\n # mapping network\n if global_cfg.tl_debug:\n VerboseModel.forward_verbose(self.mapping_network_nerf,\n inputs_args=(zs['z_nerf'],),\n submodels=['base_net'],\n name_prefix='mapping_nerf.')\n VerboseModel.forward_verbose(self.mapping_network_inr,\n inputs_args=(zs['z_inr'],),\n submodels=['base_net', ],\n input_padding=50,\n name_prefix='mapping_inr.')\n style_dict = self.mapping_network(**zs)\n\n if psi < 1:\n avg_styles = self.generate_avg_frequencies(device=self.device)\n style_dict = self.get_truncated_freq_phase(\n raw_style_dict=style_dict, avg_style_dict=avg_styles, raw_lambda=psi)\n\n if grad_points is not None and grad_points < img_size ** 2:\n imgs, pitch_yaw = self.part_grad_forward(\n style_dict=style_dict,\n img_size=img_size,\n fov=fov,\n ray_start=ray_start,\n ray_end=ray_end,\n num_steps=num_steps,\n h_stddev=h_stddev,\n v_stddev=v_stddev,\n h_mean=h_mean,\n v_mean=v_mean,\n hierarchical_sample=hierarchical_sample,\n sample_dist=sample_dist,\n lock_view_dependence=lock_view_dependence,\n clamp_mode=clamp_mode,\n nerf_noise=nerf_noise,\n white_back=white_back,\n last_back=last_back,\n return_aux_img=return_aux_img,\n grad_points=grad_points,\n camera_pos=camera_pos,\n camera_lookup=camera_lookup,\n )\n return imgs, pitch_yaw\n else:\n imgs, pitch_yaw = self.whole_grad_forward(\n style_dict=style_dict,\n img_size=img_size,\n fov=fov,\n ray_start=ray_start,\n ray_end=ray_end,\n num_steps=num_steps,\n h_stddev=h_stddev,\n v_stddev=v_stddev,\n h_mean=h_mean,\n v_mean=v_mean,\n hierarchical_sample=hierarchical_sample,\n sample_dist=sample_dist,\n lock_view_dependence=lock_view_dependence,\n clamp_mode=clamp_mode,\n nerf_noise=nerf_noise,\n white_back=white_back,\n last_back=last_back,\n return_aux_img=return_aux_img,\n forward_points=forward_points,\n camera_pos=camera_pos,\n camera_lookup=camera_lookup,\n )\n return imgs, pitch_yaw\n\n\n@MODEL_REGISTRY.register(name_prefix=__name__)\nclass GeneratorNerfINR_freeze_NeRF(Generator_Diffcam):\n\n def load_nerf_ema(self, G_ema):\n ret = self.nerf_net.load_state_dict(G_ema.nerf_net.state_dict())\n ret = self.mapping_network_nerf.load_state_dict(G_ema.mapping_network_nerf.state_dict())\n ret = self.aux_to_rbg.load_state_dict(G_ema.aux_to_rbg.state_dict())\n\n ret = self.mapping_network_inr.load_state_dict(G_ema.mapping_network_inr.state_dict())\n ret = self.nerf_rgb_mapping.load_state_dict(G_ema.nerf_rgb_mapping.state_dict())\n pass\n\n def mapping_network(self,\n z_nerf,\n z_inr):\n style_dict = {}\n with torch.no_grad():\n style_dict.update(self.mapping_network_nerf(z_nerf))\n style_dict.update(self.mapping_network_inr(z_inr))\n style_dict['nerf_rgb'] = self.nerf_rgb_mapping(style_dict['nerf_rgb'])\n\n return style_dict\n\n def points_forward(self,\n style_dict,\n transformed_points,\n transformed_ray_directions_expanded,\n num_steps,\n hierarchical_sample,\n z_vals,\n clamp_mode,\n nerf_noise,\n transformed_ray_origins,\n transformed_ray_directions,\n white_back,\n last_back,\n return_aux_img,\n idx_grad=None,\n ):\n \"\"\"\n\n :param style_dict:\n :param transformed_points: (b, n, s, 3)\n :param transformed_ray_directions_expanded: (b, n, s, 3)\n :param num_steps: sampled points along a ray\n :param hierarchical_sample:\n :param z_vals: (b, n, s, 1)\n :param clamp_mode: 'relu'\n :param nerf_noise:\n :param transformed_ray_origins: (b, n, 3)\n :param transformed_ray_directions: (b, n, 3)\n :param white_back:\n :param last_back:\n :return:\n \"\"\"\n device = transformed_points.device\n if idx_grad is not None:\n transformed_points = comm_utils.gather_points(points=transformed_points, idx_grad=idx_grad)\n transformed_ray_directions_expanded = comm_utils.gather_points(\n points=transformed_ray_directions_expanded, idx_grad=idx_grad)\n z_vals = comm_utils.gather_points(points=z_vals, idx_grad=idx_grad)\n transformed_ray_origins = comm_utils.gather_points(points=transformed_ray_origins, idx_grad=idx_grad)\n transformed_ray_directions = comm_utils.gather_points(points=transformed_ray_directions, idx_grad=idx_grad)\n\n transformed_points = rearrange(transformed_points, \"b n s c -> b (n s) c\")\n transformed_ray_directions_expanded = rearrange(transformed_ray_directions_expanded, \"b n s c -> b (n s) c\")\n\n # Model prediction on course points\n with torch.no_grad():\n coarse_output = self.nerf_net(\n x=transformed_points, # (b, n x s, 3)\n style_dict=style_dict,\n ray_directions=transformed_ray_directions_expanded,\n )\n coarse_output = rearrange(coarse_output, \"b (n s) rgb_sigma -> b n s rgb_sigma\", s=num_steps)\n\n # Re-sample fine points alont camera rays, as described in NeRF\n if hierarchical_sample:\n fine_points, fine_z_vals = self.get_fine_points_and_direction(\n coarse_output=coarse_output,\n z_vals=z_vals,\n dim_rgb=self.nerf_net.rgb_dim,\n clamp_mode=clamp_mode,\n nerf_noise=nerf_noise,\n num_steps=num_steps,\n transformed_ray_origins=transformed_ray_origins,\n transformed_ray_directions=transformed_ray_directions\n )\n\n # Model prediction on re-sampled find points\n with torch.no_grad():\n fine_output = self.nerf_net(\n x=fine_points, # (b, n x s, 3)\n style_dict=style_dict,\n ray_directions=transformed_ray_directions_expanded, # (b, n x s, 3)\n )\n fine_output = rearrange(fine_output, \"b (n s) rgb_sigma -> b n s rgb_sigma\", s=num_steps)\n\n # Combine course and fine points\n all_outputs = torch.cat([fine_output, coarse_output], dim=-2) # (b, n, s, dim_rgb_sigma)\n all_z_vals = torch.cat([fine_z_vals, z_vals], dim=-2) # (b, n, s, 1)\n _, indices = torch.sort(all_z_vals, dim=-2) # (b, n, s, 1)\n all_z_vals = torch.gather(all_z_vals, -2, indices) # (b, n, s, 1)\n # (b, n, s, dim_rgb_sigma)\n all_outputs = torch.gather(all_outputs, -2, indices.expand(-1, -1, -1, all_outputs.shape[-1]))\n else:\n all_outputs = coarse_output\n all_z_vals = z_vals\n\n # Create images with NeRF\n pixels_fea, depth, weights = pigan_utils.fancy_integration(\n rgb_sigma=all_outputs,\n z_vals=all_z_vals,\n device=device,\n dim_rgb=self.nerf_net.rgb_dim,\n white_back=white_back,\n last_back=last_back,\n clamp_mode=clamp_mode,\n noise_std=nerf_noise)\n\n inr_img = self.inr_net(pixels_fea, style_dict)\n\n if return_aux_img:\n # aux rgb_branch\n with torch.no_grad():\n aux_img = self.aux_to_rbg(pixels_fea)\n else:\n aux_img = None\n\n return inr_img, aux_img\n\n\n\n\n\n" ]
[ [ "torch.mean", "torch.sin", "torch.cat", "torch.randn", "torch.nn.ModuleList", "torch.nn.utils.spectral_norm", "torch.nn.Tanh", "torch.nn.Linear", "torch.nn.Identity", "torch.no_grad", "torch.nn.LeakyReLU", "torch.sort", "torch.rand", "torch.gather" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cihuang123/pyrobot
[ "fe620097e31d11453b5ea7ac15e40f5f5721b29a", "fe620097e31d11453b5ea7ac15e40f5f5721b29a" ]
[ "src/pyrobot/habitat/base.py", "robots/LoCoBot/locobot_control/nodes/pointrobot3factor_ros_server.py" ]
[ "import numpy as np\nimport math\nimport pyrobot.utils.util as prutil\nimport rospy\nimport habitat_sim.agent as habAgent\nimport habitat_sim.utils as habUtils\nfrom habitat_sim.agent.controls import ActuationSpec\nimport habitat_sim.errors\n\nimport quaternion\nfrom tf.transformations import euler_from_quaternion, euler_from_matrix\n\n\nclass LoCoBotBase(object):\n \"\"\"docstring for SimpleBase\"\"\"\n\n def __init__(self, configs, simulator):\n self.configs = configs\n self.sim = simulator.sim\n self.agent = self.sim.get_agent(self.configs.COMMON.SIMULATOR.DEFAULT_AGENT_ID)\n\n self.transform = None\n self.init_state = self.get_full_state()\n\n def execute_action(self, action_name, actuation):\n # actions = \"turn_right\" or \"turn_left\" or \"move_forward\"\n # returns a bool showing if collided or not\n\n return self._act(action_name, actuation)\n\n def get_full_state(self):\n # Returns habitat_sim.agent.AgentState\n return self.agent.get_state()\n\n def _rot_matrix(self, habitat_quat):\n quat_list = [habitat_quat.x, habitat_quat.y, habitat_quat.z, habitat_quat.w]\n return prutil.quat_to_rot_mat(quat_list)\n\n def get_state(self, state_type=\"odom\"):\n # Returns (x, y, yaw)\n assert state_type == \"odom\", \"Error: Only Odom state is available\"\n cur_state = self.get_full_state()\n\n init_rotation = self._rot_matrix(self.init_state.rotation)\n\n # true position here refers to the relative position from\n # where `self.init_state` is treated as origin\n true_position = cur_state.position - self.init_state.position\n true_position = np.matmul(init_rotation.transpose(), true_position, dtype=np.float64)\n\n cur_rotation = self._rot_matrix(cur_state.rotation)\n cur_rotation = np.matmul(init_rotation.transpose(), cur_rotation, dtype=np.float64)\n\n (r, pitch, yaw) = euler_from_matrix(cur_rotation, axes=\"sxzy\")\n # Habitat has y perpendicular to map where as ROS has z perpendicular\n # to the map. Where as x is same.\n # Here ROS_X = -1 * habitat_z and ROS_Y = -1*habitat_x\n return (-1 * true_position[2], -1 * true_position[0], yaw)\n\n def stop(self):\n raise NotImplementedError(\"Veclocity control is not supported in Habitat-Sim!!\")\n\n def set_vel(self, fwd_speed, turn_speed, exe_time=1):\n raise NotImplementedError(\"Veclocity control is not supported in Habitat-Sim!!\")\n\n def go_to_relative(\n self, xyt_position, use_map=False, close_loop=False, smooth=False\n ):\n \"\"\"\n\t\tMoves the robot to the robot to given\n\t\tgoal state relative to its initial pose.\n\n\t\t:param xyt_position: The relative goal state of the form (x,y,t)\n\t\t:param use_map: When set to \"True\", ensures that controler is\n\t\t using only free space on the map to move the robot.\n\t\t:param close_loop: When set to \"True\", ensures that controler is\n\t\t operating in open loop by\n\t\t taking account of odometry.\n\t\t:param smooth: When set to \"True\", ensures that the motion\n\t\t leading to the goal is a smooth one.\n\n\t\t:type xyt_position: list\n\t\t:type use_map: bool\n\t\t:type close_loop: bool\n\t\t:type smooth: bool\n\n\t\t:return: True if successful; False otherwise (timeout, etc.)\n\t\t:rtype: bool\n\t\t\"\"\"\n\n try:\n if use_map:\n raise NotImplementedError(\n \"Using map feature is not yet supported for Habitat-Sim\"\n )\n if close_loop:\n raise NotImplementedError(\n \"Closed-loop postion control is not supported in Habitat-Sim!\"\n )\n if smooth:\n raise NotImplementedError(\n \"Smooth position control feature is not yet for Habitat-Sim\"\n )\n except Exception as error:\n print(error)\n return False\n\n (cur_x, cur_y, cur_yaw) = self.get_state()\n abs_yaw = cur_yaw + xyt_position[2]\n return self._go_to_relative_pose(xyt_position[0], xyt_position[1], abs_yaw)\n\n def go_to_absolute(\n self, xyt_position, use_map=False, close_loop=False, smooth=False\n ):\n \"\"\"\n\t\tMoves the robot to the robot to given goal state in the world frame.\n\n\t\t:param xyt_position: The goal state of the form (x,y,t)\n\t\t in the world (map) frame.\n\t\t:param use_map: When set to \"True\", ensures that controler is using\n\t\t only free space on the map to move the robot.\n\t\t:param close_loop: When set to \"True\", ensures that controler is\n\t\t operating in open loop by\n\t\t taking account of odometry.\n\t\t:param smooth: When set to \"True\", ensures that the motion\n\t\t leading to the goal is a smooth one.\n\n\t\t:type xyt_position: list\n\t\t:type use_map: bool\n\t\t:type close_loop: bool\n\t\t:type smooth: bool\n\n\t\t:return: True if successful; False otherwise (timeout, etc.)\n\t\t:rtype: bool\n\t\t\"\"\"\n\n try:\n if use_map:\n raise NotImplementedError(\n \"Using map feature is not yet supported for Habitat-Sim\"\n )\n if close_loop:\n raise NotImplementedError(\n \"Closed-loop postion control is not supported in Habitat-Sim!\"\n )\n if smooth:\n raise NotImplementedError(\n \"Smooth position control feature is not yet for Habitat-Sim\"\n )\n except Exception as error:\n print(error)\n return False\n\n (cur_x, cur_y, cur_yaw) = self.get_state()\n rel_X = xyt_position[0] - cur_x\n rel_Y = xyt_position[1] - cur_y\n abs_yaw = xyt_position[2]\n # convert rel_X & rel_Y from global frame to current frame\n R = np.array([[np.cos(cur_yaw), np.sin(cur_yaw)],\n [-np.sin(cur_yaw), np.cos(cur_yaw)]])\n rel_x, rel_y = np.matmul(R, np.array([rel_X, rel_Y]).reshape(-1,1))\n return self._go_to_relative_pose(rel_x[0], rel_y[0], abs_yaw)\n\n def _act(self, action_name, actuation):\n \"\"\"Take the action specified by action_id\n\n\t\t:param action_id: ID of the action. Retreives the action from\n\t\t `agent_config.action_space <AgentConfiguration.action_space>`\n\t\t:return: Whether or not the action taken resulted in a collision\n\t\t\"\"\"\n did_collide = False\n act_spec = ActuationSpec(actuation)\n did_collide = self.agent.controls.action(\n self.agent.scene_node, action_name, act_spec, apply_filter=True\n )\n\n return did_collide\n\n def _go_to_relative_pose(self, rel_x, rel_y, abs_yaw):\n # clip relative movements beyond 10 micrometer precision\n # this is done to improve determinism, as habitat-sim doesn't\n # seem to precisely move the robot beyond sub milimeter precision anyways\n if abs(rel_x) < 1e-5:\n rel_x = 0\n if abs(rel_y) < 1e-5:\n rel_y = 0\n\n if math.sqrt(rel_x ** 2 + rel_y ** 2) > 0.0:\n # rotate to point to (x, y) point\n action_name = \"turn_left\"\n if rel_y < 0.0:\n action_name = \"turn_right\"\n\n v1 = np.asarray([1, 0], dtype=np.float64)\n v2 = np.asarray([rel_x, rel_y], dtype=np.float64)\n cosine_angle = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))\n angle = np.arccos(cosine_angle)\n\n did_collide = self._act(action_name, math.degrees(angle))\n\n if did_collide:\n print(\"Error: Collision accured while 1st rotating!\")\n return False\n\n # move to (x,y) point\n did_collide = self._act(\"move_forward\", math.sqrt(rel_x ** 2 + rel_y ** 2))\n if did_collide:\n print(\"Error: Collision accured while moving straight!\")\n return False\n # rotate to match the final yaw!\n (cur_x, cur_y, cur_yaw) = self.get_state()\n rel_yaw = abs_yaw - cur_yaw\n\n # clip to micro-degree precision to preserve determinism\n if abs(rel_yaw) < 1e-4:\n rel_yaw = 0\n\n action_name = \"turn_left\"\n if rel_yaw < 0.0:\n action_name = \"turn_right\"\n rel_yaw *= -1\n\n did_collide = self._act(action_name, math.degrees(rel_yaw))\n if did_collide:\n print(\"Error: Collision accured while rotating!\")\n return False\n\n return True\n\n def track_trajectory(self, states, controls, close_loop):\n \"\"\"\n\t\tState trajectory that the robot should track.\n\n\t\t:param states: sequence of (x,y,t) states that the robot should track.\n\t\t:param controls: optionally specify control sequence as well.\n\t\t:param close_loop: whether to close loop on the\n\t\t computed control sequence or not.\n\n\t\t:type states: list\n\t\t:type controls: list\n\t\t:type close_loop: bool\n\n\t\t:return: True if successful; False otherwise (timeout, etc.)\n\t\t:rtype: bool\n\t\t\"\"\"\n raise NotImplementedError\n", "#!/usr/bin/env python\n\n#!/usr/bin/env python\n\n\nimport numpy as np\nfrom gtsam import *\nfrom gpmp2 import *\n\nimport threading\nimport copy\nimport actionlib\nimport sys\nimport math\nfrom scipy import ndimage\n\nimport rospy\nimport tf\nfrom geometry_msgs.msg import Twist, Pose, PoseStamped\nfrom sensor_msgs.msg import JointState\nfrom nav_msgs.msg import Odometry, OccupancyGrid\n\nfrom control_msgs.msg import (\n FollowJointTrajectoryAction,\n FollowJointTrajectoryGoal,\n)\nfrom trajectory_msgs.msg import JointTrajectoryPoint\n\n\n# TOPIC NAMES\nodom_topic = \"/odom\"\ncmd_vel_topic = \"/cmd_vel_mux/input/navi\"\naction_topic = \"/gpmp_ctrl\"\nocc_grid_topic = \"/move_base/local_costmap/costmap\"\n\n\nclass RobotState(object):\n \"\"\"A simple robot state object to keep track of locobot's base state\"\"\"\n\n def __init__(self):\n self.pose = None\n self.vel = None\n\n\nclass Robot(object):\n \"\"\"\n\n A simple locobot interface object which is PyRobot independent.\n Functions:\n Subscribes to robot state,\n Subscribe to occupancy grid and builds GPMP SDF\n Publishes gpmp trajectory to the trajectory action server.\n\n \"\"\"\n\n def __init__(self):\n\n self.ctrl_pub = rospy.Publisher(cmd_vel_topic, Twist, queue_size=1)\n self.state = RobotState()\n self.sdf = None\n self.sdf_lock = threading.RLock()\n\n rospy.Subscriber(odom_topic, Odometry, self._odometry_callback)\n\n rospy.Subscriber(occ_grid_topic, OccupancyGrid, self._occ_grid_callback)\n\n self.traj_client_ = actionlib.SimpleActionClient(\n \"/turtle/base_controller/trajectory\", FollowJointTrajectoryAction,\n )\n\n server_up = self.traj_client_.wait_for_server(timeout=rospy.Duration(10.0))\n if not server_up:\n rospy.logerr(\n \"Timed out waiting for Joint Trajectory\"\n \" Action Server to connect. Start the action server\"\n \" before running example.\"\n )\n rospy.signal_shutdown(\"Timed out waiting for Action Server\")\n sys.exit(1)\n\n def _occ_grid_callback(self, msg):\n cols = msg.info.width\n rows = msg.info.height\n origin_x = msg.info.origin.position.x\n origin_y = msg.info.origin.position.y\n cell_size = msg.info.resolution\n occ_map = np.zeros((rows, cols))\n\n for i in range(rows):\n for j in range(cols):\n k = i * cols + j\n if msg.data[k] > 0:\n occ_map[i][j] = 1\n else:\n occ_map[i][j] = 0\n\n # Signed Distance field\n origin_point2 = Point2(origin_x, origin_y)\n field = signedDistanceField2D(occ_map, cell_size)\n sdf = PlanarSDF(origin_point2, cell_size, field)\n\n self.sdf_lock.acquire()\n self.sdf = sdf\n self.sdf_lock.release()\n\n def _odometry_callback(self, msg):\n\n x = msg.pose.pose.position.x\n y = msg.pose.pose.position.y\n orientation_q = msg.pose.pose.orientation\n orientation_list = [\n orientation_q.x,\n orientation_q.y,\n orientation_q.z,\n orientation_q.w,\n ]\n (roll, pitch, yaw) = tf.transformations.euler_from_quaternion(orientation_list)\n x_vel = msg.twist.twist.linear.x\n y_vel = 0.0\n ang_vel = msg.twist.twist.angular.z\n self.state.pose = np.asarray([x, y, yaw])\n self.state.vel = np.asarray([x_vel, y_vel, ang_vel])\n\n def stop(self):\n rospy.loginfo(\"Stopping base!\")\n msg = Twist()\n msg.linear.x = 0\n msg.angular.z = 0\n self.ctrl_pub.publish(msg)\n\n def get_robot_state(self):\n return self.state.pose, self.state.vel\n\n def get_local_frame_vels(self, temp_vel, yaw):\n # temp_vel is velocity in global frame.\n\n vel = np.asarray([1.0,1.0,1.0])\n\n vel[0] = temp_vel[0] * np.cos(yaw) + temp_vel[1]* np.sin(yaw)\n vel[1] = -1.0 * temp_vel[0] * np.sin(yaw) + temp_vel[1] * np.cos(yaw)\n vel[2] = temp_vel[2]\n\n return vel\n \n \n def executeTrajectory(self, result, params):\n\n DOF = 3\n traj_ = FollowJointTrajectoryGoal()\n point = JointTrajectoryPoint()\n\n for i in range(params.total_time_step):\n\n pose = result.atVector(symbol(ord(\"x\"), i))\n vel = self.get_local_frame_vels(result.atVector(symbol(ord(\"v\"), i)), \n pose[2])\n\n point = JointTrajectoryPoint()\n\n for j in range(3):\n point.positions.append(pose[j])\n point.velocities.append(vel[j])\n\n point.time_from_start = rospy.Duration(\n i * params.delta_t\n ) # /(check_inter+1))\n traj_.trajectory.points.append(point)\n\n traj_.trajectory.header.stamp = rospy.Time.now()\n\n self.traj_client_.cancel_goal()\n self.traj_client_.send_goal(traj_)\n # self.traj_client_.wait_for_result()\n\n\ndef signedDistanceField2D(ground_truth_map, cell_size):\n # SIGNEDDISTANCEFIELD2D 2D signed distance field\n # Given a ground truth 2D map defined in Matrix in 0-1,\n # calculate 2D signed distance field, which is defined as a matrix\n # map matrix and signed distance field matrix have the same resolution.\n #\n # Usage: field = SIGNEDDISTANCEFIELD2D(ground_truth_map, cell_siz)\n # @map evidence grid from dataset, map use 0 show open area, 1 show objects.\n # @cell_size cell sizeto given metric information\n #\n # Output:\n # @field sdf, row is Y, col is X\n\n # regularize unknow area to open area\n cur_map = ground_truth_map > 0.75\n cur_map = cur_map.astype(int)\n\n if np.amax(cur_map) is 0:\n return np.ones(ground_truth_map.shape) * 1000\n\n # inverse map\n inv_map = 1 - cur_map\n\n # get signed distance from map and inverse map\n # since bwdist(foo) = ndimage.distance_transform_edt(1-foo)\n map_dist = ndimage.distance_transform_edt(inv_map)\n inv_map_dist = ndimage.distance_transform_edt(cur_map)\n\n field = map_dist - inv_map_dist\n\n # metric\n field = field * cell_size\n field = field.astype(float)\n\n return field\n\n\ndef get_plan(start_conf_val, start_vel, end_conf_val, end_vel, sdf, params):\n\n start_conf = start_conf_val\n end_conf = end_conf_val\n\n avg_vel = (end_conf_val - start_conf_val / params.total_time_step) / params.delta_t\n\n # plot param\n\n # init optimization\n graph = NonlinearFactorGraph()\n init_values = Values()\n\n for i in range(0, params.total_time_step + 1):\n key_pos = symbol(ord(\"x\"), i)\n key_vel = symbol(ord(\"v\"), i)\n\n #% initialize as straight line in conf space\n pose = start_conf_val\n vel = avg_vel\n\n init_values.insert(key_pos, pose)\n init_values.insert(key_vel, vel)\n\n #% start/end priors\n if i == 0:\n graph.push_back(PriorFactorVector(key_pos, start_conf, params.pose_fix))\n graph.push_back(PriorFactorVector(key_vel, start_vel, params.vel_fix))\n elif i == params.total_time_step:\n graph.push_back(PriorFactorVector(key_pos, end_conf, params.pose_fix_goal))\n graph.push_back(PriorFactorVector(key_vel, end_vel, params.vel_fix_goal))\n\n graph.add(VehicleDynamicsFactorVector(key_pos, key_vel, params.cost_sigma))\n\n # GP priors and cost factor\n if i > 0:\n # graph.push_back(PriorFactorVector(key_pos, end_conf, params.pose_fix_goal))\n # graph.push_back(PriorFactorVector(key_vel, end_vel, params.vel_fix_goal))\n key_pos1 = symbol(ord(\"x\"), i - 1)\n key_pos2 = symbol(ord(\"x\"), i)\n key_vel1 = symbol(ord(\"v\"), i - 1)\n key_vel2 = symbol(ord(\"v\"), i)\n\n temp = GaussianProcessPriorLinear(\n key_pos1, key_vel1, key_pos2, key_vel2, params.delta_t, params.Qc_model\n )\n graph.push_back(temp)\n\n #% cost factor\n graph.push_back(\n ObstaclePlanarSDFFactorPointRobot(\n key_pos,\n params.pR_model,\n sdf,\n params.cost_sigma,\n params.epsilon_dist,\n )\n )\n\n #% GP cost factor\n if params.use_GP_inter and params.check_inter > 0:\n for j in range(1, params.check_inter + 1):\n tau = j * (params.total_time_sec / params.total_check_step)\n graph.add(\n ObstaclePlanarSDFFactorGPPointRobot(\n key_pos1,\n key_vel1,\n key_pos2,\n key_vel2,\n params.pR_model,\n sdf,\n params.cost_sigma,\n params.epsilon_dist,\n params.Qc_model,\n params.delta_t,\n tau,\n )\n )\n\n if params.use_trustregion_opt:\n parameters = DoglegParams()\n optimizer = DoglegOptimizer(graph, init_values, parameters)\n else:\n parameters = GaussNewtonParams()\n optimizer = GaussNewtonOptimizer(graph, init_values, parameters)\n\n print(\"Initial Error = %d\\n\", graph.error(init_values))\n\n optimizer.optimizeSafely()\n result = optimizer.values()\n\n print(\"Final Error = %d\\n\", graph.error(result))\n\n res_flag = True\n if graph.error(result) > params.acceptable_error_threshold:\n res_flag = False\n return result, res_flag\n\n\nclass Parameters(object): # TODO: read from yaml file or rosparams\n # settings\n total_time_sec = 5.0\n total_time_step = 50\n total_check_step = 50.0\n delta_t = total_time_sec / total_time_step\n check_inter = int(total_check_step / total_time_step - 1)\n\n use_GP_inter = True\n\n # point robot model\n pR = PointRobot(3, 1)\n spheres_data = np.asarray([0.0, 0.0, 0.0, 0.0, 1.5])\n nr_body = spheres_data.shape[0]\n sphere_vec = BodySphereVector()\n sphere_vec.push_back(\n BodySphere(spheres_data[0], spheres_data[4], Point3(spheres_data[1:4]))\n )\n pR_model = PointRobotModel(pR, sphere_vec)\n\n # GP\n Qc = np.identity(pR_model.dof())\n Qc_model = noiseModel_Gaussian.Covariance(Qc)\n\n # Obstacle avoid settings\n cost_sigma = 0.005\n epsilon_dist = 0.1\n\n # prior to start/goal\n pose_fix = pose_fix_goal = noiseModel_Isotropic.Sigma(pR_model.dof(), 0.0001)\n vel_fix = vel_fix_goal = noiseModel_Isotropic.Sigma(pR_model.dof(), 0.0001)\n\n use_trustregion_opt = True\n\n pause_time = total_time_sec / total_time_step\n\n # Fixed window params\n goal_region_threshold = 0.1\n acceptable_error_threshold = 400\n sigma_goal = 4\n\n opt_timeout = 0.2\n\n\nclass GPMPController(object):\n \"\"\"docstring for GPMPController\"\"\"\n\n def __init__(self, robot, params, action_name):\n\n self.robot = robot\n self.params = params\n self._action_name = action_name\n # Action server for the pyrobot client\n\n self._as = actionlib.SimpleActionServer(\n self._action_name,\n FollowJointTrajectoryAction,\n execute_cb=self.execute_cb,\n auto_start=False,\n )\n self._as.start()\n\n def execute_cb(self, goal):\n\n # start and end conf\n end_conf_val = np.asarray(goal.trajectory.points[0].positions)\n end_vel = np.asarray(goal.trajectory.points[0].velocities)\n goal_region_threshold = goal.goal_tolerance[0].position\n duration = goal.goal_time_tolerance.to_sec()\n\n print(\"Received goal\", end_conf_val, end_vel)\n start_time = rospy.get_time()\n curstate_val, curstate_vel = self.robot.get_robot_state()\n init_distance = np.linalg.norm(curstate_val - end_conf_val)\n while np.linalg.norm(curstate_val - end_conf_val) > goal_region_threshold:\n\n # Timeout\n if rospy.get_time() - start_time > duration:\n rospy.logerr(\n \"The controller timedout trying to reach the goal.\"\n \" Consider increasing the time\"\n )\n self.robot.traj_client_.cancel_goal()\n self.robot.stop()\n self._as.set_aborted()\n return\n\n if self._as.is_preempt_requested():\n rospy.logwarn(\n \"############## %s: Preempted ####################\"\n % self._action_name\n )\n self._as.set_preempted()\n # Note: The trajectory is not cancelled for preempt as updated trajectory would be given\n return\n\n # Goal prior factors\n self.params.pose_fix_goal = noiseModel_Isotropic.Sigma(\n 3,\n self.params.sigma_goal\n * np.linalg.norm(curstate_val - end_conf_val)\n / init_distance,\n )\n self.params.vel_fix_goal = noiseModel_Isotropic.Sigma(\n 3,\n self.params.sigma_goal\n * np.linalg.norm(curstate_val - end_conf_val)\n / init_distance,\n )\n\n self.robot.sdf_lock.acquire()\n sdf = self.robot.sdf\n self.robot.sdf_lock.release()\n\n result, res_flag = get_plan(\n curstate_val, curstate_vel, end_conf_val, end_vel, sdf, self.params\n )\n\n if not res_flag:\n rospy.logerr(\"GPMP optimizer failed to produce an acceptable plan\")\n self.robot.traj_client_.cancel_goal()\n self.robot.stop()\n self._as.set_aborted()\n return\n\n self.robot.executeTrajectory(result, self.params)\n rospy.sleep(0.5)\n\n curstate_val, curstate_vel = self.robot.get_robot_state()\n print(\"Current State: \", curstate_val, curstate_vel)\n print(\"Error\", np.linalg.norm(curstate_val - end_conf_val))\n\n self.robot.traj_client_.wait_for_result() # TODO: Absorb this into the treshold\n\n self._as.set_succeeded()\n\n\ndef main():\n\n try:\n rospy.init_node(\"gpmp_controller_server\", anonymous=True)\n except rospy.exceptions.ROSException:\n rospy.logwarn(\"ROS node [gpmp_controller] has already been initialized\")\n\n robot = Robot()\n while robot.sdf is None:\n rospy.logwarn(\"Waiting for robot SDF!!\")\n rospy.sleep(0.2)\n params = Parameters()\n\n gpmp_controller = GPMPController(robot, params, \"/gpmp_controller\")\n\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.dot", "numpy.asarray", "numpy.cos", "numpy.arccos", "numpy.sin", "numpy.linalg.norm", "numpy.array" ], [ "numpy.amax", "numpy.asarray", "scipy.ndimage.distance_transform_edt", "numpy.linalg.norm", "numpy.cos", "numpy.ones", "numpy.sin", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
arkottke/MapIO
[ "dd6e347dce2d65b7bd4c489a03d8883d0e4210fc" ]
[ "test/shake_test.py" ]
[ "#!/usr/bin/env python\n\n#python 3 compatibility\nfrom __future__ import print_function\n\n#stdlib imports\nfrom xml.dom import minidom\nfrom datetime import datetime\nfrom collections import OrderedDict\nimport re\nimport sys\nimport tempfile\nimport time\nimport shutil\n\nif sys.version_info.major == 2:\n import StringIO\nelse:\n from io import StringIO\nimport os.path\n\n#hack the path so that I can debug these functions if I need to\nhomedir = os.path.dirname(os.path.abspath(__file__)) #where is this script?\nmapiodir = os.path.abspath(os.path.join(homedir,'..'))\nsys.path.insert(0,mapiodir) #put this at the front of the system path, ignoring any installed mapio stuff\n\n#third party\nfrom mapio.shake import ShakeGrid\nfrom mapio.gridbase import Grid\nfrom mapio.multiple import MultiGrid\nfrom mapio.dataset import DataSetException\nfrom mapio.grid2d import Grid2D\nfrom mapio.geodict import GeoDict\nimport numpy as np\n\ndef test_modify():\n print('Testing ShakeGrid interpolate() method...')\n geodict = GeoDict({'xmin':0.5,'xmax':6.5,'ymin':1.5,'ymax':6.5,'dx':1.0,'dy':1.0,'ny':6,'nx':7})\n data = np.arange(14,56).reshape(6,7)\n layers = OrderedDict()\n layers['pga'] = data\n shakeDict = {'event_id':'usabcd1234',\n 'shakemap_id':'usabcd1234',\n 'shakemap_version':1,\n 'code_version':'4.0',\n 'process_timestamp':datetime.utcnow(),\n 'shakemap_originator':'us',\n 'map_status':'RELEASED',\n 'shakemap_event_type':'ACTUAL'}\n eventDict = {'event_id':'usabcd1234',\n 'magnitude':7.6,\n 'depth':1.4,\n 'lat':2.0,\n 'lon':2.0,\n 'event_timestamp':datetime.utcnow(),\n 'event_network':'us',\n 'event_description':'sample event'}\n uncDict = {'pga':(0.0,0)}\n shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)\n rdata = np.random.rand(data.shape[0],data.shape[1])\n shake.setLayer('pga',rdata)\n newdata = shake.getLayer('pga').getData()\n np.testing.assert_almost_equal(rdata,newdata)\n\ndef test_interpolate():\n print('Testing ShakeGrid interpolate() method...')\n geodict = GeoDict({'xmin':0.5,'xmax':6.5,'ymin':1.5,'ymax':6.5,'dx':1.0,'dy':1.0,'ny':6,'nx':7})\n data = np.arange(14,56).reshape(6,7)\n layers = OrderedDict()\n layers['pga'] = data\n shakeDict = {'event_id':'usabcd1234',\n 'shakemap_id':'usabcd1234',\n 'shakemap_version':1,\n 'code_version':'4.0',\n 'process_timestamp':datetime.utcnow(),\n 'shakemap_originator':'us',\n 'map_status':'RELEASED',\n 'shakemap_event_type':'ACTUAL'}\n eventDict = {'event_id':'usabcd1234',\n 'magnitude':7.6,\n 'depth':1.4,\n 'lat':2.0,\n 'lon':2.0,\n 'event_timestamp':datetime.utcnow(),\n 'event_network':'us',\n 'event_description':'sample event'}\n uncDict = {'pga':(0.0,0)}\n shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)\n sampledict = GeoDict({'xmin':3.0,'xmax':4.0,\n 'ymin':3.0,'ymax':4.0,\n 'dx':1.0,'dy':1.0,\n 'ny':2,'nx':2})\n shake2 = shake.interpolateToGrid(sampledict,method='linear')\n output = np.array([[34.,35.],[41.,42.]])\n np.testing.assert_almost_equal(output,shake2.getLayer('pga').getData())\n print('Passed test of ShakeGrid interpolate() method.')\n\ndef test_read():\n xmlfile = os.path.join(homedir,'data','northridge.xml')\n tdir = tempfile.mkdtemp()\n testfile = os.path.join(tdir,'test.xml')\n try:\n shakegrid = ShakeGrid.load(xmlfile,adjust='res')\n t1 = time.time()\n shakegrid.save(testfile)\n t2 = time.time()\n print('Saving shakemap took %.2f seconds' % (t2-t1))\n except Exception as error:\n print('Failed to read grid.xml format file \"%s\". Error \"%s\".' % (xmlfile,str(error)))\n assert 0 == 1\n finally:\n if os.path.isdir(tdir):\n shutil.rmtree(tdir)\n \ndef test_save():\n tdir = tempfile.mkdtemp()\n testfile = os.path.join(tdir,'test.xml')\n try:\n print('Testing save/read functionality for shakemap grids...')\n pga = np.arange(0,16,dtype=np.float32).reshape(4,4)\n pgv = np.arange(1,17,dtype=np.float32).reshape(4,4)\n mmi = np.arange(2,18,dtype=np.float32).reshape(4,4)\n geodict = GeoDict({'xmin':0.5,'xmax':3.5,\n 'ymin':0.5,'ymax':3.5,\n 'dx':1.0,'dy':1.0,\n 'ny':4,'nx':4})\n layers = OrderedDict()\n layers['pga'] = pga\n layers['pgv'] = pgv\n layers['mmi'] = mmi\n shakeDict = {'event_id':'usabcd1234',\n 'shakemap_id':'usabcd1234',\n 'shakemap_version':1,\n 'code_version':'4.0',\n 'process_timestamp':datetime.utcnow(),\n 'shakemap_originator':'us',\n 'map_status':'RELEASED',\n 'shakemap_event_type':'ACTUAL'}\n eventDict = {'event_id':'usabcd1234',\n 'magnitude':7.6,\n 'depth':1.4,\n 'lat':2.0,\n 'lon':2.0,\n 'event_timestamp':datetime.utcnow(),\n 'event_network':'us',\n 'event_description':'sample event'}\n uncDict = {'pga':(0.0,0),\n 'pgv':(0.0,0),\n 'mmi':(0.0,0)}\n shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)\n \n print('Testing save/read functionality...')\n shake.save(testfile,version=3)\n shake2 = ShakeGrid.load(testfile)\n for layer in ['pga','pgv','mmi']:\n tdata = shake2.getLayer(layer).getData()\n np.testing.assert_almost_equal(tdata,layers[layer])\n\n print('Passed save/read functionality for shakemap grids.')\n\n print('Testing getFileGeoDict method...')\n fgeodict = ShakeGrid.getFileGeoDict(testfile)\n print('Passed save/read functionality for shakemap grids.')\n \n print('Testing loading with bounds (no resampling or padding)...')\n sampledict = GeoDict({'xmin':-0.5,'xmax':3.5,\n 'ymin':-0.5,'ymax':3.5,\n 'dx':1.0,'dy':1.0,\n 'ny':5,'nx':5})\n shake3 = ShakeGrid.load(testfile,samplegeodict=sampledict,\n resample=False,doPadding=False,padValue=np.nan)\n tdata = shake3.getLayer('pga').getData()\n np.testing.assert_almost_equal(tdata,layers['pga'])\n\n print('Passed loading with bounds (no resampling or padding)...')\n\n print('Testing loading shakemap with padding, no resampling...')\n newdict = GeoDict({'xmin':-0.5,'xmax':4.5,\n 'ymin':-0.5,'ymax':4.5,\n 'dx':1.0,'dy':1.0,\n 'ny':6,'nx':6})\n shake4 = ShakeGrid.load(testfile,samplegeodict=newdict,\n resample=False,doPadding=True,padValue=np.nan)\n output = np.array([[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan],\n [np.nan,0.0,1.0,2.0,3.0,np.nan],\n [np.nan,4.0,5.0,6.0,7.0,np.nan],\n [np.nan,8.0,9.0,10.0,11.0,np.nan],\n [np.nan,12.0,13.0,14.0,15.0,np.nan],\n [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]])\n tdata = shake4.getLayer('pga').getData()\n np.testing.assert_almost_equal(tdata,output)\n print('Passed loading shakemap with padding, no resampling...')\n\n #make a bigger grid\n pga = np.arange(0,36,dtype=np.float32).reshape(6,6)\n pgv = np.arange(1,37,dtype=np.float32).reshape(6,6)\n mmi = np.arange(2,38,dtype=np.float32).reshape(6,6)\n layers = OrderedDict()\n layers['pga'] = pga\n layers['pgv'] = pgv\n layers['mmi'] = mmi\n geodict = GeoDict({'xmin':0.5,'xmax':5.5,\n 'ymin':0.5,'ymax':5.5,\n 'dx':1.0,'dy':1.0,\n 'ny':6,'nx':6})\n shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)\n shake.save(testfile,version=3)\n\n print('Testing resampling, no padding...')\n littledict = GeoDict({'xmin':2.0,'xmax':4.0,\n 'ymin':2.0,'ymax':4.0,\n 'dx':1.0,'dy':1.0,\n 'ny':3,'nx':3})\n shake5 = ShakeGrid.load(testfile,samplegeodict=littledict,resample=True,doPadding=False,padValue=np.nan)\n output = np.array([[10.5,11.5,12.5],\n [16.5,17.5,18.5],\n [22.5,23.5,24.5]])\n tdata = shake5.getLayer('pga').getData()\n np.testing.assert_almost_equal(tdata,output)\n print('Passed resampling, no padding...')\n\n print('Testing resampling and padding...')\n pga = np.arange(0,16,dtype=np.float32).reshape(4,4)\n pgv = np.arange(1,17,dtype=np.float32).reshape(4,4)\n mmi = np.arange(2,18,dtype=np.float32).reshape(4,4)\n geodict = GeoDict({'xmin':0.5,'ymax':3.5,\n 'ymin':0.5,'xmax':3.5,\n 'dx':1.0,'dy':1.0,\n 'ny':4,'nx':4})\n layers = OrderedDict()\n layers['pga'] = pga\n layers['pgv'] = pgv\n layers['mmi'] = mmi\n shake = ShakeGrid(layers,geodict,eventDict,shakeDict,uncDict)\n shake.save(testfile,version=3)\n bigdict = GeoDict({'xmin':0.0,'xmax':4.0,\n 'ymin':0.0,'ymax':4.0,\n 'dx':1.0,'dy':1.0,\n 'ny':5,'nx':5})\n shake6 = ShakeGrid.load(testfile,samplegeodict=bigdict,resample=True,doPadding=True,padValue=np.nan)\n tdata = shake6.getLayer('pga').getData()\n output = np.array([[np.nan,np.nan,np.nan,np.nan,np.nan],\n [np.nan,2.5,3.5,4.5,np.nan],\n [np.nan,6.5,7.5,8.5,np.nan],\n [np.nan,10.5,11.5,12.5,np.nan],\n [np.nan,np.nan,np.nan,np.nan,np.nan]])\n np.testing.assert_almost_equal(tdata,output)\n print('Passed resampling and padding...')\n except Exception as error:\n print('Failed to read grid.xml format file \"%s\". Error \"%s\".' % (xmlfile,str(error)))\n assert 0 == 1\n finally:\n if os.path.isdir(tdir):\n shutil.rmtree(tdir)\n\nif __name__ == '__main__':\n test_modify()\n test_interpolate()\n test_read()\n test_save()\n \n" ]
[ [ "numpy.arange", "numpy.testing.assert_almost_equal", "numpy.array", "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
palash247/modin
[ "ffea4ee2d3556dc48c05dac7abb54b62c66f3153", "3f1e275b67a760f09db6944600c4b7f5e601cbde", "3f1e275b67a760f09db6944600c4b7f5e601cbde" ]
[ "modin/pandas/test/dataframe/test_map_metadata.py", "asv_bench/benchmarks/io/csv.py", "modin/experimental/pandas/test/test_io_exp.py" ]
[ "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport pytest\nimport numpy as np\nimport pandas\nfrom pandas.testing import assert_index_equal\nimport matplotlib\nimport modin.pandas as pd\nfrom modin.utils import get_current_backend\n\nfrom modin.pandas.test.utils import (\n random_state,\n RAND_LOW,\n RAND_HIGH,\n df_equals,\n df_is_empty,\n arg_keys,\n name_contains,\n test_data,\n test_data_values,\n test_data_keys,\n test_data_with_duplicates_values,\n test_data_with_duplicates_keys,\n numeric_dfs,\n test_func_keys,\n test_func_values,\n indices_keys,\n indices_values,\n axis_keys,\n axis_values,\n bool_arg_keys,\n bool_arg_values,\n int_arg_keys,\n int_arg_values,\n eval_general,\n create_test_dfs,\n)\nfrom modin.config import NPartitions\n\nNPartitions.put(4)\n\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use(\"Agg\")\n\n\ndef eval_insert(modin_df, pandas_df, **kwargs):\n if \"col\" in kwargs and \"column\" not in kwargs:\n kwargs[\"column\"] = kwargs.pop(\"col\")\n _kwargs = {\"loc\": 0, \"column\": \"New column\"}\n _kwargs.update(kwargs)\n\n eval_general(\n modin_df,\n pandas_df,\n operation=lambda df, **kwargs: df.insert(**kwargs),\n **_kwargs,\n )\n\n\ndef test_indexing():\n modin_df = pd.DataFrame(\n dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=[\"a\", \"b\", \"c\"]\n )\n pandas_df = pandas.DataFrame(\n dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]), index=[\"a\", \"b\", \"c\"]\n )\n\n modin_result = modin_df\n pandas_result = pandas_df\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df[\"b\"]\n pandas_result = pandas_df[\"b\"]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df[[\"b\"]]\n pandas_result = pandas_df[[\"b\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df[[\"b\", \"a\"]]\n pandas_result = pandas_df[[\"b\", \"a\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[\"b\"]\n pandas_result = pandas_df.loc[\"b\"]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[\"b\"]]\n pandas_result = pandas_df.loc[[\"b\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[\"b\", \"a\"]]\n pandas_result = pandas_df.loc[[\"b\", \"a\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[\"b\", \"a\"], [\"a\", \"c\"]]\n pandas_result = pandas_df.loc[[\"b\", \"a\"], [\"a\", \"c\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[:, [\"a\", \"c\"]]\n pandas_result = pandas_df.loc[:, [\"a\", \"c\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[:, [\"c\"]]\n pandas_result = pandas_df.loc[:, [\"c\"]]\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.loc[[]]\n pandas_result = pandas_df.loc[[]]\n df_equals(modin_result, pandas_result)\n\n\ndef test_empty_df():\n df = pd.DataFrame(index=[\"a\", \"b\"])\n df_is_empty(df)\n assert_index_equal(df.index, pd.Index([\"a\", \"b\"]))\n assert len(df.columns) == 0\n\n df = pd.DataFrame(columns=[\"a\", \"b\"])\n df_is_empty(df)\n assert len(df.index) == 0\n assert_index_equal(df.columns, pd.Index([\"a\", \"b\"]))\n\n df = pd.DataFrame()\n df_is_empty(df)\n assert len(df.index) == 0\n assert len(df.columns) == 0\n\n df = pd.DataFrame(index=[\"a\", \"b\"])\n df_is_empty(df)\n assert_index_equal(df.index, pd.Index([\"a\", \"b\"]))\n assert len(df.columns) == 0\n\n df = pd.DataFrame(columns=[\"a\", \"b\"])\n df_is_empty(df)\n assert len(df.index) == 0\n assert_index_equal(df.columns, pd.Index([\"a\", \"b\"]))\n\n df = pd.DataFrame()\n df_is_empty(df)\n assert len(df.index) == 0\n assert len(df.columns) == 0\n\n df = pd.DataFrame()\n pd_df = pandas.DataFrame()\n df[\"a\"] = [1, 2, 3, 4, 5]\n pd_df[\"a\"] = [1, 2, 3, 4, 5]\n df_equals(df, pd_df)\n\n df = pd.DataFrame()\n pd_df = pandas.DataFrame()\n df[\"a\"] = list(\"ABCDEF\")\n pd_df[\"a\"] = list(\"ABCDEF\")\n df_equals(df, pd_df)\n\n df = pd.DataFrame()\n pd_df = pandas.DataFrame()\n df[\"a\"] = pd.Series([1, 2, 3, 4, 5])\n pd_df[\"a\"] = pandas.Series([1, 2, 3, 4, 5])\n df_equals(df, pd_df)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_abs(request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.abs()\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.abs()\n else:\n modin_result = modin_df.abs()\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_add_prefix(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n test_prefix = \"TEST\"\n new_modin_df = modin_df.add_prefix(test_prefix)\n new_pandas_df = pandas_df.add_prefix(test_prefix)\n df_equals(new_modin_df.columns, new_pandas_df.columns)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"testfunc\", test_func_values, ids=test_func_keys)\ndef test_applymap(request, data, testfunc):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(ValueError):\n x = 2\n modin_df.applymap(x)\n\n try:\n pandas_result = pandas_df.applymap(testfunc)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.applymap(testfunc)\n else:\n modin_result = modin_df.applymap(testfunc)\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"testfunc\", test_func_values, ids=test_func_keys)\ndef test_applymap_numeric(request, data, testfunc):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if name_contains(request.node.name, numeric_dfs):\n try:\n pandas_result = pandas_df.applymap(testfunc)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.applymap(testfunc)\n else:\n modin_result = modin_df.applymap(testfunc)\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_add_suffix(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n test_suffix = \"TEST\"\n new_modin_df = modin_df.add_suffix(test_suffix)\n new_pandas_df = pandas_df.add_suffix(test_suffix)\n\n df_equals(new_modin_df.columns, new_pandas_df.columns)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_at(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n key1 = modin_df.columns[0]\n # Scaler\n df_equals(modin_df.at[0, key1], pandas_df.at[0, key1])\n\n # Series\n df_equals(modin_df.loc[0].at[key1], pandas_df.loc[0].at[key1])\n\n # Write Item\n modin_df_copy = modin_df.copy()\n pandas_df_copy = pandas_df.copy()\n modin_df_copy.at[1, key1] = modin_df.at[0, key1]\n pandas_df_copy.at[1, key1] = pandas_df.at[0, key1]\n df_equals(modin_df_copy, pandas_df_copy)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_axes(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n for modin_axis, pd_axis in zip(modin_df.axes, pandas_df.axes):\n assert np.array_equal(modin_axis, pd_axis)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_copy(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n # pandas_df is unused but there so there won't be confusing list comprehension\n # stuff in the pytest.mark.parametrize\n new_modin_df = modin_df.copy()\n\n assert new_modin_df is not modin_df\n if get_current_backend() != \"BaseOnPython\":\n assert np.array_equal(\n new_modin_df._query_compiler._modin_frame._partitions,\n modin_df._query_compiler._modin_frame._partitions,\n )\n assert new_modin_df is not modin_df\n df_equals(new_modin_df, modin_df)\n\n # Shallow copy tests\n modin_df = pd.DataFrame(data)\n modin_df_cp = modin_df.copy(False)\n\n modin_df[modin_df.columns[0]] = 0\n df_equals(modin_df, modin_df_cp)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_dtypes(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.dtypes, pandas_df.dtypes)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"key\", indices_values, ids=indices_keys)\ndef test_get(data, key):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.get(key), pandas_df.get(key))\n df_equals(\n modin_df.get(key, default=\"default\"), pandas_df.get(key, default=\"default\")\n )\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\n \"dummy_na\", bool_arg_values, ids=arg_keys(\"dummy_na\", bool_arg_keys)\n)\[email protected](\n \"drop_first\", bool_arg_values, ids=arg_keys(\"drop_first\", bool_arg_keys)\n)\ndef test_get_dummies(request, data, dummy_na, drop_first):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas.get_dummies(\n pandas_df, dummy_na=dummy_na, drop_first=drop_first\n )\n except Exception as e:\n with pytest.raises(type(e)):\n pd.get_dummies(modin_df, dummy_na=dummy_na, drop_first=drop_first)\n else:\n modin_result = pd.get_dummies(\n modin_df, dummy_na=dummy_na, drop_first=drop_first\n )\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_isna(data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas_df.isna()\n modin_result = modin_df.isna()\n\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_isnull(data):\n pandas_df = pandas.DataFrame(data)\n modin_df = pd.DataFrame(data)\n\n pandas_result = pandas_df.isnull()\n modin_result = modin_df.isnull()\n\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_append(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n data_to_append = {\"append_a\": 2, \"append_b\": 1000}\n\n ignore_idx_values = [True, False]\n\n for ignore in ignore_idx_values:\n try:\n pandas_result = pandas_df.append(data_to_append, ignore_index=ignore)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(data_to_append, ignore_index=ignore)\n else:\n modin_result = modin_df.append(data_to_append, ignore_index=ignore)\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.append(pandas_df.iloc[-1])\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(modin_df.iloc[-1])\n else:\n modin_result = modin_df.append(modin_df.iloc[-1])\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.append(list(pandas_df.iloc[-1]))\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(list(modin_df.iloc[-1]))\n else:\n modin_result = modin_df.append(list(modin_df.iloc[-1]))\n # Pandas has bug where sort=False is ignored\n # (https://github.com/pandas-dev/pandas/issues/35092), but Modin\n # now does the right thing, so for now manually sort to workaround\n # this. Once the Pandas bug is fixed and Modin upgrades to that\n # Pandas release, this sort will cause the test to fail, and the\n # next three lines should be deleted.\n if get_current_backend() != \"BaseOnPython\":\n assert list(modin_result.columns) == list(modin_df.columns) + [0]\n modin_result = modin_result[[0] + sorted(modin_df.columns)]\n df_equals(modin_result, pandas_result)\n\n verify_integrity_values = [True, False]\n\n for verify_integrity in verify_integrity_values:\n try:\n pandas_result = pandas_df.append(\n [pandas_df, pandas_df], verify_integrity=verify_integrity\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append([modin_df, modin_df], verify_integrity=verify_integrity)\n else:\n modin_result = modin_df.append(\n [modin_df, modin_df], verify_integrity=verify_integrity\n )\n df_equals(modin_result, pandas_result)\n\n try:\n pandas_result = pandas_df.append(\n pandas_df, verify_integrity=verify_integrity\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.append(modin_df, verify_integrity=verify_integrity)\n else:\n modin_result = modin_df.append(modin_df, verify_integrity=verify_integrity)\n df_equals(modin_result, pandas_result)\n\n\ndef test_astype():\n td = pandas.DataFrame(test_data[\"int_data\"])[[\"col1\", \"index\", \"col3\", \"col4\"]]\n modin_df = pd.DataFrame(td.values, index=td.index, columns=td.columns)\n expected_df = pandas.DataFrame(td.values, index=td.index, columns=td.columns)\n\n modin_df_casted = modin_df.astype(np.int32)\n expected_df_casted = expected_df.astype(np.int32)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df_casted = modin_df.astype(np.float64)\n expected_df_casted = expected_df.astype(np.float64)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df_casted = modin_df.astype(str)\n expected_df_casted = expected_df.astype(str)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df_casted = modin_df.astype(\"category\")\n expected_df_casted = expected_df.astype(\"category\")\n df_equals(modin_df_casted, expected_df_casted)\n\n dtype_dict = {\"col1\": np.int32, \"index\": np.int64, \"col3\": str}\n modin_df_casted = modin_df.astype(dtype_dict)\n expected_df_casted = expected_df.astype(dtype_dict)\n df_equals(modin_df_casted, expected_df_casted)\n\n # Ignore lint because this is testing bad input\n bad_dtype_dict = {\"index\": np.int32, \"index\": np.int64, \"index\": str} # noqa F601\n modin_df_casted = modin_df.astype(bad_dtype_dict)\n expected_df_casted = expected_df.astype(bad_dtype_dict)\n df_equals(modin_df_casted, expected_df_casted)\n\n modin_df = pd.DataFrame(index=[\"row1\"], columns=[\"col1\"])\n modin_df[\"col1\"][\"row1\"] = 11\n modin_df_casted = modin_df.astype(int)\n expected_df = pandas.DataFrame(index=[\"row1\"], columns=[\"col1\"])\n expected_df[\"col1\"][\"row1\"] = 11\n expected_df_casted = expected_df.astype(int)\n df_equals(modin_df_casted, expected_df_casted)\n\n with pytest.raises(KeyError):\n modin_df.astype({\"not_exists\": np.uint8})\n\n\ndef test_astype_category():\n modin_df = pd.DataFrame(\n {\"col1\": [\"A\", \"A\", \"B\", \"B\", \"A\"], \"col2\": [1, 2, 3, 4, 5]}\n )\n pandas_df = pandas.DataFrame(\n {\"col1\": [\"A\", \"A\", \"B\", \"B\", \"A\"], \"col2\": [1, 2, 3, 4, 5]}\n )\n\n modin_result = modin_df.astype({\"col1\": \"category\"})\n pandas_result = pandas_df.astype({\"col1\": \"category\"})\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n modin_result = modin_df.astype(\"category\")\n pandas_result = pandas_df.astype(\"category\")\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n\ndef test_astype_category_large():\n series_length = 10_000\n modin_df = pd.DataFrame(\n {\n \"col1\": [\"str{0}\".format(i) for i in range(0, series_length)],\n \"col2\": [i for i in range(0, series_length)],\n }\n )\n pandas_df = pandas.DataFrame(\n {\n \"col1\": [\"str{0}\".format(i) for i in range(0, series_length)],\n \"col2\": [i for i in range(0, series_length)],\n }\n )\n\n modin_result = modin_df.astype({\"col1\": \"category\"})\n pandas_result = pandas_df.astype({\"col1\": \"category\"})\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n modin_result = modin_df.astype(\"category\")\n pandas_result = pandas_df.astype(\"category\")\n df_equals(modin_result, pandas_result)\n assert modin_result.dtypes.equals(pandas_result.dtypes)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"axis\", axis_values, ids=axis_keys)\ndef test_clip(request, data, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if name_contains(request.node.name, numeric_dfs):\n ind_len = (\n len(modin_df.index)\n if not pandas.DataFrame()._get_axis_number(axis)\n else len(modin_df.columns)\n )\n # set bounds\n lower, upper = np.sort(random_state.random_integers(RAND_LOW, RAND_HIGH, 2))\n lower_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)\n upper_list = random_state.random_integers(RAND_LOW, RAND_HIGH, ind_len)\n\n # test only upper scalar bound\n modin_result = modin_df.clip(None, upper, axis=axis)\n pandas_result = pandas_df.clip(None, upper, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # test lower and upper scalar bound\n modin_result = modin_df.clip(lower, upper, axis=axis)\n pandas_result = pandas_df.clip(lower, upper, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # test lower and upper list bound on each column\n modin_result = modin_df.clip(lower_list, upper_list, axis=axis)\n pandas_result = pandas_df.clip(lower_list, upper_list, axis=axis)\n df_equals(modin_result, pandas_result)\n\n # test only upper list bound on each column\n modin_result = modin_df.clip(np.nan, upper_list, axis=axis)\n pandas_result = pandas_df.clip(np.nan, upper_list, axis=axis)\n df_equals(modin_result, pandas_result)\n\n with pytest.raises(ValueError):\n modin_df.clip(lower=[1, 2, 3], axis=None)\n\n\ndef test_drop():\n frame_data = {\"A\": [1, 2, 3, 4], \"B\": [0, 1, 2, 3]}\n simple = pandas.DataFrame(frame_data)\n modin_simple = pd.DataFrame(frame_data)\n df_equals(modin_simple.drop(\"A\", axis=1), simple[[\"B\"]])\n df_equals(modin_simple.drop([\"A\", \"B\"], axis=\"columns\"), simple[[]])\n df_equals(modin_simple.drop([0, 1, 3], axis=0), simple.loc[[2], :])\n df_equals(modin_simple.drop([0, 3], axis=\"index\"), simple.loc[[1, 2], :])\n\n pytest.raises(ValueError, modin_simple.drop, 5)\n pytest.raises(ValueError, modin_simple.drop, \"C\", 1)\n pytest.raises(ValueError, modin_simple.drop, [1, 5])\n pytest.raises(ValueError, modin_simple.drop, [\"A\", \"C\"], 1)\n\n # errors = 'ignore'\n df_equals(modin_simple.drop(5, errors=\"ignore\"), simple)\n df_equals(modin_simple.drop([0, 5], errors=\"ignore\"), simple.loc[[1, 2, 3], :])\n df_equals(modin_simple.drop(\"C\", axis=1, errors=\"ignore\"), simple)\n df_equals(modin_simple.drop([\"A\", \"C\"], axis=1, errors=\"ignore\"), simple[[\"B\"]])\n\n # non-unique\n nu_df = pandas.DataFrame(\n zip(range(3), range(-3, 1), list(\"abc\")), columns=[\"a\", \"a\", \"b\"]\n )\n modin_nu_df = pd.DataFrame(nu_df)\n df_equals(modin_nu_df.drop(\"a\", axis=1), nu_df[[\"b\"]])\n df_equals(modin_nu_df.drop(\"b\", axis=\"columns\"), nu_df[\"a\"])\n df_equals(modin_nu_df.drop([]), nu_df)\n\n nu_df = nu_df.set_index(pandas.Index([\"X\", \"Y\", \"X\"]))\n nu_df.columns = list(\"abc\")\n modin_nu_df = pd.DataFrame(nu_df)\n df_equals(modin_nu_df.drop(\"X\", axis=\"rows\"), nu_df.loc[[\"Y\"], :])\n df_equals(modin_nu_df.drop([\"X\", \"Y\"], axis=0), nu_df.loc[[], :])\n\n # inplace cache issue\n frame_data = random_state.randn(10, 3)\n df = pandas.DataFrame(frame_data, columns=list(\"abc\"))\n modin_df = pd.DataFrame(frame_data, columns=list(\"abc\"))\n expected = df[~(df.b > 0)]\n modin_df.drop(labels=df[df.b > 0].index, inplace=True)\n df_equals(modin_df, expected)\n\n midx = pd.MultiIndex(\n levels=[[\"lama\", \"cow\", \"falcon\"], [\"speed\", \"weight\", \"length\"]],\n codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]],\n )\n df = pd.DataFrame(\n index=midx,\n columns=[\"big\", \"small\"],\n data=[\n [45, 30],\n [200, 100],\n [1.5, 1],\n [30, 20],\n [250, 150],\n [1.5, 0.8],\n [320, 250],\n [1, 0.8],\n [0.3, 0.2],\n ],\n )\n with pytest.warns(UserWarning):\n df.drop(index=\"length\", level=1)\n\n\ndef test_drop_api_equivalence():\n # equivalence of the labels/axis and index/columns API's\n frame_data = [[1, 2, 3], [3, 4, 5], [5, 6, 7]]\n\n modin_df = pd.DataFrame(frame_data, index=[\"a\", \"b\", \"c\"], columns=[\"d\", \"e\", \"f\"])\n\n modin_df1 = modin_df.drop(\"a\")\n modin_df2 = modin_df.drop(index=\"a\")\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop(\"d\", 1)\n modin_df2 = modin_df.drop(columns=\"d\")\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop(labels=\"e\", axis=1)\n modin_df2 = modin_df.drop(columns=\"e\")\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop([\"a\"], axis=0)\n modin_df2 = modin_df.drop(index=[\"a\"])\n df_equals(modin_df1, modin_df2)\n\n modin_df1 = modin_df.drop([\"a\"], axis=0).drop([\"d\"], axis=1)\n modin_df2 = modin_df.drop(index=[\"a\"], columns=[\"d\"])\n df_equals(modin_df1, modin_df2)\n\n with pytest.raises(ValueError):\n modin_df.drop(labels=\"a\", index=\"b\")\n\n with pytest.raises(ValueError):\n modin_df.drop(labels=\"a\", columns=\"b\")\n\n with pytest.raises(ValueError):\n modin_df.drop(axis=1)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_drop_transpose(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n modin_result = modin_df.T.drop(columns=[0, 1, 2])\n pandas_result = pandas_df.T.drop(columns=[0, 1, 2])\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.drop(index=[\"col3\", \"col1\"])\n pandas_result = pandas_df.T.drop(index=[\"col3\", \"col1\"])\n df_equals(modin_result, pandas_result)\n\n modin_result = modin_df.T.drop(columns=[0, 1, 2], index=[\"col3\", \"col1\"])\n pandas_result = pandas_df.T.drop(columns=[0, 1, 2], index=[\"col3\", \"col1\"])\n df_equals(modin_result, pandas_result)\n\n\ndef test_droplevel():\n df = (\n pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])\n .set_index([0, 1])\n .rename_axis([\"a\", \"b\"])\n )\n df.columns = pd.MultiIndex.from_tuples(\n [(\"c\", \"e\"), (\"d\", \"f\")], names=[\"level_1\", \"level_2\"]\n )\n df.droplevel(\"a\")\n df.droplevel(\"level_2\", axis=1)\n\n\[email protected](\n \"data\", test_data_with_duplicates_values, ids=test_data_with_duplicates_keys\n)\[email protected](\n \"keep\", [\"last\", \"first\", False], ids=[\"last\", \"first\", \"False\"]\n)\[email protected](\n \"subset\",\n [None, \"col1\", \"name\", (\"col1\", \"col3\"), [\"col1\", \"col3\", \"col7\"]],\n ids=[\"None\", \"string\", \"name\", \"tuple\", \"list\"],\n)\ndef test_drop_duplicates(data, keep, subset):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset)\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset)\n else:\n df_equals(\n pandas_df.drop_duplicates(keep=keep, inplace=False, subset=subset),\n modin_df.drop_duplicates(keep=keep, inplace=False, subset=subset),\n )\n\n try:\n pandas_results = pandas_df.drop_duplicates(\n keep=keep, inplace=True, subset=subset\n )\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)\n else:\n modin_results = modin_df.drop_duplicates(keep=keep, inplace=True, subset=subset)\n df_equals(modin_results, pandas_results)\n\n\ndef test_drop_duplicates_with_missing_index_values():\n data = {\n \"columns\": [\"value\", \"time\", \"id\"],\n \"index\": [\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n 12,\n 13,\n 14,\n 15,\n 20,\n 21,\n 22,\n 23,\n 24,\n 25,\n 26,\n 27,\n 32,\n 33,\n 34,\n 35,\n 36,\n 37,\n 38,\n 39,\n 40,\n 41,\n ],\n \"data\": [\n [\"3\", 1279213398000.0, 88.0],\n [\"3\", 1279204682000.0, 88.0],\n [\"0\", 1245772835000.0, 448.0],\n [\"0\", 1270564258000.0, 32.0],\n [\"0\", 1267106669000.0, 118.0],\n [\"7\", 1300621123000.0, 5.0],\n [\"0\", 1251130752000.0, 957.0],\n [\"0\", 1311683506000.0, 62.0],\n [\"9\", 1283692698000.0, 89.0],\n [\"9\", 1270234253000.0, 64.0],\n [\"0\", 1285088818000.0, 50.0],\n [\"0\", 1218212725000.0, 695.0],\n [\"2\", 1383933968000.0, 348.0],\n [\"0\", 1368227625000.0, 257.0],\n [\"1\", 1454514093000.0, 446.0],\n [\"1\", 1428497427000.0, 134.0],\n [\"1\", 1459184936000.0, 568.0],\n [\"1\", 1502293302000.0, 599.0],\n [\"1\", 1491833358000.0, 829.0],\n [\"1\", 1485431534000.0, 806.0],\n [\"8\", 1351800505000.0, 101.0],\n [\"0\", 1357247721000.0, 916.0],\n [\"0\", 1335804423000.0, 370.0],\n [\"24\", 1327547726000.0, 720.0],\n [\"0\", 1332334140000.0, 415.0],\n [\"0\", 1309543100000.0, 30.0],\n [\"18\", 1309541141000.0, 30.0],\n [\"0\", 1298979435000.0, 48.0],\n [\"14\", 1276098160000.0, 59.0],\n [\"0\", 1233936302000.0, 109.0],\n ],\n }\n\n pandas_df = pandas.DataFrame(\n data[\"data\"], index=data[\"index\"], columns=data[\"columns\"]\n )\n modin_df = pd.DataFrame(data[\"data\"], index=data[\"index\"], columns=data[\"columns\"])\n modin_result = modin_df.sort_values([\"id\", \"time\"]).drop_duplicates([\"id\"])\n pandas_result = pandas_df.sort_values([\"id\", \"time\"]).drop_duplicates([\"id\"])\n df_equals(modin_result, pandas_result)\n\n\ndef test_drop_duplicates_after_sort():\n data = [\n {\"value\": 1, \"time\": 2},\n {\"value\": 1, \"time\": 1},\n {\"value\": 2, \"time\": 1},\n {\"value\": 2, \"time\": 2},\n ]\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n modin_result = modin_df.sort_values([\"value\", \"time\"]).drop_duplicates([\"value\"])\n pandas_result = pandas_df.sort_values([\"value\", \"time\"]).drop_duplicates([\"value\"])\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"axis\", axis_values, ids=axis_keys)\[email protected](\"how\", [\"any\", \"all\"], ids=[\"any\", \"all\"])\ndef test_dropna(data, axis, how):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n with pytest.raises(ValueError):\n modin_df.dropna(axis=axis, how=\"invalid\")\n\n with pytest.raises(TypeError):\n modin_df.dropna(axis=axis, how=None, thresh=None)\n\n with pytest.raises(KeyError):\n modin_df.dropna(axis=axis, subset=[\"NotExists\"], how=how)\n\n modin_result = modin_df.dropna(axis=axis, how=how)\n pandas_result = pandas_df.dropna(axis=axis, how=how)\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_dropna_inplace(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n pandas_result = pandas_df.dropna()\n modin_df.dropna(inplace=True)\n df_equals(modin_df, pandas_result)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n pandas_df.dropna(thresh=2, inplace=True)\n modin_df.dropna(thresh=2, inplace=True)\n df_equals(modin_df, pandas_df)\n\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n pandas_df.dropna(axis=1, how=\"any\", inplace=True)\n modin_df.dropna(axis=1, how=\"any\", inplace=True)\n df_equals(modin_df, pandas_df)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_dropna_multiple_axes(data):\n modin_df = pd.DataFrame(data)\n\n with pytest.raises(TypeError):\n modin_df.dropna(how=\"all\", axis=[0, 1])\n with pytest.raises(TypeError):\n modin_df.dropna(how=\"all\", axis=(0, 1))\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_dropna_subset(request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n column_subset = modin_df.columns[0:2]\n df_equals(\n modin_df.dropna(how=\"all\", subset=column_subset),\n pandas_df.dropna(how=\"all\", subset=column_subset),\n )\n df_equals(\n modin_df.dropna(how=\"any\", subset=column_subset),\n pandas_df.dropna(how=\"any\", subset=column_subset),\n )\n\n row_subset = modin_df.index[0:2]\n df_equals(\n modin_df.dropna(how=\"all\", axis=1, subset=row_subset),\n pandas_df.dropna(how=\"all\", axis=1, subset=row_subset),\n )\n df_equals(\n modin_df.dropna(how=\"any\", axis=1, subset=row_subset),\n pandas_df.dropna(how=\"any\", axis=1, subset=row_subset),\n )\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"axis,subset\", [(0, list(\"EF\")), (1, [4, 5])])\ndef test_dropna_subset_error(data, axis, subset):\n eval_general(*create_test_dfs(data), lambda df: df.dropna(axis=axis, subset=subset))\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"astype\", [\"category\", \"int32\", \"float\"])\ndef test_insert_dtypes(data, astype):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n\n # categories with NaN works incorrect for now\n if astype == \"category\" and pandas_df.iloc[:, 0].isnull().any():\n return\n\n eval_insert(\n modin_df,\n pandas_df,\n col=\"TypeSaver\",\n value=lambda df: df.iloc[:, 0].astype(astype),\n )\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"loc\", int_arg_values, ids=arg_keys(\"loc\", int_arg_keys))\ndef test_insert_loc(data, loc):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n value = modin_df.iloc[:, 0]\n\n eval_insert(modin_df, pandas_df, loc=loc, value=value)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_insert(data):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n\n eval_insert(\n modin_df, pandas_df, col=\"Duplicate\", value=lambda df: df[df.columns[0]]\n )\n eval_insert(modin_df, pandas_df, col=\"Scalar\", value=100)\n eval_insert(\n pd.DataFrame(columns=list(\"ab\")),\n pandas.DataFrame(columns=list(\"ab\")),\n col=lambda df: df.columns[0],\n value=lambda df: df[df.columns[0]],\n )\n eval_insert(\n pd.DataFrame(index=modin_df.index),\n pandas.DataFrame(index=pandas_df.index),\n col=lambda df: df.columns[0],\n value=lambda df: df[df.columns[0]],\n )\n eval_insert(\n modin_df,\n pandas_df,\n col=\"DataFrame insert\",\n value=lambda df: df[[df.columns[0]]],\n )\n eval_insert(\n modin_df,\n pandas_df,\n col=\"Different indices\",\n value=lambda df: df[[df.columns[0]]].set_index(df.index[::-1]),\n )\n\n # Bad inserts\n eval_insert(modin_df, pandas_df, col=\"Bad Column\", value=lambda df: df)\n eval_insert(\n modin_df,\n pandas_df,\n col=\"Too Short\",\n value=lambda df: list(df[df.columns[0]])[:-1],\n )\n eval_insert(\n modin_df,\n pandas_df,\n col=lambda df: df.columns[0],\n value=lambda df: df[df.columns[0]],\n )\n eval_insert(\n modin_df,\n pandas_df,\n loc=lambda df: len(df.columns) + 100,\n col=\"Bad Loc\",\n value=100,\n )\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_ndim(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.ndim == pandas_df.ndim\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_notna(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.notna(), pandas_df.notna())\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_notnull(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.notnull(), pandas_df.notnull())\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_round(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.round(), pandas_df.round())\n df_equals(modin_df.round(1), pandas_df.round(1))\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"axis\", axis_values, ids=axis_keys)\ndef test_set_axis(data, axis):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n x = pandas.DataFrame()._get_axis_number(axis)\n index = modin_df.columns if x else modin_df.index\n labels = [\"{0}_{1}\".format(index[i], i) for i in range(modin_df.shape[x])]\n\n modin_result = modin_df.set_axis(labels, axis=axis, inplace=False)\n pandas_result = pandas_df.set_axis(labels, axis=axis, inplace=False)\n df_equals(modin_result, pandas_result)\n\n modin_df_copy = modin_df.copy()\n modin_df.set_axis(labels, axis=axis, inplace=True)\n\n # Check that the copy and original are different\n try:\n df_equals(modin_df, modin_df_copy)\n except AssertionError:\n assert True\n else:\n assert False\n\n pandas_df.set_axis(labels, axis=axis, inplace=True)\n df_equals(modin_df, pandas_df)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\[email protected](\"drop\", bool_arg_values, ids=arg_keys(\"drop\", bool_arg_keys))\[email protected](\n \"append\", bool_arg_values, ids=arg_keys(\"append\", bool_arg_keys)\n)\ndef test_set_index(request, data, drop, append):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n key = modin_df.columns[0]\n modin_result = modin_df.set_index(key, drop=drop, append=append, inplace=False)\n pandas_result = pandas_df.set_index(\n key, drop=drop, append=append, inplace=False\n )\n df_equals(modin_result, pandas_result)\n\n modin_df_copy = modin_df.copy()\n modin_df.set_index(key, drop=drop, append=append, inplace=True)\n\n # Check that the copy and original are different\n try:\n df_equals(modin_df, modin_df_copy)\n except AssertionError:\n assert True\n else:\n assert False\n\n pandas_df.set_index(key, drop=drop, append=append, inplace=True)\n df_equals(modin_df, pandas_df)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_shape(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.shape == pandas_df.shape\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_size(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n assert modin_df.size == pandas_df.size\n\n\ndef test_squeeze():\n frame_data = {\n \"col1\": [0, 1, 2, 3],\n \"col2\": [4, 5, 6, 7],\n \"col3\": [8, 9, 10, 11],\n \"col4\": [12, 13, 14, 15],\n \"col5\": [0, 0, 0, 0],\n }\n frame_data_2 = {\"col1\": [0, 1, 2, 3]}\n frame_data_3 = {\n \"col1\": [0],\n \"col2\": [4],\n \"col3\": [8],\n \"col4\": [12],\n \"col5\": [0],\n }\n frame_data_4 = {\"col1\": [2]}\n frame_data_5 = {\"col1\": [\"string\"]}\n # Different data for different cases\n pandas_df = pandas.DataFrame(frame_data).squeeze()\n modin_df = pd.DataFrame(frame_data).squeeze()\n df_equals(modin_df, pandas_df)\n\n pandas_df_2 = pandas.DataFrame(frame_data_2).squeeze()\n modin_df_2 = pd.DataFrame(frame_data_2).squeeze()\n df_equals(modin_df_2, pandas_df_2)\n\n pandas_df_3 = pandas.DataFrame(frame_data_3).squeeze()\n modin_df_3 = pd.DataFrame(frame_data_3).squeeze()\n df_equals(modin_df_3, pandas_df_3)\n\n pandas_df_4 = pandas.DataFrame(frame_data_4).squeeze()\n modin_df_4 = pd.DataFrame(frame_data_4).squeeze()\n df_equals(modin_df_4, pandas_df_4)\n\n pandas_df_5 = pandas.DataFrame(frame_data_5).squeeze()\n modin_df_5 = pd.DataFrame(frame_data_5).squeeze()\n df_equals(modin_df_5, pandas_df_5)\n\n data = [\n [\n pd.Timestamp(\"2019-01-02\"),\n pd.Timestamp(\"2019-01-03\"),\n pd.Timestamp(\"2019-01-04\"),\n pd.Timestamp(\"2019-01-05\"),\n ],\n [1, 1, 1, 2],\n ]\n df = pd.DataFrame(data, index=[\"date\", \"value\"]).T\n pf = pandas.DataFrame(data, index=[\"date\", \"value\"]).T\n df.set_index(\"date\", inplace=True)\n pf.set_index(\"date\", inplace=True)\n df_equals(df.iloc[0], pf.iloc[0])\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test_transpose(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n df_equals(modin_df.T, pandas_df.T)\n df_equals(modin_df.transpose(), pandas_df.transpose())\n\n # Test for map across full axis for select indices\n df_equals(modin_df.T.dropna(), pandas_df.T.dropna())\n # Test for map across full axis\n df_equals(modin_df.T.nunique(), pandas_df.T.nunique())\n # Test for map across blocks\n df_equals(modin_df.T.notna(), pandas_df.T.notna())\n\n\[email protected](\n \"data, other_data\",\n [\n ({\"A\": [1, 2, 3], \"B\": [400, 500, 600]}, {\"B\": [4, 5, 6], \"C\": [7, 8, 9]}),\n (\n {\"A\": [\"a\", \"b\", \"c\"], \"B\": [\"x\", \"y\", \"z\"]},\n {\"B\": [\"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]},\n ),\n ({\"A\": [1, 2, 3], \"B\": [400, 500, 600]}, {\"B\": [4, np.nan, 6]}),\n ],\n)\ndef test_update(data, other_data):\n modin_df, pandas_df = pd.DataFrame(data), pandas.DataFrame(data)\n other_modin_df, other_pandas_df = (\n pd.DataFrame(other_data),\n pandas.DataFrame(other_data),\n )\n modin_df.update(other_modin_df)\n pandas_df.update(other_pandas_df)\n df_equals(modin_df, pandas_df)\n\n with pytest.raises(ValueError):\n modin_df.update(other_modin_df, errors=\"raise\")\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test___neg__(request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = pandas_df.__neg__()\n except Exception as e:\n with pytest.raises(type(e)):\n modin_df.__neg__()\n else:\n modin_result = modin_df.__neg__()\n df_equals(modin_result, pandas_result)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test___invert__(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n try:\n pandas_result = ~pandas_df\n except Exception as e:\n with pytest.raises(type(e)):\n repr(~modin_df)\n else:\n modin_result = ~modin_df\n df_equals(modin_result, pandas_result)\n\n\ndef test___hash__():\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n try:\n pd.DataFrame(data).__hash__()\n except TypeError:\n pass\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test___delitem__(request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n if \"empty_data\" not in request.node.name:\n key = pandas_df.columns[0]\n\n modin_df = modin_df.copy()\n pandas_df = pandas_df.copy()\n modin_df.__delitem__(key)\n pandas_df.__delitem__(key)\n df_equals(modin_df, pandas_df)\n\n # Issue 2027\n last_label = pandas_df.iloc[:, -1].name\n modin_df.__delitem__(last_label)\n pandas_df.__delitem__(last_label)\n df_equals(modin_df, pandas_df)\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test___nonzero__(data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data) # noqa F841\n\n with pytest.raises(ValueError):\n # Always raises ValueError\n modin_df.__nonzero__()\n\n\[email protected](\"data\", test_data_values, ids=test_data_keys)\ndef test___abs__(request, data):\n modin_df = pd.DataFrame(data)\n pandas_df = pandas.DataFrame(data)\n\n try:\n pandas_result = abs(pandas_df)\n except Exception as e:\n with pytest.raises(type(e)):\n abs(modin_df)\n else:\n modin_result = abs(modin_df)\n df_equals(modin_result, pandas_result)\n\n\ndef test___round__():\n data = test_data_values[0]\n with pytest.warns(UserWarning):\n pd.DataFrame(data).__round__()\n", "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport modin.pandas as pd\nimport numpy as np\n\nfrom ..utils import (\n generate_dataframe,\n RAND_LOW,\n RAND_HIGH,\n ASV_USE_IMPL,\n ASV_DATASET_SIZE,\n UNARY_OP_DATA_SIZE,\n IMPL,\n execute,\n get_shape_id,\n)\n\n\nclass BaseReadCsv:\n # test data file can de created only once\n def setup_cache(self, test_filename=\"io_test_file\"):\n test_filenames = {}\n for shape in UNARY_OP_DATA_SIZE[ASV_DATASET_SIZE]:\n shape_id = get_shape_id(shape)\n test_filenames[shape_id] = f\"{test_filename}_{shape_id}.csv\"\n df = generate_dataframe(\"pandas\", \"str_int\", *shape, RAND_LOW, RAND_HIGH)\n df.to_csv(test_filenames[shape_id], index=False)\n\n return test_filenames\n\n def setup(self, test_filenames, shape, *args, **kwargs):\n # ray init\n if ASV_USE_IMPL == \"modin\":\n pd.DataFrame([])\n self.shape_id = get_shape_id(shape)\n\n\nclass TimeReadCsvSkiprows(BaseReadCsv):\n skiprows_mapping = {\n \"lambda_even_rows\": lambda x: x % 2,\n \"range_uniform\": np.arange(1, UNARY_OP_DATA_SIZE[ASV_DATASET_SIZE][0][0] // 10),\n \"range_step2\": np.arange(1, UNARY_OP_DATA_SIZE[ASV_DATASET_SIZE][0][0], 2),\n }\n\n param_names = [\"shape\", \"skiprows\"]\n params = [\n UNARY_OP_DATA_SIZE[ASV_DATASET_SIZE],\n [\n None,\n \"lambda_even_rows\",\n \"range_uniform\",\n \"range_step2\",\n ],\n ]\n\n def setup(self, test_filenames, shape, skiprows):\n super().setup(test_filenames, shape, skiprows)\n self.skiprows = self.skiprows_mapping[skiprows] if skiprows else None\n\n def time_skiprows(self, test_filenames, shape, skiprows):\n execute(\n IMPL[ASV_USE_IMPL].read_csv(\n test_filenames[self.shape_id], skiprows=self.skiprows\n )\n )\n\n\nclass TimeReadCsvNamesDtype:\n _dtypes_params = [\"Int64\", \"Int64_Timestamp\"]\n _timestamp_columns = [\"col1\", \"col2\"]\n\n param_names = [\"shape\", \"names\", \"dtype\"]\n params = [\n UNARY_OP_DATA_SIZE[ASV_DATASET_SIZE],\n [\"array-like\"],\n _dtypes_params,\n ]\n\n def _get_file_id(self, shape, dtype):\n return get_shape_id(shape) + dtype\n\n def _add_timestamp_columns(self, df):\n df = df.copy()\n date_column = IMPL[\"pandas\"].date_range(\n \"2000\",\n periods=df.shape[0],\n freq=\"ms\",\n )\n for col in self._timestamp_columns:\n df[col] = date_column\n return df\n\n def setup_cache(self, test_filename=\"io_test_file_csv_names_dtype\"):\n # filenames with a metadata of saved dataframes\n cache = {}\n for shape in UNARY_OP_DATA_SIZE[ASV_DATASET_SIZE]:\n for dtype in self._dtypes_params:\n df = generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH)\n if dtype == \"Int64_Timestamp\":\n df = self._add_timestamp_columns(df)\n\n file_id = self._get_file_id(shape, dtype)\n cache[file_id] = (\n f\"{test_filename}_{file_id}.csv\",\n df.columns.to_list(),\n df.dtypes.to_dict(),\n )\n df.to_csv(cache[file_id][0], index=False)\n return cache\n\n def setup(self, cache, shape, names, dtype):\n # ray init\n if ASV_USE_IMPL == \"modin\":\n pd.DataFrame([])\n file_id = self._get_file_id(shape, dtype)\n self.filename, self.names, self.dtype = cache[file_id]\n\n self.parse_dates = None\n if dtype == \"Int64_Timestamp\":\n # cached version of dtype should not change\n self.dtype = self.dtype.copy()\n for col in self._timestamp_columns:\n del self.dtype[col]\n self.parse_dates = self._timestamp_columns\n\n def time_read_csv_names_dtype(self, cache, shape, names, dtype):\n execute(\n IMPL[ASV_USE_IMPL].read_csv(\n self.filename,\n names=self.names,\n header=0,\n dtype=self.dtype,\n parse_dates=self.parse_dates,\n )\n )\n", "# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. 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 distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nimport pandas\nimport pytest\nimport modin.experimental.pandas as pd\nfrom modin.config import Engine\nfrom modin.pandas.test.utils import df_equals\n\n\[email protected](\n Engine.get() == \"Dask\",\n reason=\"Dask does not have experimental API\",\n)\ndef test_from_sql_distributed(make_sql_connection): # noqa: F811\n if Engine.get() == \"Ray\":\n filename = \"test_from_sql_distributed.db\"\n table = \"test_from_sql_distributed\"\n conn = make_sql_connection(filename, table)\n query = \"select * from {0}\".format(table)\n\n pandas_df = pandas.read_sql(query, conn)\n modin_df_from_query = pd.read_sql(\n query,\n conn,\n partition_column=\"col1\",\n lower_bound=0,\n upper_bound=6,\n max_sessions=2,\n )\n modin_df_from_table = pd.read_sql(\n table,\n conn,\n partition_column=\"col1\",\n lower_bound=0,\n upper_bound=6,\n max_sessions=2,\n )\n\n df_equals(modin_df_from_query, pandas_df)\n df_equals(modin_df_from_table, pandas_df)\n\n\[email protected](\n Engine.get() == \"Dask\",\n reason=\"Dask does not have experimental API\",\n)\ndef test_from_sql_defaults(make_sql_connection): # noqa: F811\n filename = \"test_from_sql_distributed.db\"\n table = \"test_from_sql_distributed\"\n conn = make_sql_connection(filename, table)\n query = \"select * from {0}\".format(table)\n\n pandas_df = pandas.read_sql(query, conn)\n with pytest.warns(UserWarning):\n modin_df_from_query = pd.read_sql(query, conn)\n with pytest.warns(UserWarning):\n modin_df_from_table = pd.read_sql(table, conn)\n\n df_equals(modin_df_from_query, pandas_df)\n df_equals(modin_df_from_table, pandas_df)\n\n\[email protected](\"TestReadGlobCSVFixture\")\[email protected](\n Engine.get() != \"Ray\", reason=\"Currently only support Ray engine for glob paths.\"\n)\nclass TestCsvGlob:\n def test_read_multiple_small_csv(self): # noqa: F811\n pandas_df = pandas.concat([pandas.read_csv(fname) for fname in pytest.files])\n modin_df = pd.read_csv_glob(pytest.glob_path)\n\n # Indexes get messed up when concatting so we reset both.\n pandas_df = pandas_df.reset_index(drop=True)\n modin_df = modin_df.reset_index(drop=True)\n\n df_equals(modin_df, pandas_df)\n\n @pytest.mark.parametrize(\"nrows\", [35, 100])\n def test_read_multiple_csv_nrows(self, request, nrows): # noqa: F811\n pandas_df = pandas.concat([pandas.read_csv(fname) for fname in pytest.files])\n pandas_df = pandas_df.iloc[:nrows, :]\n\n modin_df = pd.read_csv_glob(pytest.glob_path, nrows=nrows)\n\n # Indexes get messed up when concatting so we reset both.\n pandas_df = pandas_df.reset_index(drop=True)\n modin_df = modin_df.reset_index(drop=True)\n\n df_equals(modin_df, pandas_df)\n\n\[email protected](\n Engine.get() != \"Ray\", reason=\"Currently only support Ray engine for glob paths.\"\n)\ndef test_read_multiple_csv_s3():\n modin_df = pd.read_csv_glob(\"S3://noaa-ghcn-pds/csv/178*.csv\")\n\n # We have to specify the columns because the column names are not identical. Since we specified the column names, we also have to skip the original column names.\n pandas_dfs = [\n pandas.read_csv(\n \"s3://noaa-ghcn-pds/csv/178{}.csv\".format(i),\n names=modin_df.columns,\n skiprows=[0],\n )\n for i in range(10)\n ]\n pandas_df = pd.concat(pandas_dfs)\n\n # Indexes get messed up when concatting so we reset both.\n pandas_df = pandas_df.reset_index(drop=True)\n modin_df = modin_df.reset_index(drop=True)\n\n df_equals(modin_df, pandas_df)\n" ]
[ [ "pandas.Series", "numpy.array_equal", "matplotlib.use", "pandas.Index", "pandas.DataFrame", "pandas.get_dummies" ], [ "numpy.arange" ], [ "pandas.read_csv", "pandas.read_sql" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
aiboyko/t3f
[ "0361b80f36a06eb5aa5d536650eef9e006289139" ]
[ "t3f/riemannian.py" ]
[ "import tensorflow.compat.v1 as tf\n\nfrom t3f.tensor_train import TensorTrain\nfrom t3f.tensor_train_batch import TensorTrainBatch\nfrom t3f import shapes\nfrom t3f import decompositions\n\n\ndef project_sum(what, where, weights=None):\n \"\"\"Project sum of `what` TTs on the tangent space of `where` TT.\n\n project_sum(what, x) = P_x(what)\n project_sum(batch_what, x) = P_x(\\sum_i batch_what[i])\n project_sum(batch_what, x, weights) = P_x(\\sum_j weights[j] * batch_what[j])\n\n This function implements the algorithm from the paper [1], theorem 3.1.\n\n [1] C. Lubich, I. Oseledets and B. Vandereycken, Time integration of\n Tensor Trains.\n\n Args:\n what: TensorTrain or TensorTrainBatch. In the case of batch returns\n projection of the sum of elements in the batch.\n where: TensorTrain, TT-tensor or TT-matrix on which tangent space to project\n weights: python list or tf.Tensor of numbers or None, weights of the sum\n\n Returns:\n a TensorTrain with the TT-ranks equal 2 * tangent_space_tens.get_tt_ranks()\n\n Complexity:\n O(d r_where^3 m) for orthogonalizing the TT-cores of where\n +O(batch_size d r_what r_where n (r_what + r_where))\n d is the number of TT-cores (what.ndims());\n r_what is the largest TT-rank of what max(what.get_tt_rank())\n r_where is the largest TT-rank of where\n n is the size of the axis dimension of what and where e.g.\n for a tensor of size 4 x 4 x 4, n is 4;\n for a 9 x 64 matrix of raw shape (3, 3, 3) x (4, 4, 4) n is 12\n \"\"\"\n # Always work with batch of TT objects for simplicity.\n what = shapes.expand_batch_dim(what)\n\n if weights is not None:\n weights = tf.convert_to_tensor(weights, dtype=where.dtype)\n\n if not isinstance(where, TensorTrain):\n raise ValueError('The first argument should be a TensorTrain object, got '\n '\"%s\".' % where)\n\n if where.get_raw_shape() != what.get_raw_shape():\n raise ValueError('The shapes of the tensor we want to project and of the '\n 'tensor on which tangent space we want to project should '\n 'match, got %s and %s.' %\n (where.get_raw_shape(),\n what.get_raw_shape()))\n\n dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or\n what.dtype.is_compatible_with(where.dtype))\n if not dtypes_compatible:\n raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %\n (where.dtype,\n what.dtype))\n\n left_tangent_space_tens = decompositions.orthogonalize_tt_cores(\n where)\n right_tangent_space_tens = decompositions.orthogonalize_tt_cores(\n left_tangent_space_tens, left_to_right=False)\n\n ndims = where.ndims()\n dtype = where.dtype\n raw_shape = shapes.lazy_raw_shape(where)\n batch_size = shapes.lazy_batch_size(what)\n right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)\n left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)\n\n # For einsum notation.\n mode_str = 'ij' if where.is_tt_matrix() else 'i'\n right_rank_dim = where.right_tt_rank_dim\n left_rank_dim = where.left_tt_rank_dim\n if weights is not None:\n weights_shape = weights.get_shape()\n output_is_batch = len(weights_shape) > 1 and weights_shape[1] > 1\n else:\n output_is_batch = False\n output_batch_str = 'o' if output_is_batch else ''\n if output_is_batch:\n right_rank_dim += 1\n left_rank_dim += 1\n output_batch_size = weights.get_shape()[1].value\n\n # Prepare rhs vectors.\n # rhs[core_idx] is of size\n # batch_size x tensor_tt_ranks[core_idx] x tangent_tt_ranks[core_idx]\n rhs = [None] * (ndims + 1)\n rhs[ndims] = tf.ones((batch_size, 1, 1), dtype=dtype)\n for core_idx in range(ndims - 1, 0, -1):\n tens_core = what.tt_cores[core_idx]\n right_tang_core = right_tangent_space_tens.tt_cores[core_idx]\n einsum_str = 'sa{0}b,sbd,c{0}d->sac'.format(mode_str)\n rhs[core_idx] = tf.einsum(einsum_str, tens_core, rhs[core_idx + 1],\n right_tang_core)\n\n # Prepare lhs vectors.\n # lhs[core_idx] is of size\n # batch_size x tangent_tt_ranks[core_idx] x tensor_tt_ranks[core_idx]\n lhs = [None] * (ndims + 1)\n lhs[0] = tf.ones((batch_size, 1, 1), dtype=dtype)\n for core_idx in range(ndims - 1):\n tens_core = what.tt_cores[core_idx]\n left_tang_core = left_tangent_space_tens.tt_cores[core_idx]\n einsum_str = 'sab,a{0}c,sb{0}d->scd'.format(mode_str)\n lhs[core_idx + 1] = tf.einsum(einsum_str, lhs[core_idx], left_tang_core,\n tens_core)\n\n # Left to right sweep.\n res_cores_list = []\n for core_idx in range(ndims):\n tens_core = what.tt_cores[core_idx]\n left_tang_core = left_tangent_space_tens.tt_cores[core_idx]\n right_tang_core = right_tangent_space_tens.tt_cores[core_idx]\n\n if core_idx < ndims - 1:\n einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)\n proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)\n einsum_str = 'a{0}b,sbc->sa{0}c'.format(mode_str)\n proj_core -= tf.einsum(einsum_str, left_tang_core, lhs[core_idx + 1])\n if weights is None:\n einsum_str = 'sa{0}b,sbc->a{0}c'.format(mode_str)\n proj_core = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])\n else:\n einsum_str = 'sa{0}b,sbc->sa{0}c'.format(mode_str, output_batch_str)\n proj_core_s = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])\n einsum_str = 's{1},sa{0}c->{1}a{0}c'.format(mode_str, output_batch_str)\n proj_core = tf.einsum(einsum_str, weights, proj_core_s)\n\n if core_idx == ndims - 1:\n if weights is None:\n einsum_str = 'sab,sb{0}c->a{0}c'.format(mode_str)\n proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)\n else:\n einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str, output_batch_str)\n proj_core_s = tf.einsum(einsum_str, lhs[core_idx], tens_core)\n einsum_str = 's{1},sa{0}c->{1}a{0}c'.format(mode_str, output_batch_str)\n proj_core = tf.einsum(einsum_str, weights, proj_core_s)\n\n if output_is_batch:\n # Add batch dimension of size output_batch_size to left_tang_core and\n # right_tang_core\n extended_left_tang_core = tf.expand_dims(left_tang_core, 0)\n extended_right_tang_core = tf.expand_dims(right_tang_core, 0)\n if where.is_tt_matrix():\n extended_left_tang_core = tf.tile(extended_left_tang_core,\n [output_batch_size, 1, 1, 1, 1])\n extended_right_tang_core = tf.tile(extended_right_tang_core,\n [output_batch_size, 1, 1, 1, 1])\n else:\n extended_left_tang_core = tf.tile(extended_left_tang_core,\n [output_batch_size, 1, 1, 1])\n extended_right_tang_core = tf.tile(extended_right_tang_core,\n [output_batch_size, 1, 1, 1])\n else:\n extended_left_tang_core = left_tang_core\n extended_right_tang_core = right_tang_core\n\n if core_idx == 0:\n res_core = tf.concat((proj_core, extended_left_tang_core),\n axis=right_rank_dim)\n elif core_idx == ndims - 1:\n res_core = tf.concat((extended_right_tang_core, proj_core), axis=left_rank_dim)\n else:\n rank_1 = right_tangent_tt_ranks[core_idx]\n rank_2 = left_tangent_tt_ranks[core_idx + 1]\n if where.is_tt_matrix():\n mode_size_n = raw_shape[0][core_idx]\n mode_size_m = raw_shape[1][core_idx]\n shape = [rank_1, mode_size_n, mode_size_m, rank_2]\n else:\n mode_size = raw_shape[0][core_idx]\n shape = [rank_1, mode_size, rank_2]\n if output_is_batch:\n shape = [output_batch_size] + shape\n zeros = tf.zeros(shape, dtype)\n upper = tf.concat((extended_right_tang_core, zeros), axis=right_rank_dim)\n lower = tf.concat((proj_core, extended_left_tang_core),\n axis=right_rank_dim)\n res_core = tf.concat((upper, lower), axis=left_rank_dim)\n res_cores_list.append(res_core)\n # TODO: TT-ranks.\n if output_is_batch:\n res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),\n batch_size=output_batch_size)\n else:\n res = TensorTrain(res_cores_list, where.get_raw_shape())\n\n res.projection_on = where\n return res\n\n\ndef project(what, where):\n \"\"\"Project `what` TTs on the tangent space of `where` TT.\n\n project(what, x) = P_x(what)\n project(batch_what, x) = batch(P_x(batch_what[0]), ..., P_x(batch_what[N]))\n\n This function implements the algorithm from the paper [1], theorem 3.1.\n\n [1] C. Lubich, I. Oseledets and B. Vandereycken, Time integration of\n Tensor Trains.\n\n Args:\n what: TensorTrain or TensorTrainBatch. In the case of batch returns\n batch with projection of each individual tensor.\n where: TensorTrain, TT-tensor or TT-matrix on which tangent space to project\n\n Returns:\n a TensorTrain with the TT-ranks equal 2 * tangent_space_tens.get_tt_ranks()\n \n Complexity:\n O(d r_where^3 m) for orthogonalizing the TT-cores of where\n +O(batch_size d r_what r_where n (r_what + r_where))\n d is the number of TT-cores (what.ndims());\n r_what is the largest TT-rank of what max(what.get_tt_rank())\n r_where is the largest TT-rank of where\n n is the size of the axis dimension of what and where e.g.\n for a tensor of size 4 x 4 x 4, n is 4;\n for a 9 x 64 matrix of raw shape (3, 3, 3) x (4, 4, 4) n is 12\n \"\"\"\n\n if not isinstance(where, TensorTrain):\n raise ValueError('The first argument should be a TensorTrain object, got '\n '\"%s\".' % where)\n\n if where.get_raw_shape() != what.get_raw_shape():\n raise ValueError('The shapes of the tensor we want to project and of the '\n 'tensor on which tangent space we want to project should '\n 'match, got %s and %s.' %\n (where.get_raw_shape(),\n what.get_raw_shape()))\n dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or\n what.dtype.is_compatible_with(where.dtype))\n if not dtypes_compatible:\n raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %\n (where.dtype,\n what.dtype))\n\n left_tangent_space_tens = decompositions.orthogonalize_tt_cores(\n where)\n right_tangent_space_tens = decompositions.orthogonalize_tt_cores(\n left_tangent_space_tens, left_to_right=False)\n\n ndims = where.ndims()\n dtype = where.dtype\n raw_shape = shapes.lazy_raw_shape(where)\n right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)\n left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)\n\n # For einsum notation.\n mode_str = 'ij' if where.is_tt_matrix() else 'i'\n right_rank_dim = what.right_tt_rank_dim\n left_rank_dim = what.left_tt_rank_dim\n output_is_batch = isinstance(what, TensorTrainBatch)\n if output_is_batch:\n output_batch_size = what.batch_size\n\n # Always work with batch of TT objects for simplicity.\n what = shapes.expand_batch_dim(what)\n batch_size = shapes.lazy_batch_size(what)\n\n # Prepare rhs vectors.\n # rhs[core_idx] is of size\n # batch_size x tensor_tt_ranks[core_idx] x tangent_tt_ranks[core_idx]\n rhs = [None] * (ndims + 1)\n rhs[ndims] = tf.ones((batch_size, 1, 1), dtype=dtype)\n for core_idx in range(ndims - 1, 0, -1):\n tens_core = what.tt_cores[core_idx]\n right_tang_core = right_tangent_space_tens.tt_cores[core_idx]\n einsum_str = 'sa{0}b,sbd,c{0}d->sac'.format(mode_str)\n rhs[core_idx] = tf.einsum(einsum_str, tens_core, rhs[core_idx + 1],\n right_tang_core)\n\n # Prepare lhs vectors.\n # lhs[core_idx] is of size\n # batch_size x tangent_tt_ranks[core_idx] x tensor_tt_ranks[core_idx]\n lhs = [None] * (ndims + 1)\n lhs[0] = tf.ones((batch_size, 1, 1), dtype=dtype)\n for core_idx in range(ndims - 1):\n tens_core = what.tt_cores[core_idx]\n left_tang_core = left_tangent_space_tens.tt_cores[core_idx]\n einsum_str = 'sab,a{0}c,sb{0}d->scd'.format(mode_str)\n lhs[core_idx + 1] = tf.einsum(einsum_str, lhs[core_idx], left_tang_core,\n tens_core)\n\n # Left to right sweep.\n res_cores_list = []\n for core_idx in range(ndims):\n tens_core = what.tt_cores[core_idx]\n left_tang_core = left_tangent_space_tens.tt_cores[core_idx]\n right_tang_core = right_tangent_space_tens.tt_cores[core_idx]\n\n if core_idx < ndims - 1:\n einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)\n proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)\n einsum_str = 'a{0}b,sbc->sa{0}c'.format(mode_str)\n proj_core -= tf.einsum(einsum_str, left_tang_core, lhs[core_idx + 1])\n if output_is_batch:\n einsum_str = 'sa{0}b,sbc->sa{0}c'.format(mode_str)\n else:\n einsum_str = 'sa{0}b,sbc->a{0}c'.format(mode_str)\n proj_core = tf.einsum(einsum_str, proj_core, rhs[core_idx + 1])\n\n if core_idx == ndims - 1:\n if output_is_batch:\n einsum_str = 'sab,sb{0}c->sa{0}c'.format(mode_str)\n else:\n einsum_str = 'sab,sb{0}c->a{0}c'.format(mode_str)\n proj_core = tf.einsum(einsum_str, lhs[core_idx], tens_core)\n\n if output_is_batch:\n # Add batch dimension of size output_batch_size to left_tang_core and\n # right_tang_core\n extended_left_tang_core = tf.expand_dims(left_tang_core, 0)\n extended_right_tang_core = tf.expand_dims(right_tang_core, 0)\n if where.is_tt_matrix():\n extended_left_tang_core = tf.tile(extended_left_tang_core,\n [output_batch_size, 1, 1, 1, 1])\n extended_right_tang_core = tf.tile(extended_right_tang_core,\n [output_batch_size, 1, 1, 1, 1])\n else:\n extended_left_tang_core = tf.tile(extended_left_tang_core,\n [output_batch_size, 1, 1, 1])\n extended_right_tang_core = tf.tile(extended_right_tang_core,\n [output_batch_size, 1, 1, 1])\n else:\n extended_left_tang_core = left_tang_core\n extended_right_tang_core = right_tang_core\n\n if core_idx == 0:\n res_core = tf.concat((proj_core, extended_left_tang_core),\n axis=right_rank_dim)\n elif core_idx == ndims - 1:\n res_core = tf.concat((extended_right_tang_core, proj_core), axis=left_rank_dim)\n else:\n rank_1 = right_tangent_tt_ranks[core_idx]\n rank_2 = left_tangent_tt_ranks[core_idx + 1]\n if where.is_tt_matrix():\n mode_size_n = raw_shape[0][core_idx]\n mode_size_m = raw_shape[1][core_idx]\n shape = [rank_1, mode_size_n, mode_size_m, rank_2]\n else:\n mode_size = raw_shape[0][core_idx]\n shape = [rank_1, mode_size, rank_2]\n if output_is_batch:\n shape = [output_batch_size] + shape\n zeros = tf.zeros(shape, dtype)\n upper = tf.concat((extended_right_tang_core, zeros), axis=right_rank_dim)\n lower = tf.concat((proj_core, extended_left_tang_core),\n axis=right_rank_dim)\n res_core = tf.concat((upper, lower), axis=left_rank_dim)\n res_cores_list.append(res_core)\n # TODO: TT-ranks.\n if output_is_batch:\n res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),\n batch_size=output_batch_size)\n else:\n res = TensorTrain(res_cores_list, where.get_raw_shape())\n\n res.projection_on = where\n return res\n\n\ndef project_matmul(what, where, matrix):\n \"\"\"Project `matrix` * `what` TTs on the tangent space of `where` TT.\n\n project(what, x) = P_x(what)\n project(batch_what, x) = batch(P_x(batch_what[0]), ..., P_x(batch_what[N]))\n\n This function implements the algorithm from the paper [1], theorem 3.1.\n\n [1] C. Lubich, I. Oseledets and B. Vandereycken, Time integration of\n Tensor Trains.\n\n Args:\n what: TensorTrain or TensorTrainBatch. In the case of batch returns\n batch with projection of each individual tensor.\n where: TensorTrain, TT-tensor or TT-matrix on which tangent space to project\n matrix: TensorTrain, TT-matrix to multiply by what\n\n Returns:\n a TensorTrain with the TT-ranks equal 2 * tangent_space_tens.get_tt_ranks()\n \n Complexity:\n O(d r_where^3 m) for orthogonalizing the TT-cores of where\n +O(batch_size d R r_what r_where (n r_what + n m R + m r_where))\n d is the number of TT-cores (what.ndims());\n r_what is the largest TT-rank of what max(what.get_tt_rank())\n r_where is the largest TT-rank of where\n matrix is of TT-rank R and of raw-shape (m, m, ..., m) x (n, n, ..., n).\n \"\"\"\n\n if not isinstance(where, TensorTrain):\n raise ValueError('The first argument should be a TensorTrain object, got '\n '\"%s\".' % where)\n\n if where.get_raw_shape() != what.get_raw_shape():\n raise ValueError('The shapes of the tensor we want to project and of the '\n 'tensor on which tangent space we want to project should '\n 'match, got %s and %s.' %\n (where.get_raw_shape(),\n what.get_raw_shape()))\n\n dtypes_compatible = (where.dtype.is_compatible_with(what.dtype) or\n what.dtype.is_compatible_with(where.dtype))\n if not dtypes_compatible:\n raise ValueError('Dtypes of the arguments should coincide, got %s and %s.' %\n (where.dtype,\n what.dtype))\n\n left_tangent_space_tens = decompositions.orthogonalize_tt_cores(\n where)\n right_tangent_space_tens = decompositions.orthogonalize_tt_cores(\n left_tangent_space_tens, left_to_right=False)\n\n ndims = where.ndims()\n dtype = where.dtype\n raw_shape = shapes.lazy_raw_shape(where)\n batch_size = shapes.lazy_batch_size(what)\n right_tangent_tt_ranks = shapes.lazy_tt_ranks(right_tangent_space_tens)\n left_tangent_tt_ranks = shapes.lazy_tt_ranks(left_tangent_space_tens)\n\n # For einsum notation.\n right_rank_dim = what.right_tt_rank_dim\n left_rank_dim = what.left_tt_rank_dim\n output_is_batch = isinstance(what, TensorTrainBatch)\n if output_is_batch:\n output_batch_size = what.batch_size\n\n # Always work with batch of TT objects for simplicity.\n what = shapes.expand_batch_dim(what)\n\n # Prepare rhs vectors.\n # rhs[core_idx] is of size\n # batch_size x tensor_tt_ranks[core_idx] x matrix_tt_ranks[core_idx] x tangent_tt_ranks[core_idx]\n rhs = [None] * (ndims + 1)\n rhs[ndims] = tf.ones((batch_size, 1, 1, 1), dtype=dtype)\n for core_idx in range(ndims - 1, 0, -1):\n tens_core = what.tt_cores[core_idx]\n right_tang_core = right_tangent_space_tens.tt_cores[core_idx]\n matrix_core = matrix.tt_cores[core_idx]\n rhs[core_idx] = tf.einsum('bije,cikf,sdef,sajkd->sabc', matrix_core,\n right_tang_core, rhs[core_idx + 1], tens_core)\n # Prepare lhs vectors.\n # lhs[core_idx] is of size\n # batch_size x tangent_tt_ranks[core_idx] x matrix_tt_ranks[core_idx] x tensor_tt_ranks[core_idx]\n lhs = [None] * (ndims + 1)\n lhs[0] = tf.ones((batch_size, 1, 1, 1), dtype=dtype)\n for core_idx in range(ndims - 1):\n tens_core = what.tt_cores[core_idx]\n left_tang_core = left_tangent_space_tens.tt_cores[core_idx]\n matrix_core = matrix.tt_cores[core_idx]\n # TODO: brutforce order of indices in lhs??\n lhs[core_idx + 1] = tf.einsum('bije,aikd,sabc,scjkf->sdef', matrix_core,\n left_tang_core, lhs[core_idx], tens_core)\n\n # Left to right sweep.\n res_cores_list = []\n for core_idx in range(ndims):\n tens_core = what.tt_cores[core_idx]\n matrix_core = matrix.tt_cores[core_idx]\n left_tang_core = left_tangent_space_tens.tt_cores[core_idx]\n right_tang_core = right_tangent_space_tens.tt_cores[core_idx]\n\n if core_idx < ndims - 1:\n proj_core = tf.einsum('scjke,sabc,bijd->saikde', tens_core,\n lhs[core_idx], matrix_core)\n proj_core -= tf.einsum('aikb,sbcd->saikcd', left_tang_core,\n lhs[core_idx + 1])\n proj_core = tf.einsum('saikcb,sbcd->saikd', proj_core, rhs[core_idx + 1])\n\n if core_idx == ndims - 1:\n # d and e dimensions take 1 value, since its the last rank.\n # To make the result shape (?, ?, ?, 1), we are summing d and leaving e,\n # but we could have done the opposite -- sum e and leave d.\n proj_core = tf.einsum('sabc,bijd,scjke->saike', lhs[core_idx], matrix_core,\n tens_core)\n\n if output_is_batch:\n # Add batch dimension of size output_batch_size to left_tang_core and\n # right_tang_core\n extended_left_tang_core = tf.expand_dims(left_tang_core, 0)\n extended_right_tang_core = tf.expand_dims(right_tang_core, 0)\n extended_left_tang_core = tf.tile(extended_left_tang_core,\n [output_batch_size, 1, 1, 1, 1])\n extended_right_tang_core = tf.tile(extended_right_tang_core,\n [output_batch_size, 1, 1, 1, 1])\n else:\n extended_left_tang_core = left_tang_core\n extended_right_tang_core = right_tang_core\n\n if core_idx == 0:\n res_core = tf.concat((proj_core, extended_left_tang_core),\n axis=right_rank_dim)\n elif core_idx == ndims - 1:\n res_core = tf.concat((extended_right_tang_core, proj_core),\n axis=left_rank_dim)\n else:\n rank_1 = right_tangent_tt_ranks[core_idx]\n rank_2 = left_tangent_tt_ranks[core_idx + 1]\n mode_size_n = raw_shape[0][core_idx]\n mode_size_m = raw_shape[1][core_idx]\n shape = [rank_1, mode_size_n, mode_size_m, rank_2]\n if output_is_batch:\n shape = [output_batch_size] + shape\n zeros = tf.zeros(shape, dtype)\n upper = tf.concat((extended_right_tang_core, zeros),\n axis=right_rank_dim)\n lower = tf.concat((proj_core, extended_left_tang_core),\n axis=right_rank_dim)\n res_core = tf.concat((upper, lower), axis=left_rank_dim)\n res_cores_list.append(res_core)\n\n # TODO: TT-ranks.\n if output_is_batch:\n res = TensorTrainBatch(res_cores_list, where.get_raw_shape(),\n batch_size=output_batch_size)\n else:\n res = TensorTrain(res_cores_list, where.get_raw_shape())\n\n res.projection_on = where\n return res\n\n\ndef pairwise_flat_inner_projected(projected_tt_vectors_1,\n projected_tt_vectors_2):\n \"\"\"Scalar products between two batches of TTs from the same tangent space.\n\n res[i, j] = t3f.flat_inner(projected_tt_vectors_1[i], projected_tt_vectors_1[j]).\n\n pairwise_flat_inner_projected(projected_tt_vectors_1, projected_tt_vectors_2)\n is equivalent to\n pairwise_flat_inner(projected_tt_vectors_1, projected_tt_vectors_2)\n , but works only on objects from the same tangent space and is much faster\n than general pairwise_flat_inner.\n\n Args:\n projected_tt_vectors_1: TensorTrainBatch of tensors projected on the same\n tangent space as projected_tt_vectors_2.\n projected_tt_vectors_2: TensorTrainBatch.\n\n Returns:\n tf.tensor with the scalar product matrix.\n \n Complexity:\n O(batch_size^2 d r^2 n), where\n d is the number of TT-cores (projected_tt_vectors_1.ndims());\n r is the largest TT-rank max(projected_tt_vectors_1.get_tt_rank())\n (i.e. 2 * {the TT-rank of the object we projected vectors onto}.\n and n is the size of the axis dimension, e.g.\n for a tensor of size 4 x 4 x 4, n is 4;\n for a 9 x 64 matrix of raw shape (3, 3, 3) x (4, 4, 4) n is 12.\n \"\"\"\n if not hasattr(projected_tt_vectors_1, 'projection_on') or \\\n not hasattr(projected_tt_vectors_2, 'projection_on'):\n raise ValueError('Both arguments should be projections on the tangent '\n 'space of some other TT-object. All projection* functions '\n 'leave .projection_on field in the resulting TT-object '\n 'which is not present in the arguments you\\'ve provided')\n\n if projected_tt_vectors_1.projection_on != projected_tt_vectors_2.projection_on:\n raise ValueError('Both arguments should be projections on the tangent '\n 'space of the same TT-object. The provided arguments are '\n 'projections on different TT-objects (%s and %s). Or at '\n 'least the pointers are different.' %\n (projected_tt_vectors_1.projection_on,\n projected_tt_vectors_2.projection_on))\n\n # Always work with batches of objects for simplicity.\n projected_tt_vectors_1 = shapes.expand_batch_dim(projected_tt_vectors_1)\n projected_tt_vectors_2 = shapes.expand_batch_dim(projected_tt_vectors_2)\n\n ndims = projected_tt_vectors_1.ndims()\n tt_ranks = shapes.lazy_tt_ranks(projected_tt_vectors_1)\n\n if projected_tt_vectors_1.is_tt_matrix():\n right_size = tt_ranks[1] // 2\n curr_core_1 = projected_tt_vectors_1.tt_cores[0]\n curr_core_2 = projected_tt_vectors_2.tt_cores[0]\n curr_du_1 = curr_core_1[:, :, :, :, :right_size]\n curr_du_2 = curr_core_2[:, :, :, :, :right_size]\n res = tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)\n for core_idx in range(1, ndims):\n left_size = tt_ranks[core_idx] // 2\n right_size = tt_ranks[core_idx + 1] // 2\n curr_core_1 = projected_tt_vectors_1.tt_cores[core_idx]\n curr_core_2 = projected_tt_vectors_2.tt_cores[core_idx]\n curr_du_1 = curr_core_1[:, left_size:, :, :, :right_size]\n curr_du_2 = curr_core_2[:, left_size:, :, :, :right_size]\n res += tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)\n\n left_size = tt_ranks[-2] // 2\n curr_core_1 = projected_tt_vectors_1.tt_cores[-1]\n curr_core_2 = projected_tt_vectors_2.tt_cores[-1]\n curr_du_1 = curr_core_1[:, left_size:, :, :, :]\n curr_du_2 = curr_core_2[:, left_size:, :, :, :]\n res += tf.einsum('paijb,qaijb->pq', curr_du_1, curr_du_2)\n else:\n # Working with TT-tensor, not TT-matrix.\n right_size = tt_ranks[1] // 2\n curr_core_1 = projected_tt_vectors_1.tt_cores[0]\n curr_core_2 = projected_tt_vectors_2.tt_cores[0]\n curr_du_1 = curr_core_1[:, :, :, :right_size]\n curr_du_2 = curr_core_2[:, :, :, :right_size]\n res = tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)\n for core_idx in range(1, ndims):\n left_size = tt_ranks[core_idx] // 2\n right_size = tt_ranks[core_idx + 1] // 2\n curr_core_1 = projected_tt_vectors_1.tt_cores[core_idx]\n curr_core_2 = projected_tt_vectors_2.tt_cores[core_idx]\n curr_du_1 = curr_core_1[:, left_size:, :, :right_size]\n curr_du_2 = curr_core_2[:, left_size:, :, :right_size]\n res += tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)\n\n left_size = tt_ranks[-2] // 2\n curr_core_1 = projected_tt_vectors_1.tt_cores[-1]\n curr_core_2 = projected_tt_vectors_2.tt_cores[-1]\n curr_du_1 = curr_core_1[:, left_size:, :, :]\n curr_du_2 = curr_core_2[:, left_size:, :, :]\n res += tf.einsum('paib,qaib->pq', curr_du_1, curr_du_2)\n return res\n\n\ndef add_n_projected(tt_objects, coef=None):\n \"\"\"Adds all input TT-objects that are projections on the same tangent space.\n\n add_projected((a, b)) is equivalent add(a, b) for a and b that are from the\n same tangent space, but doesn't increase the TT-ranks.\n\n Args:\n tt_objects: a list of TT-objects that are projections on the same tangent\n space.\n coef: a list of numbers or anything else convertable to tf.Tensor.\n If provided, computes weighted sum. The size of this array should be\n len(tt_objects) x tt_objects[0].batch_size\n\n Returns:\n TT-objects representing the sum of the tt_objects (weighted sum if coef is\n provided). The TT-rank of the result equals to the TT-ranks of the arguments.\n \"\"\"\n for tt in tt_objects:\n if not hasattr(tt, 'projection_on'):\n raise ValueError('Both arguments should be projections on the tangent '\n 'space of some other TT-object. All projection* functions '\n 'leave .projection_on field in the resulting TT-object '\n 'which is not present in the argument you\\'ve provided.')\n\n projection_on = tt_objects[0].projection_on\n for tt in tt_objects[1:]:\n if tt.projection_on != projection_on:\n raise ValueError('All tt_objects should be projections on the tangent '\n 'space of the same TT-object. The provided arguments are '\n 'projections on different TT-objects (%s and %s). Or at '\n 'least the pointers are different.' % (tt.projection_on,\n projection_on))\n if coef is not None:\n coef = tf.convert_to_tensor(coef, dtype=tt_objects[0].dtype)\n if coef.get_shape().ndims > 1:\n # In batch case we will need to multiply each core by this coefficients\n # along the first axis. To do it need to reshape the coefs to match\n # the TT-cores number of dimensions.\n some_core = tt_objects[0].tt_cores[0]\n dim_array = [1] * (some_core.get_shape().ndims + 1)\n dim_array[0] = coef.get_shape()[0].value\n dim_array[1] = coef.get_shape()[1].value\n coef = tf.reshape(coef, dim_array)\n\n ndims = tt_objects[0].ndims()\n tt_ranks = shapes.lazy_tt_ranks(tt_objects[0])\n left_rank_dim = tt_objects[0].left_tt_rank_dim\n right_rank_dim = tt_objects[0].right_tt_rank_dim\n res_cores = []\n\n def slice_tt_core(tt_core, left_idx, right_idx):\n num_tt_core_dims = len(tt_core.get_shape())\n idx = [slice(None)] * num_tt_core_dims\n idx[left_rank_dim] = left_idx\n idx[right_rank_dim] = right_idx\n return tt_core[idx]\n\n right_half_rank = tt_ranks[1] // 2\n left_chunks = []\n for obj_idx, tt in enumerate(tt_objects):\n curr_core = slice_tt_core(tt.tt_cores[0], slice(None),\n slice(0, right_half_rank))\n if coef is not None:\n curr_core *= coef[obj_idx]\n left_chunks.append(curr_core)\n left_part = tf.add_n(left_chunks)\n first_obj_core = tt_objects[0].tt_cores[0]\n right_part = slice_tt_core(first_obj_core, slice(None),\n slice(right_half_rank, None))\n first_core = tf.concat((left_part, right_part), axis=right_rank_dim)\n res_cores.append(first_core)\n\n for core_idx in range(1, ndims - 1):\n first_obj_core = tt_objects[0].tt_cores[core_idx]\n left_half_rank = tt_ranks[core_idx] // 2\n right_half_rank = tt_ranks[core_idx + 1] // 2\n\n upper_part = slice_tt_core(tt.tt_cores[core_idx], slice(0, left_half_rank),\n slice(None))\n lower_right_part = slice_tt_core(first_obj_core,\n slice(left_half_rank, None),\n slice(right_half_rank, None))\n\n lower_left_chunks = []\n for obj_idx, tt in enumerate(tt_objects):\n curr_core = slice_tt_core(tt.tt_cores[core_idx],\n slice(left_half_rank, None),\n slice(0, right_half_rank))\n if coef is not None:\n curr_core *= coef[obj_idx]\n lower_left_chunks.append(curr_core)\n lower_left_part = tf.add_n(lower_left_chunks)\n lower_part = tf.concat((lower_left_part, lower_right_part),\n axis=right_rank_dim)\n curr_core = tf.concat((upper_part, lower_part), axis=left_rank_dim)\n res_cores.append(curr_core)\n\n left_half_rank = tt_ranks[ndims - 1] // 2\n upper_part = slice_tt_core(tt.tt_cores[-1], slice(0, left_half_rank),\n slice(None))\n lower_chunks = []\n for obj_idx, tt in enumerate(tt_objects):\n curr_core = slice_tt_core(tt.tt_cores[-1], slice(left_half_rank, None),\n slice(None))\n if coef is not None:\n curr_core *= coef[obj_idx]\n lower_chunks.append(curr_core)\n lower_part = tf.add_n(lower_chunks)\n last_core = tf.concat((upper_part, lower_part), axis=left_rank_dim)\n res_cores.append(last_core)\n\n raw_shape = tt_objects[0].get_raw_shape()\n static_tt_ranks = tt_objects[0].get_tt_ranks()\n if isinstance(tt_objects[0], TensorTrain):\n res = TensorTrain(res_cores, raw_shape, static_tt_ranks)\n elif isinstance(tt_objects[0], TensorTrainBatch):\n res = TensorTrainBatch(res_cores, raw_shape, static_tt_ranks,\n tt_objects[0].batch_size)\n # Maintain the projection_on property.\n res.projection_on = tt_objects[0].projection_on\n return res\n\n\ndef tangent_space_to_deltas(tt, name='t3f_tangent_space_to_deltas'):\n \"\"\"Convert an element of the tangent space to deltas representation.\n\n Tangent space elements (outputs of t3f.project) look like:\n dP1 V2 ... Vd + U1 dP2 V3 ... Vd + ... + U1 ... Ud-1 dPd.\n\n This function takes as input an element of the tangent space and converts\n it to the list of deltas [dP1, ..., dPd].\n\n Args:\n tt: `TensorTrain` or `TensorTrainBatch` that is a result of t3f.project,\n t3f.project_matmul, or other similar functions.\n name: string, name of the Op.\n\n Returns:\n A list of delta-cores (tf.Tensors).\n \"\"\"\n if not hasattr(tt, 'projection_on') or tt.projection_on is None:\n raise ValueError('tt argument is supposed to be a projection, but it '\n 'lacks projection_on field')\n num_dims = tt.ndims()\n left_tt_rank_dim = tt.left_tt_rank_dim\n right_tt_rank_dim = tt.right_tt_rank_dim\n deltas = [None] * num_dims\n tt_ranks = shapes.lazy_tt_ranks(tt)\n for i in range(1, num_dims - 1):\n if int(tt_ranks[i] / 2) != tt_ranks[i] / 2:\n raise ValueError('tt argument is supposed to be a projection, but its '\n 'ranks are not even.')\n with tf.name_scope(name, values=tt.tt_cores):\n for i in range(1, num_dims - 1):\n r1, r2 = tt_ranks[i], tt_ranks[i + 1]\n curr_core = tt.tt_cores[i]\n slc = [slice(None)] * len(curr_core.shape)\n slc[left_tt_rank_dim] = slice(int(r1 / 2), None)\n slc[right_tt_rank_dim] = slice(0, int(r2 / 2))\n deltas[i] = curr_core[slc]\n slc = [slice(None)] * len(tt.tt_cores[0].shape)\n slc[right_tt_rank_dim] = slice(0, int(tt_ranks[1] / 2))\n deltas[0] = tt.tt_cores[0][slc]\n slc = [slice(None)] * len(tt.tt_cores[0].shape)\n slc[left_tt_rank_dim] = slice(int(tt_ranks[-2] / 2), None)\n deltas[num_dims - 1] = tt.tt_cores[num_dims - 1][slc]\n return deltas\n\n\ndef deltas_to_tangent_space(deltas, tt, left=None, right=None,\n name='t3f_deltas_to_tangent_space'):\n \"\"\"Converts deltas representation of tangent space vector to TT object.\n\n Takes as input a list of [dP1, ..., dPd] and returns\n dP1 V2 ... Vd + U1 dP2 V3 ... Vd + ... + U1 ... Ud-1 dPd.\n\n This function is hard to use correctly because deltas should abey the\n so called gauge conditions. If the don't, the function will silently return\n incorrect result. This is why this function is not imported in __init__.\n\n Args:\n deltas: a list of deltas (essentially TT-cores) obeying the gauge\n conditions.\n tt: `TensorTrain` object on which the tangent space tensor represented by\n delta is projected.\n left: t3f.orthogonilize_tt_cores(tt). If you have it already compute, you\n may pass it as argument to avoid recomputing.\n right: t3f.orthogonilize_tt_cores(left, left_to_right=False). If you have\n it already compute, you may pass it as argument to avoid recomputing.\n name: string, name of the Op.\n\n Returns:\n `TensorTrain` object constructed from deltas, that is from the tangent\n space at point `tt`.\n \"\"\"\n cores = []\n dtype = tt.dtype\n num_dims = tt.ndims()\n # TODO: add cache instead of mannually pasisng precomputed stuff?\n input_tensors = list(tt.tt_cores) + list(deltas)\n if left is not None:\n input_tensors += list(left.tt_cores)\n if right is not None:\n input_tensors += list(right.tt_cores)\n with tf.name_scope(name, values=input_tensors):\n if left is None:\n left = decompositions.orthogonalize_tt_cores(tt)\n if right is None:\n right = decompositions.orthogonalize_tt_cores(left, left_to_right=False)\n left_tangent_tt_ranks = shapes.lazy_tt_ranks(left)\n right_tangent_tt_ranks = shapes.lazy_tt_ranks(left)\n raw_shape = shapes.lazy_raw_shape(left)\n right_rank_dim = left.right_tt_rank_dim\n left_rank_dim = left.left_tt_rank_dim\n is_batch_case = len(deltas[0].shape) > len(tt.tt_cores[0].shape)\n if is_batch_case:\n right_rank_dim += 1\n left_rank_dim += 1\n batch_size = deltas[0].shape.as_list()[0]\n for i in range(num_dims):\n left_tt_core = left.tt_cores[i]\n right_tt_core = right.tt_cores[i]\n if is_batch_case:\n tile = [1] * len(left_tt_core.shape)\n tile = [batch_size] + tile\n left_tt_core = tf.tile(left_tt_core[None, ...], tile)\n right_tt_core = tf.tile(right_tt_core[None, ...], tile)\n\n if i == 0:\n tangent_core = tf.concat((deltas[i], left_tt_core),\n axis=right_rank_dim)\n elif i == num_dims - 1:\n tangent_core = tf.concat((right_tt_core, deltas[i]),\n axis=left_rank_dim)\n else:\n rank_1 = right_tangent_tt_ranks[i]\n rank_2 = left_tangent_tt_ranks[i + 1]\n if tt.is_tt_matrix():\n mode_size_n = raw_shape[0][i]\n mode_size_m = raw_shape[1][i]\n shape = [rank_1, mode_size_n, mode_size_m, rank_2]\n else:\n mode_size_n = raw_shape[0][i]\n shape = [rank_1, mode_size_n, rank_2]\n if is_batch_case:\n shape = [batch_size] + shape\n zeros = tf.zeros(shape, dtype=dtype)\n upper = tf.concat((right_tt_core, zeros), axis=right_rank_dim)\n lower = tf.concat((deltas[i], left_tt_core), axis=right_rank_dim)\n tangent_core = tf.concat((upper, lower), axis=left_rank_dim)\n cores.append(tangent_core)\n if is_batch_case:\n tangent = TensorTrainBatch(cores, batch_size=batch_size)\n else:\n tangent = TensorTrain(cores)\n tangent.projection_on = tt\n return tangent\n" ]
[ [ "tensorflow.compat.v1.ones", "tensorflow.compat.v1.concat", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.add_n", "tensorflow.compat.v1.convert_to_tensor", "tensorflow.compat.v1.einsum", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.tile", "tensorflow.compat.v1.name_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
agstephens/intake-esm
[ "25ead83497d025c37a80abdbefee9b286934308b" ]
[ "intake_esm/cat.py" ]
[ "import enum\nimport json\nimport os\nimport pathlib\nimport typing\n\nimport fsspec\nimport pandas as pd\nimport pydantic\nimport tlz\n\nfrom ._search import search, search_apply_require_all_on\n\n\nclass AggregationType(str, enum.Enum):\n join_new = 'join_new'\n join_existing = 'join_existing'\n union = 'union'\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n\nclass DataFormat(str, enum.Enum):\n netcdf = 'netcdf'\n zarr = 'zarr'\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n\nclass Attribute(pydantic.BaseModel):\n column_name: pydantic.StrictStr\n vocabulary: pydantic.StrictStr = ''\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n\nclass Assets(pydantic.BaseModel):\n column_name: pydantic.StrictStr\n format: DataFormat\n format_column_name: typing.Optional[pydantic.StrictStr]\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n @pydantic.root_validator\n def _validate_data_format(cls, values):\n data_format, format_column_name = values.get('format'), values.get('format_column_name')\n if data_format is not None and format_column_name is not None:\n raise ValueError('Cannot set both format and format_column_name')\n return values\n\n\nclass Aggregation(pydantic.BaseModel):\n type: AggregationType\n attribute_name: pydantic.StrictStr\n options: typing.Optional[typing.Dict] = {}\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n\nclass AggregationControl(pydantic.BaseModel):\n variable_column_name: pydantic.StrictStr\n groupby_attrs: typing.List[pydantic.StrictStr]\n aggregations: typing.List[Aggregation] = []\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n\nclass ESMCatalogModel(pydantic.BaseModel):\n \"\"\"\n Pydantic model for the ESM data catalog defined in https://git.io/JBWoW\n \"\"\"\n\n esmcat_version: pydantic.StrictStr\n id: str\n attributes: typing.List[Attribute]\n assets: Assets\n aggregation_control: AggregationControl\n catalog_dict: typing.Optional[typing.List[typing.Dict]] = None\n catalog_file: pydantic.StrictStr = None\n description: pydantic.StrictStr = None\n title: pydantic.StrictStr = None\n _df: typing.Optional[typing.Any] = pydantic.PrivateAttr()\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n @pydantic.root_validator\n def validate_catalog(cls, values):\n catalog_dict, catalog_file = values.get('catalog_dict'), values.get('catalog_file')\n if catalog_dict is not None and catalog_file is not None:\n raise ValueError('catalog_dict and catalog_file cannot be set at the same time')\n\n return values\n\n @classmethod\n def from_dict(cls, data: typing.Dict) -> 'ESMCatalogModel':\n esmcat = data['esmcat']\n df = data['df']\n cat = cls.parse_obj(esmcat)\n cat._df = df\n return cat\n\n def save(self, name: str, *, directory: str = None, catalog_type: str = 'dict') -> None:\n \"\"\"\n Save the catalog to a file.\n\n Parameters\n -----------\n name: str\n The name of the file to save the catalog to.\n directory: str\n The directory to save the catalog to. If None, use the current directory\n catalog_type: str\n The type of catalog to save. Whether to save the catalog table as a dictionary\n in the JSON file or as a separate CSV file. Valid options are 'dict' and 'file'.\n\n Notes\n -----\n Large catalogs can result in large JSON files. To keep the JSON file size manageable, call with\n `catalog_type='file'` to save catalog as a separate CSV file.\n\n \"\"\"\n\n if catalog_type not in {'file', 'dict'}:\n raise ValueError(\n f'catalog_type must be either \"dict\" or \"file\". Received catalog_type={catalog_type}'\n )\n csv_file_name = pathlib.Path(f'{name}.csv.gz')\n json_file_name = pathlib.Path(f'{name}.json')\n if directory:\n directory = pathlib.Path(directory)\n directory.mkdir(parents=True, exist_ok=True)\n csv_file_name = directory / csv_file_name\n json_file_name = directory / json_file_name\n\n data = self.dict().copy()\n for key in {'catalog_dict', 'catalog_file'}:\n data.pop(key, None)\n data['id'] = name\n\n if catalog_type == 'file':\n data['catalog_file'] = str(csv_file_name)\n self.df.to_csv(csv_file_name, compression='gzip', index=False)\n else:\n data['catalog_dict'] = self.df.to_dict(orient='records')\n\n with open(json_file_name, 'w') as outfile:\n json.dump(data, outfile, indent=2)\n\n print(f'Successfully wrote ESM collection json file to: {json_file_name}')\n\n @classmethod\n def load(\n cls,\n json_file: typing.Union[str, pydantic.FilePath, pydantic.AnyUrl],\n storage_options: typing.Dict[str, typing.Any] = None,\n read_csv_kwargs: typing.Dict[str, typing.Any] = None,\n ) -> 'ESMCatalogModel':\n \"\"\"\n Loads the catalog from a file\n \"\"\"\n storage_options = storage_options if storage_options is not None else {}\n read_csv_kwargs = read_csv_kwargs or {}\n _mapper = fsspec.get_mapper(json_file, **storage_options)\n\n with fsspec.open(json_file, **storage_options) as fobj:\n cat = cls.parse_raw(fobj.read())\n if cat.catalog_file:\n if _mapper.fs.exists(cat.catalog_file):\n csv_path = cat.catalog_file\n else:\n csv_path = f'{os.path.dirname(_mapper.root)}/{cat.catalog_file}'\n cat.catalog_file = csv_path\n df = pd.read_csv(\n cat.catalog_file,\n storage_options=storage_options,\n **read_csv_kwargs,\n )\n else:\n df = pd.DataFrame(cat.catalog_dict)\n\n cat._df = df\n cat._cast_agg_columns_with_iterables()\n return cat\n\n @property\n def columns_with_iterables(self) -> typing.Set[str]:\n \"\"\"Return a set of columns that have iterables.\"\"\"\n if self._df.empty:\n return set()\n has_iterables = (\n self._df.sample(20, replace=True)\n .applymap(type)\n .isin([list, tuple, set])\n .any()\n .to_dict()\n )\n return {column for column, check in has_iterables.items() if check}\n\n @property\n def has_multiple_variable_assets(self) -> bool:\n \"\"\"Return True if the catalog has multiple variable assets.\"\"\"\n return self.aggregation_control.variable_column_name in self.columns_with_iterables\n\n @property\n def df(self) -> pd.DataFrame:\n \"\"\"Return the dataframe.\"\"\"\n return self._df\n\n @df.setter\n def df(self, value: pd.DataFrame) -> None:\n self._df = value\n\n def _cast_agg_columns_with_iterables(self) -> None:\n \"\"\"Cast all agg_columns with iterables to tuple values so as\n to avoid hashing issues (e.g. TypeError: unhashable type: 'list')\n \"\"\"\n columns = list(\n self.columns_with_iterables.intersection(\n set(map(lambda agg: agg.attribute_name, self.aggregation_control.aggregations))\n )\n )\n if columns:\n self._df[columns] = self._df[columns].apply(tuple)\n\n @property\n def grouped(self) -> typing.Union[pd.core.groupby.DataFrameGroupBy, pd.DataFrame]:\n if self.aggregation_control.groupby_attrs and set(\n self.aggregation_control.groupby_attrs\n ) != set(self.df.columns):\n return self.df.groupby(self.aggregation_control.groupby_attrs)\n return self.df\n\n def _construct_group_keys(\n self, sep: str = '.'\n ) -> typing.Dict[str, typing.Union[str, typing.Tuple[str]]]:\n grouped = self.grouped\n if isinstance(grouped, pd.core.groupby.generic.DataFrameGroupBy):\n internal_keys = grouped.groups.keys()\n public_keys = map(\n lambda key: key if isinstance(key, str) else sep.join(str(value) for value in key),\n internal_keys,\n )\n\n else:\n internal_keys = grouped.index\n public_keys = (\n grouped[grouped.columns.tolist()]\n .apply(lambda row: sep.join(str(v) for v in row), axis=1)\n .tolist()\n )\n\n return dict(zip(public_keys, internal_keys))\n\n def _unique(self) -> typing.Dict:\n def _find_unique(series):\n values = series.dropna()\n if series.name in self.columns_with_iterables:\n values = tlz.concat(values)\n return list(tlz.unique(values))\n\n data = self.df[self.df.columns]\n if data.empty:\n return {col: [] for col in self.df.columns}\n else:\n return data.apply(_find_unique, result_type='reduce').to_dict()\n\n def unique(self) -> pd.Series:\n return pd.Series(self._unique())\n\n def nunique(self) -> pd.Series:\n return pd.Series(tlz.valmap(len, self._unique()))\n\n def search(\n self,\n *,\n query: typing.Union['QueryModel', typing.Dict[str, typing.Any]],\n require_all_on: typing.Union[str, typing.List[str]] = None,\n ) -> 'ESMCatalogModel':\n \"\"\"\n Search for entries in the catalog.\n\n Parameters\n ----------\n query: dict, optional\n A dictionary of query parameters to execute against the dataframe.\n require_all_on : list, str, optional\n A dataframe column or a list of dataframe columns across\n which all entries must satisfy the query criteria.\n If None, return entries that fulfill any of the criteria specified\n in the query, by default None.\n\n \"\"\"\n\n if not isinstance(query, QueryModel):\n _query = QueryModel(\n query=query, require_all_on=require_all_on, columns=self.df.columns.tolist()\n )\n else:\n _query = query\n\n results = search(\n df=self.df, query=_query.query, columns_with_iterables=self.columns_with_iterables\n )\n if _query.require_all_on is not None and not results.empty:\n results = search_apply_require_all_on(\n df=results, query=_query.query, require_all_on=_query.require_all_on\n )\n return results\n\n\nclass QueryModel(pydantic.BaseModel):\n query: typing.Dict[pydantic.StrictStr, typing.Union[typing.Any, typing.List[typing.Any]]]\n columns: typing.List[str]\n require_all_on: typing.Union[str, typing.List[typing.Any]] = None\n\n class Config:\n validate_all = True\n validate_assignment = True\n\n @pydantic.root_validator(pre=False)\n def validate_query(cls, values):\n query = values.get('query', {})\n columns = values.get('columns')\n require_all_on = values.get('require_all_on', [])\n\n if query:\n for key in query:\n if key not in columns:\n raise ValueError(f'Column {key} not in columns {columns}')\n if isinstance(require_all_on, str):\n values['require_all_on'] = [require_all_on]\n if require_all_on is not None:\n for key in values['require_all_on']:\n if key not in columns:\n raise ValueError(f'Column {key} not in columns {columns}')\n _query = query.copy()\n for key, value in _query.items():\n if isinstance(value, (str, int, float, bool)):\n _query[key] = [value]\n\n values['query'] = _query\n return values\n" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
ivanov/numpy
[ "6d2665626e40f346bb5af8d780579f5a429ff9ba", "6d2665626e40f346bb5af8d780579f5a429ff9ba", "6d2665626e40f346bb5af8d780579f5a429ff9ba", "6d2665626e40f346bb5af8d780579f5a429ff9ba", "6d2665626e40f346bb5af8d780579f5a429ff9ba", "6d2665626e40f346bb5af8d780579f5a429ff9ba" ]
[ "numpy/polynomial/hermite.py", "numpy/polynomial/tests/test_hermite_e.py", "numpy/numarray/__init__.py", "numpy/testing/tests/test_doctesting.py", "numpy/oldnumeric/arrayfns.py", "numpy/oldnumeric/__init__.py" ]
[ "\"\"\"\nObjects for dealing with Hermite series.\n\nThis module provides a number of objects (mostly functions) useful for\ndealing with Hermite series, including a `Hermite` class that\nencapsulates the usual arithmetic operations. (General information\non how this module represents and works with such polynomials is in the\ndocstring for its \"parent\" sub-package, `numpy.polynomial`).\n\nConstants\n---------\n- `hermdomain` -- Hermite series default domain, [-1,1].\n- `hermzero` -- Hermite series that evaluates identically to 0.\n- `hermone` -- Hermite series that evaluates identically to 1.\n- `hermx` -- Hermite series for the identity map, ``f(x) = x``.\n\nArithmetic\n----------\n- `hermmulx` -- multiply a Hermite series in ``P_i(x)`` by ``x``.\n- `hermadd` -- add two Hermite series.\n- `hermsub` -- subtract one Hermite series from another.\n- `hermmul` -- multiply two Hermite series.\n- `hermdiv` -- divide one Hermite series by another.\n- `hermval` -- evaluate a Hermite series at given points.\n- `hermval2d` -- evaluate a 2D Hermite series at given points.\n- `hermval3d` -- evaluate a 3D Hermite series at given points.\n- `hermgrid2d` -- evaluate a 2D Hermite series on a Cartesian product.\n- `hermgrid3d` -- evaluate a 3D Hermite series on a Cartesian product.\n\nCalculus\n--------\n- `hermder` -- differentiate a Hermite series.\n- `hermint` -- integrate a Hermite series.\n\nMisc Functions\n--------------\n- `hermfromroots` -- create a Hermite series with specified roots.\n- `hermroots` -- find the roots of a Hermite series.\n- `hermvander` -- Vandermonde-like matrix for Hermite polynomials.\n- `hermvander2d` -- Vandermonde-like matrix for 2D power series.\n- `hermvander3d` -- Vandermonde-like matrix for 3D power series.\n- `hermgauss` -- Gauss-Hermite quadrature, points and weights.\n- `hermweight` -- Hermite weight function.\n- `hermcompanion` -- symmetrized companion matrix in Hermite form.\n- `hermfit` -- least-squares fit returning a Hermite series.\n- `hermtrim` -- trim leading coefficients from a Hermite series.\n- `hermline` -- Hermite series of given straight line.\n- `herm2poly` -- convert a Hermite series to a polynomial.\n- `poly2herm` -- convert a polynomial to a Hermite series.\n\nClasses\n-------\n- `Hermite` -- A Hermite series class.\n\nSee also\n--------\n`numpy.polynomial`\n\n\"\"\"\nfrom __future__ import division, absolute_import\n\nimport numpy as np\nimport numpy.linalg as la\nfrom . import polyutils as pu\nimport warnings\nfrom .polytemplate import polytemplate\n\n__all__ = ['hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline',\n 'hermadd', 'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow',\n 'hermval', 'hermder', 'hermint', 'herm2poly', 'poly2herm',\n 'hermfromroots', 'hermvander', 'hermfit', 'hermtrim', 'hermroots',\n 'Hermite', 'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d',\n 'hermvander2d', 'hermvander3d', 'hermcompanion', 'hermgauss',\n 'hermweight']\n\nhermtrim = pu.trimcoef\n\n\ndef poly2herm(pol) :\n \"\"\"\n poly2herm(pol)\n\n Convert a polynomial to a Hermite series.\n\n Convert an array representing the coefficients of a polynomial (relative\n to the \"standard\" basis) ordered from lowest degree to highest, to an\n array of the coefficients of the equivalent Hermite series, ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n pol : array_like\n 1-D array containing the polynomial coefficients\n\n Returns\n -------\n c : ndarray\n 1-D array containing the coefficients of the equivalent Hermite\n series.\n\n See Also\n --------\n herm2poly\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite_e import poly2herme\n >>> poly2herm(np.arange(4))\n array([ 1. , 2.75 , 0.5 , 0.375])\n\n \"\"\"\n [pol] = pu.as_series([pol])\n deg = len(pol) - 1\n res = 0\n for i in range(deg, -1, -1) :\n res = hermadd(hermmulx(res), pol[i])\n return res\n\n\ndef herm2poly(c) :\n \"\"\"\n Convert a Hermite series to a polynomial.\n\n Convert an array representing the coefficients of a Hermite series,\n ordered from lowest degree to highest, to an array of the coefficients\n of the equivalent polynomial (relative to the \"standard\" basis) ordered\n from lowest to highest degree.\n\n Parameters\n ----------\n c : array_like\n 1-D array containing the Hermite series coefficients, ordered\n from lowest order term to highest.\n\n Returns\n -------\n pol : ndarray\n 1-D array containing the coefficients of the equivalent polynomial\n (relative to the \"standard\" basis) ordered from lowest order term\n to highest.\n\n See Also\n --------\n poly2herm\n\n Notes\n -----\n The easy way to do conversions between polynomial basis sets\n is to use the convert method of a class instance.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import herm2poly\n >>> herm2poly([ 1. , 2.75 , 0.5 , 0.375])\n array([ 0., 1., 2., 3.])\n\n \"\"\"\n from .polynomial import polyadd, polysub, polymulx\n\n [c] = pu.as_series([c])\n n = len(c)\n if n == 1:\n return c\n if n == 2:\n c[1] *= 2\n return c\n else:\n c0 = c[-2]\n c1 = c[-1]\n # i is the current degree of c1\n for i in range(n - 1, 1, -1) :\n tmp = c0\n c0 = polysub(c[i - 2], c1*(2*(i - 1)))\n c1 = polyadd(tmp, polymulx(c1)*2)\n return polyadd(c0, polymulx(c1)*2)\n\n#\n# These are constant arrays are of integer type so as to be compatible\n# with the widest range of other types, such as Decimal.\n#\n\n# Hermite\nhermdomain = np.array([-1,1])\n\n# Hermite coefficients representing zero.\nhermzero = np.array([0])\n\n# Hermite coefficients representing one.\nhermone = np.array([1])\n\n# Hermite coefficients representing the identity x.\nhermx = np.array([0, 1/2])\n\n\ndef hermline(off, scl) :\n \"\"\"\n Hermite series whose graph is a straight line.\n\n\n\n Parameters\n ----------\n off, scl : scalars\n The specified line is given by ``off + scl*x``.\n\n Returns\n -------\n y : ndarray\n This module's representation of the Hermite series for\n ``off + scl*x``.\n\n See Also\n --------\n polyline, chebline\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermline, hermval\n >>> hermval(0,hermline(3, 2))\n 3.0\n >>> hermval(1,hermline(3, 2))\n 5.0\n\n \"\"\"\n if scl != 0 :\n return np.array([off,scl/2])\n else :\n return np.array([off])\n\n\ndef hermfromroots(roots) :\n \"\"\"\n Generate a Hermite series with given roots.\n\n The function returns the coefficients of the polynomial\n\n .. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),\n\n in Hermite form, where the `r_n` are the roots specified in `roots`.\n If a zero has multiplicity n, then it must appear in `roots` n times.\n For instance, if 2 is a root of multiplicity three and 3 is a root of\n multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The\n roots can appear in any order.\n\n If the returned coefficients are `c`, then\n\n .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x)\n\n The coefficient of the last term is not generally 1 for monic\n polynomials in Hermite form.\n\n Parameters\n ----------\n roots : array_like\n Sequence containing the roots.\n\n Returns\n -------\n out : ndarray\n 1-D array of coefficients. If all roots are real then `out` is a\n real array, if some of the roots are complex, then `out` is complex\n even if all the coefficients in the result are real (see Examples\n below).\n\n See Also\n --------\n polyfromroots, legfromroots, lagfromroots, chebfromroots,\n hermefromroots.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermfromroots, hermval\n >>> coef = hermfromroots((-1, 0, 1))\n >>> hermval((-1, 0, 1), coef)\n array([ 0., 0., 0.])\n >>> coef = hermfromroots((-1j, 1j))\n >>> hermval((-1j, 1j), coef)\n array([ 0.+0.j, 0.+0.j])\n\n \"\"\"\n if len(roots) == 0 :\n return np.ones(1)\n else :\n [roots] = pu.as_series([roots], trim=False)\n roots.sort()\n p = [hermline(-r, 1) for r in roots]\n n = len(p)\n while n > 1:\n m, r = divmod(n, 2)\n tmp = [hermmul(p[i], p[i+m]) for i in range(m)]\n if r:\n tmp[0] = hermmul(tmp[0], p[-1])\n p = tmp\n n = m\n return p[0]\n\n\ndef hermadd(c1, c2):\n \"\"\"\n Add one Hermite series to another.\n\n Returns the sum of two Hermite series `c1` + `c2`. The arguments\n are sequences of coefficients ordered from lowest order term to\n highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the Hermite series of their sum.\n\n See Also\n --------\n hermsub, hermmul, hermdiv, hermpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the sum of two Hermite series\n is a Hermite series (without having to \"reproject\" the result onto\n the basis set) so addition, just like that of \"standard\" polynomials,\n is simply \"component-wise.\"\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermadd\n >>> hermadd([1, 2, 3], [1, 2, 3, 4])\n array([ 2., 4., 6., 4.])\n\n \"\"\"\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n if len(c1) > len(c2) :\n c1[:c2.size] += c2\n ret = c1\n else :\n c2[:c1.size] += c1\n ret = c2\n return pu.trimseq(ret)\n\n\ndef hermsub(c1, c2):\n \"\"\"\n Subtract one Hermite series from another.\n\n Returns the difference of two Hermite series `c1` - `c2`. The\n sequences of coefficients are from lowest order term to highest, i.e.,\n [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Hermite series coefficients representing their difference.\n\n See Also\n --------\n hermadd, hermmul, hermdiv, hermpow\n\n Notes\n -----\n Unlike multiplication, division, etc., the difference of two Hermite\n series is a Hermite series (without having to \"reproject\" the result\n onto the basis set) so subtraction, just like that of \"standard\"\n polynomials, is simply \"component-wise.\"\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermsub\n >>> hermsub([1, 2, 3, 4], [1, 2, 3])\n array([ 0., 0., 0., 4.])\n\n \"\"\"\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n if len(c1) > len(c2) :\n c1[:c2.size] -= c2\n ret = c1\n else :\n c2 = -c2\n c2[:c1.size] += c1\n ret = c2\n return pu.trimseq(ret)\n\n\ndef hermmulx(c):\n \"\"\"Multiply a Hermite series by x.\n\n Multiply the Hermite series `c` by x, where x is the independent\n variable.\n\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Array representing the result of the multiplication.\n\n Notes\n -----\n The multiplication uses the recursion relationship for Hermite\n polynomials in the form\n\n .. math::\n\n xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermmulx\n >>> hermmulx([1, 2, 3])\n array([ 2. , 6.5, 1. , 1.5])\n\n \"\"\"\n # c is a trimmed copy\n [c] = pu.as_series([c])\n # The zero series needs special treatment\n if len(c) == 1 and c[0] == 0:\n return c\n\n prd = np.empty(len(c) + 1, dtype=c.dtype)\n prd[0] = c[0]*0\n prd[1] = c[0]/2\n for i in range(1, len(c)):\n prd[i + 1] = c[i]/2\n prd[i - 1] += c[i]*i\n return prd\n\n\ndef hermmul(c1, c2):\n \"\"\"\n Multiply one Hermite series by another.\n\n Returns the product of two Hermite series `c1` * `c2`. The arguments\n are sequences of coefficients, from lowest order \"term\" to highest,\n e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n out : ndarray\n Of Hermite series coefficients representing their product.\n\n See Also\n --------\n hermadd, hermsub, hermdiv, hermpow\n\n Notes\n -----\n In general, the (polynomial) product of two C-series results in terms\n that are not in the Hermite polynomial basis set. Thus, to express\n the product as a Hermite series, it is necessary to \"reproject\" the\n product onto said basis set, which may produce \"unintuitive\" (but\n correct) results; see Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermmul\n >>> hermmul([1, 2, 3], [0, 1, 2])\n array([ 52., 29., 52., 7., 6.])\n\n \"\"\"\n # s1, s2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n\n if len(c1) > len(c2):\n c = c2\n xs = c1\n else:\n c = c1\n xs = c2\n\n if len(c) == 1:\n c0 = c[0]*xs\n c1 = 0\n elif len(c) == 2:\n c0 = c[0]*xs\n c1 = c[1]*xs\n else :\n nd = len(c)\n c0 = c[-2]*xs\n c1 = c[-1]*xs\n for i in range(3, len(c) + 1) :\n tmp = c0\n nd = nd - 1\n c0 = hermsub(c[-i]*xs, c1*(2*(nd - 1)))\n c1 = hermadd(tmp, hermmulx(c1)*2)\n return hermadd(c0, hermmulx(c1)*2)\n\n\ndef hermdiv(c1, c2):\n \"\"\"\n Divide one Hermite series by another.\n\n Returns the quotient-with-remainder of two Hermite series\n `c1` / `c2`. The arguments are sequences of coefficients from lowest\n order \"term\" to highest, e.g., [1,2,3] represents the series\n ``P_0 + 2*P_1 + 3*P_2``.\n\n Parameters\n ----------\n c1, c2 : array_like\n 1-D arrays of Hermite series coefficients ordered from low to\n high.\n\n Returns\n -------\n [quo, rem] : ndarrays\n Of Hermite series coefficients representing the quotient and\n remainder.\n\n See Also\n --------\n hermadd, hermsub, hermmul, hermpow\n\n Notes\n -----\n In general, the (polynomial) division of one Hermite series by another\n results in quotient and remainder terms that are not in the Hermite\n polynomial basis set. Thus, to express these results as a Hermite\n series, it is necessary to \"reproject\" the results onto the Hermite\n basis set, which may produce \"unintuitive\" (but correct) results; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermdiv\n >>> hermdiv([ 52., 29., 52., 7., 6.], [0, 1, 2])\n (array([ 1., 2., 3.]), array([ 0.]))\n >>> hermdiv([ 54., 31., 52., 7., 6.], [0, 1, 2])\n (array([ 1., 2., 3.]), array([ 2., 2.]))\n >>> hermdiv([ 53., 30., 52., 7., 6.], [0, 1, 2])\n (array([ 1., 2., 3.]), array([ 1., 1.]))\n\n \"\"\"\n # c1, c2 are trimmed copies\n [c1, c2] = pu.as_series([c1, c2])\n if c2[-1] == 0 :\n raise ZeroDivisionError()\n\n lc1 = len(c1)\n lc2 = len(c2)\n if lc1 < lc2 :\n return c1[:1]*0, c1\n elif lc2 == 1 :\n return c1/c2[-1], c1[:1]*0\n else :\n quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype)\n rem = c1\n for i in range(lc1 - lc2, - 1, -1):\n p = hermmul([0]*i + [1], c2)\n q = rem[-1]/p[-1]\n rem = rem[:-1] - q*p[:-1]\n quo[i] = q\n return quo, pu.trimseq(rem)\n\n\ndef hermpow(c, pow, maxpower=16) :\n \"\"\"Raise a Hermite series to a power.\n\n Returns the Hermite series `c` raised to the power `pow`. The\n argument `c` is a sequence of coefficients ordered from low to high.\n i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to\n high.\n pow : integer\n Power to which the series will be raised\n maxpower : integer, optional\n Maximum power allowed. This is mainly to limit growth of the series\n to unmanageable size. Default is 16\n\n Returns\n -------\n coef : ndarray\n Hermite series of power.\n\n See Also\n --------\n hermadd, hermsub, hermmul, hermdiv\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermpow\n >>> hermpow([1, 2, 3], 2)\n array([ 81., 52., 82., 12., 9.])\n\n \"\"\"\n # c is a trimmed copy\n [c] = pu.as_series([c])\n power = int(pow)\n if power != pow or power < 0 :\n raise ValueError(\"Power must be a non-negative integer.\")\n elif maxpower is not None and power > maxpower :\n raise ValueError(\"Power is too large\")\n elif power == 0 :\n return np.array([1], dtype=c.dtype)\n elif power == 1 :\n return c\n else :\n # This can be made more efficient by using powers of two\n # in the usual way.\n prd = c\n for i in range(2, power + 1) :\n prd = hermmul(prd, c)\n return prd\n\n\ndef hermder(c, m=1, scl=1, axis=0) :\n \"\"\"\n Differentiate a Hermite series.\n\n Returns the Hermite series coefficients `c` differentiated `m` times\n along `axis`. At each iteration the result is multiplied by `scl` (the\n scaling factor is for use in a linear change of variable). The argument\n `c` is an array of coefficients from low to high degree along each\n axis, e.g., [1,2,3] represents the series ``1*H_0 + 2*H_1 + 3*H_2``\n while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) +\n 2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is\n ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Hermite series coefficients. If `c` is multidimensional the\n different axis correspond to different variables with the degree in\n each axis given by the corresponding index.\n m : int, optional\n Number of derivatives taken, must be non-negative. (Default: 1)\n scl : scalar, optional\n Each differentiation is multiplied by `scl`. The end result is\n multiplication by ``scl**m``. This is for use in a linear change of\n variable. (Default: 1)\n axis : int, optional\n Axis over which the derivative is taken. (Default: 0).\n\n .. versionadded:: 1.7.0\n\n Returns\n -------\n der : ndarray\n Hermite series of the derivative.\n\n See Also\n --------\n hermint\n\n Notes\n -----\n In general, the result of differentiating a Hermite series does not\n resemble the same operation on a power series. Thus the result of this\n function may be \"unintuitive,\" albeit correct; see Examples section\n below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermder\n >>> hermder([ 1. , 0.5, 0.5, 0.5])\n array([ 1., 2., 3.])\n >>> hermder([-0.5, 1./2., 1./8., 1./12., 1./16.], m=2)\n array([ 1., 2., 3.])\n\n \"\"\"\n c = np.array(c, ndmin=1, copy=1)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n cnt, iaxis = [int(t) for t in [m, axis]]\n\n if cnt != m:\n raise ValueError(\"The order of derivation must be integer\")\n if cnt < 0:\n raise ValueError(\"The order of derivation must be non-negative\")\n if iaxis != axis:\n raise ValueError(\"The axis must be integer\")\n if not -c.ndim <= iaxis < c.ndim:\n raise ValueError(\"The axis is out of range\")\n if iaxis < 0:\n iaxis += c.ndim\n\n if cnt == 0:\n return c\n\n c = np.rollaxis(c, iaxis)\n n = len(c)\n if cnt >= n:\n c = c[:1]*0\n else :\n for i in range(cnt):\n n = n - 1\n c *= scl\n der = np.empty((n,) + c.shape[1:], dtype=c.dtype)\n for j in range(n, 0, -1):\n der[j - 1] = (2*j)*c[j]\n c = der\n c = np.rollaxis(c, 0, iaxis + 1)\n return c\n\n\ndef hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0):\n \"\"\"\n Integrate a Hermite series.\n\n Returns the Hermite series coefficients `c` integrated `m` times from\n `lbnd` along `axis`. At each iteration the resulting series is\n **multiplied** by `scl` and an integration constant, `k`, is added.\n The scaling factor is for use in a linear change of variable. (\"Buyer\n beware\": note that, depending on what one is doing, one may want `scl`\n to be the reciprocal of what one might expect; for more information,\n see the Notes section below.) The argument `c` is an array of\n coefficients from low to high degree along each axis, e.g., [1,2,3]\n represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]\n represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +\n 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.\n\n Parameters\n ----------\n c : array_like\n Array of Hermite series coefficients. If c is multidimensional the\n different axis correspond to different variables with the degree in\n each axis given by the corresponding index.\n m : int, optional\n Order of integration, must be positive. (Default: 1)\n k : {[], list, scalar}, optional\n Integration constant(s). The value of the first integral at\n ``lbnd`` is the first value in the list, the value of the second\n integral at ``lbnd`` is the second value, etc. If ``k == []`` (the\n default), all constants are set to zero. If ``m == 1``, a single\n scalar can be given instead of a list.\n lbnd : scalar, optional\n The lower bound of the integral. (Default: 0)\n scl : scalar, optional\n Following each integration the result is *multiplied* by `scl`\n before the integration constant is added. (Default: 1)\n axis : int, optional\n Axis over which the integral is taken. (Default: 0).\n\n .. versionadded:: 1.7.0\n\n Returns\n -------\n S : ndarray\n Hermite series coefficients of the integral.\n\n Raises\n ------\n ValueError\n If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or\n ``np.isscalar(scl) == False``.\n\n See Also\n --------\n hermder\n\n Notes\n -----\n Note that the result of each integration is *multiplied* by `scl`.\n Why is this important to note? Say one is making a linear change of\n variable :math:`u = ax + b` in an integral relative to `x`. Then\n .. math::`dx = du/a`, so one will need to set `scl` equal to\n :math:`1/a` - perhaps not what one would have first thought.\n\n Also note that, in general, the result of integrating a C-series needs\n to be \"reprojected\" onto the C-series basis set. Thus, typically,\n the result of this function is \"unintuitive,\" albeit correct; see\n Examples section below.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermint\n >>> hermint([1,2,3]) # integrate once, value 0 at 0.\n array([ 1. , 0.5, 0.5, 0.5])\n >>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0\n array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ])\n >>> hermint([1,2,3], k=1) # integrate once, value 1 at 0.\n array([ 2. , 0.5, 0.5, 0.5])\n >>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1\n array([-2. , 0.5, 0.5, 0.5])\n >>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1)\n array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ])\n\n \"\"\"\n c = np.array(c, ndmin=1, copy=1)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if not np.iterable(k):\n k = [k]\n cnt, iaxis = [int(t) for t in [m, axis]]\n\n if cnt != m:\n raise ValueError(\"The order of integration must be integer\")\n if cnt < 0 :\n raise ValueError(\"The order of integration must be non-negative\")\n if len(k) > cnt :\n raise ValueError(\"Too many integration constants\")\n if iaxis != axis:\n raise ValueError(\"The axis must be integer\")\n if not -c.ndim <= iaxis < c.ndim:\n raise ValueError(\"The axis is out of range\")\n if iaxis < 0:\n iaxis += c.ndim\n\n if cnt == 0:\n return c\n\n c = np.rollaxis(c, iaxis)\n k = list(k) + [0]*(cnt - len(k))\n for i in range(cnt) :\n n = len(c)\n c *= scl\n if n == 1 and np.all(c[0] == 0):\n c[0] += k[i]\n else:\n tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)\n tmp[0] = c[0]*0\n tmp[1] = c[0]/2\n for j in range(1, n):\n tmp[j + 1] = c[j]/(2*(j + 1))\n tmp[0] += k[i] - hermval(lbnd, tmp)\n c = tmp\n c = np.rollaxis(c, 0, iaxis + 1)\n return c\n\n\ndef hermval(x, c, tensor=True):\n \"\"\"\n Evaluate an Hermite series at points x.\n\n If `c` is of length `n + 1`, this function returns the value:\n\n .. math:: p(x) = c_0 * H_0(x) + c_1 * H_1(x) + ... + c_n * H_n(x)\n\n The parameter `x` is converted to an array only if it is a tuple or a\n list, otherwise it is treated as a scalar. In either case, either `x`\n or its elements must support multiplication and addition both with\n themselves and with the elements of `c`.\n\n If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If\n `c` is multidimensional, then the shape of the result depends on the\n value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +\n x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that\n scalars have shape (,).\n\n Trailing zeros in the coefficients will be used in the evaluation, so\n they should be avoided if efficiency is a concern.\n\n Parameters\n ----------\n x : array_like, compatible object\n If `x` is a list or tuple, it is converted to an ndarray, otherwise\n it is left unchanged and treated as a scalar. In either case, `x`\n or its elements must support addition and multiplication with\n with themselves and with the elements of `c`.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree n are contained in c[n]. If `c` is multidimensional the\n remaining indices enumerate multiple polynomials. In the two\n dimensional case the coefficients may be thought of as stored in\n the columns of `c`.\n tensor : boolean, optional\n If True, the shape of the coefficient array is extended with ones\n on the right, one for each dimension of `x`. Scalars have dimension 0\n for this action. The result is that every column of coefficients in\n `c` is evaluated for every element of `x`. If False, `x` is broadcast\n over the columns of `c` for the evaluation. This keyword is useful\n when `c` is multidimensional. The default value is True.\n\n .. versionadded:: 1.7.0\n\n Returns\n -------\n values : ndarray, algebra_like\n The shape of the return value is described above.\n\n See Also\n --------\n hermval2d, hermgrid2d, hermval3d, hermgrid3d\n\n Notes\n -----\n The evaluation uses Clenshaw recursion, aka synthetic division.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermval\n >>> coef = [1,2,3]\n >>> hermval(1, coef)\n 11.0\n >>> hermval([[1,2],[3,4]], coef)\n array([[ 11., 51.],\n [ 115., 203.]])\n\n \"\"\"\n c = np.array(c, ndmin=1, copy=0)\n if c.dtype.char in '?bBhHiIlLqQpP':\n c = c.astype(np.double)\n if isinstance(x, (tuple, list)):\n x = np.asarray(x)\n if isinstance(x, np.ndarray) and tensor:\n c = c.reshape(c.shape + (1,)*x.ndim)\n\n x2 = x*2\n if len(c) == 1 :\n c0 = c[0]\n c1 = 0\n elif len(c) == 2 :\n c0 = c[0]\n c1 = c[1]\n else :\n nd = len(c)\n c0 = c[-2]\n c1 = c[-1]\n for i in range(3, len(c) + 1) :\n tmp = c0\n nd = nd - 1\n c0 = c[-i] - c1*(2*(nd - 1))\n c1 = tmp + c1*x2\n return c0 + c1*x2\n\n\ndef hermval2d(x, y, c):\n \"\"\"\n Evaluate a 2-D Hermite series at points (x, y).\n\n This function returns the values:\n\n .. math:: p(x,y) = \\\\sum_{i,j} c_{i,j} * H_i(x) * H_j(y)\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars and they\n must have the same shape after conversion. In either case, either `x`\n and `y` or their elements must support multiplication and addition both\n with themselves and with the elements of `c`.\n\n If `c` is a 1-D array a one is implicitly appended to its shape to make\n it 2-D. The shape of the result will be c.shape[2:] + x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points `(x, y)`,\n where `x` and `y` must have the same shape. If `x` or `y` is a list\n or tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and if it isn't an ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term\n of multi-degree i,j is contained in ``c[i,j]``. If `c` has\n dimension greater than two the remaining indices enumerate multiple\n sets of coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points formed with\n pairs of corresponding values from `x` and `y`.\n\n See Also\n --------\n hermval, hermgrid2d, hermval3d, hermgrid3d\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n try:\n x, y = np.array((x, y), copy=0)\n except:\n raise ValueError('x, y are incompatible')\n\n c = hermval(x, c)\n c = hermval(y, c, tensor=False)\n return c\n\n\ndef hermgrid2d(x, y, c):\n \"\"\"\n Evaluate a 2-D Hermite series on the Cartesian product of x and y.\n\n This function returns the values:\n\n .. math:: p(a,b) = \\sum_{i,j} c_{i,j} * H_i(a) * H_j(b)\n\n where the points `(a, b)` consist of all pairs formed by taking\n `a` from `x` and `b` from `y`. The resulting points form a grid with\n `x` in the first dimension and `y` in the second.\n\n The parameters `x` and `y` are converted to arrays only if they are\n tuples or a lists, otherwise they are treated as a scalars. In either\n case, either `x` and `y` or their elements must support multiplication\n and addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than two dimensions, ones are implicitly appended to\n its shape to make it 2-D. The shape of the result will be c.shape[2:] +\n x.shape.\n\n Parameters\n ----------\n x, y : array_like, compatible objects\n The two dimensional series is evaluated at the points in the\n Cartesian product of `x` and `y`. If `x` or `y` is a list or\n tuple, it is first converted to an ndarray, otherwise it is left\n unchanged and, if it isn't an ndarray, it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n hermval, hermval2d, hermval3d, hermgrid3d\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n c = hermval(x, c)\n c = hermval(y, c)\n return c\n\n\ndef hermval3d(x, y, z, c):\n \"\"\"\n Evaluate a 3-D Hermite series at points (x, y, z).\n\n This function returns the values:\n\n .. math:: p(x,y,z) = \\\\sum_{i,j,k} c_{i,j,k} * H_i(x) * H_j(y) * H_k(z)\n\n The parameters `x`, `y`, and `z` are converted to arrays only if\n they are tuples or a lists, otherwise they are treated as a scalars and\n they must have the same shape after conversion. In either case, either\n `x`, `y`, and `z` or their elements must support multiplication and\n addition both with themselves and with the elements of `c`.\n\n If `c` has fewer than 3 dimensions, ones are implicitly appended to its\n shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible object\n The three dimensional series is evaluated at the points\n `(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If\n any of `x`, `y`, or `z` is a list or tuple, it is first converted\n to an ndarray, otherwise it is left unchanged and if it isn't an\n ndarray it is treated as a scalar.\n c : array_like\n Array of coefficients ordered so that the coefficient of the term of\n multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension\n greater than 3 the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the multidimensional polynomial on points formed with\n triples of corresponding values from `x`, `y`, and `z`.\n\n See Also\n --------\n hermval, hermval2d, hermgrid2d, hermgrid3d\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n try:\n x, y, z = np.array((x, y, z), copy=0)\n except:\n raise ValueError('x, y, z are incompatible')\n\n c = hermval(x, c)\n c = hermval(y, c, tensor=False)\n c = hermval(z, c, tensor=False)\n return c\n\n\ndef hermgrid3d(x, y, z, c):\n \"\"\"\n Evaluate a 3-D Hermite series on the Cartesian product of x, y, and z.\n\n This function returns the values:\n\n .. math:: p(a,b,c) = \\\\sum_{i,j,k} c_{i,j,k} * H_i(a) * H_j(b) * H_k(c)\n\n where the points `(a, b, c)` consist of all triples formed by taking\n `a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form\n a grid with `x` in the first dimension, `y` in the second, and `z` in\n the third.\n\n The parameters `x`, `y`, and `z` are converted to arrays only if they\n are tuples or a lists, otherwise they are treated as a scalars. In\n either case, either `x`, `y`, and `z` or their elements must support\n multiplication and addition both with themselves and with the elements\n of `c`.\n\n If `c` has fewer than three dimensions, ones are implicitly appended to\n its shape to make it 3-D. The shape of the result will be c.shape[3:] +\n x.shape + y.shape + z.shape.\n\n Parameters\n ----------\n x, y, z : array_like, compatible objects\n The three dimensional series is evaluated at the points in the\n Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a\n list or tuple, it is first converted to an ndarray, otherwise it is\n left unchanged and, if it isn't an ndarray, it is treated as a\n scalar.\n c : array_like\n Array of coefficients ordered so that the coefficients for terms of\n degree i,j are contained in ``c[i,j]``. If `c` has dimension\n greater than two the remaining indices enumerate multiple sets of\n coefficients.\n\n Returns\n -------\n values : ndarray, compatible object\n The values of the two dimensional polynomial at points in the Cartesian\n product of `x` and `y`.\n\n See Also\n --------\n hermval, hermval2d, hermgrid2d, hermval3d\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n c = hermval(x, c)\n c = hermval(y, c)\n c = hermval(z, c)\n return c\n\n\ndef hermvander(x, deg) :\n \"\"\"Pseudo-Vandermonde matrix of given degree.\n\n Returns the pseudo-Vandermonde matrix of degree `deg` and sample points\n `x`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., i] = H_i(x),\n\n where `0 <= i <= deg`. The leading indices of `V` index the elements of\n `x` and the last index is the degree of the Hermite polynomial.\n\n If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the\n array ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and\n ``hermval(x, c)`` are the same up to roundoff. This equivalence is\n useful both for least squares fitting and for the evaluation of a large\n number of Hermite series of the same degree and sample points.\n\n Parameters\n ----------\n x : array_like\n Array of points. The dtype is converted to float64 or complex128\n depending on whether any of the elements are complex. If `x` is\n scalar it is converted to a 1-D array.\n deg : int\n Degree of the resulting matrix.\n\n Returns\n -------\n vander : ndarray\n The pseudo-Vandermonde matrix. The shape of the returned matrix is\n ``x.shape + (deg + 1,)``, where The last index is the degree of the\n corresponding Hermite polynomial. The dtype will be the same as\n the converted `x`.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermvander\n >>> x = np.array([-1, 0, 1])\n >>> hermvander(x, 3)\n array([[ 1., -2., 2., 4.],\n [ 1., 0., -2., -0.],\n [ 1., 2., 2., -4.]])\n\n \"\"\"\n ideg = int(deg)\n if ideg != deg:\n raise ValueError(\"deg must be integer\")\n if ideg < 0:\n raise ValueError(\"deg must be non-negative\")\n\n x = np.array(x, copy=0, ndmin=1) + 0.0\n dims = (ideg + 1,) + x.shape\n dtyp = x.dtype\n v = np.empty(dims, dtype=dtyp)\n v[0] = x*0 + 1\n if ideg > 0 :\n x2 = x*2\n v[1] = x2\n for i in range(2, ideg + 1) :\n v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1)))\n return np.rollaxis(v, 0, v.ndim)\n\n\ndef hermvander2d(x, y, deg) :\n \"\"\"Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points `(x, y)`. The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., deg[1]*i + j] = H_i(x) * H_j(y),\n\n where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of\n `V` index the points `(x, y)` and the last index encodes the degrees of\n the Hermite polynomials.\n\n If ``V = hermvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`\n correspond to the elements of a 2-D coefficient array `c` of shape\n (xdeg + 1, ydeg + 1) in the order\n\n .. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...\n\n and ``np.dot(V, c.flat)`` and ``hermval2d(x, y, c)`` will be the same\n up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 2-D Hermite\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y : array_like\n Arrays of point coordinates, all of the same shape. The dtypes\n will be converted to either float64 or complex128 depending on\n whether any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg].\n\n Returns\n -------\n vander2d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same\n as the converted `x` and `y`.\n\n See Also\n --------\n hermvander, hermvander3d. hermval2d, hermval3d\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n ideg = [int(d) for d in deg]\n is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]\n if is_valid != [1, 1]:\n raise ValueError(\"degrees must be non-negative integers\")\n degx, degy = ideg\n x, y = np.array((x, y), copy=0) + 0.0\n\n vx = hermvander(x, degx)\n vy = hermvander(y, degy)\n v = vx[..., None]*vy[..., None, :]\n return v.reshape(v.shape[:-2] + (-1,))\n\n\ndef hermvander3d(x, y, z, deg) :\n \"\"\"Pseudo-Vandermonde matrix of given degrees.\n\n Returns the pseudo-Vandermonde matrix of degrees `deg` and sample\n points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,\n then The pseudo-Vandermonde matrix is defined by\n\n .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = H_i(x)*H_j(y)*H_k(z),\n\n where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading\n indices of `V` index the points `(x, y, z)` and the last index encodes\n the degrees of the Hermite polynomials.\n\n If ``V = hermvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns\n of `V` correspond to the elements of a 3-D coefficient array `c` of\n shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order\n\n .. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...\n\n and ``np.dot(V, c.flat)`` and ``hermval3d(x, y, z, c)`` will be the\n same up to roundoff. This equivalence is useful both for least squares\n fitting and for the evaluation of a large number of 3-D Hermite\n series of the same degrees and sample points.\n\n Parameters\n ----------\n x, y, z : array_like\n Arrays of point coordinates, all of the same shape. The dtypes will\n be converted to either float64 or complex128 depending on whether\n any of the elements are complex. Scalars are converted to 1-D\n arrays.\n deg : list of ints\n List of maximum degrees of the form [x_deg, y_deg, z_deg].\n\n Returns\n -------\n vander3d : ndarray\n The shape of the returned matrix is ``x.shape + (order,)``, where\n :math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will\n be the same as the converted `x`, `y`, and `z`.\n\n See Also\n --------\n hermvander, hermvander3d. hermval2d, hermval3d\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n ideg = [int(d) for d in deg]\n is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]\n if is_valid != [1, 1, 1]:\n raise ValueError(\"degrees must be non-negative integers\")\n degx, degy, degz = ideg\n x, y, z = np.array((x, y, z), copy=0) + 0.0\n\n vx = hermvander(x, degx)\n vy = hermvander(y, degy)\n vz = hermvander(z, degz)\n v = vx[..., None, None]*vy[..., None, :, None]*vz[..., None, None, :]\n return v.reshape(v.shape[:-3] + (-1,))\n\n\ndef hermfit(x, y, deg, rcond=None, full=False, w=None):\n \"\"\"\n Least squares fit of Hermite series to data.\n\n Return the coefficients of a Hermite series of degree `deg` that is the\n least squares fit to the data values `y` given at points `x`. If `y` is\n 1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple\n fits are done, one for each column of `y`, and the resulting\n coefficients are stored in the corresponding columns of a 2-D return.\n The fitted polynomial(s) are in the form\n\n .. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x),\n\n where `n` is `deg`.\n\n Since numpy version 1.7.0, hermfit also supports NA. If any of the\n elements of `x`, `y`, or `w` are NA, then the corresponding rows of the\n linear least squares problem (see Notes) are set to 0. If `y` is 2-D,\n then an NA in any row of `y` invalidates that whole row.\n\n Parameters\n ----------\n x : array_like, shape (M,)\n x-coordinates of the M sample points ``(x[i], y[i])``.\n y : array_like, shape (M,) or (M, K)\n y-coordinates of the sample points. Several data sets of sample\n points sharing the same x-coordinates can be fitted at once by\n passing in a 2D-array that contains one dataset per column.\n deg : int\n Degree of the fitting polynomial\n rcond : float, optional\n Relative condition number of the fit. Singular values smaller than\n this relative to the largest singular value will be ignored. The\n default value is len(x)*eps, where eps is the relative precision of\n the float type, about 2e-16 in most cases.\n full : bool, optional\n Switch determining nature of return value. When it is False (the\n default) just the coefficients are returned, when True diagnostic\n information from the singular value decomposition is also returned.\n w : array_like, shape (`M`,), optional\n Weights. If not None, the contribution of each point\n ``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the\n weights are chosen so that the errors of the products ``w[i]*y[i]``\n all have the same variance. The default value is None.\n\n Returns\n -------\n coef : ndarray, shape (M,) or (M, K)\n Hermite coefficients ordered from low to high. If `y` was 2-D,\n the coefficients for the data in column k of `y` are in column\n `k`.\n\n [residuals, rank, singular_values, rcond] : present when `full` = True\n Residuals of the least-squares fit, the effective rank of the\n scaled Vandermonde matrix and its singular values, and the\n specified value of `rcond`. For more details, see `linalg.lstsq`.\n\n Warns\n -----\n RankWarning\n The rank of the coefficient matrix in the least-squares fit is\n deficient. The warning is only raised if `full` = False. The\n warnings can be turned off by\n\n >>> import warnings\n >>> warnings.simplefilter('ignore', RankWarning)\n\n See Also\n --------\n chebfit, legfit, lagfit, polyfit, hermefit\n hermval : Evaluates a Hermite series.\n hermvander : Vandermonde matrix of Hermite series.\n hermweight : Hermite weight function\n linalg.lstsq : Computes a least-squares fit from the matrix.\n scipy.interpolate.UnivariateSpline : Computes spline fits.\n\n Notes\n -----\n The solution is the coefficients of the Hermite series `p` that\n minimizes the sum of the weighted squared errors\n\n .. math:: E = \\\\sum_j w_j^2 * |y_j - p(x_j)|^2,\n\n where the :math:`w_j` are the weights. This problem is solved by\n setting up the (typically) overdetermined matrix equation\n\n .. math:: V(x) * c = w * y,\n\n where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the\n coefficients to be solved for, `w` are the weights, `y` are the\n observed values. This equation is then solved using the singular value\n decomposition of `V`.\n\n If some of the singular values of `V` are so small that they are\n neglected, then a `RankWarning` will be issued. This means that the\n coefficient values may be poorly determined. Using a lower order fit\n will usually get rid of the warning. The `rcond` parameter can also be\n set to a value smaller than its default, but the resulting fit may be\n spurious and have large contributions from roundoff error.\n\n Fits using Hermite series are probably most useful when the data can be\n approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the Hermite\n weight. In that case the weight ``sqrt(w(x[i])`` should be used\n together with data values ``y[i]/sqrt(w(x[i])``. The weight function is\n available as `hermweight`.\n\n References\n ----------\n .. [1] Wikipedia, \"Curve fitting\",\n http://en.wikipedia.org/wiki/Curve_fitting\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermfit, hermval\n >>> x = np.linspace(-10, 10)\n >>> err = np.random.randn(len(x))/10\n >>> y = hermval(x, [1, 2, 3]) + err\n >>> hermfit(x, y, 2)\n array([ 0.97902637, 1.99849131, 3.00006 ])\n\n \"\"\"\n order = int(deg) + 1\n x = np.asarray(x) + 0.0\n y = np.asarray(y) + 0.0\n\n # check arguments.\n if deg < 0 :\n raise ValueError(\"expected deg >= 0\")\n if x.ndim != 1:\n raise TypeError(\"expected 1D vector for x\")\n if x.size == 0:\n raise TypeError(\"expected non-empty vector for x\")\n if y.ndim < 1 or y.ndim > 2 :\n raise TypeError(\"expected 1D or 2D array for y\")\n if len(x) != len(y):\n raise TypeError(\"expected x and y to have same length\")\n\n # set up the least squares matrices in transposed form\n lhs = hermvander(x, deg).T\n rhs = y.T\n if w is not None:\n w = np.asarray(w) + 0.0\n if w.ndim != 1:\n raise TypeError(\"expected 1D vector for w\")\n if len(x) != len(w):\n raise TypeError(\"expected x and w to have same length\")\n # apply weights. Don't use inplace operations as they\n # can cause problems with NA.\n lhs = lhs * w\n rhs = rhs * w\n\n # set rcond\n if rcond is None :\n rcond = len(x)*np.finfo(x.dtype).eps\n\n # Determine the norms of the design matrix columns.\n if issubclass(lhs.dtype.type, np.complexfloating):\n scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))\n else:\n scl = np.sqrt(np.square(lhs).sum(1))\n scl[scl == 0] = 1\n\n # Solve the least squares problem.\n c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)\n c = (c.T/scl).T\n\n # warn on rank reduction\n if rank != order and not full:\n msg = \"The fit may be poorly conditioned\"\n warnings.warn(msg, pu.RankWarning)\n\n if full :\n return c, [resids, rank, s, rcond]\n else :\n return c\n\n\ndef hermcompanion(c):\n \"\"\"Return the scaled companion matrix of c.\n\n The basis polynomials are scaled so that the companion matrix is\n symmetric when `c` is an Hermite basis polynomial. This provides\n better eigenvalue estimates than the unscaled case and for basis\n polynomials the eigenvalues are guaranteed to be real if\n `numpy.linalg.eigvalsh` is used to obtain them.\n\n Parameters\n ----------\n c : array_like\n 1-D array of Hermite series coefficients ordered from low to high\n degree.\n\n Returns\n -------\n mat : ndarray\n Scaled companion matrix of dimensions (deg, deg).\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n accprod = np.multiply.accumulate\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) < 2:\n raise ValueError('Series must have maximum degree of at least 1.')\n if len(c) == 2:\n return np.array(-.5*c[0]/c[1])\n\n n = len(c) - 1\n mat = np.zeros((n, n), dtype=c.dtype)\n scl = np.hstack((1., np.sqrt(2.*np.arange(1,n))))\n scl = np.multiply.accumulate(scl)\n top = mat.reshape(-1)[1::n+1]\n bot = mat.reshape(-1)[n::n+1]\n top[...] = np.sqrt(.5*np.arange(1,n))\n bot[...] = top\n mat[:,-1] -= (c[:-1]/c[-1])*(scl/scl[-1])*.5\n return mat\n\n\ndef hermroots(c):\n \"\"\"\n Compute the roots of a Hermite series.\n\n Return the roots (a.k.a. \"zeros\") of the polynomial\n\n .. math:: p(x) = \\\\sum_i c[i] * H_i(x).\n\n Parameters\n ----------\n c : 1-D array_like\n 1-D array of coefficients.\n\n Returns\n -------\n out : ndarray\n Array of the roots of the series. If all the roots are real,\n then `out` is also real, otherwise it is complex.\n\n See Also\n --------\n polyroots, legroots, lagroots, chebroots, hermeroots\n\n Notes\n -----\n The root estimates are obtained as the eigenvalues of the companion\n matrix, Roots far from the origin of the complex plane may have large\n errors due to the numerical instability of the series for such\n values. Roots with multiplicity greater than 1 will also show larger\n errors as the value of the series near such points is relatively\n insensitive to errors in the roots. Isolated roots near the origin can\n be improved by a few iterations of Newton's method.\n\n The Hermite series basis polynomials aren't powers of `x` so the\n results of this function may seem unintuitive.\n\n Examples\n --------\n >>> from numpy.polynomial.hermite import hermroots, hermfromroots\n >>> coef = hermfromroots([-1, 0, 1])\n >>> coef\n array([ 0. , 0.25 , 0. , 0.125])\n >>> hermroots(coef)\n array([ -1.00000000e+00, -1.38777878e-17, 1.00000000e+00])\n\n \"\"\"\n # c is a trimmed copy\n [c] = pu.as_series([c])\n if len(c) <= 1 :\n return np.array([], dtype=c.dtype)\n if len(c) == 2 :\n return np.array([-.5*c[0]/c[1]])\n\n m = hermcompanion(c)\n r = la.eigvals(m)\n r.sort()\n return r\n\n\ndef hermgauss(deg):\n \"\"\"\n Gauss-Hermite quadrature.\n\n Computes the sample points and weights for Gauss-Hermite quadrature.\n These sample points and weights will correctly integrate polynomials of\n degree :math:`2*deg - 1` or less over the interval :math:`[-\\inf, \\inf]`\n with the weight function :math:`f(x) = \\exp(-x^2)`.\n\n Parameters\n ----------\n deg : int\n Number of sample points and weights. It must be >= 1.\n\n Returns\n -------\n x : ndarray\n 1-D ndarray containing the sample points.\n y : ndarray\n 1-D ndarray containing the weights.\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n The results have only been tested up to degree 100, higher degrees may\n be problematic. The weights are determined by using the fact that\n\n .. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))\n\n where :math:`c` is a constant independent of :math:`k` and :math:`x_k`\n is the k'th root of :math:`H_n`, and then scaling the results to get\n the right value when integrating 1.\n\n \"\"\"\n ideg = int(deg)\n if ideg != deg or ideg < 1:\n raise ValueError(\"deg must be a non-negative integer\")\n\n # first approximation of roots. We use the fact that the companion\n # matrix is symmetric in this case in order to obtain better zeros.\n c = np.array([0]*deg + [1])\n m = hermcompanion(c)\n x = la.eigvals(m)\n x.sort()\n\n # improve roots by one application of Newton\n dy = hermval(x, c)\n df = hermval(x, hermder(c))\n x -= dy/df\n\n # compute the weights. We scale the factor to avoid possible numerical\n # overflow.\n fm = hermval(x, c[1:])\n fm /= np.abs(fm).max()\n df /= np.abs(df).max()\n w = 1/(fm * df)\n\n # for Hermite we can also symmetrize\n w = (w + w[::-1])/2\n x = (x - x[::-1])/2\n\n # scale w to get the right value\n w *= np.sqrt(np.pi) / w.sum()\n\n return x, w\n\n\ndef hermweight(x):\n \"\"\"\n Weight function of the Hermite polynomials.\n\n The weight function is :math:`\\exp(-x^2)` and the interval of\n integration is :math:`[-\\inf, \\inf]`. the Hermite polynomials are\n orthogonal, but not normalized, with respect to this weight function.\n\n Parameters\n ----------\n x : array_like\n Values at which the weight function will be computed.\n\n Returns\n -------\n w : ndarray\n The weight function at `x`.\n\n Notes\n -----\n\n .. versionadded::1.7.0\n\n \"\"\"\n w = np.exp(-x**2)\n return w\n\n\n#\n# Hermite series class\n#\n\nexec(polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]'))\n", "\"\"\"Tests for hermite_e module.\n\n\"\"\"\nfrom __future__ import division, absolute_import\n\nimport numpy as np\nimport numpy.polynomial.hermite_e as herme\nfrom numpy.polynomial.polynomial import polyval\nfrom numpy.testing import *\n\nHe0 = np.array([ 1 ])\nHe1 = np.array([ 0 , 1 ])\nHe2 = np.array([ -1 ,0 , 1 ])\nHe3 = np.array([ 0 , -3 ,0 , 1 ])\nHe4 = np.array([ 3 ,0 , -6 ,0 , 1 ])\nHe5 = np.array([ 0 , 15 ,0 , -10 ,0 , 1 ])\nHe6 = np.array([ -15 ,0 , 45 ,0 , -15 ,0 , 1 ])\nHe7 = np.array([ 0 , -105 ,0 , 105 ,0 , -21 ,0 , 1 ])\nHe8 = np.array([ 105 ,0 , -420 ,0 , 210 ,0 , -28 ,0 , 1 ])\nHe9 = np.array([ 0 , 945 ,0 , -1260 ,0 , 378 ,0 , -36 ,0 , 1 ])\n\nHelist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9]\n\ndef trim(x) :\n return herme.hermetrim(x, tol=1e-6)\n\n\nclass TestConstants(TestCase) :\n\n def test_hermedomain(self) :\n assert_equal(herme.hermedomain, [-1, 1])\n\n def test_hermezero(self) :\n assert_equal(herme.hermezero, [0])\n\n def test_hermeone(self) :\n assert_equal(herme.hermeone, [1])\n\n def test_hermex(self) :\n assert_equal(herme.hermex, [0, 1])\n\n\nclass TestArithmetic(TestCase) :\n x = np.linspace(-3, 3, 100)\n\n def test_hermeadd(self) :\n for i in range(5) :\n for j in range(5) :\n msg = \"At i=%d, j=%d\" % (i,j)\n tgt = np.zeros(max(i,j) + 1)\n tgt[i] += 1\n tgt[j] += 1\n res = herme.hermeadd([0]*i + [1], [0]*j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermesub(self) :\n for i in range(5) :\n for j in range(5) :\n msg = \"At i=%d, j=%d\" % (i,j)\n tgt = np.zeros(max(i,j) + 1)\n tgt[i] += 1\n tgt[j] -= 1\n res = herme.hermesub([0]*i + [1], [0]*j + [1])\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n def test_hermemulx(self):\n assert_equal(herme.hermemulx([0]), [0])\n assert_equal(herme.hermemulx([1]), [0,1])\n for i in range(1, 5):\n ser = [0]*i + [1]\n tgt = [0]*(i - 1) + [i, 0, 1]\n assert_equal(herme.hermemulx(ser), tgt)\n\n def test_hermemul(self) :\n # check values of result\n for i in range(5) :\n pol1 = [0]*i + [1]\n val1 = herme.hermeval(self.x, pol1)\n for j in range(5) :\n msg = \"At i=%d, j=%d\" % (i,j)\n pol2 = [0]*j + [1]\n val2 = herme.hermeval(self.x, pol2)\n pol3 = herme.hermemul(pol1, pol2)\n val3 = herme.hermeval(self.x, pol3)\n assert_(len(pol3) == i + j + 1, msg)\n assert_almost_equal(val3, val1*val2, err_msg=msg)\n\n def test_hermediv(self) :\n for i in range(5) :\n for j in range(5) :\n msg = \"At i=%d, j=%d\" % (i,j)\n ci = [0]*i + [1]\n cj = [0]*j + [1]\n tgt = herme.hermeadd(ci, cj)\n quo, rem = herme.hermediv(tgt, ci)\n res = herme.hermeadd(herme.hermemul(quo, ci), rem)\n assert_equal(trim(res), trim(tgt), err_msg=msg)\n\n\nclass TestEvaluation(TestCase) :\n # coefficients of 1 + 2*x + 3*x**2\n c1d = np.array([4., 2., 3.])\n c2d = np.einsum('i,j->ij', c1d, c1d)\n c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)\n\n # some random values in [-1, 1)\n x = np.random.random((3, 5))*2 - 1\n y = polyval(x, [1., 2., 3.])\n\n\n def test_hermeval(self) :\n #check empty input\n assert_equal(herme.hermeval([], [1]).size, 0)\n\n #check normal input)\n x = np.linspace(-1,1)\n y = [polyval(x, c) for c in Helist]\n for i in range(10) :\n msg = \"At i=%d\" % i\n ser = np.zeros\n tgt = y[i]\n res = herme.hermeval(x, [0]*i + [1])\n assert_almost_equal(res, tgt, err_msg=msg)\n\n #check that shape is preserved\n for i in range(3) :\n dims = [2]*i\n x = np.zeros(dims)\n assert_equal(herme.hermeval(x, [1]).shape, dims)\n assert_equal(herme.hermeval(x, [1,0]).shape, dims)\n assert_equal(herme.hermeval(x, [1,0,0]).shape, dims)\n\n def test_hermeval2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n #test exceptions\n assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)\n\n #test values\n tgt = y1*y2\n res = herme.hermeval2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n #test shape\n z = np.ones((2,3))\n res = herme.hermeval2d(z, z, self.c2d)\n assert_(res.shape == (2,3))\n\n def test_hermeval3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n #test exceptions\n assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)\n\n #test values\n tgt = y1*y2*y3\n res = herme.hermeval3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n #test shape\n z = np.ones((2,3))\n res = herme.hermeval3d(z, z, z, self.c3d)\n assert_(res.shape == (2,3))\n\n def test_hermegrid2d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n #test values\n tgt = np.einsum('i,j->ij', y1, y2)\n res = herme.hermegrid2d(x1, x2, self.c2d)\n assert_almost_equal(res, tgt)\n\n #test shape\n z = np.ones((2,3))\n res = herme.hermegrid2d(z, z, self.c2d)\n assert_(res.shape == (2, 3)*2)\n\n def test_hermegrid3d(self):\n x1, x2, x3 = self.x\n y1, y2, y3 = self.y\n\n #test values\n tgt = np.einsum('i,j,k->ijk', y1, y2, y3)\n res = herme.hermegrid3d(x1, x2, x3, self.c3d)\n assert_almost_equal(res, tgt)\n\n #test shape\n z = np.ones((2,3))\n res = herme.hermegrid3d(z, z, z, self.c3d)\n assert_(res.shape == (2, 3)*3)\n\n\nclass TestIntegral(TestCase):\n\n def test_hermeint(self) :\n # check exceptions\n assert_raises(ValueError, herme.hermeint, [0], .5)\n assert_raises(ValueError, herme.hermeint, [0], -1)\n assert_raises(ValueError, herme.hermeint, [0], 1, [0,0])\n\n # test integration of zero polynomial\n for i in range(2, 5):\n k = [0]*(i - 2) + [1]\n res = herme.hermeint([0], m=i, k=k)\n assert_almost_equal(res, [0, 1])\n\n # check single integration with integration constant\n for i in range(5) :\n scl = i + 1\n pol = [0]*i + [1]\n tgt = [i] + [0]*i + [1/scl]\n hermepol = herme.poly2herme(pol)\n hermeint = herme.hermeint(hermepol, m=1, k=[i])\n res = herme.herme2poly(hermeint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check single integration with integration constant and lbnd\n for i in range(5) :\n scl = i + 1\n pol = [0]*i + [1]\n hermepol = herme.poly2herme(pol)\n hermeint = herme.hermeint(hermepol, m=1, k=[i], lbnd=-1)\n assert_almost_equal(herme.hermeval(-1, hermeint), i)\n\n # check single integration with integration constant and scaling\n for i in range(5) :\n scl = i + 1\n pol = [0]*i + [1]\n tgt = [i] + [0]*i + [2/scl]\n hermepol = herme.poly2herme(pol)\n hermeint = herme.hermeint(hermepol, m=1, k=[i], scl=2)\n res = herme.herme2poly(hermeint)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with default k\n for i in range(5) :\n for j in range(2,5) :\n pol = [0]*i + [1]\n tgt = pol[:]\n for k in range(j) :\n tgt = herme.hermeint(tgt, m=1)\n res = herme.hermeint(pol, m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with defined k\n for i in range(5) :\n for j in range(2,5) :\n pol = [0]*i + [1]\n tgt = pol[:]\n for k in range(j) :\n tgt = herme.hermeint(tgt, m=1, k=[k])\n res = herme.hermeint(pol, m=j, k=list(range(j)))\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with lbnd\n for i in range(5) :\n for j in range(2,5) :\n pol = [0]*i + [1]\n tgt = pol[:]\n for k in range(j) :\n tgt = herme.hermeint(tgt, m=1, k=[k], lbnd=-1)\n res = herme.hermeint(pol, m=j, k=list(range(j)), lbnd=-1)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check multiple integrations with scaling\n for i in range(5) :\n for j in range(2,5) :\n pol = [0]*i + [1]\n tgt = pol[:]\n for k in range(j) :\n tgt = herme.hermeint(tgt, m=1, k=[k], scl=2)\n res = herme.hermeint(pol, m=j, k=list(range(j)), scl=2)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermeint_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T\n res = herme.hermeint(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herme.hermeint(c) for c in c2d])\n res = herme.hermeint(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d])\n res = herme.hermeint(c2d, k=3, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestDerivative(TestCase) :\n\n def test_hermeder(self) :\n # check exceptions\n assert_raises(ValueError, herme.hermeder, [0], .5)\n assert_raises(ValueError, herme.hermeder, [0], -1)\n\n # check that zeroth deriviative does nothing\n for i in range(5) :\n tgt = [0]*i + [1]\n res = herme.hermeder(tgt, m=0)\n assert_equal(trim(res), trim(tgt))\n\n # check that derivation is the inverse of integration\n for i in range(5) :\n for j in range(2,5) :\n tgt = [0]*i + [1]\n res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)\n assert_almost_equal(trim(res), trim(tgt))\n\n # check derivation with scaling\n for i in range(5) :\n for j in range(2,5) :\n tgt = [0]*i + [1]\n res = herme.hermeder(herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5)\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermeder_axis(self):\n # check that axis keyword works\n c2d = np.random.random((3, 4))\n\n tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T\n res = herme.hermeder(c2d, axis=0)\n assert_almost_equal(res, tgt)\n\n tgt = np.vstack([herme.hermeder(c) for c in c2d])\n res = herme.hermeder(c2d, axis=1)\n assert_almost_equal(res, tgt)\n\n\nclass TestVander(TestCase):\n # some random values in [-1, 1)\n x = np.random.random((3, 5))*2 - 1\n\n\n def test_hermevander(self) :\n # check for 1d x\n x = np.arange(3)\n v = herme.hermevander(x, 3)\n assert_(v.shape == (3, 4))\n for i in range(4) :\n coef = [0]*i + [1]\n assert_almost_equal(v[..., i], herme.hermeval(x, coef))\n\n # check for 2d x\n x = np.array([[1, 2], [3, 4], [5, 6]])\n v = herme.hermevander(x, 3)\n assert_(v.shape == (3, 2, 4))\n for i in range(4) :\n coef = [0]*i + [1]\n assert_almost_equal(v[..., i], herme.hermeval(x, coef))\n\n def test_hermevander2d(self) :\n # also tests hermeval2d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3))\n van = herme.hermevander2d(x1, x2, [1, 2])\n tgt = herme.hermeval2d(x1, x2, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = herme.hermevander2d([x1], [x2], [1, 2])\n assert_(van.shape == (1, 5, 6))\n\n\n def test_hermevander3d(self) :\n # also tests hermeval3d for non-square coefficient array\n x1, x2, x3 = self.x\n c = np.random.random((2, 3, 4))\n van = herme.hermevander3d(x1, x2, x3, [1, 2, 3])\n tgt = herme.hermeval3d(x1, x2, x3, c)\n res = np.dot(van, c.flat)\n assert_almost_equal(res, tgt)\n\n # check shape\n van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3])\n assert_(van.shape == (1, 5, 24))\n\n\nclass TestFitting(TestCase):\n\n def test_hermefit(self) :\n def f(x) :\n return x*(x - 1)*(x - 2)\n\n # Test exceptions\n assert_raises(ValueError, herme.hermefit, [1], [1], -1)\n assert_raises(TypeError, herme.hermefit, [[1]], [1], 0)\n assert_raises(TypeError, herme.hermefit, [], [1], 0)\n assert_raises(TypeError, herme.hermefit, [1], [[[1]]], 0)\n assert_raises(TypeError, herme.hermefit, [1, 2], [1], 0)\n assert_raises(TypeError, herme.hermefit, [1], [1, 2], 0)\n assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[[1]])\n assert_raises(TypeError, herme.hermefit, [1], [1], 0, w=[1,1])\n\n # Test fit\n x = np.linspace(0,2)\n y = f(x)\n #\n coef3 = herme.hermefit(x, y, 3)\n assert_equal(len(coef3), 4)\n assert_almost_equal(herme.hermeval(x, coef3), y)\n #\n coef4 = herme.hermefit(x, y, 4)\n assert_equal(len(coef4), 5)\n assert_almost_equal(herme.hermeval(x, coef4), y)\n #\n coef2d = herme.hermefit(x, np.array([y,y]).T, 3)\n assert_almost_equal(coef2d, np.array([coef3,coef3]).T)\n # test weighting\n w = np.zeros_like(x)\n yw = y.copy()\n w[1::2] = 1\n y[0::2] = 0\n wcoef3 = herme.hermefit(x, yw, 3, w=w)\n assert_almost_equal(wcoef3, coef3)\n #\n wcoef2d = herme.hermefit(x, np.array([yw,yw]).T, 3, w=w)\n assert_almost_equal(wcoef2d, np.array([coef3,coef3]).T)\n # test scaling with complex values x points whose square\n # is zero when summed.\n x = [1, 1j, -1, -1j]\n assert_almost_equal(herme.hermefit(x, x, 1), [0, 1])\n\nclass TestGauss(TestCase):\n\n def test_100(self):\n x, w = herme.hermegauss(100)\n\n # test orthogonality. Note that the results need to be normalized,\n # otherwise the huge values that can arise from fast growing\n # functions like Laguerre can be very confusing.\n v = herme.hermevander(x, 99)\n vv = np.dot(v.T * w, v)\n vd = 1/np.sqrt(vv.diagonal())\n vv = vd[:,None] * vv * vd\n assert_almost_equal(vv, np.eye(100))\n\n # check that the integral of 1 is correct\n tgt = np.sqrt(2*np.pi)\n assert_almost_equal(w.sum(), tgt)\n\n\nclass TestMisc(TestCase) :\n\n def test_hermefromroots(self) :\n res = herme.hermefromroots([])\n assert_almost_equal(trim(res), [1])\n for i in range(1,5) :\n roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])\n pol = herme.hermefromroots(roots)\n res = herme.hermeval(roots, pol)\n tgt = 0\n assert_(len(pol) == i + 1)\n assert_almost_equal(herme.herme2poly(pol)[-1], 1)\n assert_almost_equal(res, tgt)\n\n def test_hermeroots(self) :\n assert_almost_equal(herme.hermeroots([1]), [])\n assert_almost_equal(herme.hermeroots([1, 1]), [-1])\n for i in range(2,5) :\n tgt = np.linspace(-1, 1, i)\n res = herme.hermeroots(herme.hermefromroots(tgt))\n assert_almost_equal(trim(res), trim(tgt))\n\n def test_hermetrim(self) :\n coef = [2, -1, 1, 0]\n\n # Test exceptions\n assert_raises(ValueError, herme.hermetrim, coef, -1)\n\n # Test results\n assert_equal(herme.hermetrim(coef), coef[:-1])\n assert_equal(herme.hermetrim(coef, 1), coef[:-3])\n assert_equal(herme.hermetrim(coef, 2), [0])\n\n def test_hermeline(self) :\n assert_equal(herme.hermeline(3,4), [3, 4])\n\n def test_herme2poly(self) :\n for i in range(10) :\n assert_almost_equal(herme.herme2poly([0]*i + [1]), Helist[i])\n\n def test_poly2herme(self) :\n for i in range(10) :\n assert_almost_equal(herme.poly2herme(Helist[i]), [0]*i + [1])\n\n def test_weight(self):\n x = np.linspace(-5, 5, 11)\n tgt = np.exp(-.5*x**2)\n res = herme.hermeweight(x)\n assert_almost_equal(res, tgt)\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n", "from __future__ import division, absolute_import\n\nfrom .util import *\nfrom .numerictypes import *\nfrom .functions import *\nfrom .ufuncs import *\nfrom .compat import *\nfrom .session import *\n\nfrom . import util\nfrom . import numerictypes\nfrom . import functions\nfrom . import ufuncs\nfrom . import compat\nfrom . import session\n\n__all__ = ['session', 'numerictypes']\n__all__ += util.__all__\n__all__ += numerictypes.__all__\n__all__ += functions.__all__\n__all__ += ufuncs.__all__\n__all__ += compat.__all__\n__all__ += session.__all__\n\ndel util\ndel functions\ndel ufuncs\ndel compat\n\nfrom numpy.testing import Tester\ntest = Tester().test\nbench = Tester().bench\n", "\"\"\" Doctests for NumPy-specific nose/doctest modifications\n\n\"\"\"\nfrom __future__ import division, absolute_import\n\n# try the #random directive on the output line\ndef check_random_directive():\n '''\n >>> 2+2\n <BadExample object at 0x084D05AC> #random: may vary on your system\n '''\n\n# check the implicit \"import numpy as np\"\ndef check_implicit_np():\n '''\n >>> np.array([1,2,3])\n array([1, 2, 3])\n '''\n\n# there's some extraneous whitespace around the correct responses\ndef check_whitespace_enabled():\n '''\n # whitespace after the 3\n >>> 1+2\n 3\n\n # whitespace before the 7\n >>> 3+4\n 7\n '''\n\ndef check_empty_output():\n \"\"\" Check that no output does not cause an error.\n\n This is related to nose bug 445; the numpy plugin changed the\n doctest-result-variable default and therefore hit this bug:\n http://code.google.com/p/python-nose/issues/detail?id=445\n\n >>> a = 10\n \"\"\"\n\ndef check_skip():\n \"\"\" Check skip directive\n\n The test below should not run\n\n >>> 1/0 #doctest: +SKIP\n \"\"\"\n\n\nif __name__ == '__main__':\n # Run tests outside numpy test rig\n import nose\n from numpy.testing.noseclasses import NumpyDoctest\n argv = ['', __file__, '--with-numpydoctest']\n nose.core.TestProgram(argv=argv, addplugins=[NumpyDoctest()])\n", "\"\"\"Backward compatible with arrayfns from Numeric.\n\n\"\"\"\nfrom __future__ import division, absolute_import\n\n__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask',\n 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span',\n 'to_corners', 'zmin_zmax']\n\nimport numpy as np\nfrom numpy import asarray\n\nclass error(Exception):\n pass\n\ndef array_set(vals1, indices, vals2):\n indices = asarray(indices)\n if indices.ndim != 1:\n raise ValueError(\"index array must be 1-d\")\n if not isinstance(vals1, np.ndarray):\n raise TypeError(\"vals1 must be an ndarray\")\n vals1 = asarray(vals1)\n vals2 = asarray(vals2)\n if vals1.ndim != vals2.ndim or vals1.ndim < 1:\n raise error(\"vals1 and vals2 must have same number of dimensions (>=1)\")\n vals1[indices] = vals2\n\nfrom numpy import digitize\nfrom numpy import bincount as histogram\n\ndef index_sort(arr):\n return asarray(arr).argsort(kind='heap')\n\ndef interp(y, x, z, typ=None):\n \"\"\"y(z) interpolated by treating y(x) as piecewise function\n \"\"\"\n res = np.interp(z, x, y)\n if typ is None or typ == 'd':\n return res\n if typ == 'f':\n return res.astype('f')\n\n raise error(\"incompatible typecode\")\n\ndef nz(x):\n x = asarray(x,dtype=np.ubyte)\n if x.ndim != 1:\n raise TypeError(\"intput must have 1 dimension.\")\n indxs = np.flatnonzero(x != 0)\n return indxs[-1].item()+1\n\ndef reverse(x, n):\n x = asarray(x,dtype='d')\n if x.ndim != 2:\n raise ValueError(\"input must be 2-d\")\n y = np.empty_like(x)\n if n == 0:\n y[...] = x[::-1,:]\n elif n == 1:\n y[...] = x[:,::-1]\n return y\n\ndef span(lo, hi, num, d2=0):\n x = np.linspace(lo, hi, num)\n if d2 <= 0:\n return x\n else:\n ret = np.empty((d2,num),x.dtype)\n ret[...] = x\n return ret\n\ndef zmin_zmax(z, ireg):\n z = asarray(z, dtype=float)\n ireg = asarray(ireg, dtype=int)\n if z.shape != ireg.shape or z.ndim != 2:\n raise ValueError(\"z and ireg must be the same shape and 2-d\")\n ix, iy = np.nonzero(ireg)\n # Now, add more indices\n x1m = ix - 1\n y1m = iy-1\n i1 = x1m>=0\n i2 = y1m>=0\n i3 = i1 & i2\n nix = np.r_[ix, x1m[i1], x1m[i1], ix[i2] ]\n niy = np.r_[iy, iy[i1], y1m[i3], y1m[i2]]\n # remove any negative indices\n zres = z[nix,niy]\n return zres.min().item(), zres.max().item()\n\n\ndef find_mask(fs, node_edges):\n raise NotImplementedError\n\ndef to_corners(arr, nv, nvsum):\n raise NotImplementedError\n\n\ndef construct3(mask, itype):\n raise NotImplementedError\n", "\"\"\"Don't add these to the __all__ variable though\n\n\"\"\"\nfrom __future__ import division, absolute_import\n\nfrom numpy import *\n\ndef _move_axis_to_0(a, axis):\n if axis == 0:\n return a\n n = len(a.shape)\n if axis < 0:\n axis += n\n axes = list(range(1, axis+1)) + [0,] + list(range(axis+1, n))\n return transpose(a, axes)\n\n# Add these\nfrom .compat import *\nfrom .functions import *\nfrom .precision import *\nfrom .ufuncs import *\nfrom .misc import *\n\nfrom . import compat\nfrom . import precision\nfrom . import functions\nfrom . import misc\nfrom . import ufuncs\n\nimport numpy\n__version__ = numpy.__version__\ndel numpy\n\n__all__ = ['__version__']\n__all__ += compat.__all__\n__all__ += precision.__all__\n__all__ += functions.__all__\n__all__ += ufuncs.__all__\n__all__ += misc.__all__\n\ndel compat\ndel functions\ndel precision\ndel ufuncs\ndel misc\n\nfrom numpy.testing import Tester\ntest = Tester().test\nbench = Tester().bench\n" ]
[ [ "numpy.rollaxis", "numpy.square", "numpy.linalg.eigvals", "numpy.iterable", "numpy.sqrt", "numpy.abs", "numpy.asarray", "numpy.arange", "numpy.multiply.accumulate", "numpy.ones", "numpy.all", "numpy.linalg.lstsq", "numpy.finfo", "numpy.exp", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "numpy.dot", "numpy.sqrt", "numpy.linspace", "numpy.einsum", "numpy.polynomial.hermite_e.hermefit", "numpy.zeros_like", "numpy.exp", "numpy.polynomial.hermite_e.hermeroots", "numpy.polynomial.hermite_e.herme2poly", "numpy.polynomial.hermite_e.hermeval", "numpy.arange", "numpy.polynomial.hermite_e.hermeweight", "numpy.eye", "numpy.polynomial.hermite_e.hermeval3d", "numpy.polynomial.hermite_e.hermegrid3d", "numpy.polynomial.hermite_e.hermetrim", "numpy.zeros", "numpy.polynomial.hermite_e.hermeadd", "numpy.polynomial.hermite_e.hermevander", "numpy.polynomial.hermite_e.hermediv", "numpy.polynomial.hermite_e.hermeint", "numpy.polynomial.hermite_e.hermevander3d", "numpy.polynomial.polynomial.polyval", "numpy.polynomial.hermite_e.hermeval2d", "numpy.array", "numpy.polynomial.hermite_e.hermegauss", "numpy.polynomial.hermite_e.hermefromroots", "numpy.polynomial.hermite_e.hermemulx", "numpy.polynomial.hermite_e.poly2herme", "numpy.polynomial.hermite_e.hermemul", "numpy.random.random", "numpy.polynomial.hermite_e.hermeline", "numpy.polynomial.hermite_e.hermegrid2d", "numpy.polynomial.hermite_e.hermevander2d", "numpy.ones", "numpy.polynomial.hermite_e.hermeder", "numpy.polynomial.hermite_e.hermesub" ], [ "numpy.testing.Tester" ], [ "numpy.testing.noseclasses.NumpyDoctest" ], [ "numpy.linspace", "numpy.nonzero", "numpy.asarray", "numpy.empty_like", "numpy.flatnonzero", "numpy.interp", "numpy.empty" ], [ "numpy.testing.Tester" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.11", "1.10", "1.12", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
oguzdemirbasci/DynamicVocabAbstractiveSummariser
[ "2e8ba9efd6eddd7d1870d540638f05c80bfe9894" ]
[ "fairseq/fairseq/data/indexed_dataset.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom functools import lru_cache\nimport os\nimport shutil\nimport struct\n\nimport numpy as np\nimport torch\n\nfrom . import FairseqDataset\n\n\ndef __best_fitting_dtype(vocab_size=None):\n if vocab_size is not None and vocab_size < 65500:\n return np.uint16\n else:\n return np.int32\n\n\ndef get_available_dataset_impl():\n return ['raw', 'lazy', 'cached', 'mmap']\n\n\ndef infer_dataset_impl(path):\n if IndexedRawTextDataset.exists(path):\n return 'raw'\n elif IndexedDataset.exists(path):\n with open(index_file_path(path), 'rb') as f:\n magic = f.read(8)\n if magic == IndexedDataset._HDR_MAGIC:\n return 'cached'\n elif magic == MMapIndexedDataset.Index._HDR_MAGIC[:8]:\n return 'mmap'\n else:\n return None\n else:\n return None\n\n\ndef make_builder(out_file, impl, vocab_size=None):\n if impl == 'mmap':\n return MMapIndexedDatasetBuilder(out_file, dtype=__best_fitting_dtype(vocab_size))\n else:\n return IndexedDatasetBuilder(out_file)\n\n\ndef make_dataset(path, impl, fix_lua_indexing=False, dictionary=None):\n if impl == 'raw' and IndexedRawTextDataset.exists(path):\n assert dictionary is not None\n return IndexedRawTextDataset(path, dictionary)\n elif impl == 'lazy' and IndexedDataset.exists(path):\n return IndexedDataset(path, fix_lua_indexing=fix_lua_indexing)\n elif impl == 'cached' and IndexedDataset.exists(path):\n return IndexedCachedDataset(path, fix_lua_indexing=fix_lua_indexing)\n elif impl == 'mmap' and MMapIndexedDataset.exists(path):\n return MMapIndexedDataset(path)\n return None\n\n\ndef dataset_exists(path, impl):\n if impl == 'raw':\n return IndexedRawTextDataset.exists(path)\n elif impl == 'mmap':\n return MMapIndexedDataset.exists(path)\n else:\n return IndexedDataset.exists(path)\n\n\ndef read_longs(f, n):\n a = np.empty(n, dtype=np.int64)\n f.readinto(a)\n return a\n\n\ndef write_longs(f, a):\n f.write(np.array(a, dtype=np.int64))\n\n\ndtypes = {\n 1: np.uint8,\n 2: np.int8,\n 3: np.int16,\n 4: np.int32,\n 5: np.int64,\n 6: np.float,\n 7: np.double,\n 8: np.uint16\n}\n\n\ndef code(dtype):\n for k in dtypes.keys():\n if dtypes[k] == dtype:\n return k\n raise ValueError(dtype)\n\n\ndef index_file_path(prefix_path):\n return prefix_path + '.idx'\n\n\ndef data_file_path(prefix_path):\n return prefix_path + '.bin'\n\n\nclass IndexedDataset(FairseqDataset):\n \"\"\"Loader for TorchNet IndexedDataset\"\"\"\n _HDR_MAGIC = b'TNTIDX\\x00\\x00'\n\n def __init__(self, path, fix_lua_indexing=False):\n super().__init__()\n self.path = path\n self.fix_lua_indexing = fix_lua_indexing\n self.data_file = None\n self.read_index(path)\n\n def read_index(self, path):\n with open(index_file_path(path), 'rb') as f:\n magic = f.read(8)\n assert magic == self._HDR_MAGIC, (\n 'Index file doesn\\'t match expected format. '\n 'Make sure that --dataset-impl is configured properly.'\n )\n version = f.read(8)\n assert struct.unpack('<Q', version) == (1,)\n code, self.element_size = struct.unpack('<QQ', f.read(16))\n self.dtype = dtypes[code]\n self._len, self.s = struct.unpack('<QQ', f.read(16))\n self.dim_offsets = read_longs(f, self._len + 1)\n self.data_offsets = read_longs(f, self._len + 1)\n self.sizes = read_longs(f, self.s)\n\n def read_data(self, path):\n self.data_file = open(data_file_path(path), 'rb', buffering=0)\n\n def check_index(self, i):\n if i < 0 or i >= self._len:\n raise IndexError('index out of range')\n\n def __del__(self):\n if self.data_file:\n self.data_file.close()\n\n @lru_cache(maxsize=8)\n def __getitem__(self, i):\n if not self.data_file:\n self.read_data(self.path)\n self.check_index(i)\n tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]]\n a = np.empty(tensor_size, dtype=self.dtype)\n self.data_file.seek(self.data_offsets[i] * self.element_size)\n self.data_file.readinto(a)\n item = torch.from_numpy(a).long()\n if self.fix_lua_indexing:\n item -= 1 # subtract 1 for 0-based indexing\n return item\n\n def __len__(self):\n return self._len\n\n def num_tokens(self, index):\n return self.sizes[index]\n\n def size(self, index):\n return self.sizes[index]\n\n @staticmethod\n def exists(path):\n return (\n os.path.exists(index_file_path(path)) and os.path.exists(data_file_path(path))\n )\n\n @property\n def supports_prefetch(self):\n return False # avoid prefetching to save memory\n\n\nclass IndexedCachedDataset(IndexedDataset):\n\n def __init__(self, path, fix_lua_indexing=False):\n super().__init__(path, fix_lua_indexing=fix_lua_indexing)\n self.cache = None\n self.cache_index = {}\n\n @property\n def supports_prefetch(self):\n return True\n\n def prefetch(self, indices):\n if all(i in self.cache_index for i in indices):\n return\n if not self.data_file:\n self.read_data(self.path)\n indices = sorted(set(indices))\n total_size = 0\n for i in indices:\n total_size += self.data_offsets[i + 1] - self.data_offsets[i]\n self.cache = np.empty(total_size, dtype=self.dtype)\n ptx = 0\n self.cache_index.clear()\n for i in indices:\n self.cache_index[i] = ptx\n size = self.data_offsets[i + 1] - self.data_offsets[i]\n a = self.cache[ptx: ptx + size]\n self.data_file.seek(self.data_offsets[i] * self.element_size)\n self.data_file.readinto(a)\n ptx += size\n if self.data_file:\n # close and delete data file after prefetch so we can pickle\n self.data_file.close()\n self.data_file = None\n\n @lru_cache(maxsize=8)\n def __getitem__(self, i):\n self.check_index(i)\n tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]]\n a = np.empty(tensor_size, dtype=self.dtype)\n ptx = self.cache_index[i]\n np.copyto(a, np.reshape(self.cache[ptx: ptx + a.size], tensor_size))\n item = torch.from_numpy(a).long()\n if self.fix_lua_indexing:\n item -= 1 # subtract 1 for 0-based indexing\n return item\n\n\nclass IndexedRawTextDataset(FairseqDataset):\n \"\"\"Takes a text file as input and binarizes it in memory at instantiation.\n Original lines are also kept in memory\"\"\"\n\n def __init__(self, path, dictionary, append_eos=True, reverse_order=False):\n self.tokens_list = []\n self.lines = []\n self.sizes = []\n self.append_eos = append_eos\n self.reverse_order = reverse_order\n self.read_data(path, dictionary)\n self.size = len(self.tokens_list)\n\n def read_data(self, path, dictionary):\n with open(path, 'r', encoding='utf-8') as f:\n for line in f:\n self.lines.append(line.strip('\\n'))\n tokens = dictionary.encode_line(\n line, add_if_not_exist=False,\n append_eos=self.append_eos, reverse_order=self.reverse_order,\n ).long()\n self.tokens_list.append(tokens)\n self.sizes.append(len(tokens))\n self.sizes = np.array(self.sizes)\n\n def check_index(self, i):\n if i < 0 or i >= self.size:\n raise IndexError('index out of range')\n\n @lru_cache(maxsize=8)\n def __getitem__(self, i):\n self.check_index(i)\n return self.tokens_list[i]\n\n def get_original_text(self, i):\n self.check_index(i)\n return self.lines[i]\n\n def __del__(self):\n pass\n\n def __len__(self):\n return self.size\n\n def num_tokens(self, index):\n return self.sizes[index]\n\n def size(self, index):\n return self.sizes[index]\n\n @staticmethod\n def exists(path):\n return os.path.exists(path)\n\n\nclass IndexedDatasetBuilder(object):\n element_sizes = {\n np.uint8: 1,\n np.int8: 1,\n np.int16: 2,\n np.int32: 4,\n np.int64: 8,\n np.float: 4,\n np.double: 8\n }\n\n def __init__(self, out_file, dtype=np.int32):\n self.out_file = open(out_file, 'wb')\n self.dtype = dtype\n self.data_offsets = [0]\n self.dim_offsets = [0]\n self.sizes = []\n self.element_size = self.element_sizes[self.dtype]\n\n def add_item(self, tensor):\n # +1 for Lua compatibility\n bytes = self.out_file.write(np.array(tensor.numpy() + 1, dtype=self.dtype))\n self.data_offsets.append(self.data_offsets[-1] + bytes / self.element_size)\n for s in tensor.size():\n self.sizes.append(s)\n self.dim_offsets.append(self.dim_offsets[-1] + len(tensor.size()))\n\n def merge_file_(self, another_file):\n index = IndexedDataset(another_file)\n assert index.dtype == self.dtype\n\n begin = self.data_offsets[-1]\n for offset in index.data_offsets[1:]:\n self.data_offsets.append(begin + offset)\n self.sizes.extend(index.sizes)\n begin = self.dim_offsets[-1]\n for dim_offset in index.dim_offsets[1:]:\n self.dim_offsets.append(begin + dim_offset)\n\n with open(data_file_path(another_file), 'rb') as f:\n while True:\n data = f.read(1024)\n if data:\n self.out_file.write(data)\n else:\n break\n\n def finalize(self, index_file):\n self.out_file.close()\n index = open(index_file, 'wb')\n index.write(b'TNTIDX\\x00\\x00')\n index.write(struct.pack('<Q', 1))\n index.write(struct.pack('<QQ', code(self.dtype), self.element_size))\n index.write(struct.pack('<QQ', len(self.data_offsets) - 1, len(self.sizes)))\n write_longs(index, self.dim_offsets)\n write_longs(index, self.data_offsets)\n write_longs(index, self.sizes)\n index.close()\n\n\ndef _warmup_mmap_file(path):\n with open(path, 'rb') as stream:\n while stream.read(100 * 1024 * 1024):\n pass\n\n\nclass MMapIndexedDataset(torch.utils.data.Dataset):\n class Index(object):\n _HDR_MAGIC = b'MMIDIDX\\x00\\x00'\n\n @classmethod\n def writer(cls, path, dtype):\n class _Writer(object):\n def __enter__(self):\n self._file = open(path, 'wb')\n\n self._file.write(cls._HDR_MAGIC)\n self._file.write(struct.pack('<Q', 1))\n self._file.write(struct.pack('<B', code(dtype)))\n\n return self\n\n @staticmethod\n def _get_pointers(sizes):\n dtype_size = dtype().itemsize\n address = 0\n pointers = []\n\n for size in sizes:\n pointers.append(address)\n address += size * dtype_size\n\n return pointers\n\n def write(self, sizes):\n pointers = self._get_pointers(sizes)\n\n self._file.write(struct.pack('<Q', len(sizes)))\n\n sizes = np.array(sizes, dtype=np.int32)\n self._file.write(sizes.tobytes(order='C'))\n del sizes\n\n pointers = np.array(pointers, dtype=np.int64)\n self._file.write(pointers.tobytes(order='C'))\n del pointers\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._file.close()\n\n return _Writer()\n\n def __init__(self, path):\n with open(path, 'rb') as stream:\n magic_test = stream.read(9)\n assert self._HDR_MAGIC == magic_test, (\n 'Index file doesn\\'t match expected format. '\n 'Make sure that --dataset-impl is configured properly.'\n )\n version = struct.unpack('<Q', stream.read(8))\n assert (1,) == version\n\n dtype_code, = struct.unpack('<B', stream.read(1))\n self._dtype = dtypes[dtype_code]\n self._dtype_size = self._dtype().itemsize\n\n self._len = struct.unpack('<Q', stream.read(8))[0]\n offset = stream.tell()\n\n _warmup_mmap_file(path)\n\n self._bin_buffer_mmap = np.memmap(path, mode='r', order='C')\n self._bin_buffer = memoryview(self._bin_buffer_mmap)\n self._sizes = np.frombuffer(self._bin_buffer, dtype=np.int32, count=self._len, offset=offset)\n self._pointers = np.frombuffer(self._bin_buffer, dtype=np.int64, count=self._len,\n offset=offset + self._sizes.nbytes)\n\n def __del__(self):\n self._bin_buffer_mmap._mmap.close()\n del self._bin_buffer_mmap\n\n @property\n def dtype(self):\n return self._dtype\n\n @property\n def sizes(self):\n return self._sizes\n\n @lru_cache(maxsize=8)\n def __getitem__(self, i):\n return self._pointers[i], self._sizes[i]\n\n def __len__(self):\n return self._len\n\n def __init__(self, path):\n super().__init__()\n\n self._path = None\n self._index = None\n self._bin_buffer = None\n\n self._do_init(path)\n\n def __getstate__(self):\n return self._path\n\n def __setstate__(self, state):\n self._do_init(state)\n\n def _do_init(self, path):\n self._path = path\n self._index = self.Index(index_file_path(self._path))\n\n _warmup_mmap_file(data_file_path(self._path))\n self._bin_buffer_mmap = np.memmap(data_file_path(self._path), mode='r', order='C')\n self._bin_buffer = memoryview(self._bin_buffer_mmap)\n\n def __del__(self):\n self._bin_buffer_mmap._mmap.close()\n del self._bin_buffer_mmap\n del self._index\n\n def __len__(self):\n return len(self._index)\n\n @lru_cache(maxsize=8)\n def __getitem__(self, i):\n ptr, size = self._index[i]\n np_array = np.frombuffer(self._bin_buffer, dtype=self._index.dtype, count=size, offset=ptr)\n if self._index.dtype != np.int64:\n np_array = np_array.astype(np.int64)\n\n return torch.from_numpy(np_array)\n\n @property\n def sizes(self):\n return self._index.sizes\n\n @property\n def supports_prefetch(self):\n return False\n\n @staticmethod\n def exists(path):\n return (\n os.path.exists(index_file_path(path)) and os.path.exists(data_file_path(path))\n )\n\n\nclass MMapIndexedDatasetBuilder(object):\n def __init__(self, out_file, dtype=np.int64):\n self._data_file = open(out_file, 'wb')\n self._dtype = dtype\n self._sizes = []\n\n def add_item(self, tensor):\n np_array = np.array(tensor.numpy(), dtype=self._dtype)\n self._data_file.write(np_array.tobytes(order='C'))\n self._sizes.append(np_array.size)\n\n def merge_file_(self, another_file):\n # Concatenate index\n index = MMapIndexedDataset.Index(index_file_path(another_file))\n assert index.dtype == self._dtype\n\n for size in index.sizes:\n self._sizes.append(size)\n\n # Concatenate data\n with open(data_file_path(another_file), 'rb') as f:\n shutil.copyfileobj(f, self._data_file)\n\n def finalize(self, index_file):\n self._data_file.close()\n\n with MMapIndexedDataset.Index.writer(index_file, self._dtype) as index:\n index.write(self._sizes)\n" ]
[ [ "numpy.reshape", "numpy.memmap", "torch.from_numpy", "numpy.frombuffer", "numpy.array", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
deciding/Voicefilter
[ "dda34da9d1cfca48102b2d1b4274bfd76e5a2e1c" ]
[ "utils/audio.py" ]
[ "# adapted from Keith Ito's tacotron implementation\n# https://github.com/keithito/tacotron/blob/master/util/audio.py\n\nimport librosa\nimport numpy as np\n\n\nclass Audio():\n def __init__(self, hp):\n self.hp = hp\n self.mel_basis = librosa.filters.mel(sr=hp.audio.sample_rate,\n n_fft=hp.embedder.n_fft,\n n_mels=hp.embedder.num_mels)\n\n self.audio_mel_basis = librosa.filters.mel(sr=hp.audio.sample_rate,\n n_fft=hp.audio.n_fft,\n n_mels=80)\n\n def get_mel(self, y):\n y = librosa.core.stft(y=y, n_fft=self.hp.embedder.n_fft,\n hop_length=self.hp.audio.hop_length,\n win_length=self.hp.audio.win_length,\n window='hann')\n magnitudes = np.abs(y) ** 2\n mel = np.log10(np.dot(self.mel_basis, magnitudes) + 1e-6)\n return mel\n\n def wav2spec(self, y):\n D = self.stft(y)\n S = self.amp_to_db(np.abs(D)) - self.hp.audio.ref_level_db\n S, D = self.normalize(S), np.angle(D)\n S, D = S.T, D.T # to make [time, freq]\n return S, D\n\n def wav2mel(self, y):\n D = self.stft(y)\n S = np.dot(self.audio_mel_basis, np.abs(D))\n S = self.amp_to_db(S) - self.hp.audio.ref_level_db\n S = self.normalize(S)\n return S.T\n\n def spec2wav(self, spectrogram, phase):\n spectrogram, phase = spectrogram.T, phase.T\n # used during inference only\n # spectrogram: enhanced output\n # phase: use noisy input's phase, so no GLA is required\n S = self.db_to_amp(self.denormalize(spectrogram) + self.hp.audio.ref_level_db)\n return self.istft(S, phase)\n\n def stft(self, y):\n return librosa.stft(y=y, n_fft=self.hp.audio.n_fft,\n hop_length=self.hp.audio.hop_length,\n win_length=self.hp.audio.win_length)\n\n def istft(self, mag, phase):\n stft_matrix = mag * np.exp(1j*phase)\n return librosa.istft(stft_matrix,\n hop_length=self.hp.audio.hop_length,\n win_length=self.hp.audio.win_length)\n\n def amp_to_db(self, x):\n return 20.0 * np.log10(np.maximum(1e-5, x))\n\n def db_to_amp(self, x):\n return np.power(10.0, x * 0.05)\n\n def normalize(self, S):\n return np.clip(S / -self.hp.audio.min_level_db, -1.0, 0.0) + 1.0\n\n def denormalize(self, S):\n return (np.clip(S, 0.0, 1.0) - 1.0) * -self.hp.audio.min_level_db\n" ]
[ [ "numpy.dot", "numpy.maximum", "numpy.abs", "numpy.clip", "numpy.power", "numpy.angle", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hummat/detectron2
[ "ef2f4df474b4a07049cada4793392e8e36c3e746" ]
[ "demo/demo.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\nimport argparse\nimport glob\nimport multiprocessing as mp\nimport numpy as np\nimport os\nimport tempfile\nimport time\nimport warnings\nimport cv2\nimport tqdm\n\nfrom detectron2.config import get_cfg\nfrom detectron2.data.detection_utils import read_image\nfrom detectron2.utils.logger import setup_logger\n\nfrom predictor import VisualizationDemo\n\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.data.datasets import load_coco_json\n\npath_to_coco_json = \"/home/matthias/Data/Ubuntu/data/datasets/porta_filter/front3d/coco_data/coco_annotations.json\"\npath_to_images = \"/home/matthias/Data/Ubuntu/data/datasets/porta_filter/front3d\"\n# path_to_config_yaml = \"/home/matthias/Data/Ubuntu/git/detectron2/configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml\"\nDatasetCatalog.register(\"porta_filter\", lambda: load_coco_json(path_to_coco_json, path_to_images))\nMetadataCatalog.get(\"porta_filter\").set(thing_classes=[\"porta filter\"], json_file=path_to_coco_json, image_root=path_to_images)\n\n# constants\nWINDOW_NAME = \"COCO detections\"\n\n\ndef setup_cfg(args):\n # load config from file and command-line arguments\n cfg = get_cfg()\n # To use demo for Panoptic-DeepLab, please uncomment the following two lines.\n # from detectron2.projects.panoptic_deeplab import add_panoptic_deeplab_config # noqa\n # add_panoptic_deeplab_config(cfg)\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n # Set score_threshold for builtin models\n cfg.MODEL.RETINANET.SCORE_THRESH_TEST = args.confidence_threshold\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.confidence_threshold\n cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = args.confidence_threshold\n cfg.freeze()\n return cfg\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(description=\"Detectron2 demo for builtin configs\")\n parser.add_argument(\n \"--config-file\",\n default=\"configs/quick_schedules/mask_rcnn_R_50_FPN_inference_acc_test.yaml\",\n metavar=\"FILE\",\n help=\"path to config file\",\n )\n parser.add_argument(\"--webcam\", action=\"store_true\", help=\"Take inputs from webcam.\")\n parser.add_argument(\"--video-input\", help=\"Path to video file.\")\n parser.add_argument(\n \"--input\",\n nargs=\"+\",\n help=\"A list of space separated input images; \"\n \"or a single glob pattern such as 'directory/*.jpg'\",\n )\n parser.add_argument(\n \"--output\",\n help=\"A file or directory to save output visualizations. \"\n \"If not given, will show output in an OpenCV window.\",\n )\n\n parser.add_argument(\n \"--confidence-threshold\",\n type=float,\n default=0.5,\n help=\"Minimum score for instance predictions to be shown\",\n )\n parser.add_argument(\n \"--opts\",\n help=\"Modify config options using the command-line 'KEY VALUE' pairs\",\n default=[],\n nargs=argparse.REMAINDER,\n )\n return parser\n\n\ndef test_opencv_video_format(codec, file_ext):\n with tempfile.TemporaryDirectory(prefix=\"video_format_test\") as dir:\n filename = os.path.join(dir, \"test_file\" + file_ext)\n writer = cv2.VideoWriter(\n filename=filename,\n fourcc=cv2.VideoWriter_fourcc(*codec),\n fps=float(30),\n frameSize=(10, 10),\n isColor=True,\n )\n [writer.write(np.zeros((10, 10, 3), np.uint8)) for _ in range(30)]\n writer.release()\n if os.path.isfile(filename):\n return True\n return False\n\n\nif __name__ == \"__main__\":\n mp.set_start_method(\"spawn\", force=True)\n args = get_parser().parse_args()\n setup_logger(name=\"fvcore\")\n logger = setup_logger()\n logger.info(\"Arguments: \" + str(args))\n\n cfg = setup_cfg(args)\n\n demo = VisualizationDemo(cfg)\n\n if args.input:\n if len(args.input) == 1:\n args.input = glob.glob(os.path.expanduser(args.input[0]))\n assert args.input, \"The input path(s) was not found\"\n for path in tqdm.tqdm(args.input, disable=not args.output):\n # use PIL, to be consistent with evaluation\n img = read_image(path, format=\"BGR\")\n start_time = time.time()\n predictions, visualized_output = demo.run_on_image(img)\n logger.info(\n \"{}: {} in {:.2f}s\".format(\n path,\n \"detected {} instances\".format(len(predictions[\"instances\"]))\n if \"instances\" in predictions\n else \"finished\",\n time.time() - start_time,\n )\n )\n\n if args.output:\n if os.path.isdir(args.output):\n assert os.path.isdir(args.output), args.output\n out_filename = os.path.join(args.output, os.path.basename(path))\n else:\n assert len(args.input) == 1, \"Please specify a directory with args.output\"\n out_filename = args.output\n visualized_output.save(out_filename)\n else:\n cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)\n cv2.imshow(WINDOW_NAME, visualized_output.get_image()[:, :, ::-1])\n if cv2.waitKey(0) == 27:\n break # esc to quit\n elif args.webcam:\n assert args.input is None, \"Cannot have both --input and --webcam!\"\n assert args.output is None, \"output not yet supported with --webcam!\"\n cam = cv2.VideoCapture(0)\n for vis in tqdm.tqdm(demo.run_on_video(cam)):\n cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)\n cv2.imshow(WINDOW_NAME, vis)\n if cv2.waitKey(1) == 27:\n break # esc to quit\n cam.release()\n cv2.destroyAllWindows()\n elif args.video_input:\n video = cv2.VideoCapture(args.video_input)\n width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))\n frames_per_second = video.get(cv2.CAP_PROP_FPS)\n num_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))\n basename = os.path.basename(args.video_input)\n codec, file_ext = (\n (\"x264\", \".mkv\") if test_opencv_video_format(\"x264\", \".mkv\") else (\"mp4v\", \".mp4\")\n )\n if codec == \".mp4v\":\n warnings.warn(\"x264 codec not available, switching to mp4v\")\n if args.output:\n if os.path.isdir(args.output):\n output_fname = os.path.join(args.output, basename)\n output_fname = os.path.splitext(output_fname)[0] + file_ext\n else:\n output_fname = args.output\n assert not os.path.isfile(output_fname), output_fname\n output_file = cv2.VideoWriter(\n filename=output_fname,\n # some installation of opencv may not support x264 (due to its license),\n # you can try other format (e.g. MPEG)\n fourcc=cv2.VideoWriter_fourcc(*codec),\n fps=float(frames_per_second),\n frameSize=(width, height),\n isColor=True,\n )\n assert os.path.isfile(args.video_input)\n for vis_frame in tqdm.tqdm(demo.run_on_video(video), total=num_frames):\n if args.output:\n output_file.write(vis_frame)\n else:\n cv2.namedWindow(basename, cv2.WINDOW_NORMAL)\n cv2.imshow(basename, vis_frame)\n if cv2.waitKey(1) == 27:\n break # esc to quit\n video.release()\n if args.output:\n output_file.release()\n else:\n cv2.destroyAllWindows()\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rserran/FLAML
[ "7d6822aa40883550e72c4ee24adb765c6e937ce7" ]
[ "flaml/model.py" ]
[ "# !\r\n# * Copyright (c) FLAML authors. All rights reserved.\r\n# * Licensed under the MIT License. See LICENSE file in the\r\n# * project root for license information.\r\nfrom contextlib import contextmanager\r\nfrom functools import partial\r\nimport signal\r\nimport os\r\nfrom typing import Callable, List\r\nimport numpy as np\r\nimport time\r\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\r\nfrom sklearn.ensemble import ExtraTreesRegressor, ExtraTreesClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.dummy import DummyClassifier, DummyRegressor\r\nfrom scipy.sparse import issparse\r\nimport logging\r\nimport shutil\r\nfrom pandas import DataFrame, Series, to_datetime\r\nimport sys\r\nimport math\r\nfrom . import tune\r\nfrom .data import (\r\n group_counts,\r\n CLASSIFICATION,\r\n TS_FORECASTREGRESSION,\r\n TS_TIMESTAMP_COL,\r\n TS_VALUE_COL,\r\n SEQCLASSIFICATION,\r\n SEQREGRESSION,\r\n TOKENCLASSIFICATION,\r\n SUMMARIZATION,\r\n NLG_TASKS,\r\n MULTICHOICECLASSIFICATION,\r\n)\r\n\r\ntry:\r\n import psutil\r\nexcept ImportError:\r\n psutil = None\r\ntry:\r\n import resource\r\nexcept ImportError:\r\n resource = None\r\n\r\nlogger = logging.getLogger(\"flaml.automl\")\r\nFREE_MEM_RATIO = 0.2\r\n\r\n\r\ndef TimeoutHandler(sig, frame):\r\n raise TimeoutError(sig, frame)\r\n\r\n\r\n@contextmanager\r\ndef limit_resource(memory_limit, time_limit):\r\n if memory_limit > 0:\r\n soft, hard = resource.getrlimit(resource.RLIMIT_AS)\r\n if soft < 0 and (hard < 0 or memory_limit <= hard) or memory_limit < soft:\r\n try:\r\n resource.setrlimit(resource.RLIMIT_AS, (int(memory_limit), hard))\r\n except ValueError:\r\n # According to https://bugs.python.org/issue40518, it's a mac-specific error.\r\n pass\r\n main_thread = False\r\n if time_limit is not None:\r\n try:\r\n signal.signal(signal.SIGALRM, TimeoutHandler)\r\n signal.alarm(int(time_limit) or 1)\r\n main_thread = True\r\n except ValueError:\r\n pass\r\n try:\r\n yield\r\n finally:\r\n if main_thread:\r\n signal.alarm(0)\r\n if memory_limit > 0:\r\n resource.setrlimit(resource.RLIMIT_AS, (soft, hard))\r\n\r\n\r\nclass BaseEstimator:\r\n \"\"\"The abstract class for all learners.\r\n\r\n Typical examples:\r\n * XGBoostEstimator: for regression.\r\n * XGBoostSklearnEstimator: for classification.\r\n * LGBMEstimator, RandomForestEstimator, LRL1Classifier, LRL2Classifier:\r\n for both regression and classification.\r\n \"\"\"\r\n\r\n def __init__(self, task=\"binary\", **config):\r\n \"\"\"Constructor.\r\n\r\n Args:\r\n task: A string of the task type, one of\r\n 'binary', 'multiclass', 'regression', 'rank', 'seq-classification',\r\n 'seq-regression', 'token-classification', 'multichoice-classification',\r\n 'summarization', 'ts_forecast', 'ts_forecast_classification'.\r\n config: A dictionary containing the hyperparameter names, 'n_jobs' as keys.\r\n n_jobs is the number of parallel threads.\r\n \"\"\"\r\n self._task = task\r\n self.params = self.config2params(config)\r\n self.estimator_class = self._model = None\r\n if \"_estimator_type\" in config:\r\n self._estimator_type = self.params.pop(\"_estimator_type\")\r\n else:\r\n self._estimator_type = (\r\n \"classifier\" if task in CLASSIFICATION else \"regressor\"\r\n )\r\n\r\n def get_params(self, deep=False):\r\n params = self.params.copy()\r\n params[\"task\"] = self._task\r\n if hasattr(self, \"_estimator_type\"):\r\n params[\"_estimator_type\"] = self._estimator_type\r\n return params\r\n\r\n @property\r\n def classes_(self):\r\n return self._model.classes_\r\n\r\n @property\r\n def n_features_in_(self):\r\n return self._model.n_features_in_\r\n\r\n @property\r\n def model(self):\r\n \"\"\"Trained model after fit() is called, or None before fit() is called.\"\"\"\r\n return self._model\r\n\r\n @property\r\n def estimator(self):\r\n \"\"\"Trained model after fit() is called, or None before fit() is called.\"\"\"\r\n return self._model\r\n\r\n def _preprocess(self, X):\r\n return X\r\n\r\n def _fit(self, X_train, y_train, **kwargs):\r\n\r\n current_time = time.time()\r\n if \"groups\" in kwargs:\r\n kwargs = kwargs.copy()\r\n groups = kwargs.pop(\"groups\")\r\n if self._task == \"rank\":\r\n kwargs[\"group\"] = group_counts(groups)\r\n # groups_val = kwargs.get('groups_val')\r\n # if groups_val is not None:\r\n # kwargs['eval_group'] = [group_counts(groups_val)]\r\n # kwargs['eval_set'] = [\r\n # (kwargs['X_val'], kwargs['y_val'])]\r\n # kwargs['verbose'] = False\r\n # del kwargs['groups_val'], kwargs['X_val'], kwargs['y_val']\r\n X_train = self._preprocess(X_train)\r\n model = self.estimator_class(**self.params)\r\n if logger.level == logging.DEBUG:\r\n # xgboost 1.6 doesn't display all the params in the model str\r\n logger.debug(f\"flaml.model - {model} fit started with params {self.params}\")\r\n model.fit(X_train, y_train, **kwargs)\r\n if logger.level == logging.DEBUG:\r\n logger.debug(f\"flaml.model - {model} fit finished\")\r\n train_time = time.time() - current_time\r\n self._model = model\r\n return train_time\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n \"\"\"Train the model from given training data.\r\n\r\n Args:\r\n X_train: A numpy array or a dataframe of training data in shape n*m.\r\n y_train: A numpy array or a series of labels in shape n*1.\r\n budget: A float of the time budget in seconds.\r\n\r\n Returns:\r\n train_time: A float of the training time in seconds.\r\n \"\"\"\r\n if (\r\n getattr(self, \"limit_resource\", None)\r\n and resource is not None\r\n and (budget is not None or psutil is not None)\r\n ):\r\n start_time = time.time()\r\n mem = psutil.virtual_memory() if psutil is not None else None\r\n try:\r\n with limit_resource(\r\n mem.available * (1 - FREE_MEM_RATIO)\r\n + psutil.Process(os.getpid()).memory_info().rss\r\n if mem is not None\r\n else -1,\r\n budget,\r\n ):\r\n train_time = self._fit(X_train, y_train, **kwargs)\r\n except (MemoryError, TimeoutError) as e:\r\n logger.warning(f\"{e.__class__} {e}\")\r\n if self._task in CLASSIFICATION:\r\n model = DummyClassifier()\r\n else:\r\n model = DummyRegressor()\r\n X_train = self._preprocess(X_train)\r\n model.fit(X_train, y_train)\r\n self._model = model\r\n train_time = time.time() - start_time\r\n else:\r\n train_time = self._fit(X_train, y_train, **kwargs)\r\n return train_time\r\n\r\n def predict(self, X, **kwargs):\r\n \"\"\"Predict label from features.\r\n\r\n Args:\r\n X: A numpy array or a dataframe of featurized instances, shape n*m.\r\n\r\n Returns:\r\n A numpy array of shape n*1.\r\n Each element is the label for a instance.\r\n \"\"\"\r\n if self._model is not None:\r\n X = self._preprocess(X)\r\n return self._model.predict(X)\r\n else:\r\n logger.warning(\r\n \"Estimator is not fit yet. Please run fit() before predict().\"\r\n )\r\n return np.ones(X.shape[0])\r\n\r\n def predict_proba(self, X, **kwargs):\r\n \"\"\"Predict the probability of each class from features.\r\n\r\n Only works for classification problems\r\n\r\n Args:\r\n X: A numpy array of featurized instances, shape n*m.\r\n\r\n Returns:\r\n A numpy array of shape n*c. c is the # classes.\r\n Each element at (i,j) is the probability for instance i to be in\r\n class j.\r\n \"\"\"\r\n assert self._task in CLASSIFICATION, \"predict_proba() only for classification.\"\r\n\r\n X = self._preprocess(X)\r\n return self._model.predict_proba(X)\r\n\r\n def score(self, X_val: DataFrame, y_val: Series, **kwargs):\r\n \"\"\"Report the evaluation score of a trained estimator.\r\n\r\n\r\n Args:\r\n X_val: A pandas dataframe of the validation input data.\r\n y_val: A pandas series of the validation label.\r\n kwargs: keyword argument of the evaluation function, for example:\r\n - metric: A string of the metric name or a function\r\n e.g., 'accuracy', 'roc_auc', 'roc_auc_ovr', 'roc_auc_ovo',\r\n 'f1', 'micro_f1', 'macro_f1', 'log_loss', 'mae', 'mse', 'r2',\r\n 'mape'. Default is 'auto'.\r\n If metric is given, the score will report the user specified metric.\r\n If metric is not given, the metric is set to accuracy for classification and r2\r\n for regression.\r\n You can also pass a customized metric function, for examples on how to pass a\r\n customized metric function, please check\r\n [test/nlp/test_autohf_custom_metric.py](https://github.com/microsoft/FLAML/blob/main/test/nlp/test_autohf_custom_metric.py) and\r\n [test/automl/test_multiclass.py](https://github.com/microsoft/FLAML/blob/main/test/automl/test_multiclass.py).\r\n\r\n Returns:\r\n The evaluation score on the validation dataset.\r\n \"\"\"\r\n from .ml import metric_loss_score\r\n from .ml import is_min_metric\r\n\r\n if self._model is not None:\r\n if self._task == \"rank\":\r\n raise NotImplementedError(\r\n \"AutoML.score() is not implemented for ranking\"\r\n )\r\n else:\r\n X_val = self._preprocess(X_val)\r\n metric = kwargs.get(\"metric\", None)\r\n if metric:\r\n y_pred = self.predict(X_val, **kwargs)\r\n if is_min_metric(metric):\r\n return metric_loss_score(metric, y_pred, y_val)\r\n else:\r\n return 1.0 - metric_loss_score(metric, y_pred, y_val)\r\n else:\r\n return self._model.score(X_val, y_val, **kwargs)\r\n else:\r\n logger.warning(\r\n \"Estimator is not fit yet. Please run fit() before predict().\"\r\n )\r\n return 0.0\r\n\r\n def cleanup(self):\r\n del self._model\r\n self._model = None\r\n\r\n @classmethod\r\n def search_space(cls, data_size, task, **params):\r\n \"\"\"[required method] search space.\r\n\r\n Args:\r\n data_size: A tuple of two integers, number of rows and columns.\r\n task: A str of the task type, e.g., \"binary\", \"multiclass\", \"regression\".\r\n\r\n Returns:\r\n A dictionary of the search space.\r\n Each key is the name of a hyperparameter, and value is a dict with\r\n its domain (required) and low_cost_init_value, init_value,\r\n cat_hp_cost (if applicable).\r\n e.g., ```{'domain': tune.randint(lower=1, upper=10), 'init_value': 1}```.\r\n \"\"\"\r\n return {}\r\n\r\n @classmethod\r\n def size(cls, config: dict) -> float:\r\n \"\"\"[optional method] memory size of the estimator in bytes.\r\n\r\n Args:\r\n config: A dict of the hyperparameter config.\r\n\r\n Returns:\r\n A float of the memory size required by the estimator to train the\r\n given config.\r\n \"\"\"\r\n return 1.0\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls) -> float:\r\n \"\"\"[optional method] relative cost compared to lightgbm.\"\"\"\r\n return 1.0\r\n\r\n @classmethod\r\n def init(cls):\r\n \"\"\"[optional method] initialize the class.\"\"\"\r\n pass\r\n\r\n def config2params(self, config: dict) -> dict:\r\n \"\"\"[optional method] config dict to params dict\r\n\r\n Args:\r\n config: A dict of the hyperparameter config.\r\n\r\n Returns:\r\n A dict that will be passed to self.estimator_class's constructor.\r\n \"\"\"\r\n params = config.copy()\r\n if \"FLAML_sample_size\" in params:\r\n params.pop(\"FLAML_sample_size\")\r\n return params\r\n\r\n\r\nclass TransformersEstimator(BaseEstimator):\r\n \"\"\"The class for fine-tuning language models, using huggingface transformers API.\"\"\"\r\n\r\n ITER_HP = \"global_max_steps\"\r\n\r\n def __init__(self, task=\"seq-classification\", **config):\r\n super().__init__(task, **config)\r\n import uuid\r\n\r\n self.trial_id = str(uuid.uuid1().hex)[:8]\r\n if task not in NLG_TASKS: # TODO: not in NLG_TASKS\r\n from .nlp.huggingface.training_args import (\r\n TrainingArgumentsForAuto as TrainingArguments,\r\n )\r\n else:\r\n from .nlp.huggingface.training_args import (\r\n Seq2SeqTrainingArgumentsForAuto as TrainingArguments,\r\n )\r\n self._TrainingArguments = TrainingArguments\r\n\r\n @staticmethod\r\n def _join(X_train, y_train, task):\r\n y_train = DataFrame(y_train, index=X_train.index)\r\n y_train.columns = [\"label\"] if task != TOKENCLASSIFICATION else [\"labels\"]\r\n train_df = X_train.join(y_train)\r\n return train_df\r\n\r\n @classmethod\r\n def search_space(cls, data_size, task, **params):\r\n search_space_dict = {\r\n \"learning_rate\": {\r\n \"domain\": tune.loguniform(lower=1e-6, upper=1e-3),\r\n \"init_value\": 1e-5,\r\n },\r\n \"num_train_epochs\": {\r\n \"domain\": tune.loguniform(lower=0.1, upper=10.0),\r\n \"init_value\": 3.0, # to be consistent with roberta\r\n },\r\n \"per_device_train_batch_size\": {\r\n \"domain\": tune.choice([4, 8, 16, 32]),\r\n \"init_value\": 32,\r\n },\r\n \"warmup_ratio\": {\r\n \"domain\": tune.uniform(lower=0.0, upper=0.3),\r\n \"init_value\": 0.0,\r\n },\r\n \"weight_decay\": {\r\n \"domain\": tune.uniform(lower=0.0, upper=0.3),\r\n \"init_value\": 0.0,\r\n },\r\n \"adam_epsilon\": {\r\n \"domain\": tune.loguniform(lower=1e-8, upper=1e-6),\r\n \"init_value\": 1e-6,\r\n },\r\n \"seed\": {\"domain\": tune.choice(list(range(40, 45))), \"init_value\": 42},\r\n \"global_max_steps\": {\r\n \"domain\": sys.maxsize,\r\n \"init_value\": sys.maxsize,\r\n },\r\n }\r\n\r\n return search_space_dict\r\n\r\n @property\r\n def checkpoint_freq(self):\r\n return (\r\n int(\r\n min(self._training_args.num_train_epochs, 1)\r\n * len(self._X_train)\r\n / self._training_args.per_device_train_batch_size\r\n / self._training_args.ckpt_per_epoch\r\n )\r\n + 1\r\n )\r\n\r\n @property\r\n def fp16(self):\r\n return self._kwargs.get(\"gpu_per_trial\") and self._training_args.fp16\r\n\r\n @property\r\n def no_cuda(self):\r\n return not self._kwargs.get(\"gpu_per_trial\")\r\n\r\n def _set_training_args(self, **kwargs):\r\n from .nlp.utils import date_str, Counter\r\n\r\n for (key, val) in kwargs.items():\r\n assert key not in self.params, (\r\n \"Since {} is in the search space, it cannot exist in 'custom_fit_kwargs' at the same time.\"\r\n \"If you need to fix the value of {} to {}, the only way is to add a single-value domain in the search \"\r\n \"space by adding:\\n '{}': {{ 'domain': {} }} to 'custom_hp'. For example:\"\r\n 'automl_settings[\"custom_hp\"] = {{ \"transformer\": {{ \"model_path\": {{ \"domain\" : '\r\n '\"google/electra-small-discriminator\" }} }} }}'.format(\r\n key, key, val, key, val\r\n )\r\n )\r\n\r\n \"\"\"\r\n If use has specified any custom args for TrainingArguments, update these arguments\r\n \"\"\"\r\n self._training_args = self._TrainingArguments(**kwargs)\r\n\r\n \"\"\"\r\n Update the attributes in TrainingArguments with self.params values\r\n \"\"\"\r\n for key, val in self.params.items():\r\n if hasattr(self._training_args, key):\r\n setattr(self._training_args, key, val)\r\n\r\n \"\"\"\r\n Update the attributes in TrainingArguments that depends on the values of self.params\r\n \"\"\"\r\n local_dir = os.path.join(\r\n self._training_args.output_dir, \"train_{}\".format(date_str())\r\n )\r\n if self._use_ray is True:\r\n import ray\r\n\r\n self._training_args.output_dir = ray.tune.get_trial_dir()\r\n else:\r\n self._training_args.output_dir = Counter.get_trial_fold_name(\r\n local_dir, self.params, self.trial_id\r\n )\r\n\r\n self._training_args.eval_steps = (\r\n self._training_args.logging_steps\r\n ) = self._training_args.saving_steps = self.checkpoint_freq\r\n self._training_args.fp16 = self.fp16\r\n self._training_args.no_cuda = self.no_cuda\r\n\r\n def _preprocess(self, X, y=None, **kwargs):\r\n from .nlp.utils import tokenize_text, is_a_list_of_str\r\n\r\n is_str = str(X.dtypes[0]) in (\"string\", \"str\")\r\n is_list_of_str = is_a_list_of_str(X[list(X.keys())[0]].to_list()[0])\r\n\r\n if is_str or is_list_of_str:\r\n return tokenize_text(\r\n X=X,\r\n Y=y,\r\n task=self._task,\r\n hf_args=self._training_args,\r\n tokenizer=self.tokenizer,\r\n )\r\n else:\r\n return X, None\r\n\r\n def _model_init(self):\r\n from .nlp.utils import load_model\r\n\r\n this_model = load_model(\r\n checkpoint_path=self._training_args.model_path,\r\n task=self._task,\r\n num_labels=self.num_labels,\r\n )\r\n return this_model\r\n\r\n def preprocess_data(self, X, y):\r\n from datasets import Dataset\r\n\r\n if (self._task not in NLG_TASKS) and (self._task != TOKENCLASSIFICATION):\r\n processed_X, _ = self._preprocess(X=X, **self._kwargs)\r\n processed_y = y\r\n else:\r\n processed_X, processed_y = self._preprocess(X=X, y=y, **self._kwargs)\r\n\r\n processed_dataset = Dataset.from_pandas(\r\n TransformersEstimator._join(processed_X, processed_y, self._task)\r\n )\r\n return processed_dataset, processed_X, processed_y\r\n\r\n @property\r\n def num_labels(self):\r\n from .data import SEQCLASSIFICATION, SEQREGRESSION, TOKENCLASSIFICATION\r\n\r\n if self._task == SEQREGRESSION:\r\n return 1\r\n elif self._task == SEQCLASSIFICATION:\r\n return len(set(self._y_train))\r\n elif self._task == TOKENCLASSIFICATION:\r\n return len(set([a for b in self._y_train.tolist() for a in b]))\r\n else:\r\n return None\r\n\r\n @property\r\n def tokenizer(self):\r\n from transformers import AutoTokenizer\r\n\r\n if self._task == SUMMARIZATION:\r\n return AutoTokenizer.from_pretrained(\r\n pretrained_model_name_or_path=self._training_args.model_path,\r\n cache_dir=None,\r\n use_fast=True,\r\n revision=\"main\",\r\n use_auth_token=None,\r\n )\r\n else:\r\n return AutoTokenizer.from_pretrained(\r\n self._training_args.model_path,\r\n use_fast=True,\r\n add_prefix_space=True\r\n if \"roberta\" in self._training_args.model_path\r\n else False, # If roberta model, must set add_prefix_space to True to avoid the assertion error at\r\n # https://github.com/huggingface/transformers/blob/main/src/transformers/models/roberta/tokenization_roberta_fast.py#L249\r\n )\r\n\r\n @property\r\n def data_collator(self):\r\n from .nlp.huggingface.data_collator import task_to_datacollator_class\r\n\r\n return (\r\n task_to_datacollator_class[self._task](\r\n tokenizer=self.tokenizer,\r\n pad_to_multiple_of=8, # if self._training_args.fp16 else None,\r\n )\r\n if self._task in (MULTICHOICECLASSIFICATION, TOKENCLASSIFICATION)\r\n else None\r\n )\r\n\r\n def fit(\r\n self,\r\n X_train: DataFrame,\r\n y_train: Series,\r\n budget=None,\r\n X_val=None,\r\n y_val=None,\r\n gpu_per_trial=None,\r\n metric=None,\r\n **kwargs,\r\n ):\r\n import transformers\r\n\r\n transformers.logging.set_verbosity_error()\r\n\r\n from transformers import TrainerCallback\r\n from transformers.trainer_utils import set_seed\r\n from .nlp.huggingface.trainer import TrainerForAuto\r\n\r\n try:\r\n from ray.tune import is_session_enabled\r\n\r\n self._use_ray = is_session_enabled()\r\n except ImportError:\r\n self._use_ray = False\r\n\r\n this_params = self.params\r\n self._kwargs = kwargs\r\n\r\n self._X_train, self._y_train = X_train, y_train\r\n self._set_training_args(**kwargs)\r\n\r\n train_dataset, self._X_train, self._y_train = self.preprocess_data(\r\n X_train, y_train\r\n )\r\n if X_val is not None:\r\n eval_dataset, self._X_val, self._y_val = self.preprocess_data(X_val, y_val)\r\n else:\r\n eval_dataset, self._X_val, self._y_val = None, None, None\r\n\r\n set_seed(self.params.get(\"seed\", self._training_args.seed))\r\n self._metric = metric\r\n\r\n class EarlyStoppingCallbackForAuto(TrainerCallback):\r\n def on_train_begin(self, args, state, control, **callback_kwargs):\r\n self.train_begin_time = time.time()\r\n\r\n def on_step_begin(self, args, state, control, **callback_kwargs):\r\n self.step_begin_time = time.time()\r\n\r\n def on_step_end(self, args, state, control, **callback_kwargs):\r\n if state.global_step == 1:\r\n self.time_per_iter = time.time() - self.step_begin_time\r\n if (\r\n budget\r\n and (\r\n time.time() + self.time_per_iter\r\n > self.train_begin_time + budget\r\n )\r\n or state.global_step >= this_params[TransformersEstimator.ITER_HP]\r\n ):\r\n control.should_training_stop = True\r\n control.should_save = True\r\n control.should_evaluate = True\r\n return control\r\n\r\n def on_epoch_end(self, args, state, control, **callback_kwargs):\r\n if (\r\n control.should_training_stop\r\n or state.epoch + 1 >= args.num_train_epochs\r\n ):\r\n control.should_save = True\r\n control.should_evaluate = True\r\n\r\n self._trainer = TrainerForAuto(\r\n args=self._training_args,\r\n model_init=self._model_init,\r\n train_dataset=train_dataset,\r\n eval_dataset=eval_dataset,\r\n tokenizer=self.tokenizer,\r\n data_collator=self.data_collator,\r\n compute_metrics=self._compute_metrics_by_dataset_name,\r\n callbacks=[EarlyStoppingCallbackForAuto],\r\n )\r\n\r\n if self._task in NLG_TASKS:\r\n setattr(self._trainer, \"_is_seq2seq\", True)\r\n\r\n \"\"\"\r\n When not using ray for tuning, set the limit of CUDA_VISIBLE_DEVICES to math.ceil(gpu_per_trial),\r\n so each estimator does not see all the GPUs\r\n \"\"\"\r\n if gpu_per_trial is not None:\r\n tmp_cuda_visible_devices = os.environ.get(\"CUDA_VISIBLE_DEVICES\", \"\")\r\n self._trainer.args._n_gpu = gpu_per_trial\r\n\r\n # if gpu_per_trial == 0:\r\n # os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\r\n if tmp_cuda_visible_devices.count(\",\") != math.ceil(gpu_per_trial) - 1:\r\n\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \",\".join(\r\n [str(x) for x in range(math.ceil(gpu_per_trial))]\r\n )\r\n\r\n import time\r\n\r\n start_time = time.time()\r\n self._trainer.train()\r\n\r\n if gpu_per_trial is not None:\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = tmp_cuda_visible_devices\r\n\r\n self.params[self.ITER_HP] = self._trainer.state.global_step\r\n\r\n self._checkpoint_path = self._select_checkpoint(self._trainer)\r\n self._ckpt_remains = list(self._trainer.ckpt_to_metric.keys())\r\n\r\n if hasattr(self._trainer, \"intermediate_results\"):\r\n self.intermediate_results = [\r\n x[1]\r\n for x in sorted(\r\n self._trainer.intermediate_results.items(), key=lambda x: x[0]\r\n )\r\n ]\r\n self._trainer = None\r\n\r\n return time.time() - start_time\r\n\r\n def _delete_one_ckpt(self, ckpt_location):\r\n if self._use_ray is False:\r\n try:\r\n shutil.rmtree(ckpt_location)\r\n except FileNotFoundError:\r\n logger.warning(\"checkpoint {} not found\".format(ckpt_location))\r\n\r\n def cleanup(self):\r\n super().cleanup()\r\n if hasattr(self, \"_ckpt_remains\"):\r\n for each_ckpt in self._ckpt_remains:\r\n self._delete_one_ckpt(each_ckpt)\r\n\r\n def _select_checkpoint(self, trainer):\r\n from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR\r\n\r\n if trainer.ckpt_to_metric:\r\n best_ckpt, _ = min(\r\n trainer.ckpt_to_metric.items(), key=lambda x: x[1][\"eval_loss\"]\r\n )\r\n best_ckpt_global_step = trainer.ckpt_to_global_step[best_ckpt]\r\n for each_ckpt in list(trainer.ckpt_to_metric):\r\n if each_ckpt != best_ckpt:\r\n del trainer.ckpt_to_metric[each_ckpt]\r\n del trainer.ckpt_to_global_step[each_ckpt]\r\n self._delete_one_ckpt(each_ckpt)\r\n else:\r\n best_ckpt_global_step = trainer.state.global_step\r\n best_ckpt = os.path.join(\r\n trainer.args.output_dir,\r\n f\"{PREFIX_CHECKPOINT_DIR}-{best_ckpt_global_step}\",\r\n )\r\n self.params[self.ITER_HP] = best_ckpt_global_step\r\n logger.debug(trainer.state.global_step)\r\n logger.debug(trainer.ckpt_to_global_step)\r\n return best_ckpt\r\n\r\n def _compute_metrics_by_dataset_name(self, eval_pred):\r\n if isinstance(self._metric, str):\r\n from .ml import metric_loss_score\r\n from .nlp.utils import postprocess_text\r\n\r\n predictions, labels = eval_pred\r\n if self._task in NLG_TASKS:\r\n if isinstance(predictions, tuple):\r\n predictions = np.argmax(predictions[0], axis=2)\r\n decoded_preds = self.tokenizer.batch_decode(\r\n predictions, skip_special_tokens=True\r\n )\r\n labels = np.where(labels != -100, labels, self.tokenizer.pad_token_id)\r\n decoded_labels = self.tokenizer.batch_decode(\r\n labels, skip_special_tokens=True\r\n )\r\n predictions, labels = postprocess_text(decoded_preds, decoded_labels)\r\n else:\r\n predictions = (\r\n np.squeeze(predictions)\r\n if self._task == SEQREGRESSION\r\n else np.argmax(predictions, axis=2)\r\n if self._task == TOKENCLASSIFICATION\r\n else np.argmax(predictions, axis=1)\r\n )\r\n metric_dict = {\r\n \"automl_metric\": metric_loss_score(\r\n metric_name=self._metric,\r\n y_predict=predictions,\r\n y_true=labels,\r\n labels=self._training_args.label_list,\r\n )\r\n }\r\n else:\r\n loss, metric_dict = self._metric(\r\n X_test=self._X_val,\r\n y_test=self._y_val,\r\n estimator=self,\r\n labels=None,\r\n X_train=self._X_train,\r\n y_train=self._y_train,\r\n )\r\n metric_dict[\"automl_metric\"] = loss\r\n\r\n return metric_dict\r\n\r\n def _init_model_for_predict(self):\r\n from .nlp.huggingface.trainer import TrainerForAuto\r\n\r\n \"\"\"\r\n Need to reinit training_args because of a bug in deepspeed: if not reinit, the deepspeed config will be inconsistent\r\n with HF config https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py#L947\r\n \"\"\"\r\n training_args = self._TrainingArguments(\r\n local_rank=-1, model_path=self._checkpoint_path, fp16=self.fp16\r\n )\r\n for key, val in self._training_args.__dict__.items():\r\n if key not in (\"local_rank\", \"model_path\", \"fp16\"):\r\n setattr(training_args, key, val)\r\n self._training_args = training_args\r\n\r\n new_trainer = TrainerForAuto(\r\n model=self._model_init(),\r\n args=self._training_args,\r\n data_collator=self.data_collator,\r\n compute_metrics=self._compute_metrics_by_dataset_name,\r\n )\r\n if self._task in NLG_TASKS:\r\n setattr(new_trainer, \"_is_seq2seq\", True)\r\n return new_trainer\r\n\r\n def predict_proba(self, X, **pred_kwargs):\r\n from datasets import Dataset\r\n\r\n if pred_kwargs:\r\n for key, val in pred_kwargs.items():\r\n setattr(self._training_args, key, val)\r\n\r\n assert (\r\n self._task in CLASSIFICATION\r\n ), \"predict_proba() only for classification tasks.\"\r\n\r\n X_test, _ = self._preprocess(X, **self._kwargs)\r\n test_dataset = Dataset.from_pandas(X_test)\r\n\r\n new_trainer = self._init_model_for_predict()\r\n predictions = new_trainer.predict(test_dataset)\r\n return predictions.predictions\r\n\r\n def score(self, X_val: DataFrame, y_val: Series, **kwargs):\r\n import transformers\r\n\r\n transformers.logging.set_verbosity_error()\r\n\r\n self._metric = kwargs[\"metric\"]\r\n\r\n eval_dataset, X_val, y_val = self.preprocess_data(X_val, y_val)\r\n\r\n new_trainer = self._init_model_for_predict()\r\n return new_trainer.evaluate(eval_dataset)\r\n\r\n def predict(self, X, **pred_kwargs):\r\n import transformers\r\n from datasets import Dataset\r\n\r\n transformers.logging.set_verbosity_error()\r\n\r\n if pred_kwargs:\r\n for key, val in pred_kwargs.items():\r\n setattr(self._training_args, key, val)\r\n\r\n X_test, _ = self._preprocess(X, **self._kwargs)\r\n test_dataset = Dataset.from_pandas(X_test)\r\n\r\n new_trainer = self._init_model_for_predict()\r\n\r\n if self._task not in NLG_TASKS:\r\n predictions = new_trainer.predict(test_dataset)\r\n else:\r\n predictions = new_trainer.predict(\r\n test_dataset,\r\n metric_key_prefix=\"predict\",\r\n )\r\n\r\n if self._task == SEQCLASSIFICATION:\r\n return np.argmax(predictions.predictions, axis=1)\r\n elif self._task == SEQREGRESSION:\r\n return predictions.predictions.reshape((len(predictions.predictions),))\r\n elif self._task == TOKENCLASSIFICATION:\r\n return np.argmax(predictions.predictions, axis=2)\r\n elif self._task == SUMMARIZATION:\r\n decoded_preds = self.tokenizer.batch_decode(\r\n predictions.predictions, skip_special_tokens=True\r\n )\r\n return decoded_preds\r\n elif self._task == MULTICHOICECLASSIFICATION:\r\n return np.argmax(predictions.predictions, axis=1)\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n params[TransformersEstimator.ITER_HP] = params.get(\r\n TransformersEstimator.ITER_HP, sys.maxsize\r\n )\r\n return params\r\n\r\n\r\nclass TransformersEstimatorModelSelection(TransformersEstimator):\r\n def __init__(self, task=\"seq-classification\", **config):\r\n super().__init__(task, **config)\r\n\r\n @classmethod\r\n def search_space(cls, data_size, task, **params):\r\n search_space_dict = TransformersEstimator.search_space(\r\n data_size, task, **params\r\n )\r\n\r\n \"\"\"\r\n For model selection, use the same search space regardless of memory constraint\r\n If OOM, user should change the search space themselves\r\n \"\"\"\r\n\r\n search_space_dict[\"model_path\"] = {\r\n \"domain\": tune.choice(\r\n [\r\n \"google/electra-base-discriminator\",\r\n \"bert-base-uncased\",\r\n \"roberta-base\",\r\n \"facebook/muppet-roberta-base\",\r\n \"google/electra-small-discriminator\",\r\n ]\r\n ),\r\n \"init_value\": \"facebook/muppet-roberta-base\",\r\n }\r\n return search_space_dict\r\n\r\n\r\nclass SKLearnEstimator(BaseEstimator):\r\n \"\"\"The base class for tuning scikit-learn estimators.\"\"\"\r\n\r\n def __init__(self, task=\"binary\", **config):\r\n super().__init__(task, **config)\r\n\r\n def _preprocess(self, X):\r\n if isinstance(X, DataFrame):\r\n cat_columns = X.select_dtypes(include=[\"category\"]).columns\r\n if not cat_columns.empty:\r\n X = X.copy()\r\n X[cat_columns] = X[cat_columns].apply(lambda x: x.cat.codes)\r\n elif isinstance(X, np.ndarray) and X.dtype.kind not in \"buif\":\r\n # numpy array is not of numeric dtype\r\n X = DataFrame(X)\r\n for col in X.columns:\r\n if isinstance(X[col][0], str):\r\n X[col] = X[col].astype(\"category\").cat.codes\r\n X = X.to_numpy()\r\n return X\r\n\r\n\r\nclass LGBMEstimator(BaseEstimator):\r\n \"\"\"The class for tuning LGBM, using sklearn API.\"\"\"\r\n\r\n ITER_HP = \"n_estimators\"\r\n HAS_CALLBACK = True\r\n DEFAULT_ITER = 100\r\n\r\n @classmethod\r\n def search_space(cls, data_size, **params):\r\n upper = max(5, min(32768, int(data_size[0]))) # upper must be larger than lower\r\n return {\r\n \"n_estimators\": {\r\n \"domain\": tune.lograndint(lower=4, upper=upper),\r\n \"init_value\": 4,\r\n \"low_cost_init_value\": 4,\r\n },\r\n \"num_leaves\": {\r\n \"domain\": tune.lograndint(lower=4, upper=upper),\r\n \"init_value\": 4,\r\n \"low_cost_init_value\": 4,\r\n },\r\n \"min_child_samples\": {\r\n \"domain\": tune.lograndint(lower=2, upper=2**7 + 1),\r\n \"init_value\": 20,\r\n },\r\n \"learning_rate\": {\r\n \"domain\": tune.loguniform(lower=1 / 1024, upper=1.0),\r\n \"init_value\": 0.1,\r\n },\r\n \"log_max_bin\": { # log transformed with base 2\r\n \"domain\": tune.lograndint(lower=3, upper=11),\r\n \"init_value\": 8,\r\n },\r\n \"colsample_bytree\": {\r\n \"domain\": tune.uniform(lower=0.01, upper=1.0),\r\n \"init_value\": 1.0,\r\n },\r\n \"reg_alpha\": {\r\n \"domain\": tune.loguniform(lower=1 / 1024, upper=1024),\r\n \"init_value\": 1 / 1024,\r\n },\r\n \"reg_lambda\": {\r\n \"domain\": tune.loguniform(lower=1 / 1024, upper=1024),\r\n \"init_value\": 1.0,\r\n },\r\n }\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n if \"log_max_bin\" in params:\r\n params[\"max_bin\"] = (1 << params.pop(\"log_max_bin\")) - 1\r\n return params\r\n\r\n @classmethod\r\n def size(cls, config):\r\n num_leaves = int(\r\n round(\r\n config.get(\"num_leaves\")\r\n or config.get(\"max_leaves\")\r\n or 1 << config.get(\"max_depth\", 16)\r\n )\r\n )\r\n n_estimators = int(round(config[\"n_estimators\"]))\r\n return (num_leaves * 3 + (num_leaves - 1) * 4 + 1.0) * n_estimators * 8\r\n\r\n def __init__(self, task=\"binary\", **config):\r\n super().__init__(task, **config)\r\n if \"verbose\" not in self.params:\r\n self.params[\"verbose\"] = -1\r\n if \"regression\" == task:\r\n from lightgbm import LGBMRegressor\r\n\r\n self.estimator_class = LGBMRegressor\r\n elif \"rank\" == task:\r\n from lightgbm import LGBMRanker\r\n\r\n self.estimator_class = LGBMRanker\r\n else:\r\n from lightgbm import LGBMClassifier\r\n\r\n self.estimator_class = LGBMClassifier\r\n self._time_per_iter = None\r\n self._train_size = 0\r\n self._mem_per_iter = -1\r\n self.HAS_CALLBACK = self.HAS_CALLBACK and self._callbacks(0, 0) is not None\r\n\r\n def _preprocess(self, X):\r\n if (\r\n not isinstance(X, DataFrame)\r\n and issparse(X)\r\n and np.issubdtype(X.dtype, np.integer)\r\n ):\r\n X = X.astype(float)\r\n elif isinstance(X, np.ndarray) and X.dtype.kind not in \"buif\":\r\n # numpy array is not of numeric dtype\r\n X = DataFrame(X)\r\n for col in X.columns:\r\n if isinstance(X[col][0], str):\r\n X[col] = X[col].astype(\"category\").cat.codes\r\n X = X.to_numpy()\r\n return X\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n start_time = time.time()\r\n deadline = start_time + budget if budget else np.inf\r\n n_iter = self.params.get(self.ITER_HP, self.DEFAULT_ITER)\r\n trained = False\r\n if not self.HAS_CALLBACK:\r\n mem0 = psutil.virtual_memory().available if psutil is not None else 1\r\n if (\r\n (\r\n not self._time_per_iter\r\n or abs(self._train_size - X_train.shape[0]) > 4\r\n )\r\n and budget is not None\r\n or self._mem_per_iter < 0\r\n and psutil is not None\r\n ) and n_iter > 1:\r\n self.params[self.ITER_HP] = 1\r\n self._t1 = self._fit(X_train, y_train, **kwargs)\r\n if budget is not None and self._t1 >= budget or n_iter == 1:\r\n return self._t1\r\n mem1 = psutil.virtual_memory().available if psutil is not None else 1\r\n self._mem1 = mem0 - mem1\r\n self.params[self.ITER_HP] = min(n_iter, 4)\r\n self._t2 = self._fit(X_train, y_train, **kwargs)\r\n mem2 = psutil.virtual_memory().available if psutil is not None else 1\r\n self._mem2 = max(mem0 - mem2, self._mem1)\r\n # if self._mem1 <= 0:\r\n # self._mem_per_iter = self._mem2 / (self.params[self.ITER_HP] + 1)\r\n # elif self._mem2 <= 0:\r\n # self._mem_per_iter = self._mem1\r\n # else:\r\n self._mem_per_iter = min(\r\n self._mem1, self._mem2 / self.params[self.ITER_HP]\r\n )\r\n # if self._mem_per_iter <= 1 and psutil is not None:\r\n # n_iter = self.params[self.ITER_HP]\r\n self._time_per_iter = (\r\n (self._t2 - self._t1) / (self.params[self.ITER_HP] - 1)\r\n if self._t2 > self._t1\r\n else self._t1\r\n if self._t1\r\n else 0.001\r\n )\r\n self._train_size = X_train.shape[0]\r\n if (\r\n budget is not None\r\n and self._t1 + self._t2 >= budget\r\n or n_iter == self.params[self.ITER_HP]\r\n ):\r\n # self.params[self.ITER_HP] = n_iter\r\n return time.time() - start_time\r\n trained = True\r\n # logger.debug(mem0)\r\n # logger.debug(self._mem_per_iter)\r\n if n_iter > 1:\r\n max_iter = min(\r\n n_iter,\r\n int(\r\n (budget - time.time() + start_time - self._t1)\r\n / self._time_per_iter\r\n + 1\r\n )\r\n if budget is not None\r\n else n_iter,\r\n int((1 - FREE_MEM_RATIO) * mem0 / self._mem_per_iter)\r\n if psutil is not None and self._mem_per_iter > 0\r\n else n_iter,\r\n )\r\n if trained and max_iter <= self.params[self.ITER_HP]:\r\n return time.time() - start_time\r\n # when not trained, train at least one iter\r\n self.params[self.ITER_HP] = max(max_iter, 1)\r\n if self.HAS_CALLBACK:\r\n kwargs_callbacks = kwargs.get(\"callbacks\")\r\n if kwargs_callbacks:\r\n callbacks = kwargs_callbacks + self._callbacks(start_time, deadline)\r\n kwargs.pop(\"callbacks\")\r\n else:\r\n callbacks = self._callbacks(start_time, deadline)\r\n if isinstance(self, XGBoostSklearnEstimator):\r\n from xgboost import __version__\r\n\r\n if __version__ >= \"1.6.0\":\r\n # since xgboost>=1.6.0, callbacks can't be passed in fit()\r\n self.params[\"callbacks\"] = callbacks\r\n callbacks = None\r\n self._fit(\r\n X_train,\r\n y_train,\r\n callbacks=callbacks,\r\n **kwargs,\r\n )\r\n if callbacks is None:\r\n # for xgboost>=1.6.0, pop callbacks to enable pickle\r\n callbacks = self.params.pop(\"callbacks\")\r\n self._model.set_params(callbacks=callbacks[:-1])\r\n best_iteration = (\r\n self._model.get_booster().best_iteration\r\n if isinstance(self, XGBoostSklearnEstimator)\r\n else self._model.best_iteration_\r\n )\r\n if best_iteration is not None:\r\n self._model.set_params(n_estimators=best_iteration + 1)\r\n else:\r\n self._fit(X_train, y_train, **kwargs)\r\n train_time = time.time() - start_time\r\n return train_time\r\n\r\n def _callbacks(self, start_time, deadline) -> List[Callable]:\r\n return [partial(self._callback, start_time, deadline)]\r\n\r\n def _callback(self, start_time, deadline, env) -> None:\r\n from lightgbm.callback import EarlyStopException\r\n\r\n now = time.time()\r\n if env.iteration == 0:\r\n self._time_per_iter = now - start_time\r\n if now + self._time_per_iter > deadline:\r\n raise EarlyStopException(env.iteration, env.evaluation_result_list)\r\n if psutil is not None:\r\n mem = psutil.virtual_memory()\r\n if mem.available / mem.total < FREE_MEM_RATIO:\r\n raise EarlyStopException(env.iteration, env.evaluation_result_list)\r\n\r\n\r\nclass XGBoostEstimator(SKLearnEstimator):\r\n \"\"\"The class for tuning XGBoost regressor, not using sklearn API.\"\"\"\r\n\r\n DEFAULT_ITER = 10\r\n\r\n @classmethod\r\n def search_space(cls, data_size, **params):\r\n upper = max(5, min(32768, int(data_size[0]))) # upper must be larger than lower\r\n return {\r\n \"n_estimators\": {\r\n \"domain\": tune.lograndint(lower=4, upper=upper),\r\n \"init_value\": 4,\r\n \"low_cost_init_value\": 4,\r\n },\r\n \"max_leaves\": {\r\n \"domain\": tune.lograndint(lower=4, upper=upper),\r\n \"init_value\": 4,\r\n \"low_cost_init_value\": 4,\r\n },\r\n \"max_depth\": {\r\n \"domain\": tune.choice([0, 6, 12]),\r\n \"init_value\": 0,\r\n },\r\n \"min_child_weight\": {\r\n \"domain\": tune.loguniform(lower=0.001, upper=128),\r\n \"init_value\": 1.0,\r\n },\r\n \"learning_rate\": {\r\n \"domain\": tune.loguniform(lower=1 / 1024, upper=1.0),\r\n \"init_value\": 0.1,\r\n },\r\n \"subsample\": {\r\n \"domain\": tune.uniform(lower=0.1, upper=1.0),\r\n \"init_value\": 1.0,\r\n },\r\n \"colsample_bylevel\": {\r\n \"domain\": tune.uniform(lower=0.01, upper=1.0),\r\n \"init_value\": 1.0,\r\n },\r\n \"colsample_bytree\": {\r\n \"domain\": tune.uniform(lower=0.01, upper=1.0),\r\n \"init_value\": 1.0,\r\n },\r\n \"reg_alpha\": {\r\n \"domain\": tune.loguniform(lower=1 / 1024, upper=1024),\r\n \"init_value\": 1 / 1024,\r\n },\r\n \"reg_lambda\": {\r\n \"domain\": tune.loguniform(lower=1 / 1024, upper=1024),\r\n \"init_value\": 1.0,\r\n },\r\n }\r\n\r\n @classmethod\r\n def size(cls, config):\r\n return LGBMEstimator.size(config)\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 1.6\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n max_depth = params[\"max_depth\"] = params.get(\"max_depth\", 0)\r\n if max_depth == 0:\r\n params[\"grow_policy\"] = params.get(\"grow_policy\", \"lossguide\")\r\n params[\"tree_method\"] = params.get(\"tree_method\", \"hist\")\r\n # params[\"booster\"] = params.get(\"booster\", \"gbtree\")\r\n params[\"use_label_encoder\"] = params.get(\"use_label_encoder\", False)\r\n if \"n_jobs\" in config:\r\n params[\"nthread\"] = params.pop(\"n_jobs\")\r\n return params\r\n\r\n def __init__(\r\n self,\r\n task=\"regression\",\r\n **config,\r\n ):\r\n super().__init__(task, **config)\r\n self.params[\"verbosity\"] = 0\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n import xgboost as xgb\r\n\r\n start_time = time.time()\r\n deadline = start_time + budget if budget else np.inf\r\n if issparse(X_train):\r\n if xgb.__version__ < \"1.6.0\":\r\n # \"auto\" fails for sparse input since xgboost 1.6.0\r\n self.params[\"tree_method\"] = \"auto\"\r\n else:\r\n X_train = self._preprocess(X_train)\r\n if \"sample_weight\" in kwargs:\r\n dtrain = xgb.DMatrix(X_train, label=y_train, weight=kwargs[\"sample_weight\"])\r\n else:\r\n dtrain = xgb.DMatrix(X_train, label=y_train)\r\n\r\n objective = self.params.get(\"objective\")\r\n if isinstance(objective, str):\r\n obj = None\r\n else:\r\n obj = objective\r\n if \"objective\" in self.params:\r\n del self.params[\"objective\"]\r\n _n_estimators = self.params.pop(\"n_estimators\")\r\n callbacks = XGBoostEstimator._callbacks(start_time, deadline)\r\n if callbacks:\r\n self._model = xgb.train(\r\n self.params,\r\n dtrain,\r\n _n_estimators,\r\n obj=obj,\r\n callbacks=callbacks,\r\n )\r\n self.params[\"n_estimators\"] = self._model.best_iteration + 1\r\n else:\r\n self._model = xgb.train(self.params, dtrain, _n_estimators, obj=obj)\r\n self.params[\"n_estimators\"] = _n_estimators\r\n self.params[\"objective\"] = objective\r\n del dtrain\r\n train_time = time.time() - start_time\r\n return train_time\r\n\r\n def predict(self, X, **kwargs):\r\n import xgboost as xgb\r\n\r\n if not issparse(X):\r\n X = self._preprocess(X)\r\n dtest = xgb.DMatrix(X)\r\n return super().predict(dtest)\r\n\r\n @classmethod\r\n def _callbacks(cls, start_time, deadline):\r\n try:\r\n from xgboost.callback import TrainingCallback\r\n except ImportError: # for xgboost<1.3\r\n return None\r\n\r\n class ResourceLimit(TrainingCallback):\r\n def after_iteration(self, model, epoch, evals_log) -> bool:\r\n now = time.time()\r\n if epoch == 0:\r\n self._time_per_iter = now - start_time\r\n if now + self._time_per_iter > deadline:\r\n return True\r\n if psutil is not None:\r\n mem = psutil.virtual_memory()\r\n if mem.available / mem.total < FREE_MEM_RATIO:\r\n return True\r\n return False\r\n\r\n return [ResourceLimit()]\r\n\r\n\r\nclass XGBoostSklearnEstimator(SKLearnEstimator, LGBMEstimator):\r\n \"\"\"The class for tuning XGBoost with unlimited depth, using sklearn API.\"\"\"\r\n\r\n DEFAULT_ITER = 10\r\n\r\n @classmethod\r\n def search_space(cls, data_size, **params):\r\n space = XGBoostEstimator.search_space(data_size)\r\n space.pop(\"max_depth\")\r\n return space\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return XGBoostEstimator.cost_relative2lgbm()\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n max_depth = params[\"max_depth\"] = params.get(\"max_depth\", 0)\r\n if max_depth == 0:\r\n params[\"grow_policy\"] = params.get(\"grow_policy\", \"lossguide\")\r\n params[\"tree_method\"] = params.get(\"tree_method\", \"hist\")\r\n params[\"use_label_encoder\"] = params.get(\"use_label_encoder\", False)\r\n return params\r\n\r\n def __init__(\r\n self,\r\n task=\"binary\",\r\n **config,\r\n ):\r\n super().__init__(task, **config)\r\n del self.params[\"verbose\"]\r\n self.params[\"verbosity\"] = 0\r\n import xgboost as xgb\r\n\r\n self.estimator_class = xgb.XGBRegressor\r\n if \"rank\" == task:\r\n self.estimator_class = xgb.XGBRanker\r\n elif task in CLASSIFICATION:\r\n self.estimator_class = xgb.XGBClassifier\r\n self._xgb_version = xgb.__version__\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n if issparse(X_train) and self._xgb_version < \"1.6.0\":\r\n # \"auto\" fails for sparse input since xgboost 1.6.0\r\n self.params[\"tree_method\"] = \"auto\"\r\n if kwargs.get(\"gpu_per_trial\"):\r\n self.params[\"tree_method\"] = \"gpu_hist\"\r\n kwargs.pop(\"gpu_per_trial\")\r\n return super().fit(X_train, y_train, budget, **kwargs)\r\n\r\n def _callbacks(self, start_time, deadline) -> List[Callable]:\r\n return XGBoostEstimator._callbacks(start_time, deadline)\r\n\r\n\r\nclass XGBoostLimitDepthEstimator(XGBoostSklearnEstimator):\r\n \"\"\"The class for tuning XGBoost with limited depth, using sklearn API.\"\"\"\r\n\r\n @classmethod\r\n def search_space(cls, data_size, **params):\r\n space = XGBoostEstimator.search_space(data_size)\r\n space.pop(\"max_leaves\")\r\n upper = max(6, int(np.log2(data_size[0])))\r\n space[\"max_depth\"] = {\r\n \"domain\": tune.randint(lower=1, upper=min(upper, 16)),\r\n \"init_value\": 6,\r\n \"low_cost_init_value\": 1,\r\n }\r\n space[\"learning_rate\"][\"init_value\"] = 0.3\r\n space[\"n_estimators\"][\"init_value\"] = 10\r\n return space\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 64\r\n\r\n\r\nclass RandomForestEstimator(SKLearnEstimator, LGBMEstimator):\r\n \"\"\"The class for tuning Random Forest.\"\"\"\r\n\r\n HAS_CALLBACK = False\r\n nrows = 101\r\n\r\n @classmethod\r\n def search_space(cls, data_size, task, **params):\r\n RandomForestEstimator.nrows = int(data_size[0])\r\n upper = min(2048, RandomForestEstimator.nrows)\r\n init = 1 / np.sqrt(data_size[1]) if task in CLASSIFICATION else 1\r\n lower = min(0.1, init)\r\n space = {\r\n \"n_estimators\": {\r\n \"domain\": tune.lograndint(lower=4, upper=max(5, upper)),\r\n \"init_value\": 4,\r\n \"low_cost_init_value\": 4,\r\n },\r\n \"max_features\": {\r\n \"domain\": tune.loguniform(lower=lower, upper=1.0),\r\n \"init_value\": init,\r\n },\r\n \"max_leaves\": {\r\n \"domain\": tune.lograndint(\r\n lower=4,\r\n upper=max(5, min(32768, RandomForestEstimator.nrows >> 1)), #\r\n ),\r\n \"init_value\": 4,\r\n \"low_cost_init_value\": 4,\r\n },\r\n }\r\n if task in CLASSIFICATION:\r\n space[\"criterion\"] = {\r\n \"domain\": tune.choice([\"gini\", \"entropy\"]),\r\n # \"init_value\": \"gini\",\r\n }\r\n return space\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 2\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n if \"max_leaves\" in params:\r\n params[\"max_leaf_nodes\"] = params.get(\r\n \"max_leaf_nodes\", params.pop(\"max_leaves\")\r\n )\r\n if self._task not in CLASSIFICATION and \"criterion\" in config:\r\n params.pop(\"criterion\")\r\n return params\r\n\r\n def __init__(\r\n self,\r\n task=\"binary\",\r\n **params,\r\n ):\r\n super().__init__(task, **params)\r\n self.params[\"verbose\"] = 0\r\n self.estimator_class = RandomForestRegressor\r\n if task in CLASSIFICATION:\r\n self.estimator_class = RandomForestClassifier\r\n\r\n\r\nclass ExtraTreesEstimator(RandomForestEstimator):\r\n \"\"\"The class for tuning Extra Trees.\"\"\"\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 1.9\r\n\r\n def __init__(self, task=\"binary\", **params):\r\n super().__init__(task, **params)\r\n if \"regression\" in task:\r\n self.estimator_class = ExtraTreesRegressor\r\n else:\r\n self.estimator_class = ExtraTreesClassifier\r\n\r\n\r\nclass LRL1Classifier(SKLearnEstimator):\r\n \"\"\"The class for tuning Logistic Regression with L1 regularization.\"\"\"\r\n\r\n @classmethod\r\n def search_space(cls, **params):\r\n return {\r\n \"C\": {\r\n \"domain\": tune.loguniform(lower=0.03125, upper=32768.0),\r\n \"init_value\": 1.0,\r\n },\r\n }\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 160\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n params[\"tol\"] = params.get(\"tol\", 0.0001)\r\n params[\"solver\"] = params.get(\"solver\", \"saga\")\r\n params[\"penalty\"] = params.get(\"penalty\", \"l1\")\r\n return params\r\n\r\n def __init__(self, task=\"binary\", **config):\r\n super().__init__(task, **config)\r\n assert task in CLASSIFICATION, \"LogisticRegression for classification task only\"\r\n self.estimator_class = LogisticRegression\r\n\r\n\r\nclass LRL2Classifier(SKLearnEstimator):\r\n \"\"\"The class for tuning Logistic Regression with L2 regularization.\"\"\"\r\n\r\n limit_resource = True\r\n\r\n @classmethod\r\n def search_space(cls, **params):\r\n return LRL1Classifier.search_space(**params)\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 25\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n params[\"tol\"] = params.get(\"tol\", 0.0001)\r\n params[\"solver\"] = params.get(\"solver\", \"lbfgs\")\r\n params[\"penalty\"] = params.get(\"penalty\", \"l2\")\r\n return params\r\n\r\n def __init__(self, task=\"binary\", **config):\r\n super().__init__(task, **config)\r\n assert task in CLASSIFICATION, \"LogisticRegression for classification task only\"\r\n self.estimator_class = LogisticRegression\r\n\r\n\r\nclass CatBoostEstimator(BaseEstimator):\r\n \"\"\"The class for tuning CatBoost.\"\"\"\r\n\r\n ITER_HP = \"n_estimators\"\r\n DEFAULT_ITER = 1000\r\n\r\n @classmethod\r\n def search_space(cls, data_size, **params):\r\n upper = max(min(round(1500000 / data_size[0]), 150), 12)\r\n return {\r\n \"early_stopping_rounds\": {\r\n \"domain\": tune.lograndint(lower=10, upper=upper),\r\n \"init_value\": 10,\r\n \"low_cost_init_value\": 10,\r\n },\r\n \"learning_rate\": {\r\n \"domain\": tune.loguniform(lower=0.005, upper=0.2),\r\n \"init_value\": 0.1,\r\n },\r\n \"n_estimators\": {\r\n \"domain\": 8192,\r\n \"init_value\": 8192,\r\n },\r\n }\r\n\r\n @classmethod\r\n def size(cls, config):\r\n n_estimators = config.get(\"n_estimators\", 8192)\r\n max_leaves = 64\r\n return (max_leaves * 3 + (max_leaves - 1) * 4 + 1.0) * n_estimators * 8\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 15\r\n\r\n def _preprocess(self, X):\r\n if isinstance(X, DataFrame):\r\n cat_columns = X.select_dtypes(include=[\"category\"]).columns\r\n if not cat_columns.empty:\r\n X = X.copy()\r\n X[cat_columns] = X[cat_columns].apply(\r\n lambda x: x.cat.rename_categories(\r\n [\r\n str(c) if isinstance(c, float) else c\r\n for c in x.cat.categories\r\n ]\r\n )\r\n )\r\n elif isinstance(X, np.ndarray) and X.dtype.kind not in \"buif\":\r\n # numpy array is not of numeric dtype\r\n X = DataFrame(X)\r\n for col in X.columns:\r\n if isinstance(X[col][0], str):\r\n X[col] = X[col].astype(\"category\").cat.codes\r\n X = X.to_numpy()\r\n return X\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n params[\"n_estimators\"] = params.get(\"n_estimators\", 8192)\r\n if \"n_jobs\" in params:\r\n params[\"thread_count\"] = params.pop(\"n_jobs\")\r\n return params\r\n\r\n def __init__(\r\n self,\r\n task=\"binary\",\r\n **config,\r\n ):\r\n super().__init__(task, **config)\r\n self.params.update(\r\n {\r\n \"verbose\": config.get(\"verbose\", False),\r\n \"random_seed\": config.get(\"random_seed\", 10242048),\r\n }\r\n )\r\n from catboost import CatBoostRegressor\r\n\r\n self.estimator_class = CatBoostRegressor\r\n if task in CLASSIFICATION:\r\n from catboost import CatBoostClassifier\r\n\r\n self.estimator_class = CatBoostClassifier\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n start_time = time.time()\r\n deadline = start_time + budget if budget else np.inf\r\n train_dir = f\"catboost_{str(start_time)}\"\r\n X_train = self._preprocess(X_train)\r\n if isinstance(X_train, DataFrame):\r\n cat_features = list(X_train.select_dtypes(include=\"category\").columns)\r\n else:\r\n cat_features = []\r\n n = max(int(len(y_train) * 0.9), len(y_train) - 1000)\r\n X_tr, y_tr = X_train[:n], y_train[:n]\r\n if \"sample_weight\" in kwargs:\r\n weight = kwargs[\"sample_weight\"]\r\n if weight is not None:\r\n kwargs[\"sample_weight\"] = weight[:n]\r\n else:\r\n weight = None\r\n from catboost import Pool, __version__\r\n\r\n model = self.estimator_class(train_dir=train_dir, **self.params)\r\n if __version__ >= \"0.26\":\r\n model.fit(\r\n X_tr,\r\n y_tr,\r\n cat_features=cat_features,\r\n eval_set=Pool(\r\n data=X_train[n:], label=y_train[n:], cat_features=cat_features\r\n ),\r\n callbacks=CatBoostEstimator._callbacks(start_time, deadline),\r\n **kwargs,\r\n )\r\n else:\r\n model.fit(\r\n X_tr,\r\n y_tr,\r\n cat_features=cat_features,\r\n eval_set=Pool(\r\n data=X_train[n:], label=y_train[n:], cat_features=cat_features\r\n ),\r\n **kwargs,\r\n )\r\n shutil.rmtree(train_dir, ignore_errors=True)\r\n if weight is not None:\r\n kwargs[\"sample_weight\"] = weight\r\n self._model = model\r\n self.params[self.ITER_HP] = self._model.tree_count_\r\n train_time = time.time() - start_time\r\n return train_time\r\n\r\n @classmethod\r\n def _callbacks(cls, start_time, deadline):\r\n class ResourceLimit:\r\n def after_iteration(self, info) -> bool:\r\n now = time.time()\r\n if info.iteration == 1:\r\n self._time_per_iter = now - start_time\r\n if now + self._time_per_iter > deadline:\r\n return False\r\n if psutil is not None:\r\n mem = psutil.virtual_memory()\r\n if mem.available / mem.total < FREE_MEM_RATIO:\r\n return False\r\n return True # can continue\r\n\r\n return [ResourceLimit()]\r\n\r\n\r\nclass KNeighborsEstimator(BaseEstimator):\r\n @classmethod\r\n def search_space(cls, data_size, **params):\r\n upper = min(512, int(data_size[0] / 2))\r\n return {\r\n \"n_neighbors\": {\r\n \"domain\": tune.lograndint(lower=1, upper=max(2, upper)),\r\n \"init_value\": 5,\r\n \"low_cost_init_value\": 1,\r\n },\r\n }\r\n\r\n @classmethod\r\n def cost_relative2lgbm(cls):\r\n return 30\r\n\r\n def config2params(self, config: dict) -> dict:\r\n params = super().config2params(config)\r\n params[\"weights\"] = params.get(\"weights\", \"distance\")\r\n return params\r\n\r\n def __init__(self, task=\"binary\", **config):\r\n super().__init__(task, **config)\r\n if task in CLASSIFICATION:\r\n from sklearn.neighbors import KNeighborsClassifier\r\n\r\n self.estimator_class = KNeighborsClassifier\r\n else:\r\n from sklearn.neighbors import KNeighborsRegressor\r\n\r\n self.estimator_class = KNeighborsRegressor\r\n\r\n def _preprocess(self, X):\r\n if isinstance(X, DataFrame):\r\n cat_columns = X.select_dtypes([\"category\"]).columns\r\n if X.shape[1] == len(cat_columns):\r\n raise ValueError(\"kneighbor requires at least one numeric feature\")\r\n X = X.drop(cat_columns, axis=1)\r\n elif isinstance(X, np.ndarray) and X.dtype.kind not in \"buif\":\r\n # drop categocial columns if any\r\n X = DataFrame(X)\r\n cat_columns = []\r\n for col in X.columns:\r\n if isinstance(X[col][0], str):\r\n cat_columns.append(col)\r\n X = X.drop(cat_columns, axis=1)\r\n X = X.to_numpy()\r\n return X\r\n\r\n\r\nclass Prophet(SKLearnEstimator):\r\n \"\"\"The class for tuning Prophet.\"\"\"\r\n\r\n @classmethod\r\n def search_space(cls, **params):\r\n space = {\r\n \"changepoint_prior_scale\": {\r\n \"domain\": tune.loguniform(lower=0.001, upper=0.05),\r\n \"init_value\": 0.05,\r\n \"low_cost_init_value\": 0.001,\r\n },\r\n \"seasonality_prior_scale\": {\r\n \"domain\": tune.loguniform(lower=0.01, upper=10),\r\n \"init_value\": 10,\r\n },\r\n \"holidays_prior_scale\": {\r\n \"domain\": tune.loguniform(lower=0.01, upper=10),\r\n \"init_value\": 10,\r\n },\r\n \"seasonality_mode\": {\r\n \"domain\": tune.choice([\"additive\", \"multiplicative\"]),\r\n \"init_value\": \"multiplicative\",\r\n },\r\n }\r\n return space\r\n\r\n def __init__(self, task=\"ts_forecast\", n_jobs=1, **params):\r\n super().__init__(task, **params)\r\n\r\n def _join(self, X_train, y_train):\r\n assert TS_TIMESTAMP_COL in X_train, (\r\n \"Dataframe for training ts_forecast model must have column\"\r\n f' \"{TS_TIMESTAMP_COL}\" with the dates in X_train.'\r\n )\r\n y_train = DataFrame(y_train, columns=[TS_VALUE_COL])\r\n train_df = X_train.join(y_train)\r\n return train_df\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n from prophet import Prophet\r\n\r\n current_time = time.time()\r\n train_df = self._join(X_train, y_train)\r\n train_df = self._preprocess(train_df)\r\n cols = list(train_df)\r\n cols.remove(TS_TIMESTAMP_COL)\r\n cols.remove(TS_VALUE_COL)\r\n logging.getLogger(\"prophet\").setLevel(logging.WARNING)\r\n model = Prophet(**self.params)\r\n for regressor in cols:\r\n model.add_regressor(regressor)\r\n with suppress_stdout_stderr():\r\n model.fit(train_df)\r\n train_time = time.time() - current_time\r\n self._model = model\r\n return train_time\r\n\r\n def predict(self, X, **kwargs):\r\n if isinstance(X, int):\r\n raise ValueError(\r\n \"predict() with steps is only supported for arima/sarimax.\"\r\n \" For Prophet, pass a dataframe with the first column containing\"\r\n \" the timestamp values.\"\r\n )\r\n if self._model is not None:\r\n X = self._preprocess(X)\r\n forecast = self._model.predict(X)\r\n return forecast[\"yhat\"]\r\n else:\r\n logger.warning(\r\n \"Estimator is not fit yet. Please run fit() before predict().\"\r\n )\r\n return np.ones(X.shape[0])\r\n\r\n def score(self, X_val: DataFrame, y_val: Series, **kwargs):\r\n from sklearn.metrics import r2_score\r\n from .ml import metric_loss_score\r\n\r\n y_pred = self.predict(X_val)\r\n self._metric = kwargs.get(\"metric\", None)\r\n if self._metric:\r\n return metric_loss_score(self._metric, y_pred, y_val)\r\n else:\r\n return r2_score(y_pred, y_val)\r\n\r\n\r\nclass ARIMA(Prophet):\r\n \"\"\"The class for tuning ARIMA.\"\"\"\r\n\r\n @classmethod\r\n def search_space(cls, **params):\r\n space = {\r\n \"p\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 2,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"d\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 2,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"q\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 1,\r\n \"low_cost_init_value\": 0,\r\n },\r\n }\r\n return space\r\n\r\n def _join(self, X_train, y_train):\r\n train_df = super()._join(X_train, y_train)\r\n train_df.index = to_datetime(train_df[TS_TIMESTAMP_COL])\r\n train_df = train_df.drop(TS_TIMESTAMP_COL, axis=1)\r\n return train_df\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n import warnings\r\n\r\n warnings.filterwarnings(\"ignore\")\r\n from statsmodels.tsa.arima.model import ARIMA as ARIMA_estimator\r\n\r\n current_time = time.time()\r\n train_df = self._join(X_train, y_train)\r\n train_df = self._preprocess(train_df)\r\n regressors = list(train_df)\r\n regressors.remove(TS_VALUE_COL)\r\n if regressors:\r\n model = ARIMA_estimator(\r\n train_df[[TS_VALUE_COL]],\r\n exog=train_df[regressors],\r\n order=(self.params[\"p\"], self.params[\"d\"], self.params[\"q\"]),\r\n enforce_stationarity=False,\r\n enforce_invertibility=False,\r\n )\r\n else:\r\n model = ARIMA_estimator(\r\n train_df,\r\n order=(self.params[\"p\"], self.params[\"d\"], self.params[\"q\"]),\r\n enforce_stationarity=False,\r\n enforce_invertibility=False,\r\n )\r\n with suppress_stdout_stderr():\r\n model = model.fit()\r\n train_time = time.time() - current_time\r\n self._model = model\r\n return train_time\r\n\r\n def predict(self, X, **kwargs):\r\n if self._model is not None:\r\n if isinstance(X, int):\r\n forecast = self._model.forecast(steps=X)\r\n elif isinstance(X, DataFrame):\r\n start = X[TS_TIMESTAMP_COL].iloc[0]\r\n end = X[TS_TIMESTAMP_COL].iloc[-1]\r\n if len(X.columns) > 1:\r\n X = self._preprocess(X.drop(columns=TS_TIMESTAMP_COL))\r\n regressors = list(X)\r\n forecast = self._model.predict(\r\n start=start, end=end, exog=X[regressors]\r\n )\r\n else:\r\n forecast = self._model.predict(start=start, end=end)\r\n else:\r\n raise ValueError(\r\n \"X needs to be either a pandas Dataframe with dates as the first column\"\r\n \" or an int number of periods for predict().\"\r\n )\r\n return forecast\r\n else:\r\n return np.ones(X if isinstance(X, int) else X.shape[0])\r\n\r\n\r\nclass SARIMAX(ARIMA):\r\n \"\"\"The class for tuning SARIMA.\"\"\"\r\n\r\n @classmethod\r\n def search_space(cls, **params):\r\n space = {\r\n \"p\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 2,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"d\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 2,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"q\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 1,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"P\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 1,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"D\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 1,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"Q\": {\r\n \"domain\": tune.qrandint(lower=0, upper=10, q=1),\r\n \"init_value\": 1,\r\n \"low_cost_init_value\": 0,\r\n },\r\n \"s\": {\r\n \"domain\": tune.choice([1, 4, 6, 12]),\r\n \"init_value\": 12,\r\n },\r\n }\r\n return space\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n import warnings\r\n\r\n warnings.filterwarnings(\"ignore\")\r\n from statsmodels.tsa.statespace.sarimax import SARIMAX as SARIMAX_estimator\r\n\r\n current_time = time.time()\r\n train_df = self._join(X_train, y_train)\r\n train_df = self._preprocess(train_df)\r\n regressors = list(train_df)\r\n regressors.remove(TS_VALUE_COL)\r\n if regressors:\r\n model = SARIMAX_estimator(\r\n train_df[[TS_VALUE_COL]],\r\n exog=train_df[regressors],\r\n order=(self.params[\"p\"], self.params[\"d\"], self.params[\"q\"]),\r\n seasonality_order=(\r\n self.params[\"P\"],\r\n self.params[\"D\"],\r\n self.params[\"Q\"],\r\n self.params[\"s\"],\r\n ),\r\n enforce_stationarity=False,\r\n enforce_invertibility=False,\r\n )\r\n else:\r\n model = SARIMAX_estimator(\r\n train_df,\r\n order=(self.params[\"p\"], self.params[\"d\"], self.params[\"q\"]),\r\n seasonality_order=(\r\n self.params[\"P\"],\r\n self.params[\"D\"],\r\n self.params[\"Q\"],\r\n self.params[\"s\"],\r\n ),\r\n enforce_stationarity=False,\r\n enforce_invertibility=False,\r\n )\r\n with suppress_stdout_stderr():\r\n model = model.fit()\r\n train_time = time.time() - current_time\r\n self._model = model\r\n return train_time\r\n\r\n\r\nclass TS_SKLearn(SKLearnEstimator):\r\n \"\"\"The class for tuning SKLearn Regressors for time-series forecasting, using hcrystalball\"\"\"\r\n\r\n base_class = SKLearnEstimator\r\n\r\n @classmethod\r\n def search_space(cls, data_size, pred_horizon, **params):\r\n space = cls.base_class.search_space(data_size, **params)\r\n space.update(\r\n {\r\n \"optimize_for_horizon\": {\r\n \"domain\": tune.choice([True, False]),\r\n \"init_value\": False,\r\n \"low_cost_init_value\": False,\r\n },\r\n \"lags\": {\r\n \"domain\": tune.randint(\r\n lower=1, upper=max(2, int(np.sqrt(data_size[0])))\r\n ),\r\n \"init_value\": 3,\r\n },\r\n }\r\n )\r\n return space\r\n\r\n def __init__(self, task=\"ts_forecast\", **params):\r\n super().__init__(task, **params)\r\n self.hcrystaball_model = None\r\n self.ts_task = (\r\n \"regression\" if task in TS_FORECASTREGRESSION else \"classification\"\r\n )\r\n\r\n def transform_X(self, X):\r\n cols = list(X)\r\n if len(cols) == 1:\r\n ds_col = cols[0]\r\n X = DataFrame(index=X[ds_col])\r\n elif len(cols) > 1:\r\n ds_col = cols[0]\r\n exog_cols = cols[1:]\r\n X = X[exog_cols].set_index(X[ds_col])\r\n return X\r\n\r\n def _fit(self, X_train, y_train, budget=None, **kwargs):\r\n from hcrystalball.wrappers import get_sklearn_wrapper\r\n\r\n X_train = self.transform_X(X_train)\r\n X_train = self._preprocess(X_train)\r\n params = self.params.copy()\r\n lags = params.pop(\"lags\")\r\n optimize_for_horizon = params.pop(\"optimize_for_horizon\")\r\n estimator = self.base_class(task=self.ts_task, **params)\r\n self.hcrystaball_model = get_sklearn_wrapper(estimator.estimator_class)\r\n self.hcrystaball_model.lags = int(lags)\r\n self.hcrystaball_model.fit(X_train, y_train)\r\n if optimize_for_horizon:\r\n # Direct Multi-step Forecast Strategy - fit a seperate model for each horizon\r\n model_list = []\r\n for i in range(1, kwargs[\"period\"] + 1):\r\n (\r\n X_fit,\r\n y_fit,\r\n ) = self.hcrystaball_model._transform_data_to_tsmodel_input_format(\r\n X_train, y_train, i\r\n )\r\n self.hcrystaball_model.model.set_params(**estimator.params)\r\n model = self.hcrystaball_model.model.fit(X_fit, y_fit)\r\n model_list.append(model)\r\n self._model = model_list\r\n else:\r\n (\r\n X_fit,\r\n y_fit,\r\n ) = self.hcrystaball_model._transform_data_to_tsmodel_input_format(\r\n X_train, y_train, kwargs[\"period\"]\r\n )\r\n self.hcrystaball_model.model.set_params(**estimator.params)\r\n model = self.hcrystaball_model.model.fit(X_fit, y_fit)\r\n self._model = model\r\n\r\n def fit(self, X_train, y_train, budget=None, **kwargs):\r\n current_time = time.time()\r\n self._fit(X_train, y_train, budget=budget, **kwargs)\r\n train_time = time.time() - current_time\r\n return train_time\r\n\r\n def predict(self, X, **kwargs):\r\n if self._model is not None:\r\n X = self.transform_X(X)\r\n X = self._preprocess(X)\r\n if isinstance(self._model, list):\r\n assert len(self._model) == len(\r\n X\r\n ), \"Model is optimized for horizon, length of X must be equal to `period`.\"\r\n preds = []\r\n for i in range(1, len(self._model) + 1):\r\n (\r\n X_pred,\r\n _,\r\n ) = self.hcrystaball_model._transform_data_to_tsmodel_input_format(\r\n X.iloc[:i, :]\r\n )\r\n preds.append(self._model[i - 1].predict(X_pred)[-1])\r\n forecast = DataFrame(\r\n data=np.asarray(preds).reshape(-1, 1),\r\n columns=[self.hcrystaball_model.name],\r\n index=X.index,\r\n )\r\n else:\r\n (\r\n X_pred,\r\n _,\r\n ) = self.hcrystaball_model._transform_data_to_tsmodel_input_format(X)\r\n forecast = self._model.predict(X_pred)\r\n return forecast\r\n else:\r\n logger.warning(\r\n \"Estimator is not fit yet. Please run fit() before predict().\"\r\n )\r\n return np.ones(X.shape[0])\r\n\r\n\r\nclass LGBM_TS(TS_SKLearn):\r\n \"\"\"The class for tuning LGBM Regressor for time-series forecasting\"\"\"\r\n\r\n base_class = LGBMEstimator\r\n\r\n\r\nclass XGBoost_TS(TS_SKLearn):\r\n \"\"\"The class for tuning XGBoost Regressor for time-series forecasting\"\"\"\r\n\r\n base_class = XGBoostSklearnEstimator\r\n\r\n\r\n# catboost regressor is invalid because it has a `name` parameter, making it incompatible with hcrystalball\r\n# class CatBoost_TS_Regressor(TS_Regressor):\r\n# base_class = CatBoostEstimator\r\n\r\n\r\nclass RF_TS(TS_SKLearn):\r\n \"\"\"The class for tuning Random Forest Regressor for time-series forecasting\"\"\"\r\n\r\n base_class = RandomForestEstimator\r\n\r\n\r\nclass ExtraTrees_TS(TS_SKLearn):\r\n \"\"\"The class for tuning Extra Trees Regressor for time-series forecasting\"\"\"\r\n\r\n base_class = ExtraTreesEstimator\r\n\r\n\r\nclass XGBoostLimitDepth_TS(TS_SKLearn):\r\n \"\"\"The class for tuning XGBoost Regressor with unlimited depth for time-series forecasting\"\"\"\r\n\r\n base_class = XGBoostLimitDepthEstimator\r\n\r\n\r\nclass suppress_stdout_stderr(object):\r\n def __init__(self):\r\n # Open a pair of null files\r\n self.null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]\r\n # Save the actual stdout (1) and stderr (2) file descriptors.\r\n self.save_fds = (os.dup(1), os.dup(2))\r\n\r\n def __enter__(self):\r\n # Assign the null pointers to stdout and stderr.\r\n os.dup2(self.null_fds[0], 1)\r\n os.dup2(self.null_fds[1], 2)\r\n\r\n def __exit__(self, *_):\r\n # Re-assign the real stdout/stderr back to (1) and (2)\r\n os.dup2(self.save_fds[0], 1)\r\n os.dup2(self.save_fds[1], 2)\r\n # Close the null files\r\n os.close(self.null_fds[0])\r\n os.close(self.null_fds[1])\r\n" ]
[ [ "pandas.to_datetime", "sklearn.metrics.r2_score", "scipy.sparse.issparse", "numpy.log2", "numpy.sqrt", "sklearn.dummy.DummyClassifier", "numpy.asarray", "numpy.issubdtype", "numpy.squeeze", "sklearn.dummy.DummyRegressor", "pandas.DataFrame", "numpy.ones", "numpy.argmax", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
Raniac/NEURO-LEARN
[ "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a", "3c3acc55de8ba741e673063378e6cbaf10b64c7a" ]
[ "env/lib/python3.6/site-packages/nibabel/tests/test_image_load_save.py", "env/share/doc/dipy/examples/quick_start.py", "env/lib/python3.6/site-packages/dipy/reconst/tests/test_interpolate.py", "env/lib/python3.6/site-packages/dipy/tracking/tests/test_life.py", "env/lib/python3.6/site-packages/nibabel/tests/test_quaternions.py", "env/lib/python3.6/site-packages/dipy/denoise/tests/test_nlmeans.py", "env/lib/python3.6/site-packages/dipy/direction/peaks.py", "env/lib/python3.6/site-packages/dipy/__init__.py", "env/lib/python3.6/site-packages/dipy/io/tests/test_io_gradients.py", "env/lib/python3.6/site-packages/dipy/reconst/csdeconv.py" ]
[ "# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the NiBabel package for the\n# copyright and license terms.\n#\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n''' Tests for loader function '''\nfrom __future__ import division, print_function, absolute_import\nfrom io import BytesIO\n\nimport shutil\nfrom os.path import dirname, join as pjoin\nfrom tempfile import mkdtemp\n\nimport numpy as np\n\nfrom .. import analyze as ana\nfrom .. import spm99analyze as spm99\nfrom .. import spm2analyze as spm2\nfrom .. import nifti1 as ni1\nfrom .. import loadsave as nils\nfrom .. import (Nifti1Image, Nifti1Header, Nifti1Pair, Nifti2Image, Nifti2Pair,\n Minc1Image, Minc2Image, Spm2AnalyzeImage, Spm99AnalyzeImage,\n AnalyzeImage, MGHImage, all_image_classes)\nfrom ..tmpdirs import InTemporaryDirectory\nfrom ..volumeutils import native_code, swapped_code\nfrom ..optpkg import optional_package\nfrom ..spatialimages import SpatialImage\n\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\nfrom nose.tools import assert_true, assert_equal, assert_raises\n\n_, have_scipy, _ = optional_package('scipy') # No scipy=>no SPM-format writing\nDATA_PATH = pjoin(dirname(__file__), 'data')\nMGH_DATA_PATH = pjoin(dirname(__file__), '..', 'freesurfer', 'tests', 'data')\n\n\ndef round_trip(img):\n # round trip a nifti single\n sio = BytesIO()\n img.file_map['image'].fileobj = sio\n img.to_file_map()\n img2 = Nifti1Image.from_file_map(img.file_map)\n return img2\n\n\ndef test_conversion_spatialimages():\n shape = (2, 4, 6)\n affine = np.diag([1, 2, 3, 1])\n klasses = [klass for klass in all_image_classes\n if klass.rw and issubclass(klass, SpatialImage)]\n for npt in np.float32, np.int16:\n data = np.arange(np.prod(shape), dtype=npt).reshape(shape)\n for r_class in klasses:\n if not r_class.makeable:\n continue\n img = r_class(data, affine)\n img.set_data_dtype(npt)\n for w_class in klasses:\n if not w_class.makeable:\n continue\n img2 = w_class.from_image(img)\n assert_array_equal(img2.get_data(), data)\n assert_array_equal(img2.affine, affine)\n\n\ndef test_save_load_endian():\n shape = (2, 4, 6)\n affine = np.diag([1, 2, 3, 1])\n data = np.arange(np.prod(shape), dtype='f4').reshape(shape)\n # Native endian image\n img = Nifti1Image(data, affine)\n assert_equal(img.header.endianness, native_code)\n img2 = round_trip(img)\n assert_equal(img2.header.endianness, native_code)\n assert_array_equal(img2.get_data(), data)\n # byte swapped endian image\n bs_hdr = img.header.as_byteswapped()\n bs_img = Nifti1Image(data, affine, bs_hdr)\n assert_equal(bs_img.header.endianness, swapped_code)\n # of course the data is the same because it's not written to disk\n assert_array_equal(bs_img.get_data(), data)\n # Check converting to another image\n cbs_img = AnalyzeImage.from_image(bs_img)\n # this will make the header native by doing the header conversion\n cbs_hdr = cbs_img.header\n assert_equal(cbs_hdr.endianness, native_code)\n # and the byte order follows it back into another image\n cbs_img2 = Nifti1Image.from_image(cbs_img)\n cbs_hdr2 = cbs_img2.header\n assert_equal(cbs_hdr2.endianness, native_code)\n # Try byteswapped round trip\n bs_img2 = round_trip(bs_img)\n bs_data2 = bs_img2.get_data()\n # now the data dtype was swapped endian, so the read data is too\n assert_equal(bs_data2.dtype.byteorder, swapped_code)\n assert_equal(bs_img2.header.endianness, swapped_code)\n assert_array_equal(bs_data2, data)\n # Now mix up byteswapped data and non-byteswapped header\n mixed_img = Nifti1Image(bs_data2, affine)\n assert_equal(mixed_img.header.endianness, native_code)\n m_img2 = round_trip(mixed_img)\n assert_equal(m_img2.header.endianness, native_code)\n assert_array_equal(m_img2.get_data(), data)\n\n\ndef test_save_load():\n shape = (2, 4, 6)\n npt = np.float32\n data = np.arange(np.prod(shape), dtype=npt).reshape(shape)\n affine = np.diag([1, 2, 3, 1])\n affine[:3, 3] = [3, 2, 1]\n img = ni1.Nifti1Image(data, affine)\n img.set_data_dtype(npt)\n with InTemporaryDirectory() as pth:\n nifn = 'an_image.nii'\n sifn = 'another_image.img'\n ni1.save(img, nifn)\n re_img = nils.load(nifn)\n assert_true(isinstance(re_img, ni1.Nifti1Image))\n assert_array_equal(re_img.get_data(), data)\n assert_array_equal(re_img.affine, affine)\n # These and subsequent del statements are to prevent confusing\n # windows errors when trying to open files or delete the\n # temporary directory.\n del re_img\n if have_scipy: # skip we we cannot read .mat files\n spm2.save(img, sifn)\n re_img2 = nils.load(sifn)\n assert_true(isinstance(re_img2, spm2.Spm2AnalyzeImage))\n assert_array_equal(re_img2.get_data(), data)\n assert_array_equal(re_img2.affine, affine)\n del re_img2\n spm99.save(img, sifn)\n re_img3 = nils.load(sifn)\n assert_true(isinstance(re_img3,\n spm99.Spm99AnalyzeImage))\n assert_array_equal(re_img3.get_data(), data)\n assert_array_equal(re_img3.affine, affine)\n ni1.save(re_img3, nifn)\n del re_img3\n re_img = nils.load(nifn)\n assert_true(isinstance(re_img, ni1.Nifti1Image))\n assert_array_equal(re_img.get_data(), data)\n assert_array_equal(re_img.affine, affine)\n del re_img\n\n\ndef test_two_to_one():\n # test going from two to one file in save\n shape = (2, 4, 6)\n npt = np.float32\n data = np.arange(np.prod(shape), dtype=npt).reshape(shape)\n affine = np.diag([1, 2, 3, 1])\n affine[:3, 3] = [3, 2, 1]\n # single file format\n img = ni1.Nifti1Image(data, affine)\n assert_equal(img.header['magic'], b'n+1')\n str_io = BytesIO()\n img.file_map['image'].fileobj = str_io\n # check that the single format vox offset stays at zero\n img.to_file_map()\n assert_equal(img.header['magic'], b'n+1')\n assert_equal(img.header['vox_offset'], 0)\n # make a new pair image, with the single image header\n pimg = ni1.Nifti1Pair(data, affine, img.header)\n isio = BytesIO()\n hsio = BytesIO()\n pimg.file_map['image'].fileobj = isio\n pimg.file_map['header'].fileobj = hsio\n pimg.to_file_map()\n # the offset stays at zero (but is 352 on disk)\n assert_equal(pimg.header['magic'], b'ni1')\n assert_equal(pimg.header['vox_offset'], 0)\n assert_array_equal(pimg.get_data(), data)\n # same for from_image, going from single image to pair format\n ana_img = ana.AnalyzeImage.from_image(img)\n assert_equal(ana_img.header['vox_offset'], 0)\n # back to the single image, save it again to a stringio\n str_io = BytesIO()\n img.file_map['image'].fileobj = str_io\n img.to_file_map()\n assert_equal(img.header['vox_offset'], 0)\n aimg = ana.AnalyzeImage.from_image(img)\n assert_equal(aimg.header['vox_offset'], 0)\n aimg = spm99.Spm99AnalyzeImage.from_image(img)\n assert_equal(aimg.header['vox_offset'], 0)\n aimg = spm2.Spm2AnalyzeImage.from_image(img)\n assert_equal(aimg.header['vox_offset'], 0)\n nfimg = ni1.Nifti1Pair.from_image(img)\n assert_equal(nfimg.header['vox_offset'], 0)\n # now set the vox offset directly\n hdr = nfimg.header\n hdr['vox_offset'] = 16\n assert_equal(nfimg.header['vox_offset'], 16)\n # check it gets properly set by the nifti single image\n nfimg = ni1.Nifti1Image.from_image(img)\n assert_equal(nfimg.header['vox_offset'], 0)\n\n\ndef test_negative_load_save():\n shape = (1, 2, 5)\n data = np.arange(10).reshape(shape) - 10.0\n affine = np.eye(4)\n hdr = ni1.Nifti1Header()\n hdr.set_data_dtype(np.int16)\n img = Nifti1Image(data, affine, hdr)\n str_io = BytesIO()\n img.file_map['image'].fileobj = str_io\n img.to_file_map()\n str_io.seek(0)\n re_img = Nifti1Image.from_file_map(img.file_map)\n assert_array_almost_equal(re_img.get_data(), data, 4)\n\n\ndef test_filename_save():\n # This is to test the logic in the load and save routines, relating\n # extensions to filetypes\n # Tuples of class, ext, loadedclass\n inklass_ext_loadklasses = (\n (Nifti1Image, '.nii', Nifti1Image),\n (Nifti2Image, '.nii', Nifti2Image),\n (Nifti1Pair, '.nii', Nifti1Image),\n (Nifti2Pair, '.nii', Nifti2Image),\n (Nifti1Image, '.img', Nifti1Pair),\n (Nifti2Image, '.img', Nifti2Pair),\n (Nifti1Pair, '.img', Nifti1Pair),\n (Nifti2Pair, '.img', Nifti2Pair),\n (Nifti1Image, '.hdr', Nifti1Pair),\n (Nifti2Image, '.hdr', Nifti2Pair),\n (Nifti1Pair, '.hdr', Nifti1Pair),\n (Nifti2Pair, '.hdr', Nifti2Pair),\n (Minc1Image, '.nii', Nifti1Image),\n (Minc1Image, '.img', Nifti1Pair),\n (Spm2AnalyzeImage, '.nii', Nifti1Image),\n (Spm2AnalyzeImage, '.img', Spm2AnalyzeImage),\n (Spm99AnalyzeImage, '.nii', Nifti1Image),\n (Spm99AnalyzeImage, '.img', Spm2AnalyzeImage),\n (AnalyzeImage, '.nii', Nifti1Image),\n (AnalyzeImage, '.img', Spm2AnalyzeImage),\n )\n shape = (2, 4, 6)\n affine = np.diag([1, 2, 3, 1])\n data = np.arange(np.prod(shape), dtype='f4').reshape(shape)\n for inklass, out_ext, loadklass in inklass_ext_loadklasses:\n if not have_scipy:\n # We can't load a SPM analyze type without scipy. These types have\n # a 'mat' file (the type we can't load)\n if ('mat', '.mat') in loadklass.files_types:\n continue\n img = inklass(data, affine)\n try:\n pth = mkdtemp()\n fname = pjoin(pth, 'image' + out_ext)\n nils.save(img, fname)\n rt_img = nils.load(fname)\n assert_array_almost_equal(rt_img.get_data(), data)\n assert_true(type(rt_img) is loadklass)\n # delete image to allow file close. Otherwise windows\n # raises an error when trying to delete the directory\n del rt_img\n finally:\n shutil.rmtree(pth)\n\n\ndef test_analyze_detection():\n # Test detection of Analyze, Nifti1 and Nifti2\n # Algorithm is as described in loadsave:which_analyze_type\n def wat(hdr):\n return nils.which_analyze_type(hdr.binaryblock)\n n1_hdr = Nifti1Header(b'\\0' * 348, check=False)\n assert_equal(wat(n1_hdr), None)\n n1_hdr['sizeof_hdr'] = 540\n assert_equal(wat(n1_hdr), 'nifti2')\n assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti2')\n n1_hdr['sizeof_hdr'] = 348\n assert_equal(wat(n1_hdr), 'analyze')\n assert_equal(wat(n1_hdr.as_byteswapped()), 'analyze')\n n1_hdr['magic'] = b'n+1'\n assert_equal(wat(n1_hdr), 'nifti1')\n assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti1')\n n1_hdr['magic'] = b'ni1'\n assert_equal(wat(n1_hdr), 'nifti1')\n assert_equal(wat(n1_hdr.as_byteswapped()), 'nifti1')\n # Doesn't matter what magic is if it's not a nifti1 magic\n n1_hdr['magic'] = b'ni2'\n assert_equal(wat(n1_hdr), 'analyze')\n n1_hdr['sizeof_hdr'] = 0\n n1_hdr['magic'] = b''\n assert_equal(wat(n1_hdr), None)\n n1_hdr['magic'] = 'n+1'\n assert_equal(wat(n1_hdr), 'nifti1')\n n1_hdr['magic'] = 'ni1'\n assert_equal(wat(n1_hdr), 'nifti1')\n\n\ndef test_guessed_image_type():\n # Test whether we can guess the image type from example files\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'example4d.nii.gz')),\n Nifti1Image)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'nifti1.hdr')),\n Nifti1Pair)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'example_nifti2.nii.gz')),\n Nifti2Image)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'nifti2.hdr')),\n Nifti2Pair)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'tiny.mnc')),\n Minc1Image)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'small.mnc')),\n Minc2Image)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'test.mgz')),\n MGHImage)\n assert_equal(nils.guessed_image_type(\n pjoin(DATA_PATH, 'analyze.hdr')),\n Spm2AnalyzeImage)\n\n\ndef test_fail_save():\n with InTemporaryDirectory():\n dataobj = np.ones((10, 10, 10), dtype=np.float16)\n affine = np.eye(4, dtype=np.float32)\n img = SpatialImage(dataobj, affine)\n # Fails because float16 is not supported.\n with assert_raises(AttributeError):\n nils.save(img, 'foo.nii.gz')\n del img\n", "\"\"\"\n=========================\nGetting started with DIPY\n=========================\n\nIn diffusion MRI (dMRI) usually we use three types of files, a Nifti file with the\ndiffusion weighted data, and two text files one with b-values and\none with the b-vectors.\n\nIn DIPY_ we provide tools to load and process these files and we also provide\naccess to publicly available datasets for those who haven't acquired yet\ntheir own datasets.\n\nWith the following commands we can download a dMRI dataset\n\"\"\"\n\nfrom dipy.data import fetch_sherbrooke_3shell\nfetch_sherbrooke_3shell()\n\n\"\"\"\nBy default these datasets will go in the ``.dipy`` folder inside your home directory.\nHere is how you can access them.\n\"\"\"\n\nfrom os.path import expanduser, join\nhome = expanduser('~')\n\n\"\"\"\n``dname`` holds the directory name where the 3 files are in.\n\"\"\"\n\ndname = join(home, '.dipy', 'sherbrooke_3shell')\n\n\"\"\"\nHere, we show the complete filenames of the 3 files\n\"\"\"\n\nfdwi = join(dname, 'HARDI193.nii.gz')\n\nprint(fdwi)\n\nfbval = join(dname, 'HARDI193.bval')\n\nprint(fbval)\n\nfbvec = join(dname, 'HARDI193.bvec')\n\nprint(fbvec)\n\n\"\"\"\n``/home/username/.dipy/sherbrooke_3shell/HARDI193.nii.gz``\n\n``/home/username/.dipy/sherbrooke_3shell/HARDI193.bval``\n\n``/home/username/.dipy/sherbrooke_3shell/HARDI193.bvec``\n\nNow, that we have their filenames we can start checking what these look like.\n\nLet's start first by loading the dMRI datasets. For this purpose, we\nuse a python library called nibabel_ which enables us to read and write\nneuroimaging-specific file formats.\n\"\"\"\n\nimport nibabel as nib\nimg = nib.load(fdwi)\ndata = img.get_data()\n\n\"\"\"\n``data`` is a 4D array where the first 3 dimensions are the i, j, k voxel\ncoordinates and the last dimension is the number of non-weighted (S0s) and\ndiffusion-weighted volumes.\n\nWe can very easily check the size of ``data`` in the following way:\n\"\"\"\n\nprint(data.shape)\n\n\"\"\"\n``(128, 128, 60, 193)``\n\nWe can also check the dimensions of each voxel in the following way:\n\"\"\"\n\nprint(img.header.get_zooms()[:3])\n\n\"\"\"\n``(2.0, 2.0, 2.0)``\n\nWe can quickly visualize the results using matplotlib_. For example,\nlet's show here the middle axial slices of volume 0 and volume 10.\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\naxial_middle = data.shape[2] // 2\nplt.figure('Showing the datasets')\nplt.subplot(1, 2, 1).set_axis_off()\nplt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')\nplt.subplot(1, 2, 2).set_axis_off()\nplt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')\nplt.show()\nplt.savefig('data.png', bbox_inches='tight')\n\n\"\"\"\n.. figure:: data.png\n :align: center\n\n Showing the middle axial slice without (left) and with (right) diffusion weighting.\n\nThe next step is to load the b-values and b-vectors from the disk using\nthe function ``read_bvals_bvecs``.\n\"\"\"\n\nfrom dipy.io import read_bvals_bvecs\nbvals, bvecs = read_bvals_bvecs(fbval, fbvec)\n\n\"\"\"\nIn DIPY, we use an object called ``GradientTable`` which holds all the\nacquisition specific parameters, e.g. b-values, b-vectors, timings and others.\nTo create this object you can use the function ``gradient_table``.\n\"\"\"\n\nfrom dipy.core.gradients import gradient_table\ngtab = gradient_table(bvals, bvecs)\n\n\"\"\"\nFinally, you can use ``gtab`` (the GradientTable object) to show some information about the\nacquisition parameters\n\"\"\"\n\nprint(gtab.info)\n\n\"\"\"\nB-values shape (193,)\n min 0.000000\n max 3500.000000\nB-vectors shape (193, 3)\n min -0.964050\n max 0.999992\n\nYou can also see the b-values using:\n\"\"\"\n\nprint(gtab.bvals)\n\n\"\"\"\n\n::\n\n [ 0. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000.\n 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000.\n 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000.\n 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000.\n 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000.\n 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000. 1000.\n 1000. 1000. 1000. 1000. 1000. 2000. 2000. 2000. 2000. 2000.\n 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000.\n 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000.\n 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000.\n 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000.\n 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000.\n 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 2000. 3500.\n 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500.\n 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500.\n 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500.\n 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500.\n 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500.\n 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500. 3500.\n 3500. 3500. 3500.]\n\nOr, for example the 10 first b-vectors using:\n\"\"\"\n\nprint(gtab.bvecs[:10, :])\n\n\"\"\"\n\n::\n\n array([[ 0. , 0. , 0. ],\n [ 0.999979 , -0.00504001, -0.00402795],\n [ 0. , 0.999992 , -0.00398794],\n [-0.0257055 , 0.653861 , -0.756178 ],\n [ 0.589518 , -0.769236 , -0.246462 ],\n [-0.235785 , -0.529095 , -0.815147 ],\n [-0.893578 , -0.263559 , -0.363394 ],\n [ 0.79784 , 0.133726 , -0.587851 ],\n [ 0.232937 , 0.931884 , -0.278087 ],\n [ 0.93672 , 0.144139 , -0.31903 ]])\n\n``gtab`` can be used to tell what part of the data is the S0 volumes\n(volumes which correspond to b-values of 0).\n\"\"\"\n\nS0s = data[:, :, :, gtab.b0s_mask]\n\n\"\"\"\nHere, we had only 1 S0 as we can verify by looking at the dimensions of S0s\n\"\"\"\n\nprint(S0s.shape)\n\n\"\"\"\n``(128, 128, 60, 1)``\n\nJust, for fun let's save this in a new Nifti file.\n\"\"\"\n\nnib.save(nib.Nifti1Image(S0s, img.affine), 'HARDI193_S0.nii.gz')\n\n\"\"\"\nNow, that we learned how to load dMRI datasets we can start the analysis.\nSee example :ref:`example_reconst_dti` to learn how to create FA maps.\n\n.. include:: ../links_names.inc\n\n\"\"\"\n", "from __future__ import division, print_function, absolute_import\n\nfrom dipy.utils.six.moves import xrange\n\nfrom dipy.testing import assert_true, assert_false\nfrom numpy.testing import (assert_array_equal, assert_array_almost_equal,\n assert_equal, assert_raises)\n\nimport numpy as np\nfrom dipy.reconst.interpolate import (NearestNeighborInterpolator,\n TriLinearInterpolator,\n OutsideImage)\n\n\ndef test_NearestNeighborInterpolator():\n # Place integers values at the center of every voxel\n l, m, n, o = np.ogrid[0:6.01, 0:6.01, 0:6.01, 0:4]\n data = l + m + n + o\n\n nni = NearestNeighborInterpolator(data, (1, 1, 1))\n a, b, c = np.mgrid[.5:6.5:1.6, .5:6.5:2.7, .5:6.5:3.8]\n for ii in xrange(a.size):\n x = a.flat[ii]\n y = b.flat[ii]\n z = c.flat[ii]\n expected_result = int(x) + int(y) + int(z) + o.ravel()\n assert_array_equal(nni[x, y, z], expected_result)\n ind = np.array([x, y, z])\n assert_array_equal(nni[ind], expected_result)\n assert_raises(OutsideImage, nni.__getitem__, (-.1, 0, 0))\n assert_raises(OutsideImage, nni.__getitem__, (0, 8.2, 0))\n\n\ndef test_TriLinearInterpolator():\n # Place (0, 0, 0) at the bottom left of the image\n l, m, n, o = np.ogrid[.5:6.51, .5:6.51, .5:6.51, 0:4]\n data = l + m + n + o\n data = data.astype(\"float32\")\n\n tli = TriLinearInterpolator(data, (1, 1, 1))\n a, b, c = np.mgrid[.5:6.5:1.6, .5:6.5:2.7, .5:6.5:3.8]\n for ii in xrange(a.size):\n x = a.flat[ii]\n y = b.flat[ii]\n z = c.flat[ii]\n expected_result = x + y + z + o.ravel()\n assert_array_almost_equal(tli[x, y, z], expected_result, decimal=5)\n ind = np.array([x, y, z])\n assert_array_almost_equal(tli[ind], expected_result)\n\n # Index at 0\n expected_value = np.arange(4) + 1.5\n assert_array_almost_equal(tli[0, 0, 0], expected_value)\n # Index at shape\n expected_value = np.arange(4) + (6.5 * 3)\n assert_array_almost_equal(tli[7, 7, 7], expected_value)\n\n assert_raises(OutsideImage, tli.__getitem__, (-.1, 0, 0))\n assert_raises(OutsideImage, tli.__getitem__, (0, 7.01, 0))\n", "import os\nimport os.path as op\n\nimport numpy as np\nimport numpy.testing as npt\nimport numpy.testing.decorators as dec\nimport scipy.sparse as sps\nimport scipy.linalg as la\n\nimport nibabel as nib\n\nimport dipy.tracking.life as life\nimport dipy.tracking.eudx as edx\nimport dipy.core.sphere as dps\nimport dipy.core.gradients as dpg\nimport dipy.data as dpd\nimport dipy.core.optimize as opt\nimport dipy.core.ndindex as nd\nimport dipy.core.gradients as grad\nimport dipy.reconst.dti as dti\nfrom dipy.io.gradients import read_bvals_bvecs\n\nTHIS_DIR = op.dirname(__file__)\n\ndef test_streamline_gradients():\n streamline = [[1, 2, 3], [4, 5, 6], [5, 6, 7], [8, 9, 10]]\n grads = np.array([[3, 3, 3], [2, 2, 2], [2, 2, 2], [3, 3, 3]])\n npt.assert_array_equal(life.streamline_gradients(streamline), grads)\n\n\ndef test_streamline_tensors():\n # Small streamline\n streamline = [[1, 2, 3], [4, 5, 3], [5, 6, 3]]\n # Non-default eigenvalues:\n evals = [0.0012, 0.0006, 0.0004]\n streamline_tensors = life.streamline_tensors(streamline, evals=evals)\n npt.assert_array_almost_equal(streamline_tensors[0],\n np.array([[0.0009, 0.0003, 0.],\n [0.0003, 0.0009, 0.],\n [0., 0., 0.0004]]))\n\n # Get the eigenvalues/eigenvectors:\n eigvals, eigvecs = la.eig(streamline_tensors[0])\n eigvecs = eigvecs[np.argsort(eigvals)[::-1]]\n eigvals = eigvals[np.argsort(eigvals)[::-1]]\n\n npt.assert_array_almost_equal(eigvals,\n np.array([0.0012, 0.0006, 0.0004]))\n\n npt.assert_array_almost_equal(eigvecs[0],\n np.array([0.70710678, -0.70710678, 0.]))\n # Another small streamline\n streamline = [[1, 0, 0], [2, 0, 0], [3, 0, 0]]\n streamline_tensors = life.streamline_tensors(streamline, evals=evals)\n\n for t in streamline_tensors:\n eigvals, eigvecs = la.eig(t)\n eigvecs = eigvecs[np.argsort(eigvals)[::-1]]\n # This one has no rotations - all tensors are simply the canonical:\n npt.assert_almost_equal(np.rad2deg(np.arccos(\n np.dot(eigvecs[0], [1, 0, 0]))), 0)\n npt.assert_almost_equal(np.rad2deg(np.arccos(\n np.dot(eigvecs[1], [0, 1, 0]))), 0)\n npt.assert_almost_equal(np.rad2deg(np.arccos(\n np.dot(eigvecs[2], [0, 0, 1]))), 0)\n\n\ndef test_streamline_signal():\n data_file, bval_file, bvec_file = dpd.get_fnames('small_64D')\n gtab = dpg.gradient_table(bval_file, bvec_file)\n evals = [0.0015, 0.0005, 0.0005]\n streamline1 = [[[1, 2, 3], [4, 5, 3], [5, 6, 3], [6, 7, 3]],\n [[1, 2, 3], [4, 5, 3], [5, 6, 3]]]\n\n [life.streamline_signal(s, gtab, evals) for s in streamline1]\n\n streamline2 = [[[1, 2, 3], [4, 5, 3], [5, 6, 3], [6, 7, 3]]]\n\n [life.streamline_signal(s, gtab, evals) for s in streamline2]\n\n npt.assert_array_equal(streamline2[0], streamline1[0])\n\n\ndef test_voxel2streamline():\n streamline = [[[1.1, 2.4, 2.9], [4, 5, 3], [5, 6, 3], [6, 7, 3]],\n [[1, 2, 3], [4, 5, 3], [5, 6, 3]]]\n affine = np.eye(4)\n v2f, v2fn = life.voxel2streamline(streamline, False, affine)\n npt.assert_equal(v2f, {0: [0, 1], 1: [0, 1], 2: [0, 1], 3: [0]})\n npt.assert_equal(v2fn, {0: {0: [0], 1: [1], 2: [2], 3: [3]},\n 1: {0: [0], 1: [1], 2: [2]}})\n affine = np.array([[0.9, 0, 0, 10],\n [0, 0.9, 0, -100],\n [0, 0, 0.9, 2],\n [0, 0, 0, 1]])\n\n xform_sl = life.transform_streamlines(streamline, np.linalg.inv(affine))\n v2f, v2fn = life.voxel2streamline(xform_sl, False, affine)\n npt.assert_equal(v2f, {0: [0, 1], 1: [0, 1], 2: [0, 1], 3: [0]})\n npt.assert_equal(v2fn, {0: {0: [0], 1: [1], 2: [2], 3: [3]},\n 1: {0: [0], 1: [1], 2: [2]}})\n\n\ndef test_FiberModel_init():\n # Get some small amount of data:\n data_file, bval_file, bvec_file = dpd.get_fnames('small_64D')\n data_ni = nib.load(data_file)\n bvals, bvecs = read_bvals_bvecs(bval_file, bvec_file)\n gtab = dpg.gradient_table(bvals, bvecs)\n FM = life.FiberModel(gtab)\n\n streamline = [[[1, 2, 3], [4, 5, 3], [5, 6, 3], [6, 7, 3]],\n [[1, 2, 3], [4, 5, 3], [5, 6, 3]]]\n\n affine = np.eye(4)\n\n for sphere in [None, False, dpd.get_sphere('symmetric362')]:\n fiber_matrix, vox_coords = FM.setup(streamline, affine, sphere=sphere)\n npt.assert_array_equal(np.array(vox_coords),\n np.array([[1, 2, 3], [4, 5, 3],\n [5, 6, 3], [6, 7, 3]]))\n\n npt.assert_equal(fiber_matrix.shape, (len(vox_coords) * 64,\n len(streamline)))\n\n\ndef test_FiberFit():\n data_file, bval_file, bvec_file = dpd.get_fnames('small_64D')\n data_ni = nib.load(data_file)\n data = data_ni.get_data()\n data_aff = data_ni.affine\n bvals, bvecs = read_bvals_bvecs(bval_file, bvec_file)\n gtab = dpg.gradient_table(bvals, bvecs)\n FM = life.FiberModel(gtab)\n evals = [0.0015, 0.0005, 0.0005]\n\n streamline = [[[1, 2, 3], [4, 5, 3], [5, 6, 3], [6, 7, 3]],\n [[1, 2, 3], [4, 5, 3], [5, 6, 3]]]\n\n fiber_matrix, vox_coords = FM.setup(streamline, None, evals)\n\n w = np.array([0.5, 0.5])\n sig = opt.spdot(fiber_matrix, w) + 1.0 # Add some isotropic stuff\n S0 = data[..., gtab.b0s_mask]\n this_data = np.zeros((10, 10, 10, 64))\n this_data[vox_coords[:, 0], vox_coords[:, 1], vox_coords[:, 2]] =\\\n (sig.reshape((4, 64)) *\n S0[vox_coords[:, 0], vox_coords[:, 1], vox_coords[:, 2]])\n\n # Grab some realistic S0 values:\n this_data = np.concatenate([data[..., gtab.b0s_mask], this_data], -1)\n\n fit = FM.fit(this_data, streamline)\n npt.assert_almost_equal(fit.predict()[1],\n fit.data[1], decimal=-1)\n\n # Predict with an input GradientTable\n npt.assert_almost_equal(fit.predict(gtab)[1],\n fit.data[1], decimal=-1)\n\n npt.assert_almost_equal(\n this_data[vox_coords[:, 0], vox_coords[:, 1], vox_coords[:, 2]],\n fit.data)\n\ndef test_fit_data():\n fdata, fbval, fbvec = dpd.get_fnames('small_25')\n gtab = grad.gradient_table(fbval, fbvec)\n ni_data = nib.load(fdata)\n data = ni_data.get_data()\n dtmodel = dti.TensorModel(gtab)\n dtfit = dtmodel.fit(data)\n sphere = dpd.get_sphere()\n peak_idx = dti.quantize_evecs(dtfit.evecs, sphere.vertices)\n eu = edx.EuDX(dtfit.fa.astype('f8'), peak_idx,\n seeds=list(nd.ndindex(data.shape[:-1])),\n odf_vertices=sphere.vertices, a_low=0)\n tensor_streamlines = [streamline for streamline in eu]\n life_model = life.FiberModel(gtab)\n life_fit = life_model.fit(data, tensor_streamlines)\n model_error = life_fit.predict() - life_fit.data\n model_rmse = np.sqrt(np.mean(model_error ** 2, -1))\n matlab_rmse, matlab_weights = dpd.matlab_life_results()\n # Lower error than the matlab implementation for these data:\n npt.assert_(np.median(model_rmse) < np.median(matlab_rmse))\n # And a moderate correlation with the Matlab implementation weights:\n npt.assert_(np.corrcoef(matlab_weights, life_fit.beta)[0, 1] > 0.6)\n", "# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n#\n# See COPYING file distributed along with the NiBabel package for the\n# copyright and license terms.\n#\n### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##\n''' Test quaternion calculations '''\n\nimport numpy as np\nfrom numpy import pi\n\n# Recent (1.2) versions of numpy have this decorator\ntry:\n from numpy.testing.decorators import slow\nexcept ImportError:\n def slow(t):\n t.slow = True\n return t\n\nfrom nose.tools import assert_raises, assert_true, assert_false, \\\n assert_equal\n\nfrom numpy.testing import assert_array_almost_equal, assert_array_equal\n\nfrom .. import quaternions as nq\nfrom .. import eulerangles as nea\n\n# Example rotations '''\neg_rots = []\nparams = (-pi, pi, pi / 2)\nzs = np.arange(*params)\nys = np.arange(*params)\nxs = np.arange(*params)\nfor z in zs:\n for y in ys:\n for x in xs:\n eg_rots.append(nea.euler2mat(z, y, x))\n# Example quaternions (from rotations)\neg_quats = []\nfor M in eg_rots:\n eg_quats.append(nq.mat2quat(M))\n# M, quaternion pairs\neg_pairs = list(zip(eg_rots, eg_quats))\n\n# Set of arbitrary unit quaternions\nunit_quats = set()\nparams = range(-2, 3)\nfor w in params:\n for x in params:\n for y in params:\n for z in params:\n q = (w, x, y, z)\n Nq = np.sqrt(np.dot(q, q))\n if not Nq == 0:\n q = tuple([e / Nq for e in q])\n unit_quats.add(q)\n\n\ndef test_fillpos():\n # Takes np array\n xyz = np.zeros((3,))\n w, x, y, z = nq.fillpositive(xyz)\n yield assert_true, w == 1\n # Or lists\n xyz = [0] * 3\n w, x, y, z = nq.fillpositive(xyz)\n yield assert_true, w == 1\n # Errors with wrong number of values\n yield assert_raises, ValueError, nq.fillpositive, [0, 0]\n yield assert_raises, ValueError, nq.fillpositive, [0] * 4\n # Errors with negative w2\n yield assert_raises, ValueError, nq.fillpositive, [1.0] * 3\n # Test corner case where w is near zero\n wxyz = nq.fillpositive([1, 0, 0])\n yield assert_true, wxyz[0] == 0.0\n\n\ndef test_conjugate():\n # Takes sequence\n cq = nq.conjugate((1, 0, 0, 0))\n # Returns float type\n yield assert_true, cq.dtype.kind == 'f'\n\n\ndef test_quat2mat():\n # also tested in roundtrip case below\n M = nq.quat2mat([1, 0, 0, 0])\n yield assert_array_almost_equal, M, np.eye(3)\n M = nq.quat2mat([3, 0, 0, 0])\n yield assert_array_almost_equal, M, np.eye(3)\n M = nq.quat2mat([0, 1, 0, 0])\n yield assert_array_almost_equal, M, np.diag([1, -1, -1])\n M = nq.quat2mat([0, 2, 0, 0])\n yield assert_array_almost_equal, M, np.diag([1, -1, -1])\n M = nq.quat2mat([0, 0, 0, 0])\n yield assert_array_almost_equal, M, np.eye(3)\n\n\ndef test_inverse():\n # Takes sequence\n iq = nq.inverse((1, 0, 0, 0))\n # Returns float type\n yield assert_true, iq.dtype.kind == 'f'\n for M, q in eg_pairs:\n iq = nq.inverse(q)\n iqM = nq.quat2mat(iq)\n iM = np.linalg.inv(M)\n yield assert_true, np.allclose(iM, iqM)\n\n\ndef test_eye():\n qi = nq.eye()\n yield assert_true, qi.dtype.kind == 'f'\n yield assert_true, np.all([1, 0, 0, 0] == qi)\n yield assert_true, np.allclose(nq.quat2mat(qi), np.eye(3))\n\n\ndef test_norm():\n qi = nq.eye()\n yield assert_true, nq.norm(qi) == 1\n yield assert_true, nq.isunit(qi)\n qi[1] = 0.2\n yield assert_true, not nq.isunit(qi)\n\n\n@slow\ndef test_mult():\n # Test that quaternion * same as matrix *\n for M1, q1 in eg_pairs[0::4]:\n for M2, q2 in eg_pairs[1::4]:\n q21 = nq.mult(q2, q1)\n yield assert_array_almost_equal, np.dot(M2, M1), nq.quat2mat(q21)\n\n\ndef test_inverse():\n for M, q in eg_pairs:\n iq = nq.inverse(q)\n iqM = nq.quat2mat(iq)\n iM = np.linalg.inv(M)\n yield assert_true, np.allclose(iM, iqM)\n\n\ndef test_eye():\n qi = nq.eye()\n yield assert_true, np.all([1, 0, 0, 0] == qi)\n yield assert_true, np.allclose(nq.quat2mat(qi), np.eye(3))\n\n\ndef test_qrotate():\n for vec in np.eye(3):\n for M, q in eg_pairs:\n vdash = nq.rotate_vector(vec, q)\n vM = np.dot(M, vec)\n yield assert_array_almost_equal, vdash, vM\n\n\ndef test_quaternion_reconstruction():\n # Test reconstruction of arbitrary unit quaternions\n for q in unit_quats:\n M = nq.quat2mat(q)\n qt = nq.mat2quat(M)\n # Accept positive or negative match\n posm = np.allclose(q, qt)\n negm = np.allclose(q, -qt)\n yield assert_true, posm or negm\n\n\ndef test_angle_axis2quat():\n q = nq.angle_axis2quat(0, [1, 0, 0])\n yield assert_array_equal, q, [1, 0, 0, 0]\n q = nq.angle_axis2quat(np.pi, [1, 0, 0])\n yield assert_array_almost_equal, q, [0, 1, 0, 0]\n q = nq.angle_axis2quat(np.pi, [1, 0, 0], True)\n yield assert_array_almost_equal, q, [0, 1, 0, 0]\n q = nq.angle_axis2quat(np.pi, [2, 0, 0], False)\n yield assert_array_almost_equal, q, [0, 1, 0, 0]\n\n\ndef test_angle_axis():\n for M, q in eg_pairs:\n theta, vec = nq.quat2angle_axis(q)\n q2 = nq.angle_axis2quat(theta, vec)\n yield nq.nearly_equivalent, q, q2\n aa_mat = nq.angle_axis2mat(theta, vec)\n yield assert_array_almost_equal, aa_mat, M\n unit_vec = vec / np.sqrt(vec.dot(vec))\n aa_mat2 = nq.angle_axis2mat(theta, unit_vec, is_normalized=True)\n yield assert_array_almost_equal, aa_mat2, M\n", "import numpy as np\nfrom numpy.testing import (run_module_suite,\n assert_,\n assert_equal,\n assert_array_almost_equal,\n assert_raises)\nfrom dipy.denoise.nlmeans import nlmeans\nfrom dipy.denoise.denspeed import (add_padding_reflection, remove_padding)\nfrom dipy.utils.omp import cpu_count, have_openmp\nfrom time import time\n\n\ndef test_nlmeans_padding():\n S0 = 100 + 2 * np.random.standard_normal((50, 50, 50))\n S0 = S0.astype('f8')\n S0n = add_padding_reflection(S0, 5)\n S0n2 = remove_padding(S0n, 5)\n assert_equal(S0.shape, S0n2.shape)\n\n\ndef test_nlmeans_static():\n S0 = 100 * np.ones((20, 20, 20), dtype='f8')\n S0n = nlmeans(S0, sigma=np.ones((20, 20, 20)), rician=False)\n assert_array_almost_equal(S0, S0n)\n\n\ndef test_nlmeans_wrong():\n S0 = np.ones((2, 2, 2, 2, 2))\n assert_raises(ValueError, nlmeans, S0, 1.0)\n\n\ndef test_nlmeans_random_noise():\n S0 = 100 + 2 * np.random.standard_normal((22, 23, 30))\n\n S0n = nlmeans(S0, sigma=np.ones((22, 23, 30)) * np.std(S0), rician=False)\n\n print(S0.mean(), S0.min(), S0.max())\n print(S0n.mean(), S0n.min(), S0n.max())\n\n assert_(S0n.min() > S0.min())\n assert_(S0n.max() < S0.max())\n assert_equal(np.round(S0n.mean()), 100)\n\n\ndef test_nlmeans_boundary():\n # nlmeans preserves boundaries\n\n S0 = 100 + np.zeros((20, 20, 20))\n\n noise = 2 * np.random.standard_normal((20, 20, 20))\n\n S0 += noise\n\n S0[:10, :10, :10] = 300 + noise[:10, :10, :10]\n\n nlmeans(S0, sigma=np.ones((20, 20, 20)) * np.std(noise),\n rician=False)\n\n print(S0[9, 9, 9])\n print(S0[10, 10, 10])\n\n assert_(S0[9, 9, 9] > 290)\n assert_(S0[10, 10, 10] < 110)\n\n\ndef test_nlmeans_4D_and_mask():\n S0 = 200 * np.ones((20, 20, 20, 3), dtype='f8')\n\n mask = np.zeros((20, 20, 20))\n mask[10, 10, 10] = 1\n\n S0n = nlmeans(S0, sigma=1, mask=mask, rician=True)\n assert_equal(S0.shape, S0n.shape)\n assert_equal(np.round(S0n[10, 10, 10]), 200)\n assert_equal(S0n[8, 8, 8], 0)\n\n\ndef test_nlmeans_dtype():\n\n S0 = 200 * np.ones((20, 20, 20, 3), dtype='f4')\n mask = np.zeros((20, 20, 20))\n mask[10:14, 10:14, 10:14] = 1\n S0n = nlmeans(S0, sigma=1, mask=mask, rician=True)\n assert_equal(S0.dtype, S0n.dtype)\n\n S0 = 200 * np.ones((20, 20, 20), dtype=np.uint16)\n mask = np.zeros((20, 20, 20))\n mask[10:14, 10:14, 10:14] = 1\n S0n = nlmeans(S0, sigma=np.ones((20, 20, 20)), mask=mask, rician=True)\n assert_equal(S0.dtype, S0n.dtype)\n\[email protected](not have_openmp, 'OpenMP does not appear to be available')\ndef test_nlmeans_4d_3dsigma_and_threads():\n # Input is 4D data and 3D sigma\n data = np.ones((50, 50, 50, 5))\n sigma = np.ones(data.shape[:3])\n mask = np.zeros(data.shape[:3])\n\n # mask[25-10:25+10] = 1\n mask[:] = 1\n\n print('cpu count %d' % (cpu_count(),))\n\n print('1')\n t = time()\n new_data = nlmeans(data, sigma, mask, num_threads=1)\n duration_1core = time() - t\n print(duration_1core)\n\n print('All')\n t = time()\n new_data2 = nlmeans(data, sigma, mask, num_threads=None)\n duration_all_core = time() - t\n print(duration_all_core)\n\n print('2')\n t = time()\n new_data3 = nlmeans(data, sigma, mask, num_threads=2)\n duration_2core = time() - t\n print(duration_2core)\n\n assert_array_almost_equal(new_data, new_data2)\n assert_array_almost_equal(new_data2, new_data3)\n\n if cpu_count() > 2:\n\n assert_equal(duration_all_core < duration_2core, True)\n assert_equal(duration_2core < duration_1core, True)\n\n if cpu_count() == 2:\n\n assert_equal(duration_2core < duration_1core, True)\n\n\nif __name__ == '__main__':\n\n run_module_suite()\n", "from __future__ import division, print_function, absolute_import\n\nfrom multiprocessing import cpu_count, Pool\nfrom itertools import repeat\nfrom os import path\nfrom warnings import warn\n\nfrom dipy.utils.six.moves import xrange\n\nfrom nibabel.tmpdirs import InTemporaryDirectory\n\nimport numpy as np\nimport scipy.optimize as opt\n\nfrom dipy.reconst.odf import gfa\nfrom dipy.reconst.recspeed import (local_maxima, remove_similar_vertices,\n search_descending)\nfrom dipy.core.sphere import Sphere\nfrom dipy.data import default_sphere\nfrom dipy.core.ndindex import ndindex\nfrom dipy.reconst.shm import sh_to_sf_matrix\nfrom dipy.reconst.peak_direction_getter import PeaksAndMetricsDirectionGetter\n\n\ndef peak_directions_nl(sphere_eval, relative_peak_threshold=.25,\n min_separation_angle=25, sphere=default_sphere,\n xtol=1e-7):\n \"\"\"Non Linear Direction Finder.\n\n Parameters\n ----------\n sphere_eval : callable\n A function which can be evaluated on a sphere.\n relative_peak_threshold : float\n Only return peaks greater than ``relative_peak_threshold * m`` where m\n is the largest peak.\n min_separation_angle : float in [0, 90]\n The minimum distance between directions. If two peaks are too close\n only the larger of the two is returned.\n sphere : Sphere\n A discrete Sphere. The points on the sphere will be used for initial\n estimate of maximums.\n xtol : float\n Relative tolerance for optimization.\n\n Returns\n -------\n directions : array (N, 3)\n Points on the sphere corresponding to N local maxima on the sphere.\n values : array (N,)\n Value of sphere_eval at each point on directions.\n\n \"\"\"\n # Find discrete peaks for use as seeds in non-linear search\n discrete_values = sphere_eval(sphere)\n values, indices = local_maxima(discrete_values, sphere.edges)\n\n seeds = np.column_stack([sphere.theta[indices], sphere.phi[indices]])\n\n # Helper function\n def _helper(x):\n sphere = Sphere(theta=x[0], phi=x[1])\n return -sphere_eval(sphere)\n\n # Non-linear search\n num_seeds = len(seeds)\n theta = np.empty(num_seeds)\n phi = np.empty(num_seeds)\n for i in xrange(num_seeds):\n peak = opt.fmin(_helper, seeds[i], xtol=xtol, disp=False)\n theta[i], phi[i] = peak\n\n # Evaluate on new-found peaks\n small_sphere = Sphere(theta=theta, phi=phi)\n values = sphere_eval(small_sphere)\n\n # Sort in descending order\n order = values.argsort()[::-1]\n values = values[order]\n directions = small_sphere.vertices[order]\n\n # Remove directions that are too small\n n = search_descending(values, relative_peak_threshold)\n directions = directions[:n]\n\n # Remove peaks too close to each-other\n directions, idx = remove_similar_vertices(directions, min_separation_angle,\n return_index=True)\n values = values[idx]\n return directions, values\n\n\ndef peak_directions(odf, sphere, relative_peak_threshold=.5,\n min_separation_angle=25, minmax_norm=True):\n \"\"\"Get the directions of odf peaks.\n\n Peaks are defined as points on the odf that are greater than at least one\n neighbor and greater than or equal to all neighbors. Peaks are sorted in\n descending order by their values then filtered based on their relative size\n and spacing on the sphere. An odf may have 0 peaks, for example if the odf\n is perfectly isotropic.\n\n Parameters\n ----------\n odf : 1d ndarray\n The odf function evaluated on the vertices of `sphere`\n sphere : Sphere\n The Sphere providing discrete directions for evaluation.\n relative_peak_threshold : float in [0., 1.]\n Only peaks greater than ``min + relative_peak_threshold * scale`` are\n kept, where ``min = max(0, odf.min())`` and\n ``scale = odf.max() - min``.\n min_separation_angle : float in [0, 90]\n The minimum distance between directions. If two peaks are too close\n only the larger of the two is returned.\n\n Returns\n -------\n directions : (N, 3) ndarray\n N vertices for sphere, one for each peak\n values : (N,) ndarray\n peak values\n indices : (N,) ndarray\n peak indices of the directions on the sphere\n\n Notes\n -----\n If the odf has any negative values, they will be clipped to zeros.\n\n \"\"\"\n values, indices = local_maxima(odf, sphere.edges)\n\n # If there is only one peak return\n n = len(values)\n if n == 0 or (values[0] < 0.):\n return np.zeros((0, 3)), np.zeros(0), np.zeros(0, dtype=int)\n elif n == 1:\n return sphere.vertices[indices], values, indices\n\n odf_min = np.min(odf)\n odf_min = odf_min if (odf_min >= 0.) else 0.\n # because of the relative threshold this algorithm will give the same peaks\n # as if we divide (values - odf_min) with (odf_max - odf_min) or not so\n # here we skip the division to increase speed\n values_norm = (values - odf_min)\n\n # Remove small peaks\n n = search_descending(values_norm, relative_peak_threshold)\n indices = indices[:n]\n directions = sphere.vertices[indices]\n\n # Remove peaks too close together\n directions, uniq = remove_similar_vertices(directions,\n min_separation_angle,\n return_index=True)\n values = values[uniq]\n indices = indices[uniq]\n return directions, values, indices\n\n\ndef _pam_from_attrs(klass, sphere, peak_indices, peak_values, peak_dirs,\n gfa, qa, shm_coeff, B, odf):\n \"\"\"\n Construct PeaksAndMetrics object (or subclass) from its attributes.\n\n This is also useful for pickling/unpickling of these objects (see also\n :func:`__reduce__` below).\n\n Parameters\n ----------\n klass : class\n The class of object to be created.\n sphere : `Sphere` class instance.\n Sphere for discretization.\n peak_indices : ndarray\n Indices (in sphere vertices) of the peaks in each voxel.\n peak_values : ndarray\n The value of the peaks.\n peak_dirs : ndarray\n The direction of each peak.\n gfa : ndarray\n The Generalized Fractional Anisotropy in each voxel.\n qa : ndarray\n Quantitative Anisotropy in each voxel.\n shm_coeff : ndarray\n The coefficients of the spherical harmonic basis for the ODF in\n each voxel.\n B : ndarray\n The spherical harmonic matrix, for multiplication with the\n coefficients.\n odf : ndarray\n The orientation distribution function on the sphere in each voxel.\n\n Returns\n -------\n pam : Instance of the class `klass`.\n \"\"\"\n this_pam = klass()\n this_pam.sphere = sphere\n this_pam.peak_dirs = peak_dirs\n this_pam.peak_values = peak_values\n this_pam.peak_indices = peak_indices\n this_pam.gfa = gfa\n this_pam.qa = qa\n this_pam.shm_coeff = shm_coeff\n this_pam.B = B\n this_pam.odf = odf\n return this_pam\n\n\nclass PeaksAndMetrics(PeaksAndMetricsDirectionGetter):\n def __reduce__(self): return _pam_from_attrs, (self.__class__,\n self.sphere,\n self.peak_indices,\n self.peak_values,\n self.peak_dirs,\n self.gfa,\n self.qa,\n self.shm_coeff,\n self.B,\n self.odf)\n\n\ndef _peaks_from_model_parallel(model, data, sphere, relative_peak_threshold,\n min_separation_angle, mask, return_odf,\n return_sh, gfa_thr, normalize_peaks, sh_order,\n sh_basis_type, npeaks, B, invB, nbr_processes):\n\n if nbr_processes is None:\n try:\n nbr_processes = cpu_count()\n except NotImplementedError:\n warn(\"Cannot determine number of cpus. \"\n \"returns peaks_from_model(..., parallel=False).\")\n return peaks_from_model(model, data, sphere,\n relative_peak_threshold,\n min_separation_angle, mask, return_odf,\n return_sh, gfa_thr, normalize_peaks,\n sh_order, sh_basis_type, npeaks,\n parallel=False)\n elif nbr_processes <= 0:\n warn(\"Invalid number of processes (%d). \"\n \"returns peaks_from_model(..., parallel=False).\" % nbr_processes)\n return peaks_from_model(model, data, sphere,\n relative_peak_threshold,\n min_separation_angle, mask, return_odf,\n return_sh, gfa_thr, normalize_peaks,\n sh_order, sh_basis_type, npeaks,\n parallel=False)\n\n shape = list(data.shape)\n data = np.reshape(data, (-1, shape[-1]))\n n = data.shape[0]\n nbr_chunks = nbr_processes ** 2\n chunk_size = int(np.ceil(n / nbr_chunks))\n indices = list(zip(np.arange(0, n, chunk_size),\n np.arange(0, n, chunk_size) + chunk_size))\n\n with InTemporaryDirectory() as tmpdir:\n\n data_file_name = path.join(tmpdir, 'data.npy')\n np.save(data_file_name, data)\n if mask is not None:\n mask = mask.flatten()\n mask_file_name = path.join(tmpdir, 'mask.npy')\n np.save(mask_file_name, mask)\n else:\n mask_file_name = None\n\n pool = Pool(nbr_processes)\n\n pam_res = pool.map(_peaks_from_model_parallel_sub,\n zip(repeat((data_file_name, mask_file_name)),\n indices,\n repeat(model),\n repeat(sphere),\n repeat(relative_peak_threshold),\n repeat(min_separation_angle),\n repeat(return_odf),\n repeat(return_sh),\n repeat(gfa_thr),\n repeat(normalize_peaks),\n repeat(sh_order),\n repeat(sh_basis_type),\n repeat(npeaks),\n repeat(B),\n repeat(invB)))\n pool.close()\n\n pam = PeaksAndMetrics()\n pam.sphere = sphere\n # use memmap to reduce the memory usage\n pam.gfa = np.memmap(path.join(tmpdir, 'gfa.npy'),\n dtype=pam_res[0].gfa.dtype,\n mode='w+',\n shape=(data.shape[0]))\n\n pam.peak_dirs = np.memmap(path.join(tmpdir, 'peak_dirs.npy'),\n dtype=pam_res[0].peak_dirs.dtype,\n mode='w+',\n shape=(data.shape[0], npeaks, 3))\n pam.peak_values = np.memmap(path.join(tmpdir, 'peak_values.npy'),\n dtype=pam_res[0].peak_values.dtype,\n mode='w+',\n shape=(data.shape[0], npeaks))\n pam.peak_indices = np.memmap(path.join(tmpdir, 'peak_indices.npy'),\n dtype=pam_res[0].peak_indices.dtype,\n mode='w+',\n shape=(data.shape[0], npeaks))\n pam.qa = np.memmap(path.join(tmpdir, 'qa.npy'),\n dtype=pam_res[0].qa.dtype,\n mode='w+',\n shape=(data.shape[0], npeaks))\n if return_sh:\n nbr_shm_coeff = (sh_order + 2) * (sh_order + 1) // 2\n pam.shm_coeff = np.memmap(path.join(tmpdir, 'shm.npy'),\n dtype=pam_res[0].shm_coeff.dtype,\n mode='w+',\n shape=(data.shape[0], nbr_shm_coeff))\n pam.B = pam_res[0].B\n else:\n pam.shm_coeff = None\n pam.invB = None\n if return_odf:\n pam.odf = np.memmap(path.join(tmpdir, 'odf.npy'),\n dtype=pam_res[0].odf.dtype,\n mode='w+',\n shape=(data.shape[0], len(sphere.vertices)))\n else:\n pam.odf = None\n\n # copy subprocesses pam to a single pam (memmaps)\n for i, (start_pos, end_pos) in enumerate(indices):\n pam.gfa[start_pos: end_pos] = pam_res[i].gfa\n pam.peak_dirs[start_pos: end_pos] = pam_res[i].peak_dirs\n pam.peak_values[start_pos: end_pos] = pam_res[i].peak_values\n pam.peak_indices[start_pos: end_pos] = pam_res[i].peak_indices\n pam.qa[start_pos: end_pos] = pam_res[i].qa\n if return_sh:\n pam.shm_coeff[start_pos: end_pos] = pam_res[i].shm_coeff\n if return_odf:\n pam.odf[start_pos: end_pos] = pam_res[i].odf\n\n # load memmaps to arrays and reshape the metric\n shape[-1] = -1\n pam.gfa = np.reshape(np.array(pam.gfa), shape[:-1])\n pam.peak_dirs = np.reshape(np.array(pam.peak_dirs), shape + [3])\n pam.peak_values = np.reshape(np.array(pam.peak_values), shape)\n pam.peak_indices = np.reshape(np.array(pam.peak_indices), shape)\n pam.qa = np.reshape(np.array(pam.qa), shape)\n if return_sh:\n pam.shm_coeff = np.reshape(np.array(pam.shm_coeff), shape)\n if return_odf:\n pam.odf = np.reshape(np.array(pam.odf), shape)\n\n # Make sure all worker processes have exited before leaving context\n # manager in order to prevent temporary file deletion errors in windows\n pool.join()\n\n return pam\n\n\ndef _peaks_from_model_parallel_sub(args):\n (data_file_name, mask_file_name) = args[0]\n (start_pos, end_pos) = args[1]\n model = args[2]\n sphere = args[3]\n relative_peak_threshold = args[4]\n min_separation_angle = args[5]\n return_odf = args[6]\n return_sh = args[7]\n gfa_thr = args[8]\n normalize_peaks = args[9]\n sh_order = args[10]\n sh_basis_type = args[11]\n npeaks = args[12]\n B = args[13]\n invB = args[14]\n\n data = np.load(data_file_name, mmap_mode='r')[start_pos:end_pos]\n if mask_file_name is not None:\n mask = np.load(mask_file_name, mmap_mode='r')[start_pos:end_pos]\n else:\n mask = None\n\n return peaks_from_model(model, data, sphere, relative_peak_threshold,\n min_separation_angle, mask, return_odf,\n return_sh, gfa_thr, normalize_peaks,\n sh_order, sh_basis_type, npeaks, B, invB,\n parallel=False, nbr_processes=None)\n\n\ndef peaks_from_model(model, data, sphere, relative_peak_threshold,\n min_separation_angle, mask=None, return_odf=False,\n return_sh=True, gfa_thr=0, normalize_peaks=False,\n sh_order=8, sh_basis_type=None, npeaks=5, B=None,\n invB=None, parallel=False, nbr_processes=None):\n \"\"\"Fit the model to data and computes peaks and metrics\n\n Parameters\n ----------\n model : a model instance\n `model` will be used to fit the data.\n sphere : Sphere\n The Sphere providing discrete directions for evaluation.\n relative_peak_threshold : float\n Only return peaks greater than ``relative_peak_threshold * m`` where m\n is the largest peak.\n min_separation_angle : float in [0, 90] The minimum distance between\n directions. If two peaks are too close only the larger of the two is\n returned.\n mask : array, optional\n If `mask` is provided, voxels that are False in `mask` are skipped and\n no peaks are returned.\n return_odf : bool\n If True, the odfs are returned.\n return_sh : bool\n If True, the odf as spherical harmonics coefficients is returned\n gfa_thr : float\n Voxels with gfa less than `gfa_thr` are skipped, no peaks are returned.\n normalize_peaks : bool\n If true, all peak values are calculated relative to `max(odf)`.\n sh_order : int, optional\n Maximum SH order in the SH fit. For `sh_order`, there will be\n ``(sh_order + 1) * (sh_order + 2) / 2`` SH coefficients (default 8).\n sh_basis_type : {None, 'tournier07', 'descoteaux07'}\n ``None`` for the default DIPY basis,\n ``tournier07`` for the Tournier 2007 [2]_ basis, and\n ``descoteaux07`` for the Descoteaux 2007 [1]_ basis\n (``None`` defaults to ``descoteaux07``).\n sh_smooth : float, optional\n Lambda-regularization in the SH fit (default 0.0).\n npeaks : int\n Maximum number of peaks found (default 5 peaks).\n B : ndarray, optional\n Matrix that transforms spherical harmonics to spherical function\n ``sf = np.dot(sh, B)``.\n invB : ndarray, optional\n Inverse of B.\n parallel: bool\n If True, use multiprocessing to compute peaks and metric\n (default False). Temporary files are saved in the default temporary\n directory of the system. It can be changed using ``import tempfile``\n and ``tempfile.tempdir = '/path/to/tempdir'``.\n nbr_processes: int\n If `parallel` is True, the number of subprocesses to use\n (default multiprocessing.cpu_count()).\n\n Returns\n -------\n pam : PeaksAndMetrics\n An object with ``gfa``, ``peak_directions``, ``peak_values``,\n ``peak_indices``, ``odf``, ``shm_coeffs`` as attributes\n\n References\n ----------\n .. [1] Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.\n Regularized, Fast, and Robust Analytical Q-ball Imaging.\n Magn. Reson. Med. 2007;58:497-510.\n .. [2] Tournier J.D., Calamante F. and Connelly A. Robust determination\n of the fibre orientation distribution in diffusion MRI:\n Non-negativity constrained super-resolved spherical deconvolution.\n NeuroImage. 2007;35(4):1459-1472.\n\n \"\"\"\n if return_sh and (B is None or invB is None):\n B, invB = sh_to_sf_matrix(\n sphere, sh_order, sh_basis_type, return_inv=True)\n\n if parallel:\n # It is mandatory to provide B and invB to the parallel function.\n # Otherwise, a call to np.linalg.pinv is made in a subprocess and\n # makes it timeout on some system.\n # see https://github.com/nipy/dipy/issues/253 for details\n return _peaks_from_model_parallel(model,\n data, sphere,\n relative_peak_threshold,\n min_separation_angle,\n mask, return_odf,\n return_sh,\n gfa_thr,\n normalize_peaks,\n sh_order,\n sh_basis_type,\n npeaks,\n B,\n invB,\n nbr_processes)\n\n shape = data.shape[:-1]\n if mask is None:\n mask = np.ones(shape, dtype='bool')\n else:\n if mask.shape != shape:\n raise ValueError(\"Mask is not the same shape as data.\")\n\n gfa_array = np.zeros(shape)\n qa_array = np.zeros((shape + (npeaks,)))\n\n peak_dirs = np.zeros((shape + (npeaks, 3)))\n peak_values = np.zeros((shape + (npeaks,)))\n peak_indices = np.zeros((shape + (npeaks,)), dtype='int')\n peak_indices.fill(-1)\n\n if return_sh:\n n_shm_coeff = (sh_order + 2) * (sh_order + 1) // 2\n shm_coeff = np.zeros((shape + (n_shm_coeff,)))\n\n if return_odf:\n odf_array = np.zeros((shape + (len(sphere.vertices),)))\n\n global_max = -np.inf\n for idx in ndindex(shape):\n if not mask[idx]:\n continue\n\n odf = model.fit(data[idx]).odf(sphere)\n\n if return_sh:\n shm_coeff[idx] = np.dot(odf, invB)\n\n if return_odf:\n odf_array[idx] = odf\n\n gfa_array[idx] = gfa(odf)\n if gfa_array[idx] < gfa_thr:\n global_max = max(global_max, odf.max())\n continue\n\n # Get peaks of odf\n direction, pk, ind = peak_directions(odf, sphere,\n relative_peak_threshold,\n min_separation_angle)\n\n # Calculate peak metrics\n if pk.shape[0] != 0:\n global_max = max(global_max, pk[0])\n\n n = min(npeaks, pk.shape[0])\n qa_array[idx][:n] = pk[:n] - odf.min()\n\n peak_dirs[idx][:n] = direction[:n]\n peak_indices[idx][:n] = ind[:n]\n peak_values[idx][:n] = pk[:n]\n\n if normalize_peaks:\n peak_values[idx][:n] /= pk[0]\n peak_dirs[idx] *= peak_values[idx][:, None]\n\n qa_array /= global_max\n\n return _pam_from_attrs(PeaksAndMetrics,\n sphere,\n peak_indices,\n peak_values,\n peak_dirs,\n gfa_array,\n qa_array,\n shm_coeff if return_sh else None,\n B if return_sh else None,\n odf_array if return_odf else None)\n\n\ndef reshape_peaks_for_visualization(peaks):\n \"\"\"Reshape peaks for visualization.\n\n Reshape and convert to float32 a set of peaks for visualisation with mrtrix\n or the fibernavigator.\n\n Parameters:\n -----------\n peaks: nd array (..., N, 3) or PeaksAndMetrics object\n The peaks to be reshaped and converted to float32.\n\n Returns:\n --------\n peaks : nd array (..., 3*N)\n \"\"\"\n if isinstance(peaks, PeaksAndMetrics):\n peaks = peaks.peak_dirs\n\n return peaks.reshape(np.append(peaks.shape[:-2], -1)).astype('float32')\n", "\"\"\"\nDiffusion Imaging in Python\n============================\n\nFor more information, please visit http://dipy.org\n\nSubpackages\n-----------\n::\n\n align -- Registration, streamline alignment, volume resampling\n boots -- Bootstrapping algorithms\n core -- Spheres, gradient tables\n core.geometry -- Spherical geometry, coordinate and vector manipulation\n core.meshes -- Point distributions on the sphere\n data -- Small testing datasets\n external -- Interfaces to external tools such as FSL\n io -- Loading/saving of dpy datasets\n reconst -- Signal reconstruction modules (tensor, spherical harmonics,\n diffusion spectrum, etc.)\n segment -- Tractography segmentation\n sims -- MRI phantom signal simulation\n tracking -- Tractography, metrics for streamlines\n viz -- Visualization and GUIs\n\nUtilities\n---------\n::\n\n test -- Run unittests\n __version__ -- Dipy version\n\n\"\"\"\nimport sys\nif sys.version[0:3] < '2.6':\n raise ImportError('Dipy needs Python version 2.6 or above')\n\nfrom .info import __version__\nfrom .testing import setup_test\n\n# Test callable\nfrom numpy.testing import Tester\ntest = Tester().test\nbench = Tester().bench\ndel Tester\n\n# Plumb in version etc info stuff\nfrom .pkg_info import get_pkg_info as _get_pkg_info\ndef get_info():\n from os.path import dirname\n return _get_pkg_info(dirname(__file__))\ndel sys\n", "from __future__ import division, print_function, absolute_import\n\nimport os.path as osp\nfrom nibabel.tmpdirs import InTemporaryDirectory\n\nimport numpy as np\nimport numpy.testing as npt\n\nfrom dipy.data import get_fnames\nfrom dipy.io.gradients import read_bvals_bvecs\nfrom dipy.core.gradients import gradient_table\n\n\ndef test_read_bvals_bvecs():\n fimg, fbvals, fbvecs = get_fnames('small_101D')\n bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs)\n gt = gradient_table(bvals, bvecs)\n npt.assert_array_equal(bvals, gt.bvals)\n npt.assert_array_equal(bvecs, gt.bvecs)\n\n # None should also work as an input:\n bvals_none, bvecs_none = read_bvals_bvecs(None, fbvecs)\n npt.assert_array_equal(bvecs_none, gt.bvecs)\n bvals_none, bvecs_none = read_bvals_bvecs(fbvals, None)\n npt.assert_array_equal(bvals_none, gt.bvals)\n\n # Test for error raising with unknown file formats:\n nan_fbvecs = osp.splitext(fbvecs)[0] + '.nan' # Nonsense extension\n npt.assert_raises(ValueError, read_bvals_bvecs, fbvals, nan_fbvecs)\n\n # Test for error raising with incorrect file-contents:\n\n with InTemporaryDirectory():\n # These bvecs only have two rows/columns:\n new_bvecs1 = bvecs[:, :2]\n # Make a temporary file\n with open('test_bv_file1.txt', 'wt') as bv_file1:\n # And fill it with these 2-columned bvecs:\n for x in range(new_bvecs1.shape[0]):\n bv_file1.write('%s %s\\n' % (new_bvecs1[x][0],\n new_bvecs1[x][1]))\n npt.assert_raises(IOError, read_bvals_bvecs, fbvals, 'test_bv_file1.txt')\n\n # These bvecs are saved as one long array:\n new_bvecs2 = np.ravel(bvecs)\n with open('test_bv_file2.npy', 'w') as bv_file2:\n print('FILENAME:', bv_file2.name)\n np.save(bv_file2.name, new_bvecs2)\n npt.assert_raises(IOError, read_bvals_bvecs, fbvals, 'test_bv_file2.npy')\n\n # There are less bvecs than bvals:\n new_bvecs3 = bvecs[:-1, :]\n with open('test_bv_file3.txt', 'w') as bv_file3:\n np.savetxt(bv_file3.name, new_bvecs3)\n npt.assert_raises(IOError, read_bvals_bvecs, fbvals, 'test_bv_file3.txt')\n\n # You entered the bvecs on both sides:\n npt.assert_raises(IOError, read_bvals_bvecs, fbvecs, fbvecs)\n\n # All possible delimiters should work\n bv_file4 = 'test_space.txt'\n with open(bv_file4, 'w') as f:\n f.write(\"66 55 33\")\n bvals_1, _ = read_bvals_bvecs(bv_file4, '')\n\n bv_file5 = 'test_coma.txt'\n with open(bv_file5, 'w') as f:\n f.write(\"66, 55, 33\")\n bvals_2, _ = read_bvals_bvecs(bv_file5, '')\n\n bv_file6 = 'test_tabs.txt'\n with open(bv_file6, 'w') as f:\n f.write(\"66 \\t 55 \\t 33\")\n bvals_3, _ = read_bvals_bvecs(bv_file6, '')\n\n ans = np.array([66., 55., 33.])\n npt.assert_array_equal(ans, bvals_1)\n npt.assert_array_equal(ans, bvals_2)\n npt.assert_array_equal(ans, bvals_3)\n\n bv_file7 = 'test_space_2.txt'\n with open(bv_file7, 'w') as f:\n f.write(\"66 55 33\\n45 34 21\\n55 32 65\\n\")\n _, bvecs_1 = read_bvals_bvecs('', bv_file7)\n\n bv_file8 = 'test_coma_2.txt'\n with open(bv_file8, 'w') as f:\n f.write(\"66, 55, 33\\n45, 34, 21 \\n 55, 32, 65\\n\")\n _, bvecs_2 = read_bvals_bvecs('', bv_file8)\n\n bv_file9 = 'test_tabs_2.txt'\n with open(bv_file9, 'w') as f:\n f.write(\"66 \\t 55 \\t 33\\n45 \\t 34 \\t 21\\n55 \\t 32 \\t 65\\n\")\n _, bvecs_3 = read_bvals_bvecs('', bv_file9)\n\n bv_file10 = 'test_multiple_space.txt'\n with open(bv_file10, 'w') as f:\n f.write(\"66 55 33\\n45, 34, 21 \\n 55, 32, 65\\n\")\n _, bvecs_4 = read_bvals_bvecs('', bv_file10)\n\n ans = np.array([[66., 55., 33.], [45., 34., 21.], [55., 32., 65.]])\n npt.assert_array_equal(ans, bvecs_1)\n npt.assert_array_equal(ans, bvecs_2)\n npt.assert_array_equal(ans, bvecs_3)\n npt.assert_array_equal(ans, bvecs_4)\n\n\nif __name__ == '__main__':\n from numpy.testing import run_module_suite\n run_module_suite()\n", "from __future__ import division, print_function, absolute_import\nimport warnings\n\nimport numpy as np\nfrom scipy.integrate import quad\nfrom scipy.special import lpn, gamma\nimport scipy.linalg as la\nimport scipy.linalg.lapack as ll\n\nfrom dipy.data import small_sphere, get_sphere, default_sphere\n\nfrom dipy.core.geometry import cart2sphere\nfrom dipy.core.ndindex import ndindex\nfrom dipy.sims.voxel import single_tensor\nfrom dipy.utils.six.moves import range\n\nfrom dipy.reconst.multi_voxel import multi_voxel_fit\nfrom dipy.reconst.dti import TensorModel, fractional_anisotropy\nfrom dipy.reconst.shm import (sph_harm_ind_list, real_sph_harm,\n sph_harm_lookup, lazy_index, SphHarmFit,\n real_sym_sh_basis, sh_to_rh, forward_sdeconv_mat,\n SphHarmModel)\n\nfrom dipy.direction.peaks import peaks_from_model\nfrom dipy.core.geometry import vec2vec_rotmat\n\n\nclass AxSymShResponse(object):\n \"\"\"A simple wrapper for response functions represented using only axially\n symmetric, even spherical harmonic functions (ie, m == 0 and n even).\n\n Parameters:\n -----------\n S0 : float\n Signal with no diffusion weighting.\n dwi_response : array\n Response function signal as coefficients to axially symmetric, even\n spherical harmonic.\n\n \"\"\"\n\n def __init__(self, S0, dwi_response, bvalue=None):\n self.S0 = S0\n self.dwi_response = dwi_response\n self.bvalue = bvalue\n self.m = np.zeros(len(dwi_response))\n self.sh_order = 2 * (len(dwi_response) - 1)\n self.n = np.arange(0, self.sh_order + 1, 2)\n\n def basis(self, sphere):\n \"\"\"A basis that maps the response coefficients onto a sphere.\"\"\"\n theta = sphere.theta[:, None]\n phi = sphere.phi[:, None]\n return real_sph_harm(self.m, self.n, theta, phi)\n\n def on_sphere(self, sphere):\n \"\"\"Evaluates the response function on sphere.\"\"\"\n B = self.basis(sphere)\n return np.dot(self.dwi_response, B.T)\n\n\nclass ConstrainedSphericalDeconvModel(SphHarmModel):\n\n def __init__(self, gtab, response, reg_sphere=None, sh_order=8, lambda_=1,\n tau=0.1):\n r\"\"\" Constrained Spherical Deconvolution (CSD) [1]_.\n\n Spherical deconvolution computes a fiber orientation distribution\n (FOD), also called fiber ODF (fODF) [2]_, as opposed to a diffusion ODF\n as the QballModel or the CsaOdfModel. This results in a sharper angular\n profile with better angular resolution that is the best object to be\n used for later deterministic and probabilistic tractography [3]_.\n\n A sharp fODF is obtained because a single fiber *response* function is\n injected as *a priori* knowledge. The response function is often\n data-driven and is thus provided as input to the\n ConstrainedSphericalDeconvModel. It will be used as deconvolution\n kernel, as described in [1]_.\n\n Parameters\n ----------\n gtab : GradientTable\n response : tuple or AxSymShResponse object\n A tuple with two elements. The first is the eigen-values as an (3,)\n ndarray and the second is the signal value for the response\n function without diffusion weighting. This is to be able to\n generate a single fiber synthetic signal. The response function\n will be used as deconvolution kernel ([1]_)\n reg_sphere : Sphere (optional)\n sphere used to build the regularization B matrix.\n Default: 'symmetric362'.\n sh_order : int (optional)\n maximal spherical harmonics order. Default: 8\n lambda_ : float (optional)\n weight given to the constrained-positivity regularization part of\n the deconvolution equation (see [1]_). Default: 1\n tau : float (optional)\n threshold controlling the amplitude below which the corresponding\n fODF is assumed to be zero. Ideally, tau should be set to\n zero. However, to improve the stability of the algorithm, tau is\n set to tau*100 % of the mean fODF amplitude (here, 10% by default)\n (see [1]_). Default: 0.1\n\n References\n ----------\n .. [1] Tournier, J.D., et al. NeuroImage 2007. Robust determination of\n the fibre orientation distribution in diffusion MRI:\n Non-negativity constrained super-resolved spherical\n deconvolution\n .. [2] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and\n Probabilistic Tractography Based on Complex Fibre Orientation\n Distributions\n .. [3] C\\^ot\\'e, M-A., et al. Medical Image Analysis 2013. Tractometer:\n Towards validation of tractography pipelines\n .. [4] Tournier, J.D, et al. Imaging Systems and Technology\n 2012. MRtrix: Diffusion Tractography in Crossing Fiber Regions\n \"\"\"\n # Initialize the parent class:\n SphHarmModel.__init__(self, gtab)\n m, n = sph_harm_ind_list(sh_order)\n self.m, self.n = m, n\n self._where_b0s = lazy_index(gtab.b0s_mask)\n self._where_dwi = lazy_index(~gtab.b0s_mask)\n\n no_params = ((sh_order + 1) * (sh_order + 2)) / 2\n\n if no_params > np.sum(~gtab.b0s_mask):\n msg = \"Number of parameters required for the fit are more \"\n msg += \"than the actual data points\"\n warnings.warn(msg, UserWarning)\n\n x, y, z = gtab.gradients[self._where_dwi].T\n r, theta, phi = cart2sphere(x, y, z)\n # for the gradient sphere\n self.B_dwi = real_sph_harm(m, n, theta[:, None], phi[:, None])\n\n # for the sphere used in the regularization positivity constraint\n if reg_sphere is None:\n self.sphere = small_sphere\n else:\n self.sphere = reg_sphere\n\n r, theta, phi = cart2sphere(\n self.sphere.x,\n self.sphere.y,\n self.sphere.z\n )\n self.B_reg = real_sph_harm(m, n, theta[:, None], phi[:, None])\n\n if response is None:\n response = (np.array([0.0015, 0.0003, 0.0003]), 1)\n\n self.response = response\n if isinstance(response, AxSymShResponse):\n r_sh = response.dwi_response\n self.response_scaling = response.S0\n n_response = response.n\n m_response = response.m\n else:\n self.S_r = estimate_response(gtab, self.response[0],\n self.response[1])\n r_sh = np.linalg.lstsq(self.B_dwi, self.S_r[self._where_dwi],\n rcond=-1)[0]\n n_response = n\n m_response = m\n self.response_scaling = response[1]\n r_rh = sh_to_rh(r_sh, m_response, n_response)\n self.R = forward_sdeconv_mat(r_rh, n)\n\n # scale lambda_ to account for differences in the number of\n # SH coefficients and number of mapped directions\n # This is exactly what is done in [4]_\n lambda_ = (lambda_ * self.R.shape[0] * r_rh[0] /\n (np.sqrt(self.B_reg.shape[0]) * np.sqrt(362.)))\n self.B_reg *= lambda_\n self.sh_order = sh_order\n self.tau = tau\n self._X = X = self.R.diagonal() * self.B_dwi\n self._P = np.dot(X.T, X)\n\n @multi_voxel_fit\n def fit(self, data):\n dwi_data = data[self._where_dwi]\n shm_coeff, _ = csdeconv(dwi_data, self._X, self.B_reg, self.tau,\n P=self._P)\n return SphHarmFit(self, shm_coeff, None)\n\n def predict(self, sh_coeff, gtab=None, S0=1.):\n \"\"\"Compute a signal prediction given spherical harmonic coefficients\n for the provided GradientTable class instance.\n\n Parameters\n ----------\n sh_coeff : ndarray\n The spherical harmonic representation of the FOD from which to make\n the signal prediction.\n gtab : GradientTable\n The gradients for which the signal will be predicted. Use the\n model's gradient table by default.\n S0 : ndarray or float\n The non diffusion-weighted signal value.\n\n Returns\n -------\n pred_sig : ndarray\n The predicted signal.\n\n \"\"\"\n if gtab is None or gtab is self.gtab:\n SH_basis = self.B_dwi\n gtab = self.gtab\n else:\n x, y, z = gtab.gradients[~gtab.b0s_mask].T\n r, theta, phi = cart2sphere(x, y, z)\n SH_basis, m, n = real_sym_sh_basis(self.sh_order, theta, phi)\n\n # Because R is diagonal, the matrix multiply is written as a multiply\n predict_matrix = SH_basis * self.R.diagonal()\n S0 = np.asarray(S0)[..., None]\n scaling = S0 / self.response_scaling\n # This is the key operation: convolve and multiply by S0:\n pre_pred_sig = scaling * np.dot(sh_coeff, predict_matrix.T)\n\n # Now put everything in its right place:\n pred_sig = np.zeros(pre_pred_sig.shape[:-1] + (gtab.bvals.shape[0],))\n pred_sig[..., ~gtab.b0s_mask] = pre_pred_sig\n pred_sig[..., gtab.b0s_mask] = S0\n\n return pred_sig\n\n\nclass ConstrainedSDTModel(SphHarmModel):\n\n def __init__(self, gtab, ratio, reg_sphere=None, sh_order=8, lambda_=1.,\n tau=0.1):\n r\"\"\" Spherical Deconvolution Transform (SDT) [1]_.\n\n The SDT computes a fiber orientation distribution (FOD) as opposed to a\n diffusion ODF as the QballModel or the CsaOdfModel. This results in a\n sharper angular profile with better angular resolution. The Constrained\n SDTModel is similar to the Constrained CSDModel but mathematically it\n deconvolves the q-ball ODF as oppposed to the HARDI signal (see [1]_\n for a comparison and a through discussion).\n\n A sharp fODF is obtained because a single fiber *response* function is\n injected as *a priori* knowledge. In the SDTModel, this response is a\n single fiber q-ball ODF as opposed to a single fiber signal function\n for the CSDModel. The response function will be used as deconvolution\n kernel.\n\n Parameters\n ----------\n gtab : GradientTable\n ratio : float\n ratio of the smallest vs the largest eigenvalue of the single\n prolate tensor response function\n reg_sphere : Sphere\n sphere used to build the regularization B matrix\n sh_order : int\n maximal spherical harmonics order\n lambda_ : float\n weight given to the constrained-positivity regularization part of\n the deconvolution equation\n tau : float\n threshold (tau *mean(fODF)) controlling the amplitude below\n which the corresponding fODF is assumed to be zero.\n\n References\n ----------\n .. [1] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and\n Probabilistic Tractography Based on Complex Fibre Orientation\n Distributions.\n\n \"\"\"\n SphHarmModel.__init__(self, gtab)\n m, n = sph_harm_ind_list(sh_order)\n self.m, self.n = m, n\n self._where_b0s = lazy_index(gtab.b0s_mask)\n self._where_dwi = lazy_index(~gtab.b0s_mask)\n\n no_params = ((sh_order + 1) * (sh_order + 2)) / 2\n\n if no_params > np.sum(~gtab.b0s_mask):\n msg = \"Number of parameters required for the fit are more \"\n msg += \"than the actual data points\"\n warnings.warn(msg, UserWarning)\n\n x, y, z = gtab.gradients[self._where_dwi].T\n r, theta, phi = cart2sphere(x, y, z)\n # for the gradient sphere\n self.B_dwi = real_sph_harm(m, n, theta[:, None], phi[:, None])\n\n # for the odf sphere\n if reg_sphere is None:\n self.sphere = get_sphere('symmetric362')\n else:\n self.sphere = reg_sphere\n\n r, theta, phi = cart2sphere(\n self.sphere.x,\n self.sphere.y,\n self.sphere.z\n )\n self.B_reg = real_sph_harm(m, n, theta[:, None], phi[:, None])\n\n self.R, self.P = forward_sdt_deconv_mat(ratio, n)\n\n # scale lambda_ to account for differences in the number of\n # SH coefficients and number of mapped directions\n self.lambda_ = (lambda_ * self.R.shape[0] * self.R[0, 0] /\n self.B_reg.shape[0])\n self.tau = tau\n self.sh_order = sh_order\n\n @multi_voxel_fit\n def fit(self, data):\n s_sh = np.linalg.lstsq(self.B_dwi, data[self._where_dwi],\n rcond=-1)[0]\n # initial ODF estimation\n odf_sh = np.dot(self.P, s_sh)\n qball_odf = np.dot(self.B_reg, odf_sh)\n Z = np.linalg.norm(qball_odf)\n # normalize ODF\n odf_sh /= Z\n\n shm_coeff, num_it = odf_deconv(odf_sh, self.R, self.B_reg,\n self.lambda_, self.tau)\n # print 'SDT CSD converged after %d iterations' % num_it\n return SphHarmFit(self, shm_coeff, None)\n\n\ndef estimate_response(gtab, evals, S0):\n \"\"\" Estimate single fiber response function\n\n Parameters\n ----------\n gtab : GradientTable\n evals : ndarray\n S0 : float\n non diffusion weighted\n\n Returns\n -------\n S : estimated signal\n\n \"\"\"\n evecs = np.array([[0, 0, 1],\n [0, 1, 0],\n [1, 0, 0]])\n\n return single_tensor(gtab, S0, evals, evecs, snr=None)\n\n\ndef forward_sdt_deconv_mat(ratio, n, r2_term=False):\n \"\"\" Build forward sharpening deconvolution transform (SDT) matrix\n\n Parameters\n ----------\n ratio : float\n ratio = $\\frac{\\lambda_2}{\\lambda_1}$ of the single fiber response\n function\n n : ndarray (N,)\n The degree of spherical harmonic function associated with each row of\n the deconvolution matrix. Only even degrees are allowed.\n r2_term : bool\n True if ODF comes from an ODF computed from a model using the $r^2$\n term in the integral. For example, DSI, GQI, SHORE, CSA, Tensor,\n Multi-tensor ODFs. This results in using the proper analytical response\n function solution solving from the single-fiber ODF with the r^2 term.\n This derivation is not published anywhere but is very similar to [1]_.\n\n Returns\n -------\n R : ndarray (N, N)\n SDT deconvolution matrix\n P : ndarray (N, N)\n Funk-Radon Transform (FRT) matrix\n\n References\n ----------\n .. [1] Descoteaux, M. PhD Thesis. INRIA Sophia-Antipolis. 2008.\n\n \"\"\"\n if np.any(n % 2):\n raise ValueError(\"n has odd degrees, expecting only even degrees\")\n n_degrees = n.max() // 2 + 1\n sdt = np.zeros(n_degrees) # SDT matrix\n frt = np.zeros(n_degrees) # FRT (Funk-Radon transform) q-ball matrix\n\n for l in np.arange(0, n_degrees * 2, 2):\n if r2_term:\n sharp = quad(lambda z: lpn(l, z)[0][-1] * gamma(1.5) *\n np.sqrt(ratio / (4 * np.pi ** 3)) /\n np.power((1 - (1 - ratio) * z ** 2), 1.5), -1., 1.)\n else:\n sharp = quad(lambda z: lpn(l, z)[0][-1] *\n np.sqrt(1 / (1 - (1 - ratio) * z * z)), -1., 1.)\n\n sdt[l // 2] = sharp[0]\n frt[l // 2] = 2 * np.pi * lpn(l, 0)[0][-1]\n\n idx = n // 2\n b = sdt[idx]\n bb = frt[idx]\n return np.diag(b), np.diag(bb)\n\n\npotrf, potrs = ll.get_lapack_funcs(('potrf', 'potrs'))\n\n\ndef _solve_cholesky(Q, z):\n L, info = potrf(Q, lower=False, overwrite_a=False, clean=False)\n if info > 0:\n msg = \"%d-th leading minor not positive definite\" % info\n raise la.LinAlgError(msg)\n if info < 0:\n msg = 'illegal value in %d-th argument of internal potrf' % -info\n raise ValueError(msg)\n f, info = potrs(L, z, lower=False, overwrite_b=False)\n if info != 0:\n msg = 'illegal value in %d-th argument of internal potrs' % -info\n raise ValueError(msg)\n return f\n\n\ndef csdeconv(dwsignal, X, B_reg, tau=0.1, convergence=50, P=None):\n r\"\"\" Constrained-regularized spherical deconvolution (CSD) [1]_\n\n Deconvolves the axially symmetric single fiber response function `r_rh` in\n rotational harmonics coefficients from the diffusion weighted signal in\n `dwsignal`.\n\n Parameters\n ----------\n dwsignal : array\n Diffusion weighted signals to be deconvolved.\n X : array\n Prediction matrix which estimates diffusion weighted signals from FOD\n coefficients.\n B_reg : array (N, B)\n SH basis matrix which maps FOD coefficients to FOD values on the\n surface of the sphere. B_reg should be scaled to account for lambda.\n tau : float\n Threshold controlling the amplitude below which the corresponding fODF\n is assumed to be zero. Ideally, tau should be set to zero. However, to\n improve the stability of the algorithm, tau is set to tau*100 % of the\n max fODF amplitude (here, 10% by default). This is similar to peak\n detection where peaks below 0.1 amplitude are usually considered noise\n peaks. Because SDT is based on a q-ball ODF deconvolution, and not\n signal deconvolution, using the max instead of mean (as in CSD), is\n more stable.\n convergence : int\n Maximum number of iterations to allow the deconvolution to converge.\n P : ndarray\n This is an optimization to avoid computing ``dot(X.T, X)`` many times.\n If the same ``X`` is used many times, ``P`` can be precomputed and\n passed to this function.\n\n Returns\n -------\n fodf_sh : ndarray (``(sh_order + 1)*(sh_order + 2)/2``,)\n Spherical harmonics coefficients of the constrained-regularized fiber\n ODF.\n num_it : int\n Number of iterations in the constrained-regularization used for\n convergence.\n\n Notes\n -----\n This section describes how the fitting of the SH coefficients is done.\n Problem is to minimise per iteration:\n\n $F(f_n) = ||Xf_n - S||^2 + \\lambda^2 ||H_{n-1} f_n||^2$\n\n Where $X$ maps current FOD SH coefficients $f_n$ to DW signals $s$ and\n $H_{n-1}$ maps FOD SH coefficients $f_n$ to amplitudes along set of\n negative directions identified in previous iteration, i.e. the matrix\n formed by the rows of $B_{reg}$ for which $Hf_{n-1}<0$ where $B_{reg}$\n maps $f_n$ to FOD amplitude on a sphere.\n\n Solve by differentiating and setting to zero:\n\n $\\Rightarrow \\frac{\\delta F}{\\delta f_n} = 2X^T(Xf_n - S) + 2 \\lambda^2\n H_{n-1}^TH_{n-1}f_n=0$\n\n Or:\n\n $(X^TX + \\lambda^2 H_{n-1}^TH_{n-1})f_n = X^Ts$\n\n Define $Q = X^TX + \\lambda^2 H_{n-1}^TH_{n-1}$ , which by construction is a\n square positive definite symmetric matrix of size $n_{SH} by n_{SH}$. If\n needed, positive definiteness can be enforced with a small minimum norm\n regulariser (helps a lot with poorly conditioned direction sets and/or\n superresolution):\n\n $Q = X^TX + (\\lambda H_{n-1}^T) (\\lambda H_{n-1}) + \\mu I$\n\n Solve $Qf_n = X^Ts$ using Cholesky decomposition:\n\n $Q = LL^T$\n\n where $L$ is lower triangular. Then problem can be solved by\n back-substitution:\n\n $L_y = X^Ts$\n\n $L^Tf_n = y$\n\n To speeds things up further, form $P = X^TX + \\mu I$, and update to form\n $Q$ by rankn update with $H_{n-1}$. The dipy implementation looks like:\n\n form initially $P = X^T X + \\mu I$ and $\\lambda B_{reg}$\n\n for each voxel: form $z = X^Ts$\n\n estimate $f_0$ by solving $Pf_0=z$. We use a simplified $l_{max}=4$\n solution here, but it might not make a big difference.\n\n Then iterate until no change in rows of $H$ used in $H_n$\n\n form $H_{n}$ given $f_{n-1}$\n\n form $Q = P + (\\lambda H_{n-1}^T) (\\lambda H_{n-1}$) (this can\n be done by rankn update, but we currently do not use rankn\n update).\n\n solve $Qf_n = z$ using Cholesky decomposition\n\n We'd like to thanks Donald Tournier for his help with describing and\n implementing this algorithm.\n\n References\n ----------\n .. [1] Tournier, J.D., et al. NeuroImage 2007. Robust determination of the\n fibre orientation distribution in diffusion MRI: Non-negativity\n constrained super-resolved spherical deconvolution.\n\n \"\"\"\n mu = 1e-5\n if P is None:\n P = np.dot(X.T, X)\n z = np.dot(X.T, dwsignal)\n\n try:\n fodf_sh = _solve_cholesky(P, z)\n except la.LinAlgError:\n P = P + mu * np.eye(P.shape[0])\n fodf_sh = _solve_cholesky(P, z)\n # For the first iteration we use a smooth FOD that only uses SH orders up\n # to 4 (the first 15 coefficients).\n fodf = np.dot(B_reg[:, :15], fodf_sh[:15])\n # The mean of an fodf can be computed by taking $Y_{0,0} * coeff_{0,0}$\n threshold = B_reg[0, 0] * fodf_sh[0] * tau\n where_fodf_small = (fodf < threshold).nonzero()[0]\n\n # If the low-order fodf does not have any values less than threshold, the\n # full-order fodf is used.\n if len(where_fodf_small) == 0:\n fodf = np.dot(B_reg, fodf_sh)\n where_fodf_small = (fodf < threshold).nonzero()[0]\n # If the fodf still has no values less than threshold, return the fodf.\n if len(where_fodf_small) == 0:\n return fodf_sh, 0\n\n for num_it in range(1, convergence + 1):\n # This is the super-resolved trick. Wherever there is a negative\n # amplitude value on the fODF, it concatenates a value to the S vector\n # so that the estimation can focus on trying to eliminate it. In a\n # sense, this \"adds\" a measurement, which can help to better estimate\n # the fodf_sh, even if you have more SH coefficients to estimate than\n # actual S measurements.\n H = B_reg.take(where_fodf_small, axis=0)\n\n # We use the Cholesky decomposition to solve for the SH coefficients.\n Q = P + np.dot(H.T, H)\n fodf_sh = _solve_cholesky(Q, z)\n\n # Sample the FOD using the regularization sphere and compute k.\n fodf = np.dot(B_reg, fodf_sh)\n where_fodf_small_last = where_fodf_small\n where_fodf_small = (fodf < threshold).nonzero()[0]\n\n if (len(where_fodf_small) == len(where_fodf_small_last) and\n (where_fodf_small == where_fodf_small_last).all()):\n break\n else:\n msg = 'maximum number of iterations exceeded - failed to converge'\n warnings.warn(msg)\n\n return fodf_sh, num_it\n\n\ndef odf_deconv(odf_sh, R, B_reg, lambda_=1., tau=0.1, r2_term=False):\n r\"\"\" ODF constrained-regularized spherical deconvolution using\n the Sharpening Deconvolution Transform (SDT) [1]_, [2]_.\n\n Parameters\n ----------\n odf_sh : ndarray (``(sh_order + 1)*(sh_order + 2)/2``,)\n ndarray of SH coefficients for the ODF spherical function to be\n deconvolved\n R : ndarray (``(sh_order + 1)(sh_order + 2)/2``, ``(sh_order + 1)(sh_order + 2)/2``)\n SDT matrix in SH basis\n B_reg : ndarray (``(sh_order + 1)(sh_order + 2)/2``, ``(sh_order + 1)(sh_order + 2)/2``)\n SH basis matrix used for deconvolution\n lambda_ : float\n lambda parameter in minimization equation (default 1.0)\n tau : float\n threshold (tau *max(fODF)) controlling the amplitude below\n which the corresponding fODF is assumed to be zero.\n r2_term : bool\n True if ODF is computed from model that uses the $r^2$ term in the\n integral. Recall that Tuch's ODF (used in Q-ball Imaging [1]_) and\n the true normalized ODF definition differ from a $r^2$ term in the ODF\n integral. The original Sharpening Deconvolution Transform (SDT)\n technique [2]_ is expecting Tuch's ODF without the $r^2$ (see [3]_ for\n the mathematical details). Now, this function supports ODF that have\n been computed using the $r^2$ term because the proper analytical\n response function has be derived. For example, models such as DSI,\n GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved\n with the r2_term=True.\n\n Returns\n -------\n fodf_sh : ndarray (``(sh_order + 1)(sh_order + 2)/2``,)\n Spherical harmonics coefficients of the constrained-regularized fiber\n ODF\n num_it : int\n Number of iterations in the constrained-regularization used for\n convergence\n\n References\n ----------\n .. [1] Tuch, D. MRM 2004. Q-Ball Imaging.\n .. [2] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and\n Probabilistic Tractography Based on Complex Fibre Orientation\n Distributions\n .. [3] Descoteaux, M, PhD thesis, INRIA Sophia-Antipolis, 2008.\n \"\"\"\n # In ConstrainedSDTModel.fit, odf_sh is divided by its norm (Z) and\n # sometimes the norm is 0 which creates NaNs.\n if np.any(np.isnan(odf_sh)):\n return np.zeros_like(odf_sh), 0\n\n # Generate initial fODF estimate, which is the ODF truncated at SH order 4\n fodf_sh = np.linalg.lstsq(R, odf_sh, rcond=-1)[0]\n fodf_sh[15:] = 0\n\n fodf = np.dot(B_reg, fodf_sh)\n\n # if sharpening a q-ball odf (it is NOT properly normalized), we need to\n # force normalization otherwise, for DSI, CSA, SHORE, Tensor odfs, they are\n # normalized by construction\n if ~r2_term:\n Z = np.linalg.norm(fodf)\n fodf_sh /= Z\n\n threshold = tau * np.max(np.dot(B_reg, fodf_sh))\n\n k = []\n convergence = 50\n for num_it in range(1, convergence + 1):\n A = np.dot(B_reg, fodf_sh)\n k2 = np.nonzero(A < threshold)[0]\n\n if (k2.shape[0] + R.shape[0]) < B_reg.shape[1]:\n warnings.warn(\n 'too few negative directions identified - failed to converge')\n return fodf_sh, num_it\n\n if num_it > 1 and k.shape[0] == k2.shape[0]:\n if (k == k2).all():\n return fodf_sh, num_it\n\n k = k2\n M = np.concatenate((R, lambda_ * B_reg[k, :]))\n ODF = np.concatenate((odf_sh, np.zeros(k.shape)))\n try:\n fodf_sh = np.linalg.lstsq(M, ODF, rcond=-1)[0]\n except np.linalg.LinAlgError:\n # SVD did not converge in Linear Least Squares in current\n # voxel. Proceeding with initial SH estimate for this voxel.\n pass\n\n warnings.warn('maximum number of iterations exceeded - failed to converge')\n return fodf_sh, num_it\n\n\ndef odf_sh_to_sharp(odfs_sh, sphere, basis=None, ratio=3 / 15., sh_order=8,\n lambda_=1., tau=0.1, r2_term=False):\n r\"\"\" Sharpen odfs using the sharpening deconvolution transform [2]_\n\n This function can be used to sharpen any smooth ODF spherical function. In\n theory, this should only be used to sharpen QballModel ODFs, but in\n practice, one can play with the deconvolution ratio and sharpen almost any\n ODF-like spherical function. The constrained-regularization is stable and\n will not only sharpen the ODF peaks but also regularize the noisy peaks.\n\n Parameters\n ----------\n odfs_sh : ndarray (``(sh_order + 1)*(sh_order + 2)/2``, )\n array of odfs expressed as spherical harmonics coefficients\n sphere : Sphere\n sphere used to build the regularization matrix\n basis : {None, 'tournier07', 'descoteaux07'}\n different spherical harmonic basis:\n ``None`` for the default DIPY basis,\n ``tournier07`` for the Tournier 2007 [4]_ basis, and\n ``descoteaux07`` for the Descoteaux 2007 [3]_ basis\n (``None`` defaults to ``descoteaux07``).\n ratio : float,\n ratio of the smallest vs the largest eigenvalue of the single prolate\n tensor response function (:math:`\\frac{\\lambda_2}{\\lambda_1}`)\n sh_order : int\n maximal SH order of the SH representation\n lambda_ : float\n lambda parameter (see odfdeconv) (default 1.0)\n tau : float\n tau parameter in the L matrix construction (see odfdeconv)\n (default 0.1)\n r2_term : bool\n True if ODF is computed from model that uses the $r^2$ term in the\n integral. Recall that Tuch's ODF (used in Q-ball Imaging [1]_) and\n the true normalized ODF definition differ from a $r^2$ term in the ODF\n integral. The original Sharpening Deconvolution Transform (SDT)\n technique [2]_ is expecting Tuch's ODF without the $r^2$ (see [3]_ for\n the mathematical details). Now, this function supports ODF that have\n been computed using the $r^2$ term because the proper analytical\n response function has be derived. For example, models such as DSI,\n GQI, SHORE, CSA, Tensor, Multi-tensor ODFs, should now be deconvolved\n with the r2_term=True.\n\n Returns\n -------\n fodf_sh : ndarray\n sharpened odf expressed as spherical harmonics coefficients\n\n References\n ----------\n .. [1] Tuch, D. MRM 2004. Q-Ball Imaging.\n .. [2] Descoteaux, M., et al. IEEE TMI 2009. Deterministic and\n Probabilistic Tractography Based on Complex Fibre Orientation\n Distributions\n .. [3] Descoteaux, M., Angelino, E., Fitzgibbons, S. and Deriche, R.\n Regularized, Fast, and Robust Analytical Q-ball Imaging.\n Magn. Reson. Med. 2007;58:497-510.\n .. [4] Tournier J.D., Calamante F. and Connelly A. Robust determination\n of the fibre orientation distribution in diffusion MRI:\n Non-negativity constrained super-resolved spherical deconvolution.\n NeuroImage. 2007;35(4):1459-1472.\n\n \"\"\"\n r, theta, phi = cart2sphere(sphere.x, sphere.y, sphere.z)\n real_sym_sh = sph_harm_lookup[basis]\n\n B_reg, m, n = real_sym_sh(sh_order, theta, phi)\n R, P = forward_sdt_deconv_mat(ratio, n, r2_term=r2_term)\n\n # scale lambda to account for differences in the number of\n # SH coefficients and number of mapped directions\n lambda_ = lambda_ * R.shape[0] * R[0, 0] / B_reg.shape[0]\n\n fodf_sh = np.zeros(odfs_sh.shape)\n\n for index in ndindex(odfs_sh.shape[:-1]):\n fodf_sh[index], num_it = odf_deconv(odfs_sh[index], R, B_reg,\n lambda_=lambda_, tau=tau,\n r2_term=r2_term)\n\n return fodf_sh\n\n\ndef fa_superior(FA, fa_thr):\n \"\"\" Check that the FA is greater than the FA threshold\n\n Parameters\n ----------\n FA : array\n Fractional Anisotropy\n fa_thr : int\n FA threshold\n\n Returns\n -------\n True when the FA value is greater than the FA threshold, otherwise False.\n \"\"\"\n return FA > fa_thr\n\n\ndef fa_inferior(FA, fa_thr):\n \"\"\" Check that the FA is lower than the FA threshold\n\n Parameters\n ----------\n FA : array\n Fractional Anisotropy\n fa_thr : int\n FA threshold\n\n Returns\n -------\n True when the FA value is lower than the FA threshold, otherwise False.\n \"\"\"\n return FA < fa_thr\n\n\ndef auto_response(gtab, data, roi_center=None, roi_radius=10, fa_thr=0.7,\n fa_callable=fa_superior, return_number_of_voxels=False):\n \"\"\" Automatic estimation of response function using FA.\n\n Parameters\n ----------\n gtab : GradientTable\n data : ndarray\n diffusion data\n roi_center : tuple, (3,)\n Center of ROI in data. If center is None, it is assumed that it is\n the center of the volume with shape `data.shape[:3]`.\n roi_radius : int\n radius of cubic ROI\n fa_thr : float\n FA threshold\n fa_callable : callable\n A callable that defines an operation that compares FA with the fa_thr.\n The operator should have two positional arguments\n (e.g., `fa_operator(FA, fa_thr)`) and it should return a bool array.\n return_number_of_voxels : bool\n If True, returns the number of voxels used for estimating the response\n function.\n\n Returns\n -------\n response : tuple, (2,)\n (`evals`, `S0`)\n ratio : float\n The ratio between smallest versus largest eigenvalue of the response.\n number of voxels : int (optional)\n The number of voxels used for estimating the response function.\n\n Notes\n -----\n In CSD there is an important pre-processing step: the estimation of the\n fiber response function. In order to do this we look for voxels with very\n anisotropic configurations. For example we can use an ROI (20x20x20) at\n the center of the volume and store the signal values for the voxels with\n FA values higher than 0.7. Of course, if we haven't precalculated FA we\n need to fit a Tensor model to the datasets. Which is what we do in this\n function.\n\n For the response we also need to find the average S0 in the ROI. This is\n possible using `gtab.b0s_mask()` we can find all the S0 volumes (which\n correspond to b-values equal 0) in the dataset.\n\n The `response` consists always of a prolate tensor created by averaging\n the highest and second highest eigenvalues in the ROI with FA higher than\n threshold. We also include the average S0s.\n\n We also return the `ratio` which is used for the SDT models. If requested,\n the number of voxels used for estimating the response function is also\n returned, which can be used to judge the fidelity of the response function.\n As a rule of thumb, at least 300 voxels should be used to estimate a good\n response function (see [1]_).\n\n References\n ----------\n .. [1] Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the\n fiber orientation density function from diffusion-weighted MRI\n data using spherical deconvolution\n \"\"\"\n\n ten = TensorModel(gtab)\n if roi_center is None:\n ci, cj, ck = np.array(data.shape[:3]) // 2\n else:\n ci, cj, ck = roi_center\n w = roi_radius\n roi = data[int(ci - w): int(ci + w),\n int(cj - w): int(cj + w),\n int(ck - w): int(ck + w)]\n tenfit = ten.fit(roi)\n FA = fractional_anisotropy(tenfit.evals)\n FA[np.isnan(FA)] = 0\n indices = np.where(fa_callable(FA, fa_thr))\n\n if indices[0].size == 0:\n msg = \"No voxel with a FA higher than \" + str(fa_thr) + \" were found.\"\n msg += \" Try a larger roi or a lower threshold.\"\n warnings.warn(msg, UserWarning)\n\n lambdas = tenfit.evals[indices][:, :2]\n S0s = roi[indices][:, np.nonzero(gtab.b0s_mask)[0]]\n\n response, ratio = _get_response(S0s, lambdas)\n\n if return_number_of_voxels:\n return response, ratio, indices[0].size\n\n return response, ratio\n\n\ndef response_from_mask(gtab, data, mask):\n \"\"\" Estimate the response function from a given mask.\n\n Parameters\n ----------\n gtab : GradientTable\n data : ndarray\n Diffusion data\n mask : ndarray\n Mask to use for the estimation of the response function. For example a\n mask of the white matter voxels with FA values higher than 0.7\n (see [1]_).\n\n Returns\n -------\n response : tuple, (2,)\n (`evals`, `S0`)\n ratio : float\n The ratio between smallest versus largest eigenvalue of the response.\n\n Notes\n -----\n See csdeconv.auto_response() or csdeconv.recursive_response() if you don't\n have a computed mask for the response function estimation.\n\n References\n ----------\n .. [1] Tournier, J.D., et al. NeuroImage 2004. Direct estimation of the\n fiber orientation density function from diffusion-weighted MRI\n data using spherical deconvolution\n \"\"\"\n\n ten = TensorModel(gtab)\n indices = np.where(mask > 0)\n\n if indices[0].size == 0:\n msg = \"No voxel in mask with value > 0 were found.\"\n warnings.warn(msg, UserWarning)\n return (np.nan, np.nan), np.nan\n\n tenfit = ten.fit(data[indices])\n lambdas = tenfit.evals[:, :2]\n S0s = data[indices][:, np.nonzero(gtab.b0s_mask)[0]]\n\n return _get_response(S0s, lambdas)\n\n\ndef _get_response(S0s, lambdas):\n S0 = np.mean(S0s)\n l01 = np.mean(lambdas, axis=0)\n evals = np.array([l01[0], l01[1], l01[1]])\n response = (evals, S0)\n ratio = evals[1] / evals[0]\n return response, ratio\n\n\ndef recursive_response(gtab, data, mask=None, sh_order=8, peak_thr=0.01,\n init_fa=0.08, init_trace=0.0021, iter=8,\n convergence=0.001, parallel=True, nbr_processes=None,\n sphere=default_sphere):\n \"\"\" Recursive calibration of response function using peak threshold\n\n Parameters\n ----------\n gtab : GradientTable\n data : ndarray\n diffusion data\n mask : ndarray, optional\n mask for recursive calibration, for example a white matter mask. It has\n shape `data.shape[0:3]` and dtype=bool. Default: use the entire data\n array.\n sh_order : int, optional\n maximal spherical harmonics order. Default: 8\n peak_thr : float, optional\n peak threshold, how large the second peak can be relative to the first\n peak in order to call it a single fiber population [1]. Default: 0.01\n init_fa : float, optional\n FA of the initial 'fat' response function (tensor). Default: 0.08\n init_trace : float, optional\n trace of the initial 'fat' response function (tensor). Default: 0.0021\n iter : int, optional\n maximum number of iterations for calibration. Default: 8.\n convergence : float, optional\n convergence criterion, maximum relative change of SH\n coefficients. Default: 0.001.\n parallel : bool, optional\n Whether to use parallelization in peak-finding during the calibration\n procedure. Default: True\n nbr_processes: int\n If `parallel` is True, the number of subprocesses to use\n (default multiprocessing.cpu_count()).\n sphere : Sphere, optional.\n The sphere used for peak finding. Default: default_sphere.\n\n Returns\n -------\n response : ndarray\n response function in SH coefficients\n\n Notes\n -----\n In CSD there is an important pre-processing step: the estimation of the\n fiber response function. Using an FA threshold is not a very robust method.\n It is dependent on the dataset (non-informed used subjectivity), and still\n depends on the diffusion tensor (FA and first eigenvector),\n which has low accuracy at high b-value. This function recursively\n calibrates the response function, for more information see [1].\n\n References\n ----------\n .. [1] Tax, C.M.W., et al. NeuroImage 2014. Recursive calibration of\n the fiber response function for spherical deconvolution of\n diffusion MRI data.\n \"\"\"\n S0 = 1.\n evals = fa_trace_to_lambdas(init_fa, init_trace)\n res_obj = (evals, S0)\n\n if mask is None:\n data = data.reshape(-1, data.shape[-1])\n else:\n data = data[mask]\n\n n = np.arange(0, sh_order + 1, 2)\n where_dwi = lazy_index(~gtab.b0s_mask)\n response_p = np.ones(len(n))\n\n for _ in range(iter):\n r_sh_all = np.zeros(len(n))\n csd_model = ConstrainedSphericalDeconvModel(gtab, res_obj,\n sh_order=sh_order)\n\n csd_peaks = peaks_from_model(model=csd_model,\n data=data,\n sphere=sphere,\n relative_peak_threshold=peak_thr,\n min_separation_angle=25,\n parallel=parallel,\n nbr_processes=nbr_processes)\n\n dirs = csd_peaks.peak_dirs\n vals = csd_peaks.peak_values\n single_peak_mask = (vals[:, 1] / vals[:, 0]) < peak_thr\n data = data[single_peak_mask]\n dirs = dirs[single_peak_mask]\n\n for num_vox in range(data.shape[0]):\n rotmat = vec2vec_rotmat(dirs[num_vox, 0], np.array([0, 0, 1]))\n\n rot_gradients = np.dot(rotmat, gtab.gradients.T).T\n\n x, y, z = rot_gradients[where_dwi].T\n r, theta, phi = cart2sphere(x, y, z)\n # for the gradient sphere\n B_dwi = real_sph_harm(0, n, theta[:, None], phi[:, None])\n r_sh_all += np.linalg.lstsq(B_dwi, data[num_vox, where_dwi],\n rcond=-1)[0]\n\n response = r_sh_all / data.shape[0]\n res_obj = AxSymShResponse(data[:, gtab.b0s_mask].mean(), response)\n\n change = abs((response_p - response) / response_p)\n if all(change < convergence):\n break\n\n response_p = response\n\n return res_obj\n\n\ndef fa_trace_to_lambdas(fa=0.08, trace=0.0021):\n lambda1 = (trace / 3.) * (1 + 2 * fa / (3 - 2 * fa ** 2) ** (1 / 2.))\n lambda2 = (trace / 3.) * (1 - fa / (3 - 2 * fa ** 2) ** (1 / 2.))\n evals = np.array([lambda1, lambda2, lambda2])\n return evals\n" ]
[ [ "numpy.diag", "numpy.arange", "numpy.eye", "numpy.ones", "numpy.testing.assert_array_equal", "numpy.prod" ], [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "numpy.arange", "numpy.testing.assert_array_equal", "numpy.testing.assert_raises", "numpy.array", "numpy.testing.assert_array_almost_equal" ], [ "numpy.testing.assert_equal", "numpy.dot", "numpy.linalg.inv", "numpy.eye", "numpy.median", "numpy.testing.assert_array_equal", "numpy.concatenate", "numpy.testing.assert_almost_equal", "numpy.mean", "numpy.corrcoef", "numpy.argsort", "numpy.array", "numpy.zeros", "scipy.linalg.eig" ], [ "numpy.diag", "numpy.dot", "numpy.allclose", "numpy.linalg.inv", "numpy.arange", "numpy.eye", "numpy.all", "numpy.zeros" ], [ "numpy.testing.dec.skipif", "numpy.testing.assert_equal", "numpy.testing.run_module_suite", "numpy.random.standard_normal", "numpy.ones", "numpy.round", "numpy.std", "numpy.testing.assert_raises", "numpy.testing.assert_", "numpy.zeros", "numpy.testing.assert_array_almost_equal" ], [ "numpy.dot", "numpy.min", "numpy.reshape", "numpy.arange", "numpy.save", "numpy.ones", "numpy.ceil", "numpy.append", "scipy.optimize.fmin", "numpy.column_stack", "numpy.load", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "numpy.testing.Tester" ], [ "numpy.testing.run_module_suite", "numpy.save", "numpy.testing.assert_array_equal", "numpy.testing.assert_raises", "numpy.savetxt", "numpy.ravel", "numpy.array" ], [ "numpy.diag", "numpy.dot", "scipy.linalg.LinAlgError", "numpy.sqrt", "numpy.asarray", "numpy.concatenate", "numpy.mean", "numpy.any", "numpy.zeros_like", "numpy.where", "scipy.special.lpn", "numpy.arange", "numpy.eye", "scipy.linalg.lapack.get_lapack_funcs", "numpy.zeros", "scipy.special.gamma", "numpy.nonzero", "numpy.power", "numpy.isnan", "numpy.linalg.lstsq", "numpy.array", "numpy.sum", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
inaber0420/glTF-Modo-IO
[ "57f99aee4e9b6177d25b465b87d731b54a625532" ]
[ "addons/io_scene_gltf2/blender/exp/gltf2_blender_extract.py" ]
[ "# Copyright 2018-2021 The glTF-Blender-IO 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\nimport numpy as np\nfrom mathutils import Vector\n\nfrom . import gltf2_blender_export_keys\nfrom ...io.com.gltf2_io_debug import print_console\nfrom io_scene_gltf2.blender.exp import gltf2_blender_gather_skins\n\n\ndef extract_primitives(glTF, blender_mesh, library, blender_object, blender_vertex_groups, modifiers, export_settings):\n \"\"\"Extract primitives from a mesh.\"\"\"\n print_console('INFO', 'Extracting primitive: ' + blender_mesh.name)\n\n use_normals = export_settings[gltf2_blender_export_keys.NORMALS]\n if use_normals:\n blender_mesh.calc_normals_split()\n\n use_tangents = False\n if use_normals and export_settings[gltf2_blender_export_keys.TANGENTS]:\n if blender_mesh.uv_layers.active and len(blender_mesh.uv_layers) > 0:\n try:\n blender_mesh.calc_tangents()\n use_tangents = True\n except Exception:\n print_console('WARNING', 'Could not calculate tangents. Please try to triangulate the mesh first.')\n\n tex_coord_max = 0\n if export_settings[gltf2_blender_export_keys.TEX_COORDS]:\n if blender_mesh.uv_layers.active:\n tex_coord_max = len(blender_mesh.uv_layers)\n\n color_max = 0\n if export_settings[gltf2_blender_export_keys.COLORS]:\n color_max = len(blender_mesh.vertex_colors)\n\n armature = None\n skin = None\n if blender_vertex_groups and export_settings[gltf2_blender_export_keys.SKINS]:\n if modifiers is not None:\n modifiers_dict = {m.type: m for m in modifiers}\n if \"ARMATURE\" in modifiers_dict:\n modifier = modifiers_dict[\"ARMATURE\"]\n armature = modifier.object\n\n # Skin must be ignored if the object is parented to a bone of the armature\n # (This creates an infinite recursive error)\n # So ignoring skin in that case\n is_child_of_arma = (\n armature and\n blender_object and\n blender_object.parent_type == \"BONE\" and\n blender_object.parent.name == armature.name\n )\n if is_child_of_arma:\n armature = None\n\n if armature:\n skin = gltf2_blender_gather_skins.gather_skin(armature, export_settings)\n if not skin:\n armature = None\n\n use_morph_normals = use_normals and export_settings[gltf2_blender_export_keys.MORPH_NORMAL]\n use_morph_tangents = use_morph_normals and use_tangents and export_settings[gltf2_blender_export_keys.MORPH_TANGENT]\n\n key_blocks = []\n if blender_mesh.shape_keys and export_settings[gltf2_blender_export_keys.MORPH]:\n key_blocks = [\n key_block\n for key_block in blender_mesh.shape_keys.key_blocks\n if not (key_block == key_block.relative_key or key_block.mute)\n ]\n\n use_materials = export_settings[gltf2_blender_export_keys.MATERIALS]\n\n # Fetch vert positions and bone data (joint,weights)\n\n locs, morph_locs = __get_positions(blender_mesh, key_blocks, armature, blender_object, export_settings)\n if skin:\n vert_bones, num_joint_sets = __get_bone_data(blender_mesh, skin, blender_vertex_groups)\n\n # In Blender there is both per-vert data, like position, and also per-loop\n # (loop=corner-of-poly) data, like normals or UVs. glTF only has per-vert\n # data, so we need to split Blender verts up into potentially-multiple glTF\n # verts.\n #\n # First, we'll collect a \"dot\" for every loop: a struct that stores all the\n # attributes at that loop, namely the vertex index (which determines all\n # per-vert data), and all the per-loop data like UVs, etc.\n #\n # Each unique dot will become one unique glTF vert.\n\n # List all fields the dot struct needs.\n dot_fields = [('vertex_index', np.uint32)]\n if use_normals:\n dot_fields += [('nx', np.float32), ('ny', np.float32), ('nz', np.float32)]\n if use_tangents:\n dot_fields += [('tx', np.float32), ('ty', np.float32), ('tz', np.float32), ('tw', np.float32)]\n for uv_i in range(tex_coord_max):\n dot_fields += [('uv%dx' % uv_i, np.float32), ('uv%dy' % uv_i, np.float32)]\n for col_i in range(color_max):\n dot_fields += [\n ('color%dr' % col_i, np.float32),\n ('color%dg' % col_i, np.float32),\n ('color%db' % col_i, np.float32),\n ('color%da' % col_i, np.float32),\n ]\n if use_morph_normals:\n for morph_i, _ in enumerate(key_blocks):\n dot_fields += [\n ('morph%dnx' % morph_i, np.float32),\n ('morph%dny' % morph_i, np.float32),\n ('morph%dnz' % morph_i, np.float32),\n ]\n\n dots = np.empty(len(blender_mesh.loops), dtype=np.dtype(dot_fields))\n\n vidxs = np.empty(len(blender_mesh.loops))\n blender_mesh.loops.foreach_get('vertex_index', vidxs)\n dots['vertex_index'] = vidxs\n del vidxs\n\n if use_normals:\n kbs = key_blocks if use_morph_normals else []\n normals, morph_normals = __get_normals(\n blender_mesh, kbs, armature, blender_object, export_settings\n )\n dots['nx'] = normals[:, 0]\n dots['ny'] = normals[:, 1]\n dots['nz'] = normals[:, 2]\n del normals\n for morph_i, ns in enumerate(morph_normals):\n dots['morph%dnx' % morph_i] = ns[:, 0]\n dots['morph%dny' % morph_i] = ns[:, 1]\n dots['morph%dnz' % morph_i] = ns[:, 2]\n del morph_normals\n\n if use_tangents:\n tangents = __get_tangents(blender_mesh, armature, blender_object, export_settings)\n dots['tx'] = tangents[:, 0]\n dots['ty'] = tangents[:, 1]\n dots['tz'] = tangents[:, 2]\n del tangents\n signs = __get_bitangent_signs(blender_mesh, armature, blender_object, export_settings)\n dots['tw'] = signs\n del signs\n\n for uv_i in range(tex_coord_max):\n uvs = __get_uvs(blender_mesh, uv_i)\n dots['uv%dx' % uv_i] = uvs[:, 0]\n dots['uv%dy' % uv_i] = uvs[:, 1]\n del uvs\n\n for col_i in range(color_max):\n colors = __get_colors(blender_mesh, col_i)\n dots['color%dr' % col_i] = colors[:, 0]\n dots['color%dg' % col_i] = colors[:, 1]\n dots['color%db' % col_i] = colors[:, 2]\n dots['color%da' % col_i] = colors[:, 3]\n del colors\n\n # Calculate triangles and sort them into primitives.\n\n blender_mesh.calc_loop_triangles()\n loop_indices = np.empty(len(blender_mesh.loop_triangles) * 3, dtype=np.uint32)\n blender_mesh.loop_triangles.foreach_get('loops', loop_indices)\n\n prim_indices = {} # maps material index to TRIANGLES-style indices into dots\n\n if use_materials == \"NONE\": # Only for None. For placeholder and export, keep primitives\n # Put all vertices into one primitive\n prim_indices[-1] = loop_indices\n\n else:\n # Bucket by material index.\n\n tri_material_idxs = np.empty(len(blender_mesh.loop_triangles), dtype=np.uint32)\n blender_mesh.loop_triangles.foreach_get('material_index', tri_material_idxs)\n loop_material_idxs = np.repeat(tri_material_idxs, 3) # material index for every loop\n unique_material_idxs = np.unique(tri_material_idxs)\n del tri_material_idxs\n\n for material_idx in unique_material_idxs:\n prim_indices[material_idx] = loop_indices[loop_material_idxs == material_idx]\n\n # Create all the primitives.\n\n primitives = []\n\n for material_idx, dot_indices in prim_indices.items():\n # Extract just dots used by this primitive, deduplicate them, and\n # calculate indices into this deduplicated list.\n prim_dots = dots[dot_indices]\n prim_dots, indices = np.unique(prim_dots, return_inverse=True)\n\n if len(prim_dots) == 0:\n continue\n\n # Now just move all the data for prim_dots into attribute arrays\n\n attributes = {}\n\n blender_idxs = prim_dots['vertex_index']\n\n attributes['POSITION'] = locs[blender_idxs]\n\n for morph_i, vs in enumerate(morph_locs):\n attributes['MORPH_POSITION_%d' % morph_i] = vs[blender_idxs]\n\n if use_normals:\n normals = np.empty((len(prim_dots), 3), dtype=np.float32)\n normals[:, 0] = prim_dots['nx']\n normals[:, 1] = prim_dots['ny']\n normals[:, 2] = prim_dots['nz']\n attributes['NORMAL'] = normals\n\n if use_tangents:\n tangents = np.empty((len(prim_dots), 4), dtype=np.float32)\n tangents[:, 0] = prim_dots['tx']\n tangents[:, 1] = prim_dots['ty']\n tangents[:, 2] = prim_dots['tz']\n tangents[:, 3] = prim_dots['tw']\n attributes['TANGENT'] = tangents\n\n if use_morph_normals:\n for morph_i, _ in enumerate(key_blocks):\n ns = np.empty((len(prim_dots), 3), dtype=np.float32)\n ns[:, 0] = prim_dots['morph%dnx' % morph_i]\n ns[:, 1] = prim_dots['morph%dny' % morph_i]\n ns[:, 2] = prim_dots['morph%dnz' % morph_i]\n attributes['MORPH_NORMAL_%d' % morph_i] = ns\n\n if use_morph_tangents:\n attributes['MORPH_TANGENT_%d' % morph_i] = __calc_morph_tangents(normals, ns, tangents)\n\n for tex_coord_i in range(tex_coord_max):\n uvs = np.empty((len(prim_dots), 2), dtype=np.float32)\n uvs[:, 0] = prim_dots['uv%dx' % tex_coord_i]\n uvs[:, 1] = prim_dots['uv%dy' % tex_coord_i]\n attributes['TEXCOORD_%d' % tex_coord_i] = uvs\n\n for color_i in range(color_max):\n colors = np.empty((len(prim_dots), 4), dtype=np.float32)\n colors[:, 0] = prim_dots['color%dr' % color_i]\n colors[:, 1] = prim_dots['color%dg' % color_i]\n colors[:, 2] = prim_dots['color%db' % color_i]\n colors[:, 3] = prim_dots['color%da' % color_i]\n attributes['COLOR_%d' % color_i] = colors\n\n if skin:\n joints = [[] for _ in range(num_joint_sets)]\n weights = [[] for _ in range(num_joint_sets)]\n\n for vi in blender_idxs:\n bones = vert_bones[vi]\n for j in range(0, 4 * num_joint_sets):\n if j < len(bones):\n joint, weight = bones[j]\n else:\n joint, weight = 0, 0.0\n joints[j//4].append(joint)\n weights[j//4].append(weight)\n\n for i, (js, ws) in enumerate(zip(joints, weights)):\n attributes['JOINTS_%d' % i] = js\n attributes['WEIGHTS_%d' % i] = ws\n\n primitives.append({\n 'attributes': attributes,\n 'indices': indices,\n 'material': material_idx,\n })\n\n if export_settings['gltf_loose_edges']:\n # Find loose edges\n loose_edges = [e for e in blender_mesh.edges if e.is_loose]\n blender_idxs = [vi for e in loose_edges for vi in e.vertices]\n\n if blender_idxs:\n # Export one glTF vert per unique Blender vert in a loose edge\n blender_idxs = np.array(blender_idxs, dtype=np.uint32)\n blender_idxs, indices = np.unique(blender_idxs, return_inverse=True)\n\n attributes = {}\n\n attributes['POSITION'] = locs[blender_idxs]\n\n for morph_i, vs in enumerate(morph_locs):\n attributes['MORPH_POSITION_%d' % morph_i] = vs[blender_idxs]\n\n if skin:\n joints = [[] for _ in range(num_joint_sets)]\n weights = [[] for _ in range(num_joint_sets)]\n\n for vi in blender_idxs:\n bones = vert_bones[vi]\n for j in range(0, 4 * num_joint_sets):\n if j < len(bones):\n joint, weight = bones[j]\n else:\n joint, weight = 0, 0.0\n joints[j//4].append(joint)\n weights[j//4].append(weight)\n\n for i, (js, ws) in enumerate(zip(joints, weights)):\n attributes['JOINTS_%d' % i] = js\n attributes['WEIGHTS_%d' % i] = ws\n\n primitives.append({\n 'attributes': attributes,\n 'indices': indices,\n 'mode': 1, # LINES\n 'material': 0,\n })\n\n if export_settings['gltf_loose_points']:\n # Find loose points\n verts_in_edge = set(vi for e in blender_mesh.edges for vi in e.vertices)\n blender_idxs = [\n vi for vi, _ in enumerate(blender_mesh.vertices)\n if vi not in verts_in_edge\n ]\n\n if blender_idxs:\n blender_idxs = np.array(blender_idxs, dtype=np.uint32)\n\n attributes = {}\n\n attributes['POSITION'] = locs[blender_idxs]\n\n for morph_i, vs in enumerate(morph_locs):\n attributes['MORPH_POSITION_%d' % morph_i] = vs[blender_idxs]\n\n if skin:\n joints = [[] for _ in range(num_joint_sets)]\n weights = [[] for _ in range(num_joint_sets)]\n\n for vi in blender_idxs:\n bones = vert_bones[vi]\n for j in range(0, 4 * num_joint_sets):\n if j < len(bones):\n joint, weight = bones[j]\n else:\n joint, weight = 0, 0.0\n joints[j//4].append(joint)\n weights[j//4].append(weight)\n\n for i, (js, ws) in enumerate(zip(joints, weights)):\n attributes['JOINTS_%d' % i] = js\n attributes['WEIGHTS_%d' % i] = ws\n\n primitives.append({\n 'attributes': attributes,\n 'mode': 0, # POINTS\n 'material': 0,\n })\n\n print_console('INFO', 'Primitives created: %d' % len(primitives))\n\n return primitives\n\n\ndef __get_positions(blender_mesh, key_blocks, armature, blender_object, export_settings):\n locs = np.empty(len(blender_mesh.vertices) * 3, dtype=np.float32)\n source = key_blocks[0].relative_key.data if key_blocks else blender_mesh.vertices\n source.foreach_get('co', locs)\n locs = locs.reshape(len(blender_mesh.vertices), 3)\n\n morph_locs = []\n for key_block in key_blocks:\n vs = np.empty(len(blender_mesh.vertices) * 3, dtype=np.float32)\n key_block.data.foreach_get('co', vs)\n vs = vs.reshape(len(blender_mesh.vertices), 3)\n morph_locs.append(vs)\n\n # Transform for skinning\n if armature and blender_object:\n apply_matrix = armature.matrix_world.inverted_safe() @ blender_object.matrix_world\n loc_transform = armature.matrix_world @ apply_matrix\n\n loc_transform = blender_object.matrix_world\n locs[:] = __apply_mat_to_all(loc_transform, locs)\n for vs in morph_locs:\n vs[:] = __apply_mat_to_all(loc_transform, vs)\n\n # glTF stores deltas in morph targets\n for vs in morph_locs:\n vs -= locs\n\n if export_settings[gltf2_blender_export_keys.YUP]:\n __zup2yup(locs)\n for vs in morph_locs:\n __zup2yup(vs)\n\n return locs, morph_locs\n\n\ndef __get_normals(blender_mesh, key_blocks, armature, blender_object, export_settings):\n \"\"\"Get normal for each loop.\"\"\"\n if key_blocks:\n normals = key_blocks[0].relative_key.normals_split_get()\n normals = np.array(normals, dtype=np.float32)\n else:\n normals = np.empty(len(blender_mesh.loops) * 3, dtype=np.float32)\n blender_mesh.calc_normals_split()\n blender_mesh.loops.foreach_get('normal', normals)\n\n normals = normals.reshape(len(blender_mesh.loops), 3)\n\n morph_normals = []\n for key_block in key_blocks:\n ns = np.array(key_block.normals_split_get(), dtype=np.float32)\n ns = ns.reshape(len(blender_mesh.loops), 3)\n morph_normals.append(ns)\n\n # Transform for skinning\n if armature and blender_object:\n apply_matrix = (armature.matrix_world.inverted_safe() @ blender_object.matrix_world)\n apply_matrix = apply_matrix.to_3x3().inverted_safe().transposed()\n normal_transform = armature.matrix_world.to_3x3() @ apply_matrix\n\n normals[:] = __apply_mat_to_all(normal_transform, normals)\n __normalize_vecs(normals)\n for ns in morph_normals:\n ns[:] = __apply_mat_to_all(normal_transform, ns)\n __normalize_vecs(ns)\n\n for ns in [normals, *morph_normals]:\n # Replace zero normals with the unit UP vector.\n # Seems to happen sometimes with degenerate tris?\n is_zero = ~ns.any(axis=1)\n ns[is_zero, 2] = 1\n\n # glTF stores deltas in morph targets\n for ns in morph_normals:\n ns -= normals\n\n if export_settings[gltf2_blender_export_keys.YUP]:\n __zup2yup(normals)\n for ns in morph_normals:\n __zup2yup(ns)\n\n return normals, morph_normals\n\n\ndef __get_tangents(blender_mesh, armature, blender_object, export_settings):\n \"\"\"Get an array of the tangent for each loop.\"\"\"\n tangents = np.empty(len(blender_mesh.loops) * 3, dtype=np.float32)\n blender_mesh.loops.foreach_get('tangent', tangents)\n tangents = tangents.reshape(len(blender_mesh.loops), 3)\n\n # Transform for skinning\n if armature and blender_object:\n apply_matrix = armature.matrix_world.inverted_safe() @ blender_object.matrix_world\n tangent_transform = apply_matrix.to_quaternion().to_matrix()\n tangents = __apply_mat_to_all(tangent_transform, tangents)\n __normalize_vecs(tangents)\n\n if export_settings[gltf2_blender_export_keys.YUP]:\n __zup2yup(tangents)\n\n return tangents\n\n\ndef __get_bitangent_signs(blender_mesh, armature, blender_object, export_settings):\n signs = np.empty(len(blender_mesh.loops), dtype=np.float32)\n blender_mesh.loops.foreach_get('bitangent_sign', signs)\n\n # Transform for skinning\n if armature and blender_object:\n # Bitangent signs should flip when handedness changes\n # TODO: confirm\n apply_matrix = armature.matrix_world.inverted_safe() @ blender_object.matrix_world\n tangent_transform = apply_matrix.to_quaternion().to_matrix()\n flipped = tangent_transform.determinant() < 0\n if flipped:\n signs *= -1\n\n # No change for Zup -> Yup\n\n return signs\n\n\ndef __calc_morph_tangents(normals, morph_normal_deltas, tangents):\n # TODO: check if this works\n morph_tangent_deltas = np.empty((len(normals), 3), dtype=np.float32)\n\n for i in range(len(normals)):\n n = Vector(normals[i])\n morph_n = n + Vector(morph_normal_deltas[i]) # convert back to non-delta\n t = Vector(tangents[i, :3])\n\n rotation = morph_n.rotation_difference(n)\n\n t_morph = Vector(t)\n t_morph.rotate(rotation)\n morph_tangent_deltas[i] = t_morph - t # back to delta\n\n return morph_tangent_deltas\n\n\ndef __get_uvs(blender_mesh, uv_i):\n layer = blender_mesh.uv_layers[uv_i]\n uvs = np.empty(len(blender_mesh.loops) * 2, dtype=np.float32)\n layer.data.foreach_get('uv', uvs)\n uvs = uvs.reshape(len(blender_mesh.loops), 2)\n\n # Blender UV space -> glTF UV space\n # u,v -> u,1-v\n uvs[:, 1] *= -1\n uvs[:, 1] += 1\n\n return uvs\n\n\ndef __get_colors(blender_mesh, color_i):\n layer = blender_mesh.vertex_colors[color_i]\n colors = np.empty(len(blender_mesh.loops) * 4, dtype=np.float32)\n layer.data.foreach_get('color', colors)\n colors = colors.reshape(len(blender_mesh.loops), 4)\n\n # sRGB -> Linear\n rgb = colors[:, :-1]\n not_small = rgb >= 0.04045\n small_result = np.where(rgb < 0.0, 0.0, rgb * (1.0 / 12.92))\n large_result = np.power((rgb + 0.055) * (1.0 / 1.055), 2.4, where=not_small)\n rgb[:] = np.where(not_small, large_result, small_result)\n\n return colors\n\n\ndef __get_bone_data(blender_mesh, skin, blender_vertex_groups):\n joint_name_to_index = {joint.name: index for index, joint in enumerate(skin.joints)}\n group_to_joint = [joint_name_to_index.get(g.name) for g in blender_vertex_groups]\n\n # List of (joint, weight) pairs for each vert\n vert_bones = []\n max_num_influences = 0\n\n for vertex in blender_mesh.vertices:\n bones = []\n if vertex.groups:\n for group_element in vertex.groups:\n weight = group_element.weight\n if weight <= 0.0:\n continue\n try:\n joint = group_to_joint[group_element.group]\n except Exception:\n continue\n if joint is None:\n continue\n bones.append((joint, weight))\n bones.sort(key=lambda x: x[1], reverse=True)\n if not bones: bones = ((0, 1.0),) # HACK for verts with zero weight (#308)\n vert_bones.append(bones)\n if len(bones) > max_num_influences:\n max_num_influences = len(bones)\n\n # How many joint sets do we need? 1 set = 4 influences\n num_joint_sets = (max_num_influences + 3) // 4\n\n return vert_bones, num_joint_sets\n\n\ndef __zup2yup(array):\n # x,y,z -> x,z,-y\n array[:, [1,2]] = array[:, [2,1]] # x,z,y\n array[:, 2] *= -1 # x,z,-y\n\n\ndef __apply_mat_to_all(matrix, vectors):\n \"\"\"Given matrix m and vectors [v1,v2,...], computes [m@v1,m@v2,...]\"\"\"\n # Linear part\n m = matrix.to_3x3() if len(matrix) == 4 else matrix\n res = np.matmul(vectors, np.array(m.transposed()))\n # Translation part\n if len(matrix) == 4:\n res += np.array(matrix.translation)\n return res\n\n\ndef __normalize_vecs(vectors):\n norms = np.linalg.norm(vectors, axis=1, keepdims=True)\n np.divide(vectors, norms, out=vectors, where=norms != 0)\n" ]
[ [ "numpy.power", "numpy.unique", "numpy.linalg.norm", "numpy.dtype", "numpy.repeat", "numpy.array", "numpy.where", "numpy.divide" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ichen20/oreilly_book
[ "8098d8096d9decca6aa5afbb267b9f05ce0570f2" ]
[ "07_train/privacy/tensorflow_privacy/privacy/membership_inference_attack/membership_inference_attack.py" ]
[ "# Copyright 2020, The TensorFlow 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# Lint as: python3\n\"\"\"Code that runs membership inference attacks based on the model outputs.\n\nThis file belongs to the new API for membership inference attacks. This file\nwill be renamed to membership_inference_attack.py after the old API is removed.\n\"\"\"\n\nfrom typing import Iterable\nimport numpy as np\nfrom sklearn import metrics\n\nfrom tensorflow_privacy.privacy.membership_inference_attack import models\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import AttackInputData\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import AttackResults\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import AttackType\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import \\\n PrivacyReportMetadata\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import RocCurve\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import SingleAttackResult\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import SingleSliceSpec\nfrom tensorflow_privacy.privacy.membership_inference_attack.data_structures import SlicingSpec\nfrom tensorflow_privacy.privacy.membership_inference_attack.dataset_slicing import get_single_slice_specs\nfrom tensorflow_privacy.privacy.membership_inference_attack.dataset_slicing import get_slice\n\n\ndef _get_slice_spec(data: AttackInputData) -> SingleSliceSpec:\n if hasattr(data, 'slice_spec'):\n return data.slice_spec\n return SingleSliceSpec()\n\n\ndef _run_trained_attack(attack_input: AttackInputData,\n attack_type: AttackType,\n balance_attacker_training: bool = True):\n \"\"\"Classification attack done by ML models.\"\"\"\n attacker = None\n\n if attack_type == AttackType.LOGISTIC_REGRESSION:\n attacker = models.LogisticRegressionAttacker()\n elif attack_type == AttackType.MULTI_LAYERED_PERCEPTRON:\n attacker = models.MultilayerPerceptronAttacker()\n elif attack_type == AttackType.RANDOM_FOREST:\n attacker = models.RandomForestAttacker()\n elif attack_type == AttackType.K_NEAREST_NEIGHBORS:\n attacker = models.KNearestNeighborsAttacker()\n else:\n raise NotImplementedError('Attack type %s not implemented yet.' %\n attack_type)\n\n prepared_attacker_data = models.create_attacker_data(\n attack_input, balance=balance_attacker_training)\n\n attacker.train_model(prepared_attacker_data.features_train,\n prepared_attacker_data.is_training_labels_train)\n\n # Run the attacker on (permuted) test examples.\n predictions_test = attacker.predict(prepared_attacker_data.features_test)\n\n # Generate ROC curves with predictions.\n fpr, tpr, thresholds = metrics.roc_curve(\n prepared_attacker_data.is_training_labels_test, predictions_test)\n\n roc_curve = RocCurve(tpr=tpr, fpr=fpr, thresholds=thresholds)\n\n return SingleAttackResult(\n slice_spec=_get_slice_spec(attack_input),\n attack_type=attack_type,\n roc_curve=roc_curve)\n\n\ndef _run_threshold_attack(attack_input: AttackInputData):\n fpr, tpr, thresholds = metrics.roc_curve(\n np.concatenate((np.zeros(attack_input.get_train_size()),\n np.ones(attack_input.get_test_size()))),\n np.concatenate(\n (attack_input.get_loss_train(), attack_input.get_loss_test())))\n\n roc_curve = RocCurve(tpr=tpr, fpr=fpr, thresholds=thresholds)\n\n return SingleAttackResult(\n slice_spec=_get_slice_spec(attack_input),\n attack_type=AttackType.THRESHOLD_ATTACK,\n roc_curve=roc_curve)\n\n\ndef _run_threshold_entropy_attack(attack_input: AttackInputData):\n fpr, tpr, thresholds = metrics.roc_curve(\n np.concatenate((np.zeros(attack_input.get_train_size()),\n np.ones(attack_input.get_test_size()))),\n np.concatenate(\n (attack_input.get_entropy_train(), attack_input.get_entropy_test())))\n\n roc_curve = RocCurve(tpr=tpr, fpr=fpr, thresholds=thresholds)\n\n return SingleAttackResult(\n slice_spec=_get_slice_spec(attack_input),\n attack_type=AttackType.THRESHOLD_ENTROPY_ATTACK,\n roc_curve=roc_curve)\n\n\ndef _run_attack(attack_input: AttackInputData,\n attack_type: AttackType,\n balance_attacker_training: bool = True):\n attack_input.validate()\n if attack_type.is_trained_attack:\n return _run_trained_attack(attack_input, attack_type,\n balance_attacker_training)\n if attack_type == AttackType.THRESHOLD_ENTROPY_ATTACK:\n return _run_threshold_entropy_attack(attack_input)\n return _run_threshold_attack(attack_input)\n\n\ndef run_attacks(attack_input: AttackInputData,\n slicing_spec: SlicingSpec = None,\n attack_types: Iterable[AttackType] = (\n AttackType.THRESHOLD_ATTACK,),\n privacy_report_metadata: PrivacyReportMetadata = None,\n balance_attacker_training: bool = True) -> AttackResults:\n \"\"\"Runs membership inference attacks on a classification model.\n\n It runs attacks specified by attack_types on each attack_input slice which is\n specified by slicing_spec.\n\n Args:\n attack_input: input data for running an attack\n slicing_spec: specifies attack_input slices to run attack on\n attack_types: attacks to run\n privacy_report_metadata: the metadata of the model under attack.\n balance_attacker_training: Whether the training and test sets for the\n membership inference attacker should have a balanced (roughly equal)\n number of samples from the training and test sets used to develop\n the model under attack.\n\n Returns:\n the attack result.\n \"\"\"\n attack_input.validate()\n attack_results = []\n\n if slicing_spec is None:\n slicing_spec = SlicingSpec(entire_dataset=True)\n input_slice_specs = get_single_slice_specs(slicing_spec,\n attack_input.num_classes)\n for single_slice_spec in input_slice_specs:\n attack_input_slice = get_slice(attack_input, single_slice_spec)\n for attack_type in attack_types:\n attack_results.append(\n _run_attack(attack_input_slice, attack_type,\n balance_attacker_training))\n\n privacy_report_metadata = _compute_missing_privacy_report_metadata(\n privacy_report_metadata, attack_input)\n\n return AttackResults(\n single_attack_results=attack_results,\n privacy_report_metadata=privacy_report_metadata)\n\n\ndef _compute_missing_privacy_report_metadata(\n metadata: PrivacyReportMetadata,\n attack_input: AttackInputData) -> PrivacyReportMetadata:\n \"\"\"Populates metadata fields if they are missing.\"\"\"\n if metadata is None:\n metadata = PrivacyReportMetadata()\n if metadata.accuracy_train is None:\n metadata.accuracy_train = _get_accuracy(attack_input.logits_train,\n attack_input.labels_train)\n if metadata.accuracy_test is None:\n metadata.accuracy_test = _get_accuracy(attack_input.logits_test,\n attack_input.labels_test)\n if metadata.loss_train is None:\n metadata.loss_train = np.average(attack_input.get_loss_train())\n if metadata.loss_test is None:\n metadata.loss_test = np.average(attack_input.get_loss_test())\n return metadata\n\n\ndef _get_accuracy(logits, labels):\n \"\"\"Computes the accuracy if it is missing.\"\"\"\n if logits is None or labels is None:\n return None\n return metrics.accuracy_score(labels, np.argmax(logits, axis=1))\n" ]
[ [ "numpy.argmax", "sklearn.metrics.roc_curve" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fujibo/poseHG
[ "e582a6ca1badc9a894b8b7e2a5e0acf9eb348c5c" ]
[ "chainer/snap2model.py" ]
[ "import numpy as np\nimport tempfile\n\n\ndef snap2model_parser(path_snapshot, path_model=None):\n \"\"\"convert snapshot to model\n\n :param path_snapshot: str\n :param path_model: str, default None\n :return: file descriptor (path_model is None) or None (otherwise)\n \"\"\"\n snapshot = np.load(path_snapshot)\n\n model = dict()\n for key in snapshot.keys():\n parse = key.split('/')\n if parse[0] == 'updater' and parse[1] == 'optimizer:main':\n if parse[2] == 'model':\n model_key = '/'.join(parse[3:-1])\n model[model_key] = snapshot[key]\n\n if path_model is None:\n outfile = tempfile.TemporaryFile()\n np.savez(outfile, **model)\n outfile.seek(0)\n return outfile\n\n else:\n np.savez(path_model, **model)\n return None\n\n\ndef snap2model_trainer(path_snapshot, path_model=None):\n import chainer\n from dataset import MPIIDataset\n from train import TrainChain\n from net import StackedHG\n\n train_data = MPIIDataset(split='train')\n model = StackedHG(16)\n train_chain = TrainChain(model)\n optimizer = chainer.optimizers.RMSprop(lr=2.5e-4)\n optimizer.setup(train_chain)\n\n # original batch size 6\n train_iter = chainer.iterators.SerialIterator(train_data, 1, repeat=True, shuffle=True)\n updater = chainer.training.StandardUpdater(train_iter, optimizer, device=-1)\n trainer = chainer.training.Trainer(updater, (100, 'epoch'), out='')\n chainer.serializers.load_npz(path_snapshot, trainer)\n\n if path_model is None:\n outfile = tempfile.TemporaryFile()\n chainer.serializers.save_npz(outfile, model)\n outfile.seek(0)\n return outfile\n\n else:\n chainer.serializers.save_npz(path_model, model)\n return None\n" ]
[ [ "numpy.load", "numpy.savez" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vltmedia/ROMP
[ "1d2d96bd39f67a0a86ce7e397e3af856b3c5ee00" ]
[ "romp/lib/loss_funcs/params_loss.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\n\nimport time\nimport pickle\nimport numpy as np\n\nimport config\nimport constants\nfrom config import args\nfrom utils import batch_rodrigues, rotation_matrix_to_angle_axis\n\n\ndef batch_l2_loss(real,predict):\n loss_batch = torch.norm(real-predict, p=2, dim=1)\n return loss_batch.mean()\n\ndef batch_l2_loss_param(real,predict):\n # convert to rot mat, multiple angular maps to the same rotation with Pi as a period.\n batch_size = real.shape[0]\n real = batch_rodrigues(real.reshape(-1,3)).contiguous()#(N*J)*3 -> (N*J)*3*3\n predict = batch_rodrigues(predict.reshape(-1,3)).contiguous()#(N*J)*3 -> (N*J)*3*3\n loss = torch.norm((real-predict).view(-1,9), p=2, dim=-1)#self.sl1loss(real,predict)#\n loss = loss.reshape(batch_size, -1).mean(-1)\n return loss\n\ndef _calc_MPJAE(rel_pose_pred,rel_pose_real):\n global_pose_rotmat_pred = trans_relative_rot_to_global_rotmat(rel_pose_pred, with_global_rot=True)\n global_pose_rotmat_real = trans_relative_rot_to_global_rotmat(rel_pose_real, with_global_rot=True)\n MPJAE_error = _calc_joint_angle_error(global_pose_rotmat_pred, global_pose_rotmat_real).cpu().numpy()\n return MPJAE_error\n\n\ndef trans_relative_rot_to_global_rotmat(params, with_global_rot=False):\n '''\n calculate absolute rotation matrix in the global coordinate frame of K body parts. \n The rotation is the map from the local bone coordinate frame to the global one.\n K= 9 parts in the following order: \n root (JOINT 0) , left hip (JOINT 1), right hip (JOINT 2), left knee (JOINT 4), right knee (JOINT 5), \n left shoulder (JOINT 16), right shoulder (JOINT 17), left elbow (JOINT 18), right elbow (JOINT 19).\n parent kinetic tree [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19, 20, 21]\n '''\n batch_size, param_num = params.shape[0], params.shape[1]//3\n pose_rotmat = batch_rodrigues(params.reshape(-1,3)).view(batch_size, param_num, 3, 3).contiguous()\n if with_global_rot:\n sellect_joints = np.array([0,1,2,4,5,16,17,18,19],dtype=np.int)\n results = [pose_rotmat[:, 0]]\n for idx in range(param_num-1):\n i_val = int(idx + 1)\n joint_rot = pose_rotmat[:, i_val]\n parent = constants.kintree_parents[i_val]\n glob_transf_mat = torch.matmul(results[parent], joint_rot)\n results.append(glob_transf_mat)\n else:\n sellect_joints = np.array([1,2,4,5,16,17,18,19],dtype=np.int)-1\n results = [torch.eye(3,3)[None].cuda().repeat(batch_size,1,1)]\n for i_val in range(param_num-1):\n #i_val = int(idx + 1)\n joint_rot = pose_rotmat[:, i_val]\n parent = constants.kintree_parents[i_val+1]\n glob_transf_mat = torch.matmul(results[parent], joint_rot)\n results.append(glob_transf_mat)\n global_rotmat = torch.stack(results, axis=1)[:, sellect_joints].contiguous()\n return global_rotmat\n\ndef _calc_joint_angle_error(pred_mat, gt_mat, return_axis_angle=False):\n \"\"\"\n Compute the geodesic distance between the two input matrices.\n :param pred_mat: predicted rotation matrices. Shape: ( Seq, 9g, 3, 3)\n :param gt_mat: ground truth rotation matrices. Shape: ( Seq, 9, 3, 3)\n :return: Mean geodesic distance between input matrices.\n \"\"\"\n\n # Reshape the matrices into B x 3 x 3 arrays\n r1 = pred_mat.reshape(-1,3,3)\n r2 = gt_mat.reshape(-1,3,3)\n # Transpose gt matrices\n r2t = r2.permute(0,2,1)\n r = torch.matmul(r1, r2t)\n # Convert rotation matrix to axis angle representation and find the angle\n axis_angles = rotation_matrix_to_angle_axis(r)\n angles = torch.norm(axis_angles, dim=-1)*(180./np.pi)\n\n if return_axis_angle:\n return angles,axis_angles\n return angles\n" ]
[ [ "torch.norm", "torch.eye", "torch.matmul", "torch.stack", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
L-Net-1992/Paddle
[ "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "4d0ca02ba56760b456f3d4b42a538555b9b6c307" ]
[ "python/paddle/fluid/tests/unittests/xpu/test_expand_v2_op_xpu.py", "python/paddle/distributed/auto_parallel/process_mesh.py", "python/paddle/fluid/tests/unittests/test_dygraph_mnist_fp16.py", "python/paddle/fluid/tests/unittests/ipu/test_elemetwise_x_op_ipu.py", "python/paddle/fluid/tests/unittests/ipu/test_lr_sheduler_ipu.py", "python/paddle/fluid/tests/unittests/parallel_dygraph_no_sync_gradient_check.py", "python/paddle/fluid/tests/unittests/dygraph_to_static/test_grad.py", "python/paddle/fluid/tests/unittests/mlu/test_conv2d_op_mlu.py", "python/paddle/fluid/tests/unittests/xpu/test_arg_max_op_xpu.py", "python/paddle/fluid/tests/unittests/test_lod_tensor_array.py", "python/paddle/fluid/tests/unittests/mkldnn/test_pool2d_bf16_mkldnn_op.py", "python/paddle/fluid/tests/unittests/ipu/test_scaled_optimizer_state_ipu.py", "python/paddle/fluid/tests/unittests/test_dygraph_recompute.py", "python/paddle/fluid/tests/unittests/dygraph_to_static/test_break_continue.py", "python/paddle/vision/transforms/transforms.py", "python/paddle/fluid/tests/unittests/ipu/test_transpose_op_ipu.py", "python/paddle/fluid/tests/unittests/ir/inference/test_trt_convert_multiclass_nms3.py", "python/paddle/fluid/tests/unittests/test_imperative_data_loader_exception.py", "python/paddle/fluid/tests/unittests/test_tensor_fill_diagonal_tensor_.py", "python/paddle/fluid/tests/unittests/npu/test_multinomial_op_npu.py", "python/paddle/tests/test_callback_early_stop.py", "python/paddle/distributed/auto_parallel/dist_loader.py", "python/paddle/fluid/tests/unittests/dist_mnist_gradient_merge_raw_optimizer.py", "python/paddle/fluid/tests/unittests/test_split_program.py", "python/paddle/fluid/tests/unittests/ipu/test_reduce_x_op_ipu.py", "python/paddle/fluid/tests/unittests/mlu/test_relu6_op_mlu.py", "python/paddle/fluid/tests/unittests/test_buffer_shared_memory_reuse_pass.py", "python/paddle/fluid/lod_tensor.py", "python/paddle/fluid/tests/unittests/test_tdm_sampler_op.py", "python/paddle/fluid/tests/unittests/ipu/test_cross_entropy2_op_ipu.py", "python/paddle/fluid/tests/unittests/hybrid_parallel_pp_transformer.py", "python/paddle/fluid/tests/unittests/xpu/test_accuracy_op_xpu.py", "python/paddle/distribution/categorical.py", "python/paddle/fluid/tests/unittests/dygraph_to_static/test_resnet_v2.py", "python/paddle/fluid/tests/unittests/mlu/test_conv2d_transposed_op_mlu.py", "python/paddle/fluid/tests/unittests/ipu/test_sum_op_ipu.py", "python/paddle/fluid/tests/unittests/test_mv_op.py", "python/paddle/fluid/tests/unittests/npu/test_elementwise_add_op_npu.py", "python/paddle/fluid/tests/unittests/ir/inference/test_trt_convert_yolo_box_head.py", "python/paddle/tests/dist_hapi_mnist_dynamic.py", "python/paddle/fluid/tests/unittests/test_multiprocess_dataloader_static.py", "python/paddle/fluid/tests/unittests/test_dist_save_load.py", "python/paddle/fluid/tests/unittests/test_bfgs.py", "python/paddle/fluid/tests/unittests/ipu/test_print_op_ipu.py", "python/paddle/fluid/tests/unittests/test_rank_attention_op.py", "python/paddle/fluid/tests/unittests/xpu/test_adamw_op_xpu.py" ]
[ "# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport unittest\nimport sys\nimport numpy as np\n\nsys.path.append(\"..\")\nfrom op_test import OpTest\nfrom op_test_xpu import XPUOpTest\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program, program_guard\nimport paddle\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\nnp.random.seed(10)\n\n\n# CANN Op Support X: float32, int32, int64\n# Situation 1: shape is a list(without tensor)\nclass XPUTestExpandV2Op(XPUOpTestWrapper):\n\n def __init__(self):\n self.op_name = 'expand_v2'\n self.use_dynamic_create_class = False\n\n class TestExpandV2XPUOp(XPUOpTest):\n\n def setUp(self):\n self.init_dtype()\n self.set_xpu()\n self.op_type = \"expand_v2\"\n self.place = paddle.XPUPlace(0)\n self.init_data()\n self.inputs = {\n 'X': np.random.random(self.ori_shape).astype(self.dtype)\n }\n self.attrs = {'shape': self.shape}\n output = np.tile(self.inputs['X'], self.expand_times)\n self.outputs = {'Out': output}\n\n def init_dtype(self):\n self.dtype = self.in_type\n\n def set_xpu(self):\n self.__class__.use_xpu = True\n self.__class__.no_need_check_grad = True\n\n def init_data(self):\n self.ori_shape = [100]\n self.shape = [100]\n self.expand_times = [1]\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n class TestExpandV2OpRank2_DimExpanding(TestExpandV2XPUOp):\n\n def init_data(self):\n self.ori_shape = [120]\n self.shape = [2, 120]\n self.expand_times = [2, 1]\n\n class TestExpandV2OpRank2(TestExpandV2XPUOp):\n\n def init_data(self):\n self.ori_shape = [1, 140]\n self.shape = [12, 140]\n self.expand_times = [12, 1]\n\n class TestExpandV2OpRank3_Corner(TestExpandV2XPUOp):\n\n def init_data(self):\n self.ori_shape = (2, 10, 5)\n self.shape = (2, 10, 5)\n self.expand_times = (1, 1, 1)\n\n class TestExpandV2OpRank4(TestExpandV2XPUOp):\n\n def init_data(self):\n self.ori_shape = (2, 4, 5, 7)\n self.shape = (-1, -1, -1, -1)\n self.expand_times = (1, 1, 1, 1)\n\n class TestExpandV2OpRank5(TestExpandV2XPUOp):\n\n def init_data(self):\n self.ori_shape = (2, 4, 1, 15)\n self.shape = (2, -1, 4, -1)\n self.expand_times = (1, 1, 4, 1)\n\n class TestExpandV2OpRank6(TestExpandV2XPUOp):\n\n def init_data(self):\n self.ori_shape = (4, 1, 30)\n self.shape = (2, -1, 4, 30)\n self.expand_times = (2, 1, 4, 1)\n\n # Situation 2: shape is a list(with tensor)\n class TestExpandV2OpXPURank1_tensor_attr(TestExpandV2XPUOp):\n\n def setUp(self):\n self.set_xpu()\n self.place = paddle.XPUPlace(0)\n self.op_type = \"expand_v2\"\n self.init_data()\n self.dtype = np.float32\n expand_shapes_tensor = []\n for index, ele in enumerate(self.expand_shape):\n expand_shapes_tensor.append((\"x\" + str(index), np.ones(\n (1)).astype('int32') * ele))\n\n self.inputs = {\n 'X': np.random.random(self.ori_shape).astype(self.dtype),\n 'expand_shapes_tensor': expand_shapes_tensor,\n }\n self.attrs = {\"shape\": self.infer_expand_shape}\n output = np.tile(self.inputs['X'], self.expand_times)\n self.outputs = {'Out': output}\n\n def init_data(self):\n self.ori_shape = [100]\n self.expand_times = [1]\n self.expand_shape = [100]\n self.infer_expand_shape = [-1]\n\n class TestExpandV2OpRank2_Corner_tensor_attr(\n TestExpandV2OpXPURank1_tensor_attr):\n\n def init_data(self):\n self.ori_shape = [12, 14]\n self.expand_times = [1, 1]\n self.expand_shape = [12, 14]\n self.infer_expand_shape = [12, -1]\n\n # Situation 3: shape is a tensor\n class TestExpandV2XPUOp_tensor(TestExpandV2XPUOp):\n\n def setUp(self):\n self.set_xpu()\n self.place = paddle.XPUPlace(0)\n self.op_type = \"expand_v2\"\n self.init_data()\n self.dtype = np.float32\n\n self.inputs = {\n 'X': np.random.random(self.ori_shape).astype(self.dtype),\n 'Shape': np.array(self.expand_shape).astype(\"int32\"),\n }\n self.attrs = {}\n output = np.tile(self.inputs['X'], self.expand_times)\n self.outputs = {'Out': output}\n\n def init_data(self):\n self.ori_shape = [100]\n self.expand_times = [2, 1]\n self.expand_shape = [2, 100]\n\n\n# Situation 5: input x is int32\n# skip grad check for int32\nclass TestExpandV2OpInteger(XPUOpTest):\n\n def init_type(self):\n self.dtype = 'int32'\n\n def setUp(self):\n self.set_xpu()\n self.init_type()\n self.place = paddle.XPUPlace(0)\n self.op_type = \"expand_v2\"\n self.inputs = {\n 'X': np.random.randint(10, size=(2, 4, 20)).astype(self.dtype)\n }\n self.attrs = {'shape': [2, 4, 20]}\n output = np.tile(self.inputs['X'], (1, 1, 1))\n self.outputs = {'Out': output}\n\n def set_xpu(self):\n self.__class__.use_xpu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n pass\n\n\n# Test python API\nclass TestExpandV2API(unittest.TestCase):\n\n def test_static(self):\n with fluid.program_guard(fluid.Program(), fluid.Program()):\n input = np.random.random([12, 14]).astype(\"float32\")\n x = fluid.layers.data(name='x',\n shape=[12, 14],\n append_batch_size=False,\n dtype=\"float32\")\n\n positive_2 = fluid.layers.fill_constant([1], \"int32\", 12)\n expand_shape = fluid.layers.data(name=\"expand_shape\",\n shape=[2],\n append_batch_size=False,\n dtype=\"int32\")\n\n out_1 = paddle.expand(x, shape=[12, 14])\n out_2 = paddle.expand(x, shape=[positive_2, 14])\n out_3 = paddle.expand(x, shape=expand_shape)\n\n g0 = fluid.backward.calc_gradient(out_2, x)\n\n exe = fluid.Executor(place=paddle.XPUPlace(0))\n res_1, res_2, res_3 = exe.run(fluid.default_main_program(),\n feed={\n \"x\":\n input,\n \"expand_shape\":\n np.array([12, 14]).astype(\"int32\")\n },\n fetch_list=[out_1, out_2, out_3])\n\n assert np.array_equal(res_1, np.tile(input, (1, 1)))\n assert np.array_equal(res_2, np.tile(input, (1, 1)))\n assert np.array_equal(res_3, np.tile(input, (1, 1)))\n\n\nsupport_types = get_xpu_op_support_types('expand_v2')\nfor stype in support_types:\n create_test_class(globals(), XPUTestExpandV2Op, stype)\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport numpy\nimport copy\n\n\ndef _get_nested_list_shape(nested_list):\n \"\"\"\n Get the shape of a nested_list.\n \"\"\"\n result = []\n while isinstance(nested_list, list):\n result.append(len(nested_list))\n nested_list = nested_list[0]\n return result\n\n\ndef _flatten_nested_list(nested_list):\n \"\"\"\n Get a list of all items in a nested_list.\n Ref: https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists\n \"\"\"\n result = numpy.array(nested_list).flatten().tolist()\n return result\n\n\nclass ProcessMesh(object):\n r\"\"\"\n The class `Processmesh` describes the topology of logical processes. \n A mesh is an N-dimensional array. The shape of the N-dimensional\n array represents the topology of logical processes and every\n element of the N-dimensional array represent a logical process. For\n example, the 2-dimensional array [[2, 4, 5], [0, 1, 3]]\n illustrates six logical processes organized as the topology [2, 3],\n i.e., the shape of the 2-dimensional array. With the above topology,\n there are two parallel groups, where the first parallel group has a\n parallel degree of 2 and the second one has a parallel degree of 3.\n And the first logical process is the one with id=2.\n\n Args:\n mesh (list): an N-dimensional array (nested list) describes the toplogy\n of logical processes. The shape of the N-dimensional array\n represents the topology of logical processes and every \n element of the N-dimensional array represents a logical process.\n \n Returns:\n None\n\n Raises:\n ValueError: If `mesh` is not an instance of list.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import paddle.distributed as dist\n \n paddle.enable_static()\n \n mesh = dist.ProcessMesh([[2, 4, 5], [0, 1, 3]])\n assert mesh.topology == [2, 3]\n assert mesh.processes == [2, 4, 5, 0, 1, 3]\n\n \"\"\"\n\n def __init__(self, mesh):\n if mesh is None or not isinstance(mesh, list):\n raise ValueError('mesh must be an instance of list.')\n\n processes = _flatten_nested_list(mesh)\n\n assert all(isinstance(p, int) for p in processes), \\\n (\"All elements of mesh must be integer\")\n\n assert min(processes) >= 0, ('All elements of mesh must be >= 0.')\n\n unique_processes = set(processes)\n assert len(unique_processes) == len(processes), (\n 'All elements of mesh must be unique.')\n\n self._topology = _get_nested_list_shape(mesh)\n self._processes = processes\n\n # Store all process meshes\n from .dist_context import get_default_distributed_context\n default_dist_cxt = get_default_distributed_context()\n default_dist_cxt.add_process_mesh(self)\n # Add new processes to process group 0\n from .process_group import get_process_group\n pg0 = get_process_group(0)\n pg0.add_ranks(self.processes)\n\n @property\n def topology(self):\n r\"\"\"\n Get the topology of logical processes belonging to this ProcessMesh.\n This is the shape of `mesh` used to initialized this ProcessMesh.\n \"\"\"\n return self._topology\n\n @property\n def processes(self):\n r\"\"\"\n Get a list of all processes belonging to this ProcessMesh.\n \"\"\"\n return self._processes\n\n @property\n def ndim(self):\n r\"\"\"\n Get the number of dimension of ProcessMesh.\n \"\"\"\n return len(self._topology)\n\n def __eq__(self, other):\n if not isinstance(other, ProcessMesh):\n return False\n if self.topology != other.topology or self.processes != other.processes:\n return False\n return True\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __str__(self):\n str = \"shape {} and process group {}\".format(self.topology,\n self.processes)\n return str\n", "# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\n\nimport paddle.fluid as fluid\nfrom paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\nfrom paddle.fluid.framework import _test_eager_guard\n\n\nclass SimpleImgConvPool(fluid.dygraph.Layer):\n\n def __init__(self,\n num_channels,\n num_filters,\n filter_size,\n pool_size,\n pool_stride,\n pool_padding=0,\n pool_type='max',\n global_pooling=False,\n conv_stride=1,\n conv_padding=0,\n conv_dilation=1,\n conv_groups=1,\n act=None,\n use_cudnn=False,\n dtype='float32',\n param_attr=None,\n bias_attr=None):\n super(SimpleImgConvPool, self).__init__()\n\n self._conv2d = Conv2D(num_channels=num_channels,\n num_filters=num_filters,\n filter_size=filter_size,\n stride=conv_stride,\n padding=conv_padding,\n dilation=conv_dilation,\n groups=conv_groups,\n param_attr=param_attr,\n bias_attr=bias_attr,\n use_cudnn=use_cudnn,\n dtype=dtype,\n act=act)\n\n self._pool2d = Pool2D(pool_size=pool_size,\n pool_type=pool_type,\n pool_stride=pool_stride,\n pool_padding=pool_padding,\n global_pooling=global_pooling,\n use_cudnn=use_cudnn)\n\n def forward(self, inputs):\n x = self._conv2d(inputs)\n x = self._pool2d(x)\n return x\n\n\nclass MNIST(fluid.dygraph.Layer):\n\n def __init__(self, dtype=\"float32\"):\n super(MNIST, self).__init__()\n\n self._simple_img_conv_pool_1 = SimpleImgConvPool(num_channels=3,\n num_filters=20,\n filter_size=5,\n pool_size=2,\n pool_stride=2,\n act=\"relu\",\n dtype=dtype,\n use_cudnn=True)\n\n self._simple_img_conv_pool_2 = SimpleImgConvPool(num_channels=20,\n num_filters=50,\n filter_size=5,\n pool_size=2,\n pool_stride=2,\n act=\"relu\",\n dtype=dtype,\n use_cudnn=True)\n\n self.pool_2_shape = 50 * 53 * 53\n SIZE = 10\n scale = (2.0 / (self.pool_2_shape**2 * SIZE))**0.5\n self._linear = Linear(\n self.pool_2_shape,\n 10,\n param_attr=fluid.param_attr.ParamAttr(\n initializer=fluid.initializer.NormalInitializer(loc=0.0,\n scale=scale)),\n act=\"softmax\",\n dtype=dtype)\n\n def forward(self, inputs, label):\n x = self._simple_img_conv_pool_1(inputs)\n x = self._simple_img_conv_pool_2(x)\n x = fluid.layers.reshape(x, shape=[-1, self.pool_2_shape])\n cost = self._linear(x)\n loss = fluid.layers.cross_entropy(cost, label)\n avg_loss = fluid.layers.mean(loss)\n return avg_loss\n\n\nclass TestMnist(unittest.TestCase):\n\n def func_mnist_fp16(self):\n if not fluid.is_compiled_with_cuda():\n return\n x = np.random.randn(1, 3, 224, 224).astype(\"float16\")\n y = np.random.randint(10, size=[1, 1], dtype=\"int64\")\n with fluid.dygraph.guard(fluid.CUDAPlace(0)):\n model = MNIST(dtype=\"float16\")\n x = fluid.dygraph.to_variable(x)\n y = fluid.dygraph.to_variable(y)\n loss = model(x, y)\n print(loss.numpy())\n\n def test_mnist_fp16(self):\n with _test_eager_guard():\n self.func_mnist_fp16()\n self.func_mnist_fp16()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestMul(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_test_op()\n\n @property\n def fp16_enabled(self):\n if IPUOpTest.use_ipumodel():\n return False\n else:\n return True\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_mul\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n\n @IPUOpTest.static_graph\n def build_model(self):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype='float32')\n y = paddle.static.data(name=self.feed_list[1],\n shape=self.feed_shape[1],\n dtype='float32')\n out = self.op(x, y, **self.attrs)\n self.fetch_list = [out.name]\n\n def run_model(self, exec_mode):\n self.run_op_test(exec_mode)\n\n def run_test_base(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model()\n self.run_model(m)\n self.check()\n\n def test_case0(self):\n data_x = np.random.uniform(size=(2, 3, 4, 5))\n data_y = np.random.uniform(size=(2, 3, 4, 5))\n\n self.feed_fp32 = {\n \"x\": data_x.astype('float32'),\n \"y\": data_y.astype('float32'),\n }\n self.feed_fp16 = {\n \"x\": data_x.astype('float16'),\n \"y\": data_y.astype('float16'),\n }\n self.attrs = {}\n self.set_feed_attr()\n self.run_test_base()\n\n def test_case1(self):\n data_x = np.random.uniform(size=(2, 3, 4, 5))\n data_y = np.random.uniform(size=(3, 4))\n self.feed_fp32 = {\n \"x\": data_x.astype('float32'),\n \"y\": data_y.astype('float32'),\n }\n self.feed_fp16 = {\n \"x\": data_x.astype('float16'),\n \"y\": data_y.astype('float16'),\n }\n self.set_feed_attr()\n self.attrs = {\"axis\": 1}\n self.run_test_base()\n\n def test_case2(self):\n data_x = np.random.uniform(size=(2, 3, 4, 5))\n data_y = np.random.uniform(size=(5))\n self.feed_fp32 = {\n \"x\": data_x.astype('float32'),\n \"y\": data_y.astype('float32'),\n }\n self.feed_fp16 = {\n \"x\": data_x.astype('float16'),\n \"y\": data_y.astype('float16'),\n }\n self.set_feed_attr()\n self.attrs = {\"axis\": -1}\n self.run_test_base()\n\n def test_case3(self):\n data_x = np.random.uniform(size=(2, 3, 4, 5))\n data_y = np.random.uniform(size=(2))\n self.feed_fp32 = {\n \"x\": data_x.astype('float32'),\n \"y\": data_y.astype('float32'),\n }\n self.feed_fp16 = {\n \"x\": data_x.astype('float16'),\n \"y\": data_y.astype('float16'),\n }\n self.set_feed_attr()\n self.attrs = {\"axis\": 0}\n self.run_test_base()\n\n\nclass TestAdd(TestMul):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_add\n\n\nclass TestSub(TestMul):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_sub\n\n\nclass TestDiv(TestMul):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_div\n\n\nclass TestMin(TestMul):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_min\n\n\nclass TestMax(TestMul):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_max\n\n\nclass TestPow(TestMul):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_pow\n\n\nclass TestMod(TestMul):\n\n def set_atol(self):\n self.atol = 1e-7\n self.rtol = 1e-5\n self.atol_fp16 = 1e-2\n self.rtol_fp16 = 1e-3\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.elementwise_mod\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport numpy as np\nimport unittest\nimport paddle\nimport paddle.static\nfrom paddle.optimizer.lr import LRScheduler\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\nclass LR_New(LRScheduler):\n\n def __init__(self, learning_rate=1e-5, last_epoch=-1, verbose=False):\n super(LR_New, self).__init__(learning_rate, last_epoch, verbose)\n\n def get_lr(self):\n self.base_lr = self.base_lr + 1e-4\n self.last_epoch = self.last_epoch + 1\n return self.base_lr\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestConvNet(IPUOpTest):\n\n @IPUOpTest.static_graph\n def build_model(self):\n image = paddle.static.data(name='image',\n shape=[1, 3, 10, 10],\n dtype='float32')\n conv1 = paddle.static.nn.conv2d(image,\n num_filters=3,\n filter_size=3,\n bias_attr=False)\n loss = paddle.mean(conv1)\n\n opt = paddle.optimizer.Lamb(learning_rate=LR_New())\n opt.minimize(loss)\n self.feed_list = [image.name]\n self.fetch_list = [loss.name]\n\n def run_model(self, run_ipu=True):\n self.build_model()\n if run_ipu:\n place = paddle.IPUPlace()\n else:\n place = paddle.CPUPlace()\n exe = paddle.static.Executor(place)\n exe.run(self.startup_prog)\n if run_ipu:\n ipu_strategy = paddle.static.IpuStrategy()\n ipu_strategy.set_graph_config(is_training=True)\n program = paddle.static.IpuCompiledProgram(\n self.main_prog,\n ipu_strategy=ipu_strategy).compile(self.feed_list,\n self.fetch_list)\n else:\n program = self.main_prog\n\n result = []\n for _ in range(100):\n if hasattr(program, \"lr_sheduler\"):\n program.lr_sheduler.step()\n loss_res = exe.run(program,\n feed=self.feed,\n fetch_list=self.fetch_list)\n result.append(loss_res)\n return np.array(result)\n\n def test_training(self):\n data = np.random.rand(1, 3, 10, 10).astype(np.float32)\n self.feed = {'image': data}\n # cpu and ipu dimenstion mismatch, cpu:(100, 1, 1), ipu:(100, 1)\n ipu_loss = self.run_model(True).flatten()\n cpu_loss = self.run_model(False).flatten()\n\n self.assertTrue(np.allclose(ipu_loss, cpu_loss, atol=1e-10))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\n\nimport paddle\nimport numpy as np\nimport paddle.distributed as dist\nimport paddle.fluid as fluid\nfrom paddle.fluid.dygraph.nn import Linear\n\npaddle.seed(1024)\nnp.random.seed(2021)\n\nbatch = 1\nin_dim = 10\nout_dim = 20\n\n\nclass SimpleNet(fluid.Layer):\n\n def __init__(self, train_id):\n super(SimpleNet, self).__init__()\n self.w1 = self.create_parameter(shape=[in_dim, out_dim],\n dtype=\"float32\")\n self.w2 = self.create_parameter(shape=[in_dim, out_dim],\n dtype=\"float32\")\n self.share_net = Linear(out_dim, 1)\n\n self.unused_param = self.create_parameter(shape=[out_dim, in_dim],\n dtype=\"float32\")\n\n # just for test sync_params_buffers\n self.register_buffer(\"queue\", paddle.randn([10, 5]))\n self.queue = paddle.nn.functional.normalize(self.queue, axis=0)\n self.register_buffer(\"queue_ptr\", paddle.zeros([1], 'int64'))\n\n self.trainer_id = train_id\n\n def forward(self, x):\n is_use = (paddle.equal_all(\n x, paddle.ones(shape=(batch, in_dim))).numpy()[0]\n and self.trainer_id == 1)\n\n if is_use:\n tmp = paddle.matmul(x, self.w1)\n else:\n tmp = paddle.matmul(x, self.w2)\n\n return self.share_net(tmp)\n\n\nclass TestDistTraning(unittest.TestCase):\n\n def test_multiple_gpus(self):\n self.trainer_id = dist.get_rank()\n dist.init_parallel_env()\n\n model_a = SimpleNet(self.trainer_id)\n model_b = SimpleNet(self.trainer_id)\n\n state_dict = model_a.state_dict()\n model_b.set_state_dict(state_dict)\n\n model_a = paddle.DataParallel(model_a, find_unused_parameters=True)\n model_b = paddle.DataParallel(model_b, find_unused_parameters=True)\n\n ones_input = paddle.ones(shape=(batch, in_dim))\n ones_input.stop_gradient = True\n\n for step_id in range(1, 31):\n random_input = paddle.rand(shape=(batch, in_dim))\n random_input.stop_gradient = True\n\n if step_id % 5 != 0:\n with model_a.no_sync():\n self.dp_layer(step_id, model_a, model_b, random_input,\n ones_input)\n else:\n self.dp_layer(step_id, model_a, model_b, random_input,\n ones_input)\n\n self.check_gradient(model_a.parameters())\n self.check_gradient(model_b.parameters())\n\n self.check_acc(model_a._layers.w1.grad, model_b._layers.w1.grad)\n self.check_acc(model_a._layers.w2.grad, model_b._layers.w2.grad)\n\n model_a.clear_gradients()\n model_b.clear_gradients()\n\n def dp_layer(self, step_id, model_a, model_b, random_input, ones_input):\n if step_id % 2 == 0:\n out_a = model_a(random_input)\n out_b = model_b(random_input)\n else:\n out_a = model_a(ones_input)\n out_b = model_b(ones_input)\n out_a.sum().backward()\n out_b.sum().backward()\n\n def check_acc(self, grad, acc_grad):\n grad = grad.numpy() if grad is not None else None\n acc_grad = acc_grad.numpy() if acc_grad is not None else None\n return np.testing.assert_allclose(grad, acc_grad, rtol=1e-6)\n\n def print_trainer_0(self, *args):\n if self.trainer_id == 0:\n print(*args)\n\n def broadcast_param(self, param, root):\n paddle.distributed.broadcast(param, root)\n return param\n\n def check_gradient(self, params):\n other_param = []\n for param in params:\n if param.trainable and (param._grad_ivar() is not None):\n grad = param._grad_ivar()\n other_grad = self.broadcast_param(grad.clone(), root=1)\n if self.trainer_id == 0:\n np.testing.assert_allclose(other_grad.numpy(), grad.numpy())\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport paddle\nimport unittest\nimport os\nimport tempfile\n\n\nclass GradLayer(paddle.nn.Layer):\n\n def __init__(self):\n super(GradLayer, self).__init__()\n\n @paddle.jit.to_static\n def forward(self, x):\n x.stop_gradient = False\n y = x * x\n dx = paddle.grad(outputs=[y], inputs=[x])[0]\n return dx\n\n\nclass GradLinearLayer(paddle.nn.Layer):\n\n def __init__(self):\n super(GradLinearLayer, self).__init__()\n self.linear = paddle.nn.Linear(5, 5, bias_attr=False)\n\n @paddle.jit.to_static\n def forward(self, x):\n x.stop_gradient = False\n tmp = x + x\n for i in range(10):\n tmp = self.linear(tmp)\n out = tmp\n dx = paddle.grad([out], [x],\n None,\n create_graph=True,\n allow_unused=False)[0]\n return dx\n\n\nclass NoGradLinearLayer(paddle.nn.Layer):\n\n def __init__(self):\n super(NoGradLinearLayer, self).__init__()\n self.linear = paddle.nn.Linear(5, 5, bias_attr=False)\n\n @paddle.jit.to_static\n def forward(self, x):\n x.stop_gradient = False\n\n with paddle.no_grad():\n y = self.linear(x)\n\n out = y + x\n return out\n\n\nclass TestGrad(unittest.TestCase):\n\n def setUp(self):\n self.func = GradLayer()\n self.x = paddle.ones(shape=[10, 2, 5], dtype='float32')\n self.x.stop_gradient = False\n\n def _run(self, func, to_static):\n prog_trans = paddle.jit.ProgramTranslator()\n prog_trans.enable(to_static)\n ret = func(self.x).numpy()\n prog_trans.enable(True)\n return ret\n\n def test_forward(self):\n dygraph_res = self._run(self.func, to_static=False)\n static_res = self._run(self.func, to_static=True)\n self.assertTrue(np.allclose(static_res, dygraph_res))\n\n\nclass TestGradLinear(TestGrad):\n\n def setUp(self):\n self.func = GradLinearLayer()\n self.x = paddle.ones(shape=[10, 2, 5], dtype='float32')\n self.x.stop_gradient = False\n\n self.temp_dir = tempfile.TemporaryDirectory()\n self.infer_model_path = os.path.join(self.temp_dir.name,\n 'double_grad_infer_model')\n self.train_model_path = os.path.join(self.temp_dir.name,\n 'double_grad_train_model')\n\n def tearDown(self):\n self.temp_dir.cleanup()\n\n def test_save_infer_program(self):\n input_spec = [\n paddle.static.InputSpec(shape=[10, 2, 5], dtype='float32')\n ]\n paddle.jit.save(self.func, self.infer_model_path, input_spec=input_spec)\n load_func = paddle.jit.load(self.infer_model_path)\n\n origin_res = self.func(self.x).numpy()\n load_res = load_func(self.x).numpy()\n self.assertTrue(np.allclose(origin_res, load_res))\n\n def test_save_train_program(self):\n grad_clip = paddle.nn.ClipGradByGlobalNorm(2.0)\n optimizer = paddle.optimizer.SGD(learning_rate=0.01,\n grad_clip=grad_clip,\n parameters=self.func.parameters())\n for i in range(10):\n out = self.func(self.x)\n avg_loss = paddle.mean(paddle.abs(out - 1))\n avg_loss.backward()\n optimizer.minimize(avg_loss)\n\n self.func.clear_gradients()\n\n paddle.jit.save(self.func, self.train_model_path)\n load_func = paddle.jit.load(self.train_model_path)\n\n origin_res = self.func(self.x).numpy()\n load_res = load_func(self.x).numpy()\n self.assertTrue(np.allclose(origin_res, load_res))\n\n\nclass TestNoGradLinear(TestGradLinear):\n\n def setUp(self):\n self.func = NoGradLinearLayer()\n self.x = paddle.ones(shape=[10, 2, 5], dtype='float32')\n self.x.stop_gradient = False\n\n self.temp_dir = tempfile.TemporaryDirectory()\n self.infer_model_path = os.path.join(self.temp_dir.name,\n 'no_grad_infer_model')\n self.train_model_path = os.path.join(self.temp_dir.name,\n 'no_grad_train_model')\n\n def tearDown(self):\n self.temp_dir.cleanup()\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\")\nimport paddle\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom op_test import OpTest\n\nfrom test_conv2d_op import conv2d_forward_naive\n\npaddle.enable_static()\n\n\ndef create_test_channel_last_class(parent):\n\n class TestChannelLastCase(parent):\n\n def init_data_format(self):\n self.data_format = \"NHWC\"\n\n def init_test_case_2(self):\n N, C, H, W = self.input_size\n self.input_size = [N, H, W, C]\n\n cls_name = \"{0}_{1}\".format(parent.__name__, \"ChannelLast\")\n TestChannelLastCase.__name__ = cls_name\n globals()[cls_name] = TestChannelLastCase\n\n\ndef create_test_padding_SAME_class(parent):\n\n class TestPaddingSMAECase(parent):\n\n def init_paddings(self):\n self.pad = [0, 0]\n self.padding_algorithm = \"SAME\"\n\n cls_name = \"{0}_{1}\".format(parent.__name__, \"PaddingSAMEOp\")\n TestPaddingSMAECase.__name__ = cls_name\n globals()[cls_name] = TestPaddingSMAECase\n\n\ndef create_test_padding_VALID_class(parent):\n\n class TestPaddingVALIDCase(parent):\n\n def init_paddings(self):\n self.pad = [1, 1]\n self.padding_algorithm = \"VALID\"\n\n cls_name = \"{0}_{1}\".format(parent.__name__, \"PaddingVALIDOp\")\n TestPaddingVALIDCase.__name__ = cls_name\n globals()[cls_name] = TestPaddingVALIDCase\n\n\ndef create_test_fp16_class(parent):\n\n class TestFp16Case(parent):\n\n def init_dtype(self):\n self.dtype = np.float16\n\n cls_name = \"{0}_{1}\".format(parent.__name__, \"Fp16\")\n TestFp16Case.__name__ = cls_name\n globals()[cls_name] = TestFp16Case\n\n\nclass TestConv2DOp(OpTest):\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def init_dtype(self):\n self.dtype = np.float32\n\n def init_data_format(self):\n self.data_format = \"NCHW\"\n\n def setUp(self):\n self.set_mlu()\n self.op_type = \"conv2d\"\n self.init_data_format()\n self.init_dtype()\n self.init_group()\n self.init_dilation()\n self.init_test_case()\n\n conv2d_param = {\n 'stride': self.stride,\n 'pad': self.pad,\n 'dilation': self.dilations\n }\n\n input = np.random.random(self.input_size).astype(self.dtype)\n filter = np.random.uniform(-1, 1, self.filter_size).astype(self.dtype)\n\n output, _, _, _, _ = conv2d_forward_naive(input,\n filter,\n self.groups,\n conv2d_param,\n data_format=self.data_format)\n output = output.astype(self.dtype)\n\n self.inputs = {\n 'Input': OpTest.np_dtype_to_fluid_dtype(input),\n 'Filter': OpTest.np_dtype_to_fluid_dtype(filter)\n }\n self.attrs = {\n 'strides': self.stride,\n 'paddings': self.pad,\n 'groups': self.groups,\n 'dilations': self.dilations,\n 'data_format': self.data_format,\n }\n self.outputs = {'Output': output}\n\n def test_check_output(self):\n self.check_output_with_place(self.place, atol=1e-2)\n\n def test_check_grad(self):\n if self.dtype == np.float16:\n return\n self.check_grad_with_place(self.place, {'Input', 'Filter'},\n 'Output',\n max_relative_error=0.03,\n numeric_place=paddle.CPUPlace())\n\n def test_check_grad_no_filter(self):\n if self.dtype == np.float16:\n return\n self.check_grad_with_place(self.place, ['Input'],\n 'Output',\n max_relative_error=0.03,\n no_grad_set=set(['Filter']),\n numeric_place=paddle.CPUPlace())\n\n def test_check_grad_no_input(self):\n if self.dtype == np.float16:\n return\n self.check_grad_with_place(self.place, ['Filter'],\n 'Output',\n max_relative_error=0.03,\n no_grad_set=set(['Input']),\n numeric_place=paddle.CPUPlace())\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [6, f_c, 3, 3]\n\n def init_dilation(self):\n self.dilations = [1, 1]\n\n def init_group(self):\n self.groups = 1\n\n\nclass TestWithPad(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [6, f_c, 3, 3]\n\n\nclass TestWithStride(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.input_size = [2, 3, 6, 6] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [6, f_c, 3, 3]\n\n\nclass TestWithGroup(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n self.group = 3\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [18, f_c, 3, 3]\n\n\nclass TestWith1x1(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [120, f_c, 1, 1]\n\n def init_group(self):\n # FIXME: Supporting group = 3 in this case.\n # NOTE(wangran16): There is an unknown error (acl error code is : 507015)\n # when group = 3, which needs to be fixed.\n self.groups = 1\n\n\nclass TestWithDepthWise5x5(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.input_size = [2, 4, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [8, f_c, 5, 5]\n\n def init_group(self):\n self.groups = 4\n\n\nclass TestWithDepthWise7x7(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.input_size = [2, 8, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [16, f_c, 7, 7]\n\n def init_group(self):\n self.groups = 8\n\n\nclass TestWithDilation(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.input_size = [2, 3, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [12, f_c, 3, 3]\n\n def init_dilation(self):\n self.dilations = [2, 2]\n\n # TODO(MLU): Depthwise opration does not support dilation yet\n # it will throw an error of CNNL_STATUS_NOT_SUPPORTED.\n # def init_group(self):\n # self.groups = 3\n\n\nclass TestWithInput1x1Filter1x1(TestConv2DOp):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.input_size = [100, 1, 1, 1] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [120, f_c, 1, 1]\n\n def init_group(self):\n self.groups = 1\n\n\nclass TestConv2DOp_v2(OpTest):\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def setUp(self):\n self.set_mlu()\n self.op_type = \"conv2d\"\n self.dtype = np.float32\n self.init_kernel_type()\n self.init_group()\n self.init_dilation()\n self.init_data_format()\n self.init_test_case()\n self.init_paddings()\n self.init_test_case_2()\n\n conv2d_param = {\n 'stride': self.stride,\n 'pad': self.pad,\n 'dilation': self.dilations\n }\n\n input = np.random.random(self.input_size).astype(self.dtype)\n filter = np.random.uniform(-1, 1, self.filter_size).astype(self.dtype)\n output, _, _, _, _ = conv2d_forward_naive(input, filter, self.groups,\n conv2d_param,\n self.padding_algorithm,\n self.data_format)\n output = output.astype(self.dtype)\n\n self.inputs = {\n 'Input': OpTest.np_dtype_to_fluid_dtype(input),\n 'Filter': OpTest.np_dtype_to_fluid_dtype(filter)\n }\n self.attrs = {\n 'strides': self.stride,\n 'paddings': self.pad,\n 'padding_algorithm': self.padding_algorithm,\n 'groups': self.groups,\n 'dilations': self.dilations,\n 'data_format': self.data_format,\n }\n self.outputs = {'Output': output}\n\n def test_check_output(self):\n self.check_output_with_place(self.place, atol=1e-2)\n\n def test_check_grad(self):\n if self.dtype == np.float16:\n return\n self.check_grad_with_place(self.place, {'Input', 'Filter'},\n 'Output',\n max_relative_error=0.02,\n numeric_place=paddle.CPUPlace())\n\n def test_check_grad_no_filter(self):\n if self.dtype == np.float16:\n return\n self.check_grad_with_place(self.place, ['Input'],\n 'Output',\n max_relative_error=0.02,\n no_grad_set=set(['Filter']),\n numeric_place=paddle.CPUPlace())\n\n def test_check_grad_no_input(self):\n if self.dtype == np.float16:\n return\n self.check_grad_with_place(self.place, ['Filter'],\n 'Output',\n no_grad_set=set(['Input']),\n numeric_place=paddle.CPUPlace())\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 2]\n self.input_size = [2, 3, 5, 5] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [6, f_c, 4, 3]\n\n def init_dilation(self):\n self.dilations = [1, 1]\n\n def init_group(self):\n self.groups = 1\n\n def init_kernel_type(self):\n pass\n\n def init_paddings(self):\n self.pad = [0, 0]\n self.padding_algorithm = \"EXPLICIT\"\n\n def init_data_format(self):\n self.data_format = \"NCHW\"\n\n def init_test_case_2(self):\n pass\n\n\nclass TestConv2DOp_AsyPadding(TestConv2DOp_v2):\n\n def init_paddings(self):\n self.pad = [0, 0, 1, 2]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithPad_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [6, f_c, 3, 3]\n\n def init_paddings(self):\n self.pad = [2, 1, 3, 2]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithStride_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [2, 2]\n self.input_size = [2, 3, 6, 6] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [6, f_c, 3, 3]\n\n def init_paddings(self):\n self.pad = [2, 1, 3, 2]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithGroup_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 2]\n self.input_size = [2, 3, 5, 5] # NCHW\n self.group = 3\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [24, f_c, 4, 3]\n\n\nclass TestWith1x1_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [120, f_c, 1, 1]\n\n def init_group(self):\n self.groups = 1\n\n def init_paddings(self):\n self.pad = [2, 2, 4, 0]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithDepthWise3x3_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.input_size = [3, 4, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [16, f_c, 3, 3]\n\n # TODO(MLU): Depthwise opration does not support dilation yet\n # it will throw an error of CNNL_STATUS_NOT_SUPPORTED.\n # def init_dilation(self):\n # self.dilations = [2, 2]\n\n def init_group(self):\n self.groups = 4\n\n def init_paddings(self):\n self.pad = [1, 3, 2, 1]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithDepthWise5x5_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.input_size = [2, 4, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [8, f_c, 5, 5]\n\n def init_group(self):\n self.groups = 4\n\n def init_paddings(self):\n self.pad = [0, 1, 1, 0]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithDepthWise7x7_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [2, 2]\n self.input_size = [2, 8, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [16, f_c, 7, 7]\n\n def init_group(self):\n self.groups = 8\n\n def init_paddings(self):\n self.pad = [1, 3, 4, 1]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithDilation_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.input_size = [2, 3, 10, 10] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [24, f_c, 3, 3]\n\n def init_dilation(self):\n self.dilations = [2, 2]\n\n # TODO(MLU): Depthwise opration does not support dilation yet\n # it will throw an error of CNNL_STATUS_NOT_SUPPORTED.\n # def init_group(self):\n # self.groups = 3\n\n def init_paddings(self):\n self.pad = [0, 1, 3, 0]\n self.padding_algorithm = \"EXPLICIT\"\n\n\nclass TestWithInput1x1Filter1x1_AsyPadding(TestConv2DOp_v2):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.input_size = [100, 1, 1, 1] # NCHW\n assert np.mod(self.input_size[1], self.groups) == 0\n f_c = self.input_size[1] // self.groups\n self.filter_size = [120, f_c, 1, 1]\n\n def init_group(self):\n self.groups = 1\n\n def init_paddings(self):\n self.pad = [0, 3, 4, 0]\n self.padding_algorithm = \"EXPLICIT\"\n\n\ncreate_test_padding_SAME_class(TestConv2DOp_AsyPadding)\ncreate_test_padding_SAME_class(TestWithPad_AsyPadding)\ncreate_test_padding_SAME_class(TestWithStride_AsyPadding)\ncreate_test_padding_SAME_class(TestWithGroup_AsyPadding)\ncreate_test_padding_SAME_class(TestWithInput1x1Filter1x1_AsyPadding)\n\ncreate_test_padding_VALID_class(TestConv2DOp_AsyPadding)\ncreate_test_padding_VALID_class(TestWithPad_AsyPadding)\ncreate_test_padding_VALID_class(TestWithStride_AsyPadding)\ncreate_test_padding_VALID_class(TestWithGroup_AsyPadding)\ncreate_test_padding_VALID_class(TestWithInput1x1Filter1x1_AsyPadding)\n\ncreate_test_channel_last_class(TestConv2DOp_AsyPadding)\ncreate_test_channel_last_class(TestWithPad_AsyPadding)\ncreate_test_channel_last_class(TestWithGroup_AsyPadding)\ncreate_test_channel_last_class(TestWith1x1_AsyPadding)\ncreate_test_channel_last_class(TestWithInput1x1Filter1x1_AsyPadding)\n\ncreate_test_fp16_class(TestConv2DOp_AsyPadding)\ncreate_test_fp16_class(TestWithPad_AsyPadding)\ncreate_test_fp16_class(TestWithStride_AsyPadding)\ncreate_test_fp16_class(TestWithGroup_AsyPadding)\ncreate_test_fp16_class(TestWithInput1x1Filter1x1_AsyPadding)\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\")\n\nimport paddle\nfrom op_test import OpTest\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestArgMax(XPUOpTestWrapper):\n\n def __init__(self):\n self.op_name = 'arg_max'\n\n class XPUBaseTestCase(XPUOpTest):\n\n def initTestCase(self):\n self.dims = (3, 4)\n self.axis = 1\n\n def setUp(self):\n self.op_type = 'arg_max'\n self.dtype = self.in_type\n self.initTestCase()\n\n self.x = (np.random.random(self.dims)).astype(self.dtype)\n self.inputs = {'X': self.x}\n self.attrs = {'axis': self.axis, 'use_xpu': True}\n self.outputs = {'Out': np.argmax(self.x, axis=self.axis)}\n\n def test_check_output(self):\n if paddle.is_compiled_with_xpu():\n place = paddle.XPUPlace(0)\n self.check_output_with_place(place)\n\n class TestArgMaxCase1(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4, 5)\n self.axis = -1\n\n class TestArgMaxCase2(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4, 5)\n self.axis = 0\n\n class TestArgMaxCase3(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4, 5)\n self.axis = 1\n\n class TestArgMaxCase4(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4, 5)\n self.axis = 2\n\n class TestArgMaxCase5(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4)\n self.axis = -1\n\n class TestArgMaxCase6(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4)\n self.axis = 0\n\n class TestArgMaxCase7(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, 4)\n self.axis = 1\n\n class TestArgMaxCase8(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (1, )\n self.axis = 0\n\n class TestArgMaxCase9(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (2, )\n self.axis = 0\n\n class TestArgMaxCase10(XPUBaseTestCase):\n\n def initTestCase(self):\n self.dims = (3, )\n self.axis = 0\n\n\nsupport_types = get_xpu_op_support_types('arg_max')\nfor stype in support_types:\n create_test_class(globals(), XPUTestArgMax, stype)\n\n\nclass TestArgMaxAPI(unittest.TestCase):\n\n def initTestCase(self):\n self.dims = (3, 4, 5)\n self.dtype = 'float32'\n self.axis = 0\n\n def setUp(self):\n self.initTestCase()\n self.__class__.use_Xpu = True\n self.place = [paddle.XPUPlace(0)]\n\n def test_dygraph_api(self):\n\n def run(place):\n paddle.disable_static(place)\n np.random.seed(2021)\n numpy_input = (np.random.random(self.dims)).astype(self.dtype)\n tensor_input = paddle.to_tensor(numpy_input)\n numpy_output = np.argmax(numpy_input, axis=self.axis)\n paddle_output = paddle.argmax(tensor_input, axis=self.axis)\n self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()),\n True)\n paddle.enable_static()\n\n for place in self.place:\n run(place)\n\n\nclass TestArgMaxAPI_2(unittest.TestCase):\n\n def initTestCase(self):\n self.dims = (3, 4, 5)\n self.dtype = 'float32'\n self.axis = 0\n self.keep_dims = True\n\n def setUp(self):\n self.initTestCase()\n self.__class__.use_xpu = True\n self.place = [paddle.XPUPlace(0)]\n\n def test_dygraph_api(self):\n\n def run(place):\n paddle.disable_static(place)\n np.random.seed(2021)\n numpy_input = (np.random.random(self.dims)).astype(self.dtype)\n tensor_input = paddle.to_tensor(numpy_input)\n numpy_output = np.argmax(numpy_input,\n axis=self.axis).reshape(1, 4, 5)\n paddle_output = paddle.argmax(tensor_input,\n axis=self.axis,\n keepdim=self.keep_dims)\n self.assertEqual(np.allclose(numpy_output, paddle_output.numpy()),\n True)\n self.assertEqual(numpy_output.shape, paddle_output.numpy().shape)\n paddle.enable_static()\n\n for place in self.place:\n run(place)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport paddle\nimport paddle.fluid.core as core\nimport numpy\n\n\nclass TestLoDTensorArray(unittest.TestCase):\n\n def test_get_set(self):\n scope = core.Scope()\n arr = scope.var('tmp_lod_tensor_array')\n tensor_array = arr.get_lod_tensor_array()\n self.assertEqual(0, len(tensor_array))\n cpu = core.CPUPlace()\n for i in range(10):\n t = core.LoDTensor()\n t.set(numpy.array([i], dtype='float32'), cpu)\n t.set_recursive_sequence_lengths([[1]])\n tensor_array.append(t)\n\n self.assertEqual(10, len(tensor_array))\n\n for i in range(10):\n t = tensor_array[i]\n self.assertEqual(numpy.array(t), numpy.array([i], dtype='float32'))\n self.assertEqual([[1]], t.recursive_sequence_lengths())\n\n t = core.LoDTensor()\n t.set(numpy.array([i + 10], dtype='float32'), cpu)\n t.set_recursive_sequence_lengths([[1]])\n tensor_array[i] = t\n t = tensor_array[i]\n self.assertEqual(numpy.array(t),\n numpy.array([i + 10], dtype='float32'))\n self.assertEqual([[1]], t.recursive_sequence_lengths())\n\n\nclass TestCreateArray(unittest.TestCase):\n\n def setUp(self):\n self.place = paddle.CPUPlace()\n self.shapes = [[10, 4], [8, 12], [1]]\n\n def test_initialized_list_and_error(self):\n paddle.disable_static()\n init_data = [\n numpy.random.random(shape).astype('float32')\n for shape in self.shapes\n ]\n array = paddle.tensor.create_array(\n 'float32', [paddle.to_tensor(x) for x in init_data])\n for res, gt in zip(array, init_data):\n self.assertTrue(numpy.array_equal(res, gt))\n\n # test for None\n array = paddle.tensor.create_array('float32')\n self.assertTrue(isinstance(array, list))\n self.assertEqual(len(array), 0)\n\n # test error\n with self.assertRaises(TypeError):\n paddle.tensor.create_array('float32', 'str')\n\n def test_static(self):\n paddle.enable_static()\n init_data = [paddle.ones(shape, dtype='int32') for shape in self.shapes]\n array = paddle.tensor.create_array('float32', init_data)\n for res, gt in zip(array, init_data):\n self.assertTrue(res.shape, gt.shape)\n\n # test error with nest list\n with self.assertRaises(TypeError):\n paddle.tensor.create_array('float32',\n [init_data[0], [init_data[1]]])\n\n # test error with not variable\n with self.assertRaises(TypeError):\n paddle.tensor.create_array('float32', (\"str\"))\n\n paddle.enable_static()\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle.fluid.core as core\nfrom paddle.fluid.tests.unittests.op_test import OpTest, OpTestTool, convert_float_to_uint16\nfrom paddle.fluid.tests.unittests.test_pool2d_op import TestPool2D_Op_Mixin, max_pool2D_forward_naive\nfrom paddle.fluid.tests.unittests.npu.test_pool2d_op_npu import pool2d_backward_navie as pool2d_backward_naive\nfrom paddle import enable_static\n\n\[email protected]_if_not_cpu_bf16()\nclass TestPoolBf16MklDNNOpGrad(TestPool2D_Op_Mixin, OpTest):\n\n def init_kernel_type(self):\n self.use_mkldnn = True\n\n def init_data_type(self):\n self.dtype = np.uint16\n\n def setUp(self):\n super(TestPoolBf16MklDNNOpGrad, self).setUp()\n self.attrs['mkldnn_data_type'] = \"bfloat16\"\n self.x_fp32 = np.random.random(self.shape).astype(np.float32)\n\n output = self.pool2D_forward_naive(self.x_fp32, self.ksize,\n self.strides, self.paddings,\n self.global_pool, self.ceil_mode,\n self.exclusive, self.adaptive,\n \"float32\").astype(np.float32)\n\n self.inputs = {'X': convert_float_to_uint16(self.x_fp32)}\n self.outputs = {'Out': convert_float_to_uint16(output)}\n\n def test_check_output(self):\n self.check_output_with_place(core.CPUPlace())\n\n def test_check_grad(self):\n x_grad = pool2d_backward_naive(self.x_fp32,\n ksize=self.ksize,\n strides=self.strides,\n paddings=self.paddings,\n global_pool=self.global_pool,\n ceil_mode=False,\n exclusive=self.exclusive,\n adaptive=self.adaptive,\n data_format=self.data_format,\n pool_type=self.pool_type,\n padding_algorithm=self.padding_algorithm)\n x_grad = x_grad / np.prod(self.outputs['Out'].shape)\n self.check_grad_with_place(core.CPUPlace(),\n set(['X']),\n 'Out',\n user_defined_grads=[x_grad])\n\n\[email protected]_if_not_cpu_bf16()\nclass TestPoolBf16MklDNNOp(TestPool2D_Op_Mixin, OpTest):\n\n def init_kernel_type(self):\n self.use_mkldnn = True\n\n def setUp(self):\n TestPool2D_Op_Mixin.setUp(self)\n self.dtype = np.uint16\n\n input = np.random.random(self.shape).astype(np.float32)\n output = (self.pool2D_forward_naive(input, self.ksize, self.strides,\n self.paddings, self.global_pool,\n self.ceil_mode, self.exclusive,\n self.adaptive,\n \"float32\")).astype(np.float32)\n\n self.inputs = {'X': convert_float_to_uint16(input)}\n self.outputs = {'Out': convert_float_to_uint16(output)}\n\n def test_check_output(self):\n self.check_output_with_place(core.CPUPlace())\n\n def test_check_grad(self):\n pass\n\n\nclass TestCase1Avg(TestPoolBf16MklDNNOp):\n\n def init_test_case(self):\n self.shape = [2, 3, 7, 7]\n self.ksize = [3, 3]\n self.strides = [1, 1]\n self.paddings = [0, 0]\n\n def init_global_pool(self):\n self.global_pool = False\n\n def init_exclusive(self):\n self.exclusive = True\n\n\nclass TestCase2Avg(TestPoolBf16MklDNNOp):\n\n def init_test_case(self):\n self.shape = [2, 3, 7, 7]\n self.ksize = [3, 3]\n self.strides = [1, 1]\n self.paddings = [1, 1]\n\n def init_global_pool(self):\n self.global_pool = False\n\n def init_exclusive(self):\n self.exclusive = False\n\n\nclass TestCase0Max(TestPoolBf16MklDNNOp):\n\n def init_pool_type(self):\n self.pool_type = \"max\"\n self.pool2D_forward_naive = max_pool2D_forward_naive\n\n\nclass TestCase1Max(TestCase1Avg):\n\n def init_pool_type(self):\n self.pool_type = \"max\"\n self.pool2D_forward_naive = max_pool2D_forward_naive\n\n\nclass TestCase2Max(TestCase2Avg):\n\n def init_pool_type(self):\n self.pool_type = \"max\"\n self.pool2D_forward_naive = max_pool2D_forward_naive\n\n\nclass TestCase1PadZeroExclusiveAvgGrad(TestPoolBf16MklDNNOpGrad):\n\n def init_test_case(self):\n self.ksize = [3, 3]\n self.strides = [1, 1]\n\n def init_shape(self):\n self.shape = [2, 3, 7, 7]\n\n def init_paddings(self):\n self.paddings = [0, 0]\n\n def init_global_pool(self):\n self.global_pool = False\n\n def init_exclusive(self):\n self.exclusive = True\n\n\nclass TestCase2PadOneNonExclusiveAvgGrad(TestCase1PadZeroExclusiveAvgGrad):\n\n def init_exclusive(self):\n self.exclusive = False\n\n\nclass TestCase0InitialMaxGrad(TestPoolBf16MklDNNOpGrad):\n\n def init_pool_type(self):\n self.pool_type = \"max\"\n self.pool2D_forward_naive = max_pool2D_forward_naive\n\n\nclass TestCase1PadZeroExclusiveMaxGrad(TestCase1PadZeroExclusiveAvgGrad):\n\n def init_pool_type(self):\n self.pool_type = \"max\"\n self.pool2D_forward_naive = max_pool2D_forward_naive\n\n\nclass TestCase2PadOneNonExclusiveMaxGrad(TestCase2PadOneNonExclusiveAvgGrad):\n\n def init_pool_type(self):\n self.pool_type = \"max\"\n self.pool2D_forward_naive = max_pool2D_forward_naive\n\n\nif __name__ == \"__main__\":\n enable_static()\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle 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\nimport numpy as np\nimport unittest\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_data_feed()\n self.set_feed_attr()\n self.set_attrs()\n\n def set_training(self):\n self.is_training = True\n self.epoch = 100\n\n def set_data_feed(self):\n data = np.random.uniform(size=[1, 3, 10, 10]).astype('float32')\n self.feed_fp32 = {\"image\": data.astype(np.float32)}\n self.feed_fp16 = {\"image\": data.astype(np.float16)}\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n self.feed_dtype = [x.dtype for x in self.feed_fp32.values()]\n\n def set_attrs(self):\n self.attrs = {\n \"optimizer\": 'lamb',\n \"weight_decay\": 0.0,\n \"scaled_optimizer_state\": True\n }\n\n @IPUOpTest.static_graph\n def build_model(self):\n image = paddle.static.data(name='image',\n shape=[1, 3, 10, 10],\n dtype='float32')\n conv1 = paddle.static.nn.conv2d(image,\n num_filters=3,\n filter_size=3,\n bias_attr=False)\n loss = paddle.mean(conv1)\n\n weight_decay = self.attrs['weight_decay']\n opt = paddle.optimizer.Adam(learning_rate=1e-1,\n weight_decay=weight_decay)\n if self.attrs['optimizer'] == 'lamb':\n opt = paddle.optimizer.Lamb(learning_rate=1e-1,\n lamb_weight_decay=weight_decay)\n opt.minimize(loss)\n self.feed_list = [image.name]\n self.fetch_list = [loss.name]\n\n def run_model(self, exec_mode):\n ipu_strategy = paddle.static.IpuStrategy()\n ipu_strategy.set_graph_config(is_training=self.is_training)\n if self.is_ipu_mode(exec_mode):\n if \"use_no_bias_optimizer\" in self.attrs.keys():\n ipu_strategy.set_options({\n \"use_no_bias_optimizer\":\n self.attrs[\"use_no_bias_optimizer\"]\n })\n if \"scaled_optimizer_state\" in self.attrs.keys():\n ipu_strategy.set_options({\n \"scaled_optimizer_state\":\n self.attrs[\"scaled_optimizer_state\"]\n })\n self.run_op_test(exec_mode, ipu_strategy=ipu_strategy)\n\n def test(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model()\n self.run_model(m)\n self.check()\n\n\nclass TestScaledAdam(TestBase):\n\n def set_attrs(self):\n self.attrs = {\n \"optimizer\": 'adam',\n \"weight_decay\": 0.0,\n \"scaled_optimizer_state\": True\n }\n\n def set_atol(self):\n super().set_atol()\n self.atol = 1e-5\n self.rtol = 1e-5\n\n\[email protected]('cpu do not support AdamNoBias')\nclass TestScaledAdamNoBias(TestBase):\n\n def set_attrs(self):\n self.attrs = {\n \"optimizer\": 'adam',\n \"weight_decay\": 0.0,\n \"use_no_bias_optimizer\": True,\n \"scaled_optimizer_state\": True\n }\n\n\[email protected]('cpu do not support LambNoBias')\nclass TestScaledLambNoBias(TestBase):\n\n def set_attrs(self):\n self.attrs = {\n \"optimizer\": 'lamb',\n \"weight_decay\": 0.0,\n \"use_no_bias_optimizer\": True,\n \"scaled_optimizer_state\": True\n }\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\n\nimport paddle\nfrom paddle.autograd import PyLayer\nfrom paddle.distributed.fleet.utils import recompute\nimport random\n\nimport paddle.fluid.layers as layers\nfrom paddle.fluid.framework import _test_eager_guard\n\n\ndef get_fc_block(block_idx, input_size, is_last=False):\n block_name = \"block_\" + str(block_idx)\n block = paddle.nn.Sequential(\n (block_name + \"_fc_0\",\n paddle.nn.Linear(input_size, input_size, bias_attr=False)),\n (block_name + \"_dropout\", paddle.nn.Dropout(p=0.5)),\n (block_name + \"_relu_1\", paddle.nn.ReLU()),\n (block_name + \"_fc_1\",\n paddle.nn.Linear(input_size, input_size, bias_attr=False)),\n (block_name + \"_relu_2\", paddle.nn.ReLU()),\n )\n if is_last:\n block.add_sublayer(block_name + \"_fc_2\",\n paddle.nn.Linear(input_size, 1,\n bias_attr=False)) # add sublayer\n else:\n block.add_sublayer(block_name + \"_fc_2\",\n paddle.nn.Linear(input_size,\n input_size,\n bias_attr=False)) # add sublayer\n return block\n\n\nclass Naive_fc_net(paddle.nn.Layer):\n\n def __init__(self,\n input_size=10,\n recompute_blocks=[1, 3],\n recompute_kwargs={}):\n super(Naive_fc_net, self).__init__()\n self.recompute_blocks = recompute_blocks\n self.recompute_kwargs = recompute_kwargs\n self.runfunc0 = get_fc_block(0, input_size, is_last=False)\n self.runfunc1 = get_fc_block(1, input_size, is_last=False)\n self.runfunc2 = get_fc_block(2, input_size, is_last=False)\n self.runfunc3 = get_fc_block(3, input_size, is_last=False)\n self.runfunc4 = get_fc_block(4, input_size, is_last=True)\n\n def forward(self, inputs):\n\n if 0 in self.recompute_blocks:\n inputs = recompute(self.runfunc0, inputs)\n else:\n inputs = self.runfunc0(inputs)\n\n if 1 in self.recompute_blocks:\n inputs = recompute(self.runfunc1, inputs)\n else:\n inputs = self.runfunc1(inputs)\n\n if 2 in self.recompute_blocks:\n inputs = recompute(self.runfunc2, inputs, **self.recompute_kwargs)\n else:\n inputs = self.runfunc2(inputs)\n\n if 3 in self.recompute_blocks:\n inputs = recompute(self.runfunc3, inputs)\n else:\n inputs = self.runfunc3(inputs)\n\n if 4 in self.recompute_blocks:\n inputs = recompute(self.runfunc4, inputs)\n else:\n inputs = self.runfunc4(inputs)\n\n return inputs\n\n\ndef run_model(recompute_block=[],\n recompute_kwargs={},\n enable_autocast=False,\n pure_fp16=False):\n gen = paddle.seed(10)\n gen.manual_seed(10)\n np.random.seed(10)\n random.seed(10)\n\n batch_size, input_size = 1, 10\n model = Naive_fc_net(input_size,\n recompute_blocks=recompute_block,\n recompute_kwargs=recompute_kwargs)\n loss_fn = paddle.nn.MSELoss(reduction='mean')\n optimizer = paddle.optimizer.SGD(learning_rate=0.01,\n parameters=model.parameters())\n\n if enable_autocast:\n scaler = paddle.amp.GradScaler()\n\n loss_ = []\n param_ = []\n grad_ = []\n for step in range(10):\n\n x_data = np.random.randn(batch_size, input_size).astype(np.float32)\n x = paddle.to_tensor(x_data)\n # x.stop_gradient = False\n level = 'O2' if pure_fp16 else 'O1'\n with paddle.amp.auto_cast(True, level=level):\n y_pred = model(x)\n loss = y_pred.mean()\n if enable_autocast:\n scaler.scale(loss).backward()\n scaler.minimize(optimizer, loss)\n else:\n loss_.append(np.asarray(loss).tolist())\n loss.backward()\n optimizer.step()\n\n param_.append(np.asarray(model.parameters()[9]).tolist())\n grad_.append(np.asarray(model.parameters()[3]._grad_ivar()).tolist())\n\n optimizer.clear_grad()\n return loss_, param_, grad_\n\n\nclass TestPyLayer(unittest.TestCase):\n\n def test_base_case(self, enable_autocast=False, pure_fp16=False):\n\n def check_identical(loss_ref, param_ref, grad_ref, loss, param, grad):\n self.assertEqual(loss_ref, loss)\n self.assertEqual(param_ref, param)\n self.assertEqual(grad_ref, grad)\n\n # without recompute\n loss_ref, param_ref, grad_ref = run_model(\n recompute_block=[],\n enable_autocast=enable_autocast,\n pure_fp16=pure_fp16)\n\n # recompute second block\n loss, param, grad = run_model(recompute_block=[1],\n enable_autocast=enable_autocast,\n pure_fp16=pure_fp16)\n check_identical(loss_ref, param_ref, grad_ref, loss, param, grad)\n\n # recompute fourth block\n loss, param, grad = run_model(recompute_block=[3],\n enable_autocast=enable_autocast,\n pure_fp16=pure_fp16)\n check_identical(loss_ref, param_ref, grad_ref, loss, param, grad)\n\n # recompute second to fourth block\n loss, param, grad = run_model(recompute_block=[1, 2, 3],\n enable_autocast=enable_autocast,\n pure_fp16=pure_fp16)\n check_identical(loss_ref, param_ref, grad_ref, loss, param, grad)\n\n # recompute second & fourth block\n loss, param, grad = run_model(recompute_block=[1, 3],\n enable_autocast=enable_autocast,\n pure_fp16=pure_fp16)\n check_identical(loss_ref, param_ref, grad_ref, loss, param, grad)\n\n def test_fc_net_with_dropout(self):\n with _test_eager_guard():\n self.test_base_case()\n self.test_base_case()\n\n def test_fc_net_without_restore_rng(self):\n with _test_eager_guard():\n loss_ref, param_ref, grad_ref = run_model(\n recompute_block=[2],\n recompute_kwargs={\"preserve_rng_state\": False},\n enable_autocast=True)\n\n def test_fc_net_with_amp(self):\n with _test_eager_guard():\n self.test_base_case(enable_autocast=True)\n self.test_base_case(enable_autocast=True)\n\n def test_fc_net_with_fp16(self):\n with _test_eager_guard():\n self.test_base_case(enable_autocast=True, pure_fp16=True)\n self.test_base_case(enable_autocast=True, pure_fp16=True)\n\n def test_recompute_kwargs(self):\n with _test_eager_guard():\n paddle.set_device(\"gpu\")\n kwargs = {\"is_test\": False}\n with self.assertRaises(ValueError):\n loss_ref, param_ref, grad_ref = run_model(\n recompute_block=[2], recompute_kwargs=kwargs)\n paddle.set_device(\"gpu\")\n kwargs = {\"is_test\": False}\n with self.assertRaises(ValueError):\n loss_ref, param_ref, grad_ref = run_model(recompute_block=[2],\n recompute_kwargs=kwargs)\n\n def test_recompute_cpu_rng(self):\n with _test_eager_guard():\n paddle.set_device(\"cpu\")\n with self.assertRaises(RuntimeError):\n loss_ref, param_ref, grad_ref = run_model(recompute_block=[2])\n\n paddle.set_device(\"cpu\")\n with self.assertRaises(RuntimeError):\n loss_ref, param_ref, grad_ref = run_model(recompute_block=[2])\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.dygraph.jit import declarative\n\nSEED = 2020\nnp.random.seed(SEED)\n\n\ndef test_continue_in_for(x):\n x = fluid.dygraph.to_variable(x)\n for i in range(10):\n x += 1\n if i > 5:\n continue\n x += 10086\n x += i\n return x\n\n\ndef test_continue_in_for_at_end(x):\n x = fluid.dygraph.to_variable(x)\n for i in range(10):\n x += 1\n if i > 5:\n continue\n return x\n\n\ndef test_continue_in_while(x):\n x = fluid.dygraph.to_variable(x)\n i = fluid.layers.fill_constant(shape=[1], dtype='int32', value=0)\n while i < 10:\n i += 1\n if i > 5:\n continue\n x += 10086\n x += i\n return x\n\n\ndef test_break_in_for(x):\n x = fluid.dygraph.to_variable(x)\n for i in range(10):\n x += 1\n if i > 5:\n break\n x += 10086\n x += i\n return x\n\n\ndef test_break_in_for_at_end(x):\n x = fluid.dygraph.to_variable(x)\n for i in range(10):\n x += 1\n if i > 5:\n break\n return x\n\n\ndef test_break_in_while(x):\n x = fluid.dygraph.to_variable(x)\n i = fluid.layers.fill_constant(shape=[1], dtype='int32', value=0)\n while i < 10:\n i += 1\n if i > 5:\n break\n x += 10086\n x += i\n return x\n\n\ndef test_break_continue_in_for(x):\n x = fluid.dygraph.to_variable(x)\n\n for i in range(1, 10, 1):\n if i <= 4:\n x += 1\n continue\n else:\n x += 10010\n break\n x += 10086\n\n a = fluid.layers.fill_constant(shape=[1], dtype='int32', value=0)\n for i in range(1, 10, 1):\n if a <= 4:\n x += 1\n a += 1\n continue\n else:\n x += 10010\n break\n x += 10086\n\n return x\n\n\ndef test_for_in_else(x):\n x = fluid.dygraph.to_variable(x)\n\n # Case 1:\n if False:\n pass\n else:\n for i in range(0, 10):\n if i > 5:\n x += 1\n break\n x += i\n\n # Case 2:\n if False:\n pass\n else:\n for i in range(0, 10):\n x += 1\n break\n x += i\n return x\n\n\ndef while_loop_class_var(x):\n\n class Foo(object):\n\n def __init__(self):\n self.a = 3\n self.b = 4\n self.c = 5\n\n foo = Foo()\n i = fluid.dygraph.to_variable(x)\n while i < 10:\n foo.b = fluid.layers.zeros(shape=[1], dtype='float32')\n foo.c = foo.b + foo.a\n i += 1\n if foo.c < 0:\n continue\n if foo.c > 6:\n break\n return foo.c\n\n\ndef test_optim_break_in_for(x):\n x = paddle.to_tensor(x)\n for i in range(10):\n if x.sum() > 5:\n break\n x += 10086\n x += i\n if i < 3:\n x = x * 2\n return x\n\n\ndef test_optim_break_in_while(x):\n x = paddle.to_tensor(x)\n i = fluid.layers.fill_constant(shape=[1], dtype='int32', value=0)\n while i < 10:\n if i > 5:\n break\n x += 10086\n x += i\n i += 1\n return x\n\n\nclass TestContinueInFor(unittest.TestCase):\n\n def setUp(self):\n self.input = np.zeros((1)).astype('int64')\n self.place = fluid.CUDAPlace(\n 0) if fluid.is_compiled_with_cuda() else fluid.CPUPlace()\n self.init_dygraph_func()\n\n def init_dygraph_func(self):\n self.dygraph_func = test_continue_in_for\n\n def run_dygraph_mode(self):\n with fluid.dygraph.guard():\n res = self.dygraph_func(self.input)\n return res.numpy()\n\n def run_static_mode(self):\n with fluid.dygraph.guard():\n res = declarative(self.dygraph_func)(self.input)\n return res.numpy()\n\n def test_transformed_static_result(self):\n static_res = self.run_static_mode()\n dygraph_res = self.run_dygraph_mode()\n self.assertTrue(np.allclose(dygraph_res, static_res),\n msg='dygraph res is {}\\nstatic_res is {}'.format(\n dygraph_res, static_res))\n\n\nclass TestContinueInForAtEnd(TestContinueInFor):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_continue_in_for_at_end\n\n\nclass TestBreakInFor(TestContinueInFor):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_break_in_for\n\n\nclass TestBreakInForAtEnd(TestContinueInFor):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_break_in_for_at_end\n\n\nclass TestBreakContinueInFor(TestContinueInFor):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_break_continue_in_for\n\n\nclass TestForInElse(TestContinueInFor):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_for_in_else\n\n\nclass TestContinueInWhile(TestContinueInFor):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_continue_in_while\n\n\nclass TestBreakInWhile(TestContinueInWhile):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_break_in_while\n\n\nclass TestWhileLoopClassVar(TestContinueInWhile):\n\n def init_dygraph_func(self):\n self.dygraph_func = while_loop_class_var\n\n\nclass TestOptimBreakInFor(TestContinueInWhile):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_optim_break_in_for\n\n\nclass TestOptimBreakInWhile(TestContinueInWhile):\n\n def init_dygraph_func(self):\n self.dygraph_func = test_optim_break_in_while\n\n\nif __name__ == '__main__':\n with fluid.framework._test_eager_guard():\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\n\nimport math\nimport sys\nimport random\n\nimport numpy as np\nimport numbers\nimport types\nimport collections\nimport warnings\nimport traceback\n\nimport paddle\nfrom paddle.utils import try_import\nfrom . import functional as F\n\nif sys.version_info < (3, 3):\n Sequence = collections.Sequence\n Iterable = collections.Iterable\nelse:\n Sequence = collections.abc.Sequence\n Iterable = collections.abc.Iterable\n\n__all__ = []\n\n\ndef _get_image_size(img):\n if F._is_pil_image(img):\n return img.size\n elif F._is_numpy_image(img):\n return img.shape[:2][::-1]\n elif F._is_tensor_image(img):\n if len(img.shape) == 3:\n return img.shape[1:][::-1] # chw -> wh\n elif len(img.shape) == 4:\n return img.shape[2:][::-1] # nchw -> wh\n else:\n raise ValueError(\n \"The dim for input Tensor should be 3-D or 4-D, but received {}\"\n .format(len(img.shape)))\n else:\n raise TypeError(\"Unexpected type {}\".format(type(img)))\n\n\ndef _check_input(value,\n name,\n center=1,\n bound=(0, float('inf')),\n clip_first_on_zero=True):\n if isinstance(value, numbers.Number):\n if value < 0:\n raise ValueError(\n \"If {} is a single number, it must be non negative.\".format(\n name))\n value = [center - value, center + value]\n if clip_first_on_zero:\n value[0] = max(value[0], 0)\n elif isinstance(value, (tuple, list)) and len(value) == 2:\n if not bound[0] <= value[0] <= value[1] <= bound[1]:\n raise ValueError(\"{} values should be between {}\".format(\n name, bound))\n else:\n raise TypeError(\n \"{} should be a single number or a list/tuple with lenght 2.\".\n format(name))\n\n if value[0] == value[1] == center:\n value = None\n return value\n\n\nclass Compose(object):\n \"\"\"\n Composes several transforms together use for composing list of transforms\n together for a dataset transform.\n\n Args:\n transforms (list|tuple): List/Tuple of transforms to compose.\n\n Returns:\n A compose object which is callable, __call__ for this Compose\n object will call each given :attr:`transforms` sequencely.\n\n Examples:\n \n .. code-block:: python\n\n from paddle.vision.datasets import Flowers\n from paddle.vision.transforms import Compose, ColorJitter, Resize\n\n transform = Compose([ColorJitter(), Resize(size=608)])\n flowers = Flowers(mode='test', transform=transform)\n\n for i in range(10):\n sample = flowers[i]\n print(sample[0].size, sample[1])\n\n \"\"\"\n\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, data):\n for f in self.transforms:\n try:\n data = f(data)\n except Exception as e:\n stack_info = traceback.format_exc()\n print(\"fail to perform transform [{}] with error: \"\n \"{} and stack:\\n{}\".format(f, e, str(stack_info)))\n raise e\n return data\n\n def __repr__(self):\n format_string = self.__class__.__name__ + '('\n for t in self.transforms:\n format_string += '\\n'\n format_string += ' {0}'.format(t)\n format_string += '\\n)'\n return format_string\n\n\nclass BaseTransform(object):\n \"\"\"\n Base class of all transforms used in computer vision.\n\n calling logic: \n\n if keys is None:\n _get_params -> _apply_image()\n else:\n _get_params -> _apply_*() for * in keys \n\n If you want to implement a self-defined transform method for image,\n rewrite _apply_* method in subclass.\n\n Args:\n keys (list[str]|tuple[str], optional): Input type. Input is a tuple contains different structures,\n key is used to specify the type of input. For example, if your input\n is image type, then the key can be None or (\"image\"). if your input\n is (image, image) type, then the keys should be (\"image\", \"image\"). \n if your input is (image, boxes), then the keys should be (\"image\", \"boxes\").\n\n Current available strings & data type are describe below:\n\n - \"image\": input image, with shape of (H, W, C) \n - \"coords\": coordinates, with shape of (N, 2) \n - \"boxes\": bounding boxes, with shape of (N, 4), \"xyxy\" format, \n \n the 1st \"xy\" represents top left point of a box, \n the 2nd \"xy\" represents right bottom point.\n\n - \"mask\": map used for segmentation, with shape of (H, W, 1)\n \n You can also customize your data types only if you implement the corresponding\n _apply_*() methods, otherwise ``NotImplementedError`` will be raised.\n \n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n import paddle.vision.transforms.functional as F\n from paddle.vision.transforms import BaseTransform\n\n def _get_image_size(img):\n if F._is_pil_image(img):\n return img.size\n elif F._is_numpy_image(img):\n return img.shape[:2][::-1]\n else:\n raise TypeError(\"Unexpected type {}\".format(type(img)))\n\n class CustomRandomFlip(BaseTransform):\n def __init__(self, prob=0.5, keys=None):\n super(CustomRandomFlip, self).__init__(keys)\n self.prob = prob\n\n def _get_params(self, inputs):\n image = inputs[self.keys.index('image')]\n params = {}\n params['flip'] = np.random.random() < self.prob\n params['size'] = _get_image_size(image)\n return params\n\n def _apply_image(self, image):\n if self.params['flip']:\n return F.hflip(image)\n return image\n\n # if you only want to transform image, do not need to rewrite this function\n def _apply_coords(self, coords):\n if self.params['flip']:\n w = self.params['size'][0]\n coords[:, 0] = w - coords[:, 0]\n return coords\n\n # if you only want to transform image, do not need to rewrite this function\n def _apply_boxes(self, boxes):\n idxs = np.array([(0, 1), (2, 1), (0, 3), (2, 3)]).flatten()\n coords = np.asarray(boxes).reshape(-1, 4)[:, idxs].reshape(-1, 2)\n coords = self._apply_coords(coords).reshape((-1, 4, 2))\n minxy = coords.min(axis=1)\n maxxy = coords.max(axis=1)\n trans_boxes = np.concatenate((minxy, maxxy), axis=1)\n return trans_boxes\n \n # if you only want to transform image, do not need to rewrite this function\n def _apply_mask(self, mask):\n if self.params['flip']:\n return F.hflip(mask)\n return mask\n\n # create fake inputs\n fake_img = Image.fromarray((np.random.rand(400, 500, 3) * 255.).astype('uint8'))\n fake_boxes = np.array([[2, 3, 200, 300], [50, 60, 80, 100]])\n fake_mask = fake_img.convert('L')\n\n # only transform for image:\n flip_transform = CustomRandomFlip(1.0)\n converted_img = flip_transform(fake_img)\n\n # transform for image, boxes and mask\n flip_transform = CustomRandomFlip(1.0, keys=('image', 'boxes', 'mask'))\n (converted_img, converted_boxes, converted_mask) = flip_transform((fake_img, fake_boxes, fake_mask))\n print('converted boxes', converted_boxes)\n\n \"\"\"\n\n def __init__(self, keys=None):\n if keys is None:\n keys = (\"image\", )\n elif not isinstance(keys, Sequence):\n raise ValueError(\n \"keys should be a sequence, but got keys={}\".format(keys))\n for k in keys:\n if self._get_apply(k) is None:\n raise NotImplementedError(\n \"{} is unsupported data structure\".format(k))\n self.keys = keys\n\n # storage some params get from function get_params()\n self.params = None\n\n def _get_params(self, inputs):\n pass\n\n def __call__(self, inputs):\n \"\"\"Apply transform on single input data\"\"\"\n if not isinstance(inputs, tuple):\n inputs = (inputs, )\n\n self.params = self._get_params(inputs)\n\n outputs = []\n for i in range(min(len(inputs), len(self.keys))):\n apply_func = self._get_apply(self.keys[i])\n if apply_func is None:\n outputs.append(inputs[i])\n else:\n outputs.append(apply_func(inputs[i]))\n if len(inputs) > len(self.keys):\n outputs.extend(inputs[len(self.keys):])\n\n if len(outputs) == 1:\n outputs = outputs[0]\n else:\n outputs = tuple(outputs)\n return outputs\n\n def _get_apply(self, key):\n return getattr(self, \"_apply_{}\".format(key), None)\n\n def _apply_image(self, image):\n raise NotImplementedError\n\n def _apply_boxes(self, boxes):\n raise NotImplementedError\n\n def _apply_mask(self, mask):\n raise NotImplementedError\n\n\nclass ToTensor(BaseTransform):\n \"\"\"Convert a ``PIL.Image`` or ``numpy.ndarray`` to ``paddle.Tensor``.\n\n Converts a PIL.Image or numpy.ndarray (H x W x C) to a paddle.Tensor of shape (C x H x W).\n\n If input is a grayscale image (H x W), it will be converted to a image of shape (H x W x 1). \n And the shape of output tensor will be (1 x H x W).\n\n If you want to keep the shape of output tensor as (H x W x C), you can set data_format = ``HWC`` .\n\n Converts a PIL.Image or numpy.ndarray in the range [0, 255] to a paddle.Tensor in the \n range [0.0, 1.0] if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, \n RGBA, CMYK, 1) or if the numpy.ndarray has dtype = np.uint8. \n\n In the other cases, tensors are returned without scaling.\n\n Args:\n data_format (str, optional): Data format of output tensor, should be 'HWC' or \n 'CHW'. Default: 'CHW'.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \n Shape:\n - img(PIL.Image|np.ndarray): The input image with shape (H x W x C).\n - output(np.ndarray): A tensor with shape (C x H x W) or (H x W x C) according option data_format.\n\n Returns:\n A callable object of ToTensor.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n\n import paddle.vision.transforms as T\n import paddle.vision.transforms.functional as F\n\n fake_img = Image.fromarray((np.random.rand(4, 5, 3) * 255.).astype(np.uint8))\n\n transform = T.ToTensor()\n\n tensor = transform(fake_img)\n \n print(tensor.shape)\n # [3, 4, 5]\n \n print(tensor.dtype)\n # paddle.float32\n \"\"\"\n\n def __init__(self, data_format='CHW', keys=None):\n super(ToTensor, self).__init__(keys)\n self.data_format = data_format\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL.Image|np.ndarray): Image to be converted to tensor.\n\n Returns:\n Tensor: Converted image.\n \"\"\"\n return F.to_tensor(img, self.data_format)\n\n\nclass Resize(BaseTransform):\n \"\"\"Resize the input Image to the given size.\n\n Args:\n size (int|list|tuple): Desired output size. If size is a sequence like\n (h, w), output size will be matched to this. If size is an int,\n smaller edge of the image will be matched to this number.\n i.e, if height > width, then image will be rescaled to\n (size * height / width, size)\n interpolation (int|str, optional): Interpolation method. Default: 'bilinear'. \n when use pil backend, support method are as following: \n - \"nearest\": Image.NEAREST, \n - \"bilinear\": Image.BILINEAR, \n - \"bicubic\": Image.BICUBIC, \n - \"box\": Image.BOX, \n - \"lanczos\": Image.LANCZOS, \n - \"hamming\": Image.HAMMING\n when use cv2 backend, support method are as following: \n - \"nearest\": cv2.INTER_NEAREST, \n - \"bilinear\": cv2.INTER_LINEAR, \n - \"area\": cv2.INTER_AREA, \n - \"bicubic\": cv2.INTER_CUBIC, \n - \"lanczos\": cv2.INTER_LANCZOS4\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A resized image.\n\n Returns:\n A callable object of Resize.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import Resize\n\n fake_img = Image.fromarray((np.random.rand(256, 300, 3) * 255.).astype(np.uint8))\n\n transform = Resize(size=224)\n converted_img = transform(fake_img)\n print(converted_img.size)\n # (262, 224)\n\n transform = Resize(size=(200,150))\n converted_img = transform(fake_img)\n print(converted_img.size)\n # (150, 200)\n \"\"\"\n\n def __init__(self, size, interpolation='bilinear', keys=None):\n super(Resize, self).__init__(keys)\n assert isinstance(size, int) or (isinstance(size, Iterable)\n and len(size) == 2)\n self.size = size\n self.interpolation = interpolation\n\n def _apply_image(self, img):\n return F.resize(img, self.size, self.interpolation)\n\n\nclass RandomResizedCrop(BaseTransform):\n \"\"\"Crop the input data to random size and aspect ratio.\n A crop of random size (default: of 0.08 to 1.0) of the original size and a random\n aspect ratio (default: of 3/4 to 1.33) of the original aspect ratio is made.\n After applying crop transfrom, the input data will be resized to given size.\n\n Args:\n size (int|list|tuple): Target size of output image, with (height, width) shape.\n scale (list|tuple): Scale range of the cropped image before resizing, relatively to the origin \n image. Default: (0.08, 1.0)\n ratio (list|tuple): Range of aspect ratio of the origin aspect ratio cropped. Default: (0.75, 1.33)\n interpolation (int|str, optional): Interpolation method. Default: 'bilinear'. when use pil backend, \n support method are as following: \n - \"nearest\": Image.NEAREST, \n - \"bilinear\": Image.BILINEAR, \n - \"bicubic\": Image.BICUBIC, \n - \"box\": Image.BOX, \n - \"lanczos\": Image.LANCZOS, \n - \"hamming\": Image.HAMMING\n when use cv2 backend, support method are as following: \n - \"nearest\": cv2.INTER_NEAREST, \n - \"bilinear\": cv2.INTER_LINEAR, \n - \"area\": cv2.INTER_AREA, \n - \"bicubic\": cv2.INTER_CUBIC, \n - \"lanczos\": cv2.INTER_LANCZOS4\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A cropped image.\n\n Returns:\n A callable object of RandomResizedCrop.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import RandomResizedCrop\n\n transform = RandomResizedCrop(224)\n\n fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.size)\n\n \"\"\"\n\n def __init__(self,\n size,\n scale=(0.08, 1.0),\n ratio=(3. / 4, 4. / 3),\n interpolation='bilinear',\n keys=None):\n super(RandomResizedCrop, self).__init__(keys)\n if isinstance(size, int):\n self.size = (size, size)\n else:\n self.size = size\n assert (scale[0] <= scale[1]), \"scale should be of kind (min, max)\"\n assert (ratio[0] <= ratio[1]), \"ratio should be of kind (min, max)\"\n self.scale = scale\n self.ratio = ratio\n self.interpolation = interpolation\n\n def _get_param(self, image, attempts=10):\n width, height = _get_image_size(image)\n area = height * width\n\n for _ in range(attempts):\n target_area = np.random.uniform(*self.scale) * area\n log_ratio = tuple(math.log(x) for x in self.ratio)\n aspect_ratio = math.exp(np.random.uniform(*log_ratio))\n\n w = int(round(math.sqrt(target_area * aspect_ratio)))\n h = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if 0 < w <= width and 0 < h <= height:\n i = random.randint(0, height - h)\n j = random.randint(0, width - w)\n return i, j, h, w\n\n # Fallback to central crop\n in_ratio = float(width) / float(height)\n if in_ratio < min(self.ratio):\n w = width\n h = int(round(w / min(self.ratio)))\n elif in_ratio > max(self.ratio):\n h = height\n w = int(round(h * max(self.ratio)))\n else:\n # return whole image\n w = width\n h = height\n i = (height - h) // 2\n j = (width - w) // 2\n return i, j, h, w\n\n def _apply_image(self, img):\n i, j, h, w = self._get_param(img)\n\n cropped_img = F.crop(img, i, j, h, w)\n return F.resize(cropped_img, self.size, self.interpolation)\n\n\nclass CenterCrop(BaseTransform):\n \"\"\"Crops the given the input data at the center.\n\n Args:\n size (int|list|tuple): Target size of output image, with (height, width) shape.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A cropped image.\n\n Returns:\n A callable object of CenterCrop.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import CenterCrop\n\n transform = CenterCrop(224)\n\n fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.size)\n \"\"\"\n\n def __init__(self, size, keys=None):\n super(CenterCrop, self).__init__(keys)\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n self.size = size\n\n def _apply_image(self, img):\n return F.center_crop(img, self.size)\n\n\nclass RandomHorizontalFlip(BaseTransform):\n \"\"\"Horizontally flip the input data randomly with a given probability.\n\n Args:\n prob (float, optional): Probability of the input data being flipped. Should be in [0, 1]. Default: 0.5\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A horiziotal flipped image.\n\n Returns:\n A callable object of RandomHorizontalFlip.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import RandomHorizontalFlip\n\n transform = RandomHorizontalFlip(0.5)\n\n fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.size)\n \"\"\"\n\n def __init__(self, prob=0.5, keys=None):\n super(RandomHorizontalFlip, self).__init__(keys)\n assert 0 <= prob <= 1, \"probability must be between 0 and 1\"\n self.prob = prob\n\n def _apply_image(self, img):\n if random.random() < self.prob:\n return F.hflip(img)\n return img\n\n\nclass RandomVerticalFlip(BaseTransform):\n \"\"\"Vertically flip the input data randomly with a given probability.\n\n Args:\n prob (float, optional): Probability of the input data being flipped. Default: 0.5\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A vertical flipped image.\n\n Returns:\n A callable object of RandomVerticalFlip.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import RandomVerticalFlip\n\n transform = RandomVerticalFlip()\n\n fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.size)\n\n \"\"\"\n\n def __init__(self, prob=0.5, keys=None):\n super(RandomVerticalFlip, self).__init__(keys)\n assert 0 <= prob <= 1, \"probability must be between 0 and 1\"\n self.prob = prob\n\n def _apply_image(self, img):\n if random.random() < self.prob:\n return F.vflip(img)\n return img\n\n\nclass Normalize(BaseTransform):\n \"\"\"Normalize the input data with mean and standard deviation.\n Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,\n this transform will normalize each channel of the input data.\n ``output[channel] = (input[channel] - mean[channel]) / std[channel]``\n\n Args:\n mean (int|float|list|tuple): Sequence of means for each channel.\n std (int|float|list|tuple): Sequence of standard deviations for each channel.\n data_format (str, optional): Data format of img, should be 'HWC' or \n 'CHW'. Default: 'CHW'.\n to_rgb (bool, optional): Whether to convert to rgb. Default: False.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A normalized array or tensor.\n\n Returns:\n A callable object of Normalize.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import Normalize\n\n normalize = Normalize(mean=[127.5, 127.5, 127.5], \n std=[127.5, 127.5, 127.5],\n data_format='HWC')\n\n fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))\n\n fake_img = normalize(fake_img)\n print(fake_img.shape)\n print(fake_img.max, fake_img.max)\n \n \"\"\"\n\n def __init__(self,\n mean=0.0,\n std=1.0,\n data_format='CHW',\n to_rgb=False,\n keys=None):\n super(Normalize, self).__init__(keys)\n if isinstance(mean, numbers.Number):\n mean = [mean, mean, mean]\n\n if isinstance(std, numbers.Number):\n std = [std, std, std]\n\n self.mean = mean\n self.std = std\n self.data_format = data_format\n self.to_rgb = to_rgb\n\n def _apply_image(self, img):\n return F.normalize(img, self.mean, self.std, self.data_format,\n self.to_rgb)\n\n\nclass Transpose(BaseTransform):\n \"\"\"Transpose input data to a target format.\n For example, most transforms use HWC mode image,\n while the Neural Network might use CHW mode input tensor.\n output image will be an instance of numpy.ndarray. \n\n Args:\n order (list|tuple, optional): Target order of input data. Default: (2, 0, 1).\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(np.ndarray|Paddle.Tensor): A transposed array or tensor. If input \n is a PIL.Image, output will be converted to np.ndarray automatically.\n\n Returns:\n A callable object of Transpose.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import Transpose\n\n transform = Transpose()\n\n fake_img = Image.fromarray((np.random.rand(300, 320, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.shape)\n \n \"\"\"\n\n def __init__(self, order=(2, 0, 1), keys=None):\n super(Transpose, self).__init__(keys)\n self.order = order\n\n def _apply_image(self, img):\n if F._is_tensor_image(img):\n return img.transpose(self.order)\n\n if F._is_pil_image(img):\n img = np.asarray(img)\n\n if len(img.shape) == 2:\n img = img[..., np.newaxis]\n return img.transpose(self.order)\n\n\nclass BrightnessTransform(BaseTransform):\n \"\"\"Adjust brightness of the image.\n\n Args:\n value (float): How much to adjust the brightness. Can be any\n non negative number. 0 gives the original image\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in brghtness.\n\n Returns:\n A callable object of BrightnessTransform.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import BrightnessTransform\n\n transform = BrightnessTransform(0.4)\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n \n \"\"\"\n\n def __init__(self, value, keys=None):\n super(BrightnessTransform, self).__init__(keys)\n self.value = _check_input(value, 'brightness')\n\n def _apply_image(self, img):\n if self.value is None:\n return img\n\n brightness_factor = random.uniform(self.value[0], self.value[1])\n return F.adjust_brightness(img, brightness_factor)\n\n\nclass ContrastTransform(BaseTransform):\n \"\"\"Adjust contrast of the image.\n\n Args:\n value (float): How much to adjust the contrast. Can be any\n non negative number. 0 gives the original image\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in contrast.\n\n Returns:\n A callable object of ContrastTransform.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import ContrastTransform\n\n transform = ContrastTransform(0.4)\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n\n \"\"\"\n\n def __init__(self, value, keys=None):\n super(ContrastTransform, self).__init__(keys)\n if value < 0:\n raise ValueError(\"contrast value should be non-negative\")\n self.value = _check_input(value, 'contrast')\n\n def _apply_image(self, img):\n if self.value is None:\n return img\n\n contrast_factor = random.uniform(self.value[0], self.value[1])\n return F.adjust_contrast(img, contrast_factor)\n\n\nclass SaturationTransform(BaseTransform):\n \"\"\"Adjust saturation of the image.\n\n Args:\n value (float): How much to adjust the saturation. Can be any\n non negative number. 0 gives the original image\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in saturation.\n\n Returns:\n A callable object of SaturationTransform.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import SaturationTransform\n\n transform = SaturationTransform(0.4)\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n \n fake_img = transform(fake_img)\n\n \"\"\"\n\n def __init__(self, value, keys=None):\n super(SaturationTransform, self).__init__(keys)\n self.value = _check_input(value, 'saturation')\n\n def _apply_image(self, img):\n if self.value is None:\n return img\n\n saturation_factor = random.uniform(self.value[0], self.value[1])\n return F.adjust_saturation(img, saturation_factor)\n\n\nclass HueTransform(BaseTransform):\n \"\"\"Adjust hue of the image.\n\n Args:\n value (float): How much to adjust the hue. Can be any number\n between 0 and 0.5, 0 gives the original image\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): An image with a transform in hue.\n\n Returns:\n A callable object of HueTransform.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import HueTransform\n\n transform = HueTransform(0.4)\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n\n \"\"\"\n\n def __init__(self, value, keys=None):\n super(HueTransform, self).__init__(keys)\n self.value = _check_input(value,\n 'hue',\n center=0,\n bound=(-0.5, 0.5),\n clip_first_on_zero=False)\n\n def _apply_image(self, img):\n if self.value is None:\n return img\n\n hue_factor = random.uniform(self.value[0], self.value[1])\n return F.adjust_hue(img, hue_factor)\n\n\nclass ColorJitter(BaseTransform):\n \"\"\"Randomly change the brightness, contrast, saturation and hue of an image.\n\n Args:\n brightness (float): How much to jitter brightness.\n Chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. Should be non negative numbers.\n contrast (float): How much to jitter contrast.\n Chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. Should be non negative numbers.\n saturation (float): How much to jitter saturation.\n Chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. Should be non negative numbers.\n hue (float): How much to jitter hue.\n Chosen uniformly from [-hue, hue]. Should have 0<= hue <= 0.5.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A color jittered image.\n\n Returns:\n A callable object of ColorJitter.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import ColorJitter\n\n transform = ColorJitter(0.4, 0.4, 0.4, 0.4)\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n\n \"\"\"\n\n def __init__(self,\n brightness=0,\n contrast=0,\n saturation=0,\n hue=0,\n keys=None):\n super(ColorJitter, self).__init__(keys)\n self.brightness = brightness\n self.contrast = contrast\n self.saturation = saturation\n self.hue = hue\n\n def _get_param(self, brightness, contrast, saturation, hue):\n \"\"\"Get a randomized transform to be applied on image.\n\n Arguments are same as that of __init__.\n\n Returns:\n Transform which randomly adjusts brightness, contrast and\n saturation in a random order.\n \"\"\"\n transforms = []\n\n if brightness is not None:\n transforms.append(BrightnessTransform(brightness, self.keys))\n\n if contrast is not None:\n transforms.append(ContrastTransform(contrast, self.keys))\n\n if saturation is not None:\n transforms.append(SaturationTransform(saturation, self.keys))\n\n if hue is not None:\n transforms.append(HueTransform(hue, self.keys))\n\n random.shuffle(transforms)\n transform = Compose(transforms)\n\n return transform\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL Image): Input image.\n\n Returns:\n PIL Image: Color jittered image.\n \"\"\"\n transform = self._get_param(self.brightness, self.contrast,\n self.saturation, self.hue)\n return transform(img)\n\n\nclass RandomCrop(BaseTransform):\n \"\"\"Crops the given CV Image at a random location.\n\n Args:\n size (sequence|int): Desired output size of the crop. If size is an\n int instead of sequence like (h, w), a square crop (size, size) is\n made.\n padding (int|sequence, optional): Optional padding on each border\n of the image. If a sequence of length 4 is provided, it is used to pad left, \n top, right, bottom borders respectively. Default: None, without padding.\n pad_if_needed (boolean, optional): It will pad the image if smaller than the\n desired size to avoid raising an exception. Default: False.\n fill (float|tuple, optional): Pixel fill value for constant fill. If a tuple of\n length 3, it is used to fill R, G, B channels respectively.\n This value is only used when the padding_mode is constant. Default: 0.\n padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default: 'constant'.\n\n - constant: pads with a constant value, this value is specified with fill\n\n - edge: pads with the last value on the edge of the image\n\n - reflect: pads with reflection of image (without repeating the last value on the edge)\n\n padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode\n will result in [3, 2, 1, 2, 3, 4, 3, 2]\n\n - symmetric: pads with reflection of image (repeating the last value on the edge)\n\n padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode\n will result in [2, 1, 1, 2, 3, 4, 4, 3]\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \n Shape\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A random cropped image.\n\n Returns:\n A callable object of RandomCrop.\n\n Examples:\n \n .. code-block:: python\n :name: code-example1\n\n import paddle\n from paddle.vision.transforms import RandomCrop\n transform = RandomCrop(224)\n\n fake_img = paddle.randint(0, 255, shape=(3, 324,300), dtype = 'int32')\n print(fake_img.shape) # [3, 324, 300]\n\n crop_img = transform(fake_img)\n print(crop_img.shape) # [3, 224, 224]\n \"\"\"\n\n def __init__(self,\n size,\n padding=None,\n pad_if_needed=False,\n fill=0,\n padding_mode='constant',\n keys=None):\n super(RandomCrop, self).__init__(keys)\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n self.size = size\n self.padding = padding\n self.pad_if_needed = pad_if_needed\n self.fill = fill\n self.padding_mode = padding_mode\n\n def _get_param(self, img, output_size):\n \"\"\"Get parameters for ``crop`` for a random crop.\n\n Args:\n img (PIL Image): Image to be cropped.\n output_size (tuple): Expected output size of the crop.\n\n Returns:\n tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.\n \"\"\"\n w, h = _get_image_size(img)\n th, tw = output_size\n if w == tw and h == th:\n return 0, 0, h, w\n\n i = random.randint(0, h - th)\n j = random.randint(0, w - tw)\n return i, j, th, tw\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be cropped.\n\n Returns:\n PIL Image: Cropped image.\n \"\"\"\n if self.padding is not None:\n img = F.pad(img, self.padding, self.fill, self.padding_mode)\n\n w, h = _get_image_size(img)\n\n # pad the width if needed\n if self.pad_if_needed and w < self.size[1]:\n img = F.pad(img, (self.size[1] - w, 0), self.fill,\n self.padding_mode)\n # pad the height if needed\n if self.pad_if_needed and h < self.size[0]:\n img = F.pad(img, (0, self.size[0] - h), self.fill,\n self.padding_mode)\n\n i, j, h, w = self._get_param(img, self.size)\n\n return F.crop(img, i, j, h, w)\n\n\nclass Pad(BaseTransform):\n \"\"\"Pads the given CV Image on all sides with the given \"pad\" value.\n\n Args:\n padding (int|list|tuple): Padding on each border. If a single int is provided this\n is used to pad all borders. If list/tuple of length 2 is provided this is the padding\n on left/right and top/bottom respectively. If a list/tuple of length 4 is provided\n this is the padding for the left, top, right and bottom borders\n respectively.\n fill (int|list|tuple): Pixel fill value for constant fill. Default is 0. If a list/tuple of\n length 3, it is used to fill R, G, B channels respectively.\n This value is only used when the padding_mode is constant\n padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.\n ``constant`` means pads with a constant value, this value is specified with fill. \n ``edge`` means pads with the last value at the edge of the image. \n ``reflect`` means pads with reflection of image (without repeating the last value on the edge) \n padding ``[1, 2, 3, 4]`` with 2 elements on both sides in reflect mode \n will result in ``[3, 2, 1, 2, 3, 4, 3, 2]``.\n ``symmetric`` menas pads with reflection of image (repeating the last value on the edge)\n padding ``[1, 2, 3, 4]`` with 2 elements on both sides in symmetric mode \n will result in ``[2, 1, 1, 2, 3, 4, 4, 3]``.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A paded image.\n\n Returns:\n A callable object of Pad.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import Pad\n\n transform = Pad(2)\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.size)\n \"\"\"\n\n def __init__(self, padding, fill=0, padding_mode='constant', keys=None):\n assert isinstance(padding, (numbers.Number, list, tuple))\n assert isinstance(fill, (numbers.Number, str, list, tuple))\n assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']\n\n if isinstance(padding, list):\n padding = tuple(padding)\n if isinstance(fill, list):\n fill = tuple(fill)\n\n if isinstance(padding, Sequence) and len(padding) not in [2, 4]:\n raise ValueError(\n \"Padding must be an int or a 2, or 4 element tuple, not a \" +\n \"{} element tuple\".format(len(padding)))\n\n super(Pad, self).__init__(keys)\n self.padding = padding\n self.fill = fill\n self.padding_mode = padding_mode\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be padded.\n\n Returns:\n PIL Image: Padded image.\n \"\"\"\n return F.pad(img, self.padding, self.fill, self.padding_mode)\n\n\ndef _check_sequence_input(x, name, req_sizes):\n msg = req_sizes[0] if len(req_sizes) < 2 else \" or \".join(\n [str(s) for s in req_sizes])\n if not isinstance(x, Sequence):\n raise TypeError(f\"{name} should be a sequence of length {msg}.\")\n if len(x) not in req_sizes:\n raise ValueError(f\"{name} should be sequence of length {msg}.\")\n\n\ndef _setup_angle(x, name, req_sizes=(2, )):\n if isinstance(x, numbers.Number):\n if x < 0:\n raise ValueError(\n f\"If {name} is a single number, it must be positive.\")\n x = [-x, x]\n else:\n _check_sequence_input(x, name, req_sizes)\n\n return [float(d) for d in x]\n\n\nclass RandomAffine(BaseTransform):\n \"\"\"Random affine transformation of the image.\n\n Args:\n degrees (int|float|tuple): The angle interval of the random rotation.\n If set as a number instead of sequence like (min, max), the range of degrees\n will be (-degrees, +degrees) in clockwise order. If set 0, will not rotate.\n translate (tuple, optional): Maximum absolute fraction for horizontal and vertical translations.\n For example translate=(a, b), then horizontal shift is randomly sampled in the range -img_width * a < dx < img_width * a\n and vertical shift is randomly sampled in the range -img_height * b < dy < img_height * b. \n Default is None, will not translate.\n scale (tuple, optional): Scaling factor interval, e.g (a, b), then scale is randomly sampled from the range a <= scale <= b. \n Default is None, will keep original scale and not scale.\n shear (sequence or number, optional): Range of degrees to shear, ranges from -180 to 180 in clockwise order.\n If set as a number, a shear parallel to the x axis in the range (-shear, +shear) will be applied. \n Else if set as a sequence of 2 values a shear parallel to the x axis in the range (shear[0], shear[1]) will be applied. \n Else if set as a sequence of 4 values, a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.\n Default is None, will not apply shear.\n interpolation (str, optional): Interpolation method. If omitted, or if the \n image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST \n according the backend. \n When use pil backend, support method are as following: \n - \"nearest\": Image.NEAREST, \n - \"bilinear\": Image.BILINEAR, \n - \"bicubic\": Image.BICUBIC\n When use cv2 backend, support method are as following: \n - \"nearest\": cv2.INTER_NEAREST, \n - \"bilinear\": cv2.INTER_LINEAR, \n - \"bicubic\": cv2.INTER_CUBIC\n fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed\n image. If given a number, the value is used for all bands respectively.\n center (2-tuple, optional): Optional center of rotation, (x, y).\n Origin is the upper left corner.\n Default is the center of the image.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): An affined image.\n\n Returns:\n A callable object of RandomAffine.\n\n Examples:\n \n .. code-block:: python\n\n import paddle\n from paddle.vision.transforms import RandomAffine\n\n transform = RandomAffine([-90, 90], translate=[0.2, 0.2], scale=[0.5, 0.5], shear=[-10, 10])\n\n fake_img = paddle.randn((3, 256, 300)).astype(paddle.float32)\n\n fake_img = transform(fake_img)\n print(fake_img.shape)\n \"\"\"\n\n def __init__(self,\n degrees,\n translate=None,\n scale=None,\n shear=None,\n interpolation='nearest',\n fill=0,\n center=None,\n keys=None):\n self.degrees = _setup_angle(degrees, name=\"degrees\", req_sizes=(2, ))\n\n super(RandomAffine, self).__init__(keys)\n assert interpolation in ['nearest', 'bilinear', 'bicubic']\n self.interpolation = interpolation\n\n if translate is not None:\n _check_sequence_input(translate, \"translate\", req_sizes=(2, ))\n for t in translate:\n if not (0.0 <= t <= 1.0):\n raise ValueError(\n \"translation values should be between 0 and 1\")\n self.translate = translate\n\n if scale is not None:\n _check_sequence_input(scale, \"scale\", req_sizes=(2, ))\n for s in scale:\n if s <= 0:\n raise ValueError(\"scale values should be positive\")\n self.scale = scale\n\n if shear is not None:\n self.shear = _setup_angle(shear, name=\"shear\", req_sizes=(2, 4))\n else:\n self.shear = shear\n\n if fill is None:\n fill = 0\n elif not isinstance(fill, (Sequence, numbers.Number)):\n raise TypeError(\"Fill should be either a sequence or a number.\")\n self.fill = fill\n\n if center is not None:\n _check_sequence_input(center, \"center\", req_sizes=(2, ))\n self.center = center\n\n def _get_param(self,\n img_size,\n degrees,\n translate=None,\n scale_ranges=None,\n shears=None):\n \"\"\"Get parameters for affine transformation\n\n Returns:\n params to be passed to the affine transformation\n \"\"\"\n angle = random.uniform(degrees[0], degrees[1])\n\n if translate is not None:\n max_dx = float(translate[0] * img_size[0])\n max_dy = float(translate[1] * img_size[1])\n tx = int(random.uniform(-max_dx, max_dx))\n ty = int(random.uniform(-max_dy, max_dy))\n translations = (tx, ty)\n else:\n translations = (0, 0)\n\n if scale_ranges is not None:\n scale = random.uniform(scale_ranges[0], scale_ranges[1])\n else:\n scale = 1.0\n\n shear_x, shear_y = 0.0, 0.0\n if shears is not None:\n shear_x = random.uniform(shears[0], shears[1])\n if len(shears) == 4:\n shear_y = random.uniform(shears[2], shears[3])\n shear = (shear_x, shear_y)\n\n return angle, translations, scale, shear\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL.Image|np.array): Image to be affine transformed.\n\n Returns:\n PIL.Image or np.array: Affine transformed image.\n \"\"\"\n\n w, h = _get_image_size(img)\n img_size = [w, h]\n\n ret = self._get_param(img_size, self.degrees, self.translate,\n self.scale, self.shear)\n\n return F.affine(img,\n *ret,\n interpolation=self.interpolation,\n fill=self.fill,\n center=self.center)\n\n\nclass RandomRotation(BaseTransform):\n \"\"\"Rotates the image by angle.\n\n Args:\n degrees (sequence or float or int): Range of degrees to select from.\n If degrees is a number instead of sequence like (min, max), the range of degrees\n will be (-degrees, +degrees) clockwise order.\n interpolation (str, optional): Interpolation method. If omitted, or if the \n image has only one channel, it is set to PIL.Image.NEAREST or cv2.INTER_NEAREST \n according the backend. when use pil backend, support method are as following: \n - \"nearest\": Image.NEAREST, \n - \"bilinear\": Image.BILINEAR, \n - \"bicubic\": Image.BICUBIC\n when use cv2 backend, support method are as following: \n - \"nearest\": cv2.INTER_NEAREST, \n - \"bilinear\": cv2.INTER_LINEAR, \n - \"bicubic\": cv2.INTER_CUBIC\n expand (bool|optional): Optional expansion flag. Default: False.\n If true, expands the output to make it large enough to hold the entire rotated image.\n If false or omitted, make the output image the same size as the input image.\n Note that the expand flag assumes rotation around the center and no translation.\n center (2-tuple|optional): Optional center of rotation.\n Origin is the upper left corner.\n Default is the center of the image.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A rotated image.\n\n Returns:\n A callable object of RandomRotation.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import RandomRotation\n\n transform = RandomRotation(90)\n\n fake_img = Image.fromarray((np.random.rand(200, 150, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(fake_img.size)\n \"\"\"\n\n def __init__(self,\n degrees,\n interpolation='nearest',\n expand=False,\n center=None,\n fill=0,\n keys=None):\n if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError(\n \"If degrees is a single number, it must be positive.\")\n self.degrees = (-degrees, degrees)\n else:\n if len(degrees) != 2:\n raise ValueError(\n \"If degrees is a sequence, it must be of len 2.\")\n self.degrees = degrees\n\n super(RandomRotation, self).__init__(keys)\n self.interpolation = interpolation\n self.expand = expand\n self.center = center\n self.fill = fill\n\n def _get_param(self, degrees):\n angle = random.uniform(degrees[0], degrees[1])\n\n return angle\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL.Image|np.array): Image to be rotated.\n\n Returns:\n PIL.Image or np.array: Rotated image.\n \"\"\"\n\n angle = self._get_param(self.degrees)\n\n return F.rotate(img, angle, self.interpolation, self.expand,\n self.center, self.fill)\n\n\nclass RandomPerspective(BaseTransform):\n \"\"\"Random perspective transformation with a given probability.\n\n Args:\n prob (float, optional): Probability of using transformation, ranges from\n 0 to 1, default is 0.5.\n distortion_scale (float, optional): Degree of distortion, ranges from\n 0 to 1, default is 0.5.\n interpolation (str, optional): Interpolation method. If omitted, or if\n the image has only one channel, it is set to PIL.Image.NEAREST or\n cv2.INTER_NEAREST.\n When use pil backend, support method are as following: \n - \"nearest\": Image.NEAREST, \n - \"bilinear\": Image.BILINEAR, \n - \"bicubic\": Image.BICUBIC\n When use cv2 backend, support method are as following: \n - \"nearest\": cv2.INTER_NEAREST, \n - \"bilinear\": cv2.INTER_LINEAR, \n - \"bicubic\": cv2.INTER_CUBIC\n fill (int|list|tuple, optional): Pixel fill value for the area outside the transformed\n image. If given a number, the value is used for all bands respectively.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): A perspectived image.\n\n Returns:\n A callable object of RandomPerspective.\n\n Examples:\n \n .. code-block:: python\n\n import paddle\n from paddle.vision.transforms import RandomPerspective\n\n transform = RandomPerspective(prob=1.0, distortion_scale=0.9)\n\n fake_img = paddle.randn((3, 200, 150)).astype(paddle.float32)\n\n fake_img = transform(fake_img)\n print(fake_img.shape)\n \"\"\"\n\n def __init__(self,\n prob=0.5,\n distortion_scale=0.5,\n interpolation='nearest',\n fill=0,\n keys=None):\n super(RandomPerspective, self).__init__(keys)\n assert 0 <= prob <= 1, \"probability must be between 0 and 1\"\n assert 0 <= distortion_scale <= 1, \"distortion_scale must be between 0 and 1\"\n assert interpolation in ['nearest', 'bilinear', 'bicubic']\n assert isinstance(fill, (numbers.Number, str, list, tuple))\n\n self.prob = prob\n self.distortion_scale = distortion_scale\n self.interpolation = interpolation\n self.fill = fill\n\n def get_params(self, width, height, distortion_scale):\n \"\"\"\n Returns:\n startpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the original image,\n endpoints (list[list[int]]): [top-left, top-right, bottom-right, bottom-left] of the transformed image.\n \"\"\"\n half_height = height // 2\n half_width = width // 2\n topleft = [\n int(random.uniform(0,\n int(distortion_scale * half_width) + 1)),\n int(random.uniform(0,\n int(distortion_scale * half_height) + 1)),\n ]\n topright = [\n int(\n random.uniform(width - int(distortion_scale * half_width) - 1,\n width)),\n int(random.uniform(0,\n int(distortion_scale * half_height) + 1)),\n ]\n botright = [\n int(\n random.uniform(width - int(distortion_scale * half_width) - 1,\n width)),\n int(\n random.uniform(height - int(distortion_scale * half_height) - 1,\n height)),\n ]\n botleft = [\n int(random.uniform(0,\n int(distortion_scale * half_width) + 1)),\n int(\n random.uniform(height - int(distortion_scale * half_height) - 1,\n height)),\n ]\n startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1],\n [0, height - 1]]\n endpoints = [topleft, topright, botright, botleft]\n\n return startpoints, endpoints\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL.Image|np.array|paddle.Tensor): Image to be Perspectively transformed.\n\n Returns:\n PIL.Image|np.array|paddle.Tensor: Perspectively transformed image.\n \"\"\"\n\n width, height = _get_image_size(img)\n\n if random.random() < self.prob:\n startpoints, endpoints = self.get_params(width, height,\n self.distortion_scale)\n return F.perspective(img, startpoints, endpoints,\n self.interpolation, self.fill)\n return img\n\n\nclass Grayscale(BaseTransform):\n \"\"\"Converts image to grayscale.\n\n Args:\n num_output_channels (int): (1 or 3) number of channels desired for output image\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n\n Shape:\n - img(PIL.Image|np.ndarray|Paddle.Tensor): The input image with shape (H x W x C).\n - output(PIL.Image|np.ndarray|Paddle.Tensor): Grayscale version of the input image. \n - If output_channels == 1 : returned image is single channel\n - If output_channels == 3 : returned image is 3 channel with r == g == b\n\n Returns:\n A callable object of Grayscale.\n\n Examples:\n \n .. code-block:: python\n\n import numpy as np\n from PIL import Image\n from paddle.vision.transforms import Grayscale\n\n transform = Grayscale()\n\n fake_img = Image.fromarray((np.random.rand(224, 224, 3) * 255.).astype(np.uint8))\n\n fake_img = transform(fake_img)\n print(np.array(fake_img).shape)\n \"\"\"\n\n def __init__(self, num_output_channels=1, keys=None):\n super(Grayscale, self).__init__(keys)\n self.num_output_channels = num_output_channels\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be converted to grayscale.\n\n Returns:\n PIL Image: Randomly grayscaled image.\n \"\"\"\n return F.to_grayscale(img, self.num_output_channels)\n\n\nclass RandomErasing(BaseTransform):\n \"\"\"Erase the pixels in a rectangle region selected randomly.\n\n Args:\n prob (float, optional): Probability of the input data being erased. Default: 0.5.\n scale (sequence, optional): The proportional range of the erased area to the input image. \n Default: (0.02, 0.33).\n ratio (sequence, optional): Aspect ratio range of the erased area. Default: (0.3, 3.3).\n value (int|float|sequence|str, optional): The value each pixel in erased area will be replaced with.\n If value is a single number, all pixels will be erased with this value. \n If value is a sequence with length 3, the R, G, B channels will be ereased \n respectively. If value is set to \"random\", each pixel will be erased with \n random values. Default: 0.\n inplace (bool, optional): Whether this transform is inplace. Default: False.\n keys (list[str]|tuple[str], optional): Same as ``BaseTransform``. Default: None.\n \n Shape:\n - img(paddle.Tensor | np.array | PIL.Image): The input image. For Tensor input, the shape should be (C, H, W). \n For np.array input, the shape should be (H, W, C).\n - output(paddle.Tensor | np.array | PIL.Image): A random erased image.\n\n Returns:\n A callable object of RandomErasing.\n\n Examples:\n \n .. code-block:: python\n\n import paddle\n \n fake_img = paddle.randn((3, 10, 10)).astype(paddle.float32)\n transform = paddle.vision.transforms.RandomErasing()\n result = transform(fake_img)\n\n print(result)\n \"\"\"\n\n def __init__(self,\n prob=0.5,\n scale=(0.02, 0.33),\n ratio=(0.3, 3.3),\n value=0,\n inplace=False,\n keys=None):\n super(RandomErasing, self).__init__(keys)\n assert isinstance(scale,\n (tuple, list)), \"scale should be a tuple or list\"\n assert (scale[0] >= 0 and scale[1] <= 1 and scale[0] <= scale[1]\n ), \"scale should be of kind (min, max) and in range [0, 1]\"\n assert isinstance(ratio,\n (tuple, list)), \"ratio should be a tuple or list\"\n assert (ratio[0] >= 0\n and ratio[0] <= ratio[1]), \"ratio should be of kind (min, max)\"\n assert (prob >= 0\n and prob <= 1), \"The probability should be in range [0, 1]\"\n assert isinstance(\n value, (numbers.Number, str, tuple,\n list)), \"value should be a number, tuple, list or str\"\n if isinstance(value, str) and value != \"random\":\n raise ValueError(\"value must be 'random' when type is str\")\n\n self.prob = prob\n self.scale = scale\n self.ratio = ratio\n self.value = value\n self.inplace = inplace\n\n def _get_param(self, img, scale, ratio, value):\n \"\"\"Get parameters for ``erase`` for a random erasing.\n\n Args:\n img (paddle.Tensor | np.array | PIL.Image): Image to be erased.\n scale (sequence, optional): The proportional range of the erased area to the input image. \n ratio (sequence, optional): Aspect ratio range of the erased area.\n value (sequence | None): The value each pixel in erased area will be replaced with.\n If value is a sequence with length 3, the R, G, B channels will be ereased \n respectively. If value is None, each pixel will be erased with random values.\n\n Returns:\n tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erase.\n \"\"\"\n if F._is_pil_image(img):\n shape = np.asarray(img).astype(np.uint8).shape\n h, w, c = shape[-3], shape[-2], shape[-1]\n elif F._is_numpy_image(img):\n h, w, c = img.shape[-3], img.shape[-2], img.shape[-1]\n elif F._is_tensor_image(img):\n c, h, w = img.shape[-3], img.shape[-2], img.shape[-1]\n\n img_area = h * w\n log_ratio = np.log(ratio)\n for _ in range(10):\n erase_area = np.random.uniform(*scale) * img_area\n aspect_ratio = np.exp(np.random.uniform(*log_ratio))\n erase_h = int(round(np.sqrt(erase_area * aspect_ratio)))\n erase_w = int(round(np.sqrt(erase_area / aspect_ratio)))\n if erase_h >= h or erase_w >= w:\n continue\n if F._is_tensor_image(img):\n if value is None:\n v = paddle.normal(shape=[c, erase_h, erase_w]).astype(\n img.dtype)\n else:\n v = paddle.to_tensor(value, dtype=img.dtype)[:, None, None]\n else:\n if value is None:\n v = np.random.normal(size=[erase_h, erase_w, c]) * 255\n else:\n v = np.array(value)[None, None, :]\n top = np.random.randint(0, h - erase_h + 1)\n left = np.random.randint(0, w - erase_w + 1)\n\n return top, left, erase_h, erase_w, v\n\n return 0, 0, h, w, img\n\n def _apply_image(self, img):\n \"\"\"\n Args:\n img (paddle.Tensor | np.array | PIL.Image): Image to be Erased.\n\n Returns:\n output (paddle.Tensor np.array | PIL.Image): A random erased image.\n \"\"\"\n\n if random.random() < self.prob:\n if isinstance(self.value, numbers.Number):\n value = [self.value]\n elif isinstance(self.value, str):\n value = None\n else:\n value = self.value\n if value is not None and not (len(value) == 1 or len(value) == 3):\n raise ValueError(\n \"Value should be a single number or a sequence with length equals to image's channel.\"\n )\n top, left, erase_h, erase_w, v = self._get_param(\n img, self.scale, self.ratio, value)\n return F.erase(img, top, left, erase_h, erase_w, v, self.inplace)\n return img\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_data_feed()\n self.set_feed_attr()\n self.set_op_attrs()\n\n def set_data_feed(self):\n data = np.random.uniform(size=[1, 3, 10, 10])\n self.feed_fp32 = {\"x\": data.astype(np.float32)}\n self.feed_fp16 = {\"x\": data.astype(np.float16)}\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n self.feed_dtype = [x.dtype for x in self.feed_fp32.values()]\n\n def set_op_attrs(self):\n self.attrs = {\"perm\": [0, 2, 3, 1]}\n\n @IPUOpTest.static_graph\n def build_model(self):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype='float32')\n out = paddle.fluid.layers.transpose(x, **self.attrs)\n self.fetch_list = [out.name]\n\n def run_model(self, exec_mode):\n self.run_op_test(exec_mode)\n\n def test(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model()\n self.run_model(m)\n self.check(check_shape=True)\n\n\nclass TestCase1(TestBase):\n\n def set_op_attrs(self):\n self.attrs = {\"perm\": [0, 1, 2, 3]}\n\n\nclass TestCase2(TestBase):\n\n def set_data_feed(self):\n data = np.random.uniform(size=[1, 2, 3, 4, 5])\n self.feed_fp32 = {\"x\": data.astype(np.float32)}\n self.feed_fp16 = {\"x\": data.astype(np.float16)}\n\n def set_op_attrs(self):\n self.attrs = {\"perm\": [4, 0, 2, 3, 1]}\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom trt_layer_auto_scan_test import TrtLayerAutoScanTest, SkipReasons\nfrom program_config import TensorConfig, ProgramConfig\nimport numpy as np\nimport paddle.inference as paddle_infer\nfrom functools import partial\nfrom typing import Optional, List, Callable, Dict, Any, Set\nimport unittest\n\n\nclass TrtConvertMulticlassNMS3Test(TrtLayerAutoScanTest):\n\n def is_program_valid(self, program_config: ProgramConfig) -> bool:\n return True\n\n def create_inference_config(self, use_trt=True) -> paddle_infer.Config:\n if use_trt:\n config = paddle_infer.Config()\n config.disable_glog_info()\n config.enable_use_gpu(100, 0)\n config.set_optim_cache_dir(self.cache_dir)\n config.switch_ir_debug()\n config.enable_tensorrt_engine(\n max_batch_size=self.trt_param.max_batch_size,\n workspace_size=self.trt_param.workspace_size,\n min_subgraph_size=self.trt_param.min_subgraph_size,\n precision_mode=self.trt_param.precision,\n use_static=self.trt_param.use_static,\n use_calib_mode=self.trt_param.use_calib_mode)\n if len(self.dynamic_shape.min_input_shape\n ) != 0 and self.dynamic_shape.min_input_shape.keys(\n ) == self.dynamic_shape.max_input_shape.keys(\n ) and self.dynamic_shape.min_input_shape.keys(\n ) == self.dynamic_shape.opt_input_shape.keys():\n config.set_trt_dynamic_shape_info(\n self.dynamic_shape.min_input_shape,\n self.dynamic_shape.max_input_shape,\n self.dynamic_shape.opt_input_shape,\n self.dynamic_shape.disable_trt_plugin_fp16)\n return config\n else:\n config = paddle_infer.Config()\n config.switch_ir_debug(True)\n config.set_optim_cache_dir(self.cache_dir)\n config.disable_glog_info()\n return config\n\n def sample_program_configs(self):\n\n def generate_boxes(batch, num_boxes):\n return np.arange(batch * num_boxes * 4,\n dtype=np.float32).reshape([batch, num_boxes, 4])\n\n def generate_scores(batch, num_boxes, num_classes):\n return np.arange(batch * num_classes * num_boxes,\n dtype=np.float32).reshape(\n [batch, num_classes, num_boxes])\n # return np.random.rand(batch, num_classes, num_boxes).astype(np.float32)\n\n for batch in [1, 2]:\n for num_boxes in [4, 12]:\n for num_classes in [2, 6]:\n for score_threshold in [\n 0.01,\n ]:\n ops_config = [{\n \"op_type\": \"multiclass_nms3\",\n \"op_inputs\": {\n \"BBoxes\": [\"input_bboxes\"],\n \"Scores\": [\"input_scores\"],\n },\n \"op_outputs\": {\n \"Out\": [\"nms_output_boxes\"],\n \"Index\": [\"nms_output_index\"],\n \"NmsRoisNum\": [\"nms_output_num\"]\n },\n \"op_attrs\": {\n \"background_label\": -1,\n \"score_threshold\": score_threshold,\n \"nms_top_k\": num_boxes,\n \"keep_top_k\": num_boxes,\n \"nms_threshold\": 0.3,\n \"normalized\": False,\n \"nms_eta\": 1.1\n }\n }]\n ops = self.generate_op_config(ops_config)\n program_config = ProgramConfig(\n ops=ops,\n weights={},\n inputs={\n \"input_bboxes\":\n TensorConfig(data_gen=partial(\n generate_boxes, batch, num_boxes)),\n \"input_scores\":\n TensorConfig(\n data_gen=partial(generate_scores, batch,\n num_boxes, num_classes))\n },\n outputs=[\n \"nms_output_boxes\", \"nms_output_num\",\n \"nms_output_index\"\n ])\n\n yield program_config\n\n def sample_predictor_configs(\n self, program_config) -> (paddle_infer.Config, List[int], float):\n\n def clear_dynamic_shape():\n self.dynamic_shape.min_input_shape = {}\n self.dynamic_shape.max_input_shape = {}\n self.dynamic_shape.opt_input_shape = {}\n\n def generate_trt_nodes_num(attrs, dynamic_shape):\n return 1, 2\n\n attrs = [\n program_config.ops[i].attrs for i in range(len(program_config.ops))\n ]\n\n # for static_shape\n clear_dynamic_shape()\n self.trt_param.precision = paddle_infer.PrecisionType.Float32\n yield self.create_inference_config(), generate_trt_nodes_num(\n attrs, False), 1e-5\n self.trt_param.precision = paddle_infer.PrecisionType.Half\n yield self.create_inference_config(), generate_trt_nodes_num(\n attrs, False), 1e-2\n\n def assert_tensors_near(self, atol: float, rtol: float,\n tensor: Dict[str, np.array],\n baseline: Dict[str, np.array]):\n # the order of tensorrt outputs are not consistent with paddle\n for key, arr in tensor.items():\n if key == \"nms_output_index\":\n continue\n if key == \"nms_output_boxes\":\n basline_arr = np.array(\n sorted(baseline[key].reshape((-1, 6)),\n key=lambda i: [i[0], i[1]]))\n arr = np.array(\n sorted(arr.reshape((-1, 6)), key=lambda i: [i[0], i[1]]))\n else:\n basline_arr = np.array(baseline[key].reshape((-1, 1)))\n arr = np.array(arr.reshape((-1, 1)))\n\n self.assertTrue(\n basline_arr.shape == arr.shape,\n \"The output shapes are not equal, the baseline shape is \" +\n str(basline_arr.shape) + ', but got ' + str(arr.shape))\n diff = abs(basline_arr - arr)\n self.assertTrue(\n np.allclose(basline_arr, arr, atol=atol, rtol=rtol),\n \"Output has diff, Maximum absolute error: {}\".format(\n np.amax(diff)))\n\n def assert_op_size(self, trt_engine_num, paddle_op_num):\n # tensorrt op num is not consistent with paddle\n return True\n\n def test(self):\n self.trt_param.workspace_size = 1 << 20\n self.run_test()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2019 PaddlePaddle 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\nimport sys\nimport time\nimport unittest\nimport numpy as np\nimport paddle.fluid as fluid\nfrom paddle.fluid import core\nimport paddle.compat as cpt\nfrom paddle.fluid.framework import _test_eager_guard\n\n\ndef get_random_images_and_labels(image_shape, label_shape):\n image = np.random.random(size=image_shape).astype('float32')\n label = np.random.random(size=label_shape).astype('int64')\n return image, label\n\n\nclass TestDygraphDataLoaderWithException(unittest.TestCase):\n\n def setUp(self):\n self.batch_size = 8\n self.batch_num = 4\n self.epoch_num = 1\n self.capacity = 5\n\n def func_test_not_capacity(self):\n with fluid.dygraph.guard():\n with self.assertRaisesRegexp(ValueError,\n \"Please give value to capacity.\"):\n fluid.io.DataLoader.from_generator()\n\n def test_not_capacity(self):\n with _test_eager_guard():\n self.func_test_not_capacity()\n self.func_test_not_capacity()\n\n def func_test_single_process_with_thread_expection(self):\n\n def error_sample_genarator(batch_num):\n\n def __reader__():\n for _ in range(batch_num):\n yield [[[1, 2], [1]]]\n\n return __reader__\n\n with fluid.dygraph.guard():\n loader = fluid.io.DataLoader.from_generator(capacity=self.capacity,\n iterable=False,\n use_multiprocess=False)\n loader.set_batch_generator(error_sample_genarator(self.batch_num),\n places=fluid.CPUPlace())\n exception = None\n try:\n for _ in loader():\n print(\"test_single_process_with_thread_expection\")\n except core.EnforceNotMet as ex:\n self.assertIn(\"Blocking queue is killed\",\n cpt.get_exception_message(ex))\n exception = ex\n self.assertIsNotNone(exception)\n\n def test_single_process_with_thread_expection(self):\n with _test_eager_guard():\n self.func_test_single_process_with_thread_expection()\n self.func_test_single_process_with_thread_expection()\n\n def func_test_multi_process_with_process_expection(self):\n\n def error_sample_genarator(batch_num):\n\n def __reader__():\n for _ in range(batch_num):\n yield [[[1, 2], [1]]]\n\n return __reader__\n\n with fluid.dygraph.guard():\n loader = fluid.io.DataLoader.from_generator(capacity=self.capacity,\n use_multiprocess=True)\n loader.set_batch_generator(error_sample_genarator(self.batch_num),\n places=fluid.CPUPlace())\n exception = None\n try:\n for _ in loader():\n print(\"test_multi_process_with_thread_expection\")\n except core.EnforceNotMet as ex:\n exception = ex\n self.assertIsNotNone(exception)\n\n def test_multi_process_with_process_expection(self):\n with _test_eager_guard():\n self.func_test_multi_process_with_process_expection()\n self.func_test_multi_process_with_process_expection()\n\n def func_test_multi_process_with_get_timeout(self):\n\n def slow_batch_generator_creator(batch_size, batch_num):\n\n def __reader__():\n for _ in range(batch_num):\n time.sleep(80)\n batch_image, batch_label = get_random_images_and_labels(\n [batch_size, 784], [batch_size, 1])\n yield batch_image, batch_label\n\n return __reader__\n\n with fluid.dygraph.guard():\n loader = fluid.io.DataLoader.from_generator(capacity=self.capacity,\n use_multiprocess=True)\n loader.set_batch_generator(slow_batch_generator_creator(\n self.batch_size, self.batch_num),\n places=fluid.CPUPlace())\n exception = None\n try:\n for _ in range(self.epoch_num):\n for image, _ in loader():\n fluid.layers.relu(image)\n except core.EnforceNotMet as ex:\n self.assertIn(\"Blocking queue is killed\",\n cpt.get_exception_message(ex))\n exception = ex\n self.assertIsNotNone(exception)\n\n def test_multi_process_with_get_timeout(self):\n with _test_eager_guard():\n self.func_test_multi_process_with_get_timeout()\n self.func_test_multi_process_with_get_timeout()\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2019 PaddlePaddle 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\nimport paddle.fluid as fluid\nimport paddle.nn.functional as F\nimport unittest\nimport numpy as np\nimport six\nimport paddle\nfrom paddle.fluid.framework import _test_eager_guard\n\n\nclass TensorFillDiagTensor_Test(unittest.TestCase):\n\n def setUp(self):\n self.typelist = ['float32', 'float64', 'int32', 'int64']\n self.places = [fluid.CPUPlace()]\n if fluid.core.is_compiled_with_cuda():\n self.places.append(fluid.CUDAPlace(0))\n\n def func_dim2(self):\n expected_np = np.array([[1, 2, 2], [2, 1, 2], [2, 2, 1],\n [2, 2, 2]]).astype('float32')\n expected_grad = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0],\n [1, 1, 1]]).astype('float32')\n\n for idx, p in enumerate(self.places):\n if idx == 0:\n paddle.set_device('cpu')\n else:\n paddle.set_device('gpu')\n for dtype in self.typelist:\n v = paddle.ones((3, ), dtype=dtype)\n var = (np.random.random() + 1)\n x = paddle.ones((4, 3), dtype=dtype)\n x.stop_gradient = False\n y = x * 2\n y.fill_diagonal_tensor_(v, offset=0, dim1=0, dim2=1)\n loss = y.sum()\n loss.backward()\n\n self.assertEqual(\n (y.numpy().astype('float32') == expected_np).all(), True)\n self.assertEqual(\n (y.grad.numpy().astype('float32') == expected_grad).all(),\n True)\n\n def test_dim2(self):\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": True})\n with _test_eager_guard():\n self.func_dim2()\n self.func_dim2()\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": False})\n\n def func_dim2_offset_1(self):\n expected_np = np.array([[2, 2, 2], [1, 2, 2], [2, 1, 2],\n [2, 2, 1]]).astype('float32')\n expected_grad = np.array([[1, 1, 1], [0, 1, 1], [1, 0, 1],\n [1, 1, 0]]).astype('float32')\n\n for idx, p in enumerate(self.places):\n if idx == 0:\n paddle.set_device('cpu')\n else:\n paddle.set_device('gpu')\n for dtype in self.typelist:\n v = paddle.ones((3, ), dtype=dtype)\n var = (np.random.random() + 1)\n x = paddle.ones((4, 3), dtype=dtype)\n x.stop_gradient = False\n y = x * 2\n y.fill_diagonal_tensor_(v, offset=-1, dim1=0, dim2=1)\n loss = y.sum()\n loss.backward()\n\n self.assertEqual(\n (y.numpy().astype('float32') == expected_np).all(), True)\n self.assertEqual(\n (y.grad.numpy().astype('float32') == expected_grad).all(),\n True)\n\n def test_dim2_offset_1(self):\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": True})\n with _test_eager_guard():\n self.func_dim2_offset_1()\n self.func_dim2_offset_1()\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": False})\n\n def func_dim2_offset1(self):\n expected_np = np.array([[2, 1, 2], [2, 2, 1], [2, 2, 2],\n [2, 2, 2]]).astype('float32')\n expected_grad = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1],\n [1, 1, 1]]).astype('float32')\n\n for idx, p in enumerate(self.places):\n if idx == 0:\n paddle.set_device('cpu')\n else:\n paddle.set_device('gpu')\n for dtype in self.typelist:\n v = paddle.ones((2, ), dtype=dtype)\n var = (np.random.random() + 1)\n x = paddle.ones((4, 3), dtype=dtype)\n x.stop_gradient = False\n y = x * 2\n y.fill_diagonal_tensor_(v, offset=1, dim1=0, dim2=1)\n loss = y.sum()\n loss.backward()\n\n self.assertEqual(\n (y.numpy().astype('float32') == expected_np).all(), True)\n self.assertEqual(\n (y.grad.numpy().astype('float32') == expected_grad).all(),\n True)\n\n def test_dim2_offset1(self):\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": True})\n with _test_eager_guard():\n self.func_dim2_offset1()\n self.func_dim2_offset1()\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": False})\n\n def func_dim4(self):\n expected_np = np.array([[[[0, 3], [2, 2], [2, 2]],\n [[2, 2], [1, 4], [2, 2]],\n [[2, 2], [2, 2], [2, 5]],\n [[2, 2], [2, 2], [2, 2]]],\n [[[6, 9], [2, 2], [2, 2]],\n [[2, 2], [7, 10], [2, 2]],\n [[2, 2], [2, 2], [8, 11]],\n [[2, 2], [2, 2], [2, 2]]]]).astype('float32')\n expected_grad = np.array([[[[0, 0], [1, 1], [1, 1]],\n [[1, 1], [0, 0], [1, 1]],\n [[1, 1], [1, 1], [0, 0]],\n [[1, 1], [1, 1], [1, 1]]],\n [[[0, 0], [1, 1], [1, 1]],\n [[1, 1], [0, 0], [1, 1]],\n [[1, 1], [1, 1], [0, 0]],\n [[1, 1], [1, 1], [1, 1]]]]).astype('float32')\n\n for idx, p in enumerate(self.places):\n if idx == 0:\n paddle.set_device('cpu')\n else:\n paddle.set_device('gpu')\n for dtype in self.typelist:\n v = paddle.to_tensor(np.arange(12).reshape(2, 2, 3),\n dtype=dtype)\n var = (np.random.random() + 1)\n x = paddle.ones((2, 4, 3, 2), dtype=dtype)\n x.stop_gradient = False\n y = x * 2\n y.fill_diagonal_tensor_(v, offset=0, dim1=1, dim2=2)\n loss = y.sum()\n loss.backward()\n\n self.assertEqual(\n (y.numpy().astype('float32') == expected_np).all(), True)\n self.assertEqual(\n (y.grad.numpy().astype('float32') == expected_grad).all(),\n True)\n\n def test_func_dim4(self):\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": True})\n with _test_eager_guard():\n self.func_dim4()\n self.func_dim4()\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": False})\n\n def func_largedim(self):\n #large dim only test on gpu because the cpu version is too slow for ci test, and the memory is limited\n if len(self.places) > 1:\n bsdim = 1024\n fsdim = 128\n paddle.set_device('gpu')\n for dtype in self.typelist:\n v = paddle.arange(bsdim * fsdim, dtype=dtype).reshape(\n (bsdim, fsdim))\n y = paddle.ones((bsdim, fsdim, fsdim), dtype=dtype)\n y.stop_gradient = False\n y = y * 2\n y.fill_diagonal_tensor_(v, offset=0, dim1=1, dim2=2)\n loss = y.sum()\n loss.backward()\n\n expected_pred = v - 2\n expected_pred = F.diag_embed(expected_pred) + 2\n expected_grad = paddle.ones(v.shape, dtype=dtype) - 2\n expected_grad = F.diag_embed(expected_grad) + 1\n\n self.assertEqual((y == expected_pred).all(), True)\n self.assertEqual((y.grad == expected_grad).all(), True)\n\n def test_largedim(self):\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": True})\n with _test_eager_guard():\n self.func_largedim()\n self.func_largedim()\n fluid.set_flags({\"FLAGS_retain_grad_for_all_tensor\": False})\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid import core\nimport sys\n\nsys.path.append(\"..\")\nfrom op_test import OpTest\nimport numpy as np\nimport os\n\npaddle.enable_static()\n\n\ndef sample_output_one_dimension(out, dim):\n # count numbers of different categories\n sample_prob = np.zeros(dim).astype(\"float32\")\n sample_index_prob = np.unique(out, return_counts=True)\n sample_prob[sample_index_prob[0]] = sample_index_prob[1]\n sample_prob /= sample_prob.sum()\n return sample_prob\n\n\ndef sample_output_two_dimension(out, shape):\n num_dist = shape[0]\n out_list = np.split(out, num_dist, axis=0)\n sample_prob = np.zeros(shape).astype(\"float32\")\n for i in range(num_dist):\n sample_index_prob = np.unique(out_list[i], return_counts=True)\n sample_prob[i][sample_index_prob[0]] = sample_index_prob[1]\n sample_prob /= sample_prob.sum(axis=-1, keepdims=True)\n return sample_prob\n\n\nclass TestMultinomialOp(OpTest):\n\n def setUp(self):\n self.set_npu()\n self.op_type = \"multinomial\"\n self.init_data()\n self.inputs = {\"X\": self.input_np}\n\n def set_npu(self):\n self.__class__.use_npu = True\n self.place = paddle.NPUPlace(0)\n\n def init_data(self):\n # input probability is a vector, and replacement is True\n self.input_np = np.random.rand(4)\n self.outputs = {\"Out\": np.zeros(100000).astype(\"int64\")}\n self.attrs = {\"num_samples\": 100000, \"replacement\": True}\n\n def test_check_output(self):\n self.check_output_customized(self.verify_output,\n custom_place=self.place)\n\n def sample_output(self, out):\n return sample_output_one_dimension(out, 4)\n\n def verify_output(self, outs):\n # normalize the input to get the probability\n prob = self.input_np / self.input_np.sum(axis=-1, keepdims=True)\n sample_prob = self.sample_output(np.array(outs[0]))\n self.assertTrue(\n np.allclose(sample_prob, prob, rtol=0, atol=0.01),\n \"sample_prob: \" + str(sample_prob) + \"\\nprob: \" + str(prob))\n\n\nclass TestMultinomialOp2(TestMultinomialOp):\n\n def init_data(self):\n # input probability is a matrix\n self.input_np = np.random.rand(3, 4)\n self.outputs = {\"Out\": np.zeros((3, 100000)).astype(\"int64\")}\n self.attrs = {\"num_samples\": 100000, \"replacement\": True}\n\n def sample_output(self, out):\n return sample_output_two_dimension(out, [3, 4])\n\n\nclass TestMultinomialOp3(TestMultinomialOp):\n\n def init_data(self):\n # replacement is False. number of samples must be less than number of categories.\n self.input_np = np.random.rand(1000)\n self.outputs = {\"Out\": np.zeros(100).astype(\"int64\")}\n self.attrs = {\"num_samples\": 100, \"replacement\": False}\n\n def verify_output(self, outs):\n out = np.array(outs[0])\n unique_out = np.unique(out)\n self.assertEqual(\n len(unique_out), 100,\n \"replacement is False. categories can't be sampled repeatedly\")\n\n\nclass TestMultinomialApi(unittest.TestCase):\n\n def test_dygraph(self):\n # input probability is a vector, and replacement is True\n paddle.set_device('npu:0')\n paddle.disable_static()\n x_numpy = np.random.rand(4)\n x = paddle.to_tensor(x_numpy)\n out = paddle.multinomial(x, num_samples=100000, replacement=True)\n\n sample_prob = sample_output_one_dimension(out.numpy(), 4)\n prob = x_numpy / x_numpy.sum(axis=-1, keepdims=True)\n self.assertTrue(\n np.allclose(sample_prob, prob, rtol=0, atol=0.01),\n \"sample_prob: \" + str(sample_prob) + \"\\nprob: \" + str(prob))\n paddle.enable_static()\n\n def test_dygraph2(self):\n # input probability is a matrix, and replacement is True\n paddle.set_device('npu:0')\n paddle.disable_static()\n x_numpy = np.random.rand(3, 4)\n x = paddle.to_tensor(x_numpy)\n out = paddle.multinomial(x, num_samples=100000, replacement=True)\n\n sample_prob = sample_output_two_dimension(out.numpy(), [3, 4])\n prob = x_numpy / x_numpy.sum(axis=-1, keepdims=True)\n self.assertTrue(\n np.allclose(sample_prob, prob, rtol=0, atol=0.01),\n \"sample_prob: \" + str(sample_prob) + \"\\nprob: \" + str(prob))\n paddle.enable_static()\n\n def test_dygraph3(self):\n # replacement is False. number of samples must be less than number of categories.\n paddle.set_device('npu:0')\n paddle.disable_static()\n x_numpy = np.random.rand(1000)\n x = paddle.to_tensor(x_numpy)\n out = paddle.multinomial(x, num_samples=100, replacement=False)\n\n unique_out = np.unique(out.numpy())\n self.assertEqual(\n len(unique_out), 100,\n \"replacement is False. categories can't be sampled repeatedly\")\n paddle.enable_static()\n\n def test_dygraph4(self):\n paddle.set_device('npu:0')\n paddle.disable_static()\n logits = -1 * paddle.ones([2800])\n # Categorical.sample API will call multinomial op with replacement=True\n cat = paddle.distribution.Categorical(logits.exp())\n cat.sample([1])\n paddle.enable_static()\n\n def test_static(self):\n paddle.set_device('npu:0')\n startup_program = fluid.Program()\n train_program = fluid.Program()\n with fluid.program_guard(train_program, startup_program):\n x = fluid.data('x', shape=[4], dtype='float32')\n out = paddle.multinomial(x, num_samples=100000, replacement=True)\n\n place = fluid.NPUPlace(0)\n exe = fluid.Executor(place)\n\n exe.run(startup_program)\n x_np = np.random.rand(4).astype('float32')\n out = exe.run(train_program, feed={'x': x_np}, fetch_list=[out])\n\n sample_prob = sample_output_one_dimension(out, 4)\n prob = x_np / x_np.sum(axis=-1, keepdims=True)\n self.assertTrue(\n np.allclose(sample_prob, prob, rtol=0, atol=0.01),\n \"sample_prob: \" + str(sample_prob) + \"\\nprob: \" + str(prob))\n\n\nclass TestMultinomialAlias(unittest.TestCase):\n\n def test_alias(self):\n paddle.set_device('npu:0')\n x = paddle.rand([4])\n out1 = paddle.multinomial(x, num_samples=10, replacement=True)\n out2 = paddle.tensor.multinomial(x, num_samples=10, replacement=True)\n out3 = paddle.tensor.random.multinomial(x,\n num_samples=10,\n replacement=True)\n\n\nclass TestMultinomialError(unittest.TestCase):\n\n def setUp(self):\n paddle.set_device('npu:0')\n paddle.disable_static()\n\n def tearDown(self):\n paddle.enable_static()\n\n def test_num_sample(self):\n\n def test_num_sample_less_than_0():\n x = paddle.rand([4])\n out = paddle.multinomial(x, num_samples=-2)\n\n self.assertRaises(ValueError, test_num_sample_less_than_0)\n\n def test_input_probs_dim(self):\n\n def test_dim_larger_than_2():\n x = paddle.rand([2, 3, 3])\n out = paddle.multinomial(x)\n\n self.assertRaises(ValueError, test_dim_larger_than_2)\n\n def test_dim_less_than_1():\n x_np = np.random.random([])\n x = paddle.to_tensor(x_np)\n out = paddle.multinomial(x)\n\n self.assertRaises(ValueError, test_dim_less_than_1)\n\n with self.assertRaises(ValueError):\n prob = paddle.rand([20, 1000])\n prob[1:0] = 0\n out = paddle.multinomial(prob)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle 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\nimport unittest\nimport time\nimport random\nimport tempfile\nimport shutil\nimport numpy as np\n\nimport paddle\nfrom paddle import Model\nfrom paddle.static import InputSpec\nfrom paddle.vision.models import LeNet\nfrom paddle.hapi.callbacks import config_callbacks\nfrom paddle.vision.datasets import MNIST\nfrom paddle.metric import Accuracy\nfrom paddle.nn.layer.loss import CrossEntropyLoss\n\n\nclass MnistDataset(MNIST):\n\n def __init__(self, mode, return_label=True, sample_num=None):\n super(MnistDataset, self).__init__(mode=mode)\n self.return_label = return_label\n if sample_num:\n self.images = self.images[:sample_num]\n self.labels = self.labels[:sample_num]\n\n def __getitem__(self, idx):\n img, label = self.images[idx], self.labels[idx]\n img = np.reshape(img, [1, 28, 28])\n if self.return_label:\n return img, np.array(self.labels[idx]).astype('int64')\n return img,\n\n def __len__(self):\n return len(self.images)\n\n\nclass TestCallbacks(unittest.TestCase):\n\n def setUp(self):\n self.save_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.save_dir)\n\n def test_earlystopping(self):\n paddle.seed(2020)\n for dynamic in [True, False]:\n paddle.enable_static if not dynamic else None\n device = paddle.set_device('cpu')\n sample_num = 100\n train_dataset = MnistDataset(mode='train', sample_num=sample_num)\n val_dataset = MnistDataset(mode='test', sample_num=sample_num)\n\n net = LeNet()\n optim = paddle.optimizer.Adam(learning_rate=0.001,\n parameters=net.parameters())\n\n inputs = [InputSpec([None, 1, 28, 28], 'float32', 'x')]\n labels = [InputSpec([None, 1], 'int64', 'label')]\n\n model = Model(net, inputs=inputs, labels=labels)\n model.prepare(optim,\n loss=CrossEntropyLoss(reduction=\"sum\"),\n metrics=[Accuracy()])\n callbacks_0 = paddle.callbacks.EarlyStopping('loss',\n mode='min',\n patience=1,\n verbose=1,\n min_delta=0,\n baseline=None,\n save_best_model=True)\n callbacks_1 = paddle.callbacks.EarlyStopping('acc',\n mode='auto',\n patience=1,\n verbose=1,\n min_delta=0,\n baseline=0,\n save_best_model=True)\n callbacks_2 = paddle.callbacks.EarlyStopping('loss',\n mode='auto_',\n patience=1,\n verbose=1,\n min_delta=0,\n baseline=None,\n save_best_model=True)\n callbacks_3 = paddle.callbacks.EarlyStopping('acc_',\n mode='max',\n patience=1,\n verbose=1,\n min_delta=0,\n baseline=0,\n save_best_model=True)\n model.fit(\n train_dataset,\n val_dataset,\n batch_size=64,\n save_freq=10,\n save_dir=self.save_dir,\n epochs=10,\n verbose=0,\n callbacks=[callbacks_0, callbacks_1, callbacks_2, callbacks_3])\n # Test for no val_loader\n model.fit(train_dataset,\n batch_size=64,\n save_freq=10,\n save_dir=self.save_dir,\n epochs=10,\n verbose=0,\n callbacks=[callbacks_0])\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle 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\nimport abc\nimport numpy as np\nimport paddle\nfrom .utils import to_list\nfrom paddle.fluid.layers.utils import flatten\nfrom paddle.io import DataLoader, DistributedBatchSampler\n\n\nclass DistributedDataLoader(metaclass=abc.ABCMeta):\n\n def __init__(self,\n dataset,\n batch_size=1,\n epochs=1,\n data_parallel_world_size=None,\n data_parallel_rank=None,\n drop_last=False):\n self.dataset = dataset\n self.batch_size = batch_size\n self.epochs = epochs\n self.data_parallel_world_size = data_parallel_world_size\n self.data_parallel_rank = data_parallel_rank\n self.drop_lost = drop_last\n if data_parallel_world_size is not None and batch_size is not None:\n assert batch_size % data_parallel_world_size == 0\n\n @abc.abstractmethod\n def __iter__(self):\n raise NotImplementedError\n\n @abc.abstractmethod\n def __next__(self):\n raise NotImplementedError\n\n\nclass NonIterableGeneratorLoader(DistributedDataLoader):\n\n def __init__(self,\n dataset,\n feed_list,\n places,\n batch_size=1,\n epochs=1,\n steps_per_epoch=None,\n data_parallel_world_size=None,\n data_parallel_rank=None,\n drop_last=False):\n self.feed_list = feed_list\n self.places = places\n self.steps_per_epoch = steps_per_epoch\n self.dp_world_size = 1 if data_parallel_world_size is None else data_parallel_world_size\n self.dp_rank = 0 if data_parallel_rank is None else data_parallel_rank\n\n super(NonIterableGeneratorLoader,\n self).__init__(dataset, batch_size, epochs,\n data_parallel_world_size, data_parallel_rank,\n drop_last)\n self._inner_dataloader = self._create_inner_dataloader()\n self._steps = self._infer_steps()\n\n def __iter__(self):\n self._cur_step = 0\n self._inner_dataloader.start()\n return self\n\n def __next__(self):\n if self._cur_step < self._steps:\n self._cur_step += 1\n else:\n self._inner_dataloader.reset()\n raise StopIteration\n\n def _infer_steps(self):\n if self.steps_per_epoch is not None:\n return self.steps_per_epoch\n try:\n if self.batch_size is None:\n steps_per_epoch = len(self.dataset)\n else:\n steps_per_epoch = len(self.dataset) // self.batch_size\n except:\n raise ValueError(\n \"Pleace set `steps_per_epoch` or implement `__len__` methond in dataset class.\"\n )\n return steps_per_epoch\n\n def _create_inner_dataloader(self):\n\n def sample_data_generator():\n batch_data = None\n for step, data in enumerate(self.dataset):\n data = flatten(data)\n if batch_data is None:\n batch_data = [[] for i in range(len(data))]\n for idx in range(len(data)):\n batch_data[idx].append(data[idx])\n if (step + 1) % self.batch_size == 0:\n partial_data = []\n for d in batch_data:\n array = np.array(d)\n partial_data.append(\n np.split(array, self.dp_world_size)[self.dp_rank])\n yield partial_data[:len(self.feed_list)]\n batch_data = None\n\n def batch_data_generator():\n for data in self.dataset:\n data = flatten(data)\n partial_data = []\n for d in data:\n assert d.shape[0] % self.dp_world_size == 0, \\\n \"Please padding dataset with data parallel size\"\n partial_data.append(\n np.split(d, self.dp_world_size)[self.dp_rank])\n yield partial_data[:len(self.feed_list)]\n\n dataloader = paddle.fluid.io.DataLoader.from_generator(\n feed_list=self.feed_list, capacity=70, iterable=False)\n if self.batch_size is not None:\n dataloader.set_batch_generator(sample_data_generator, self.places)\n else:\n dataloader.set_batch_generator(batch_data_generator, self.places)\n\n return dataloader\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport os\nimport paddle\nimport paddle.nn as nn\nimport paddle.fluid as fluid\nimport paddle.distributed.fleet as fleet\nimport numpy as np\nfrom test_dist_base import TestDistRunnerBase, runtime_main\nfrom dist_mnist import cnn_model\n\n\nclass TestDistMnistGradientMergeRawOptimizer(TestDistRunnerBase):\n\n def get_model(self, batch_size=2, single_device=False):\n paddle.enable_static()\n paddle.seed(1)\n np.random.seed(1)\n\n assert fluid.core.globals()['FLAGS_apply_pass_to_program']\n strategy = fleet.DistributedStrategy()\n build_strategy = paddle.static.BuildStrategy()\n settings = {\n \"fuse_relu_depthwise_conv\": True,\n \"fuse_bn_act_ops\": True,\n \"fuse_bn_add_act_ops\": True,\n \"fuse_elewise_add_act_ops\": True,\n \"fuse_all_optimizer_ops\": True,\n \"enable_addto\": True,\n \"enable_inplace\": True,\n }\n for k, v in settings.items():\n setattr(build_strategy, k, v)\n strategy.build_strategy = build_strategy\n\n strategy.gradient_merge = True\n avg = os.environ['enable_gm_avg'] == \"True\"\n strategy.gradient_merge_configs = {\n \"k_steps\": 2,\n \"avg\": avg,\n }\n strategy.without_graph_optimization = True\n\n fleet.init(is_collective=True, strategy=strategy)\n image = paddle.static.data(name='image',\n shape=[None, 1, 28, 28],\n dtype=\"float32\")\n label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')\n predict = cnn_model(image)\n acc = paddle.metric.accuracy(predict, label)\n loss_fn = nn.CrossEntropyLoss(use_softmax=False)\n cost = loss_fn(predict, label)\n test_program = paddle.static.default_main_program().clone(for_test=True)\n optimizer = paddle.optimizer.Adam(learning_rate=1e-3)\n if single_device:\n optimizer = fluid.optimizer.GradientMergeOptimizer(\n optimizer,\n k_steps=strategy.gradient_merge_configs[\"k_steps\"],\n avg=strategy.gradient_merge_configs[\"avg\"])\n world_size = 1\n else:\n optimizer = fleet.distributed_optimizer(optimizer)\n world_size = fleet.world_size()\n optimizer.minimize(cost)\n if world_size > 1:\n assert paddle.static.default_main_program().num_blocks == 2\n gm_block = paddle.static.default_main_program().block(1)\n start_allreduce_idx = None\n for i, op in enumerate(gm_block.ops):\n if op.type == \"c_allreduce_sum\":\n start_allreduce_idx = i\n break\n # the magic number 1 below means skip the c_sync_calc_stream op\n if avg:\n assert start_allreduce_idx > 1\n else:\n assert start_allreduce_idx == 1\n\n train_reader = paddle.batch(paddle.dataset.mnist.test(),\n batch_size=batch_size)\n test_reader = paddle.batch(paddle.dataset.mnist.test(),\n batch_size=batch_size)\n return test_program, cost, train_reader, test_reader, acc, predict\n\n\nif __name__ == \"__main__\":\n runtime_main(TestDistMnistGradientMergeRawOptimizer)\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom paddle.distributed.passes.pass_utils import split_program\nfrom paddle.vision.models import resnet18 as resnet\nimport paddle\nimport paddle.nn as nn\nimport unittest\nimport json\nimport numpy as np\n\n\nclass TestSplitProgram(unittest.TestCase):\n\n def setUp(self):\n paddle.enable_static()\n if paddle.is_compiled_with_cuda():\n paddle.set_flags({'FLAGS_cudnn_deterministic': 1})\n\n def get_model(self, batch_size):\n main = paddle.static.Program()\n startup = paddle.static.Program()\n with paddle.static.program_guard(main, startup):\n image = paddle.static.data(shape=[batch_size, 3, 224, 224],\n dtype='float32',\n name='image')\n label = paddle.static.data(shape=[batch_size, 1],\n dtype='int64',\n name='label')\n\n model = resnet(pretrained=False)\n loss_fn = nn.loss.CrossEntropyLoss()\n\n pred_out = model(image)\n loss = loss_fn(pred_out, label)\n\n optimizer = paddle.optimizer.SGD(learning_rate=1e-3)\n optimizer.minimize(loss)\n return main, startup, image, label\n\n def find_startup_vars(self, main_prog, startup_prog):\n self.assertEqual(startup_prog.num_blocks, 1)\n startup_vars = []\n for op in startup_prog.global_block().ops:\n for var_name in op.output_arg_names:\n var = main_prog.global_block().var(var_name)\n if var.persistable:\n startup_vars.append(var_name)\n return startup_vars\n\n def test_split_program(self):\n for p in self.get_places():\n vars_expected = self.check_split_program(p, use_split=False)\n vars_actual = self.check_split_program(p, use_split=True)\n self.assertEqual(len(vars_actual), len(vars_expected))\n for actual, expected in zip(vars_actual, vars_expected):\n self.assertEqual(actual.shape, expected.shape)\n self.assertTrue(np.array_equal(actual, expected),\n '{}\\n{}\\n'.format(actual, expected))\n\n def get_places(self):\n places = [paddle.CPUPlace()]\n if paddle.is_compiled_with_cuda():\n places.append(paddle.CUDAPlace(0))\n return places\n\n def get_var_values(self, scope, var_names):\n values = []\n for var_name in var_names:\n values.append(np.array(scope.find_var(var_name).get_tensor()))\n return values\n\n def check_split_program(self, place, use_split=True, seed=100, batch_num=5):\n batch_size = 2\n\n np.random.seed(seed)\n paddle.seed(seed)\n\n main_prog, startup_prog, image, label = self.get_model(batch_size)\n startup_vars = self.find_startup_vars(main_prog, startup_prog)\n exe = paddle.static.Executor(place)\n\n image_np = np.random.random(size=image.shape).astype('float32')\n label_np = np.random.randint(low=0,\n high=1000,\n dtype='int64',\n size=label.shape)\n\n scope = paddle.static.Scope()\n if not use_split:\n with paddle.static.scope_guard(scope):\n exe.run(startup_prog)\n for _ in range(batch_num):\n exe.run(main_prog,\n feed={\n image.name: image_np,\n label.name: label_np\n })\n return self.get_var_values(scope, startup_vars)\n\n op_num = len(main_prog.global_block().ops)\n split_op_indices = [int(op_num / 3.0), int(op_num * 3 / 4.0)]\n programs, input_vars, output_vars = split_program(\n main_prog, split_op_indices)\n op_nums = [0] + split_op_indices + [op_num]\n op_nums = [op_nums[i + 1] - op_nums[i] for i in range(len(op_nums) - 1)]\n num_split = len(split_op_indices) + 1\n self.assertEqual(len(programs), num_split)\n self.assertEqual(len(input_vars), num_split)\n self.assertEqual(len(output_vars), num_split)\n self.assertEqual(len(programs), len(op_nums))\n for p, n in zip(programs, op_nums):\n self.assertEqual(len(p.global_block().ops), n)\n\n with paddle.static.scope_guard(scope):\n exe.run(startup_prog)\n for _ in range(batch_num):\n tmp_vars = {image.name: image_np, label.name: label_np}\n for i, program in enumerate(programs):\n feed_dict = {}\n for in_name in input_vars[i]:\n if in_name in startup_vars:\n continue\n self.assertTrue(in_name in tmp_vars)\n if tmp_vars[in_name] is not None:\n feed_dict[in_name] = tmp_vars[in_name]\n\n output_var_values = exe.run(program,\n feed=feed_dict,\n fetch_list=output_vars[i],\n return_numpy=False)\n for out_name, out_value in zip(output_vars[i],\n output_var_values):\n if not out_value._is_initialized():\n tmp_vars[out_name] = np.ndarray(\n out_value._get_dims()).astype('float32')\n else:\n tmp_vars[out_name] = np.array(out_value)\n\n return self.get_var_values(scope, startup_vars)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestMean(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_test_op()\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.reduce_mean\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n self.feed_dtype = [x.dtype for x in self.feed_fp32.values()]\n\n @IPUOpTest.static_graph\n def build_model(self):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype='float32')\n out = self.op(x, **self.attrs)\n self.fetch_list = [out.name]\n\n def run_model(self, exec_mode):\n self.run_op_test(exec_mode)\n\n def run_test_base(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model()\n self.run_model(m)\n self.check()\n\n def set_data_feed0(self):\n data = np.random.uniform(size=[2, 4])\n self.feed_fp32 = {\"in_0\": data.astype(np.float32)}\n self.feed_fp16 = {\"in_0\": data.astype(np.float16)}\n self.set_feed_attr()\n\n def set_data_feed1(self):\n data = np.random.uniform(size=[2, 2, 2])\n self.feed_fp32 = {\"in_0\": data.astype(np.float32)}\n self.feed_fp16 = {\"in_0\": data.astype(np.float16)}\n self.set_feed_attr()\n\n def set_op_attr0(self):\n self.attrs = {}\n self.attrs['dim'] = None\n self.attrs['keep_dim'] = False\n\n def test_case0(self):\n self.set_data_feed0()\n self.set_op_attr0()\n self.run_test_base()\n\n def test_case1(self):\n self.set_data_feed0()\n self.set_op_attr0()\n self.attrs['dim'] = 0\n self.run_test_base()\n\n def test_case2(self):\n self.set_data_feed0()\n self.set_op_attr0()\n self.attrs['dim'] = -1\n self.run_test_base()\n\n def test_case3(self):\n self.set_data_feed0()\n self.set_op_attr0()\n self.attrs['dim'] = 1\n self.run_test_base()\n\n def test_case4(self):\n self.set_data_feed0()\n self.attrs = {}\n self.attrs['dim'] = 1\n self.attrs['keep_dim'] = True\n self.run_test_base()\n\n def test_case5(self):\n self.set_data_feed1()\n self.attrs = {}\n self.attrs['dim'] = [1, 2]\n self.attrs['keep_dim'] = False\n self.run_test_base()\n\n def test_case6(self):\n self.set_data_feed1()\n self.attrs = {}\n self.attrs['dim'] = [0, 1]\n self.attrs['keep_dim'] = False\n self.run_test_base()\n\n def test_case7(self):\n self.set_data_feed1()\n self.attrs = {}\n self.attrs['dim'] = [0, 1]\n self.attrs['keep_dim'] = True\n self.run_test_base()\n\n\nclass TestMax(TestMean):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.reduce_max\n\n\nclass TestMin(TestMean):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.reduce_min\n\n\nclass TestProd(TestMean):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.reduce_prod\n\n\nclass TestSum(TestMean):\n\n def set_test_op(self):\n self.op = paddle.fluid.layers.reduce_sum\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport paddle.fluid as fluid\nimport paddle\nfrom op_test import OpTest\n\nimport numpy as np\nimport unittest\nimport sys\n\nsys.path.append(\"..\")\n\npaddle.enable_static()\nSEED = 2021\n\n\ndef ref_relu6(x, threshold=6.0):\n out = np.copy(x)\n out[np.abs(x - threshold) < 0.005] = threshold + 0.02\n out = np.minimum(np.maximum(x, 0), threshold)\n return out\n\n\nclass TestRelu6(OpTest):\n\n def setUp(self):\n self.set_mlu()\n self.op_type = \"relu6\"\n self.place = paddle.MLUPlace(0)\n\n self.init_dtype()\n np.random.seed(SEED)\n x = np.random.uniform(-1, 10, [10, 12]).astype(self.dtype)\n x[np.abs(x) < 0.005] = 0.02\n out = ref_relu6(x)\n\n self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}\n self.attrs = {'threshold': 6.0}\n self.outputs = {'Out': out}\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad(self):\n self.check_grad_with_place(self.place, ['X'], 'Out')\n\n def init_dtype(self):\n self.dtype = np.float32\n\n\nclass TestRelu6Float16(TestRelu6):\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.__class__.no_need_check_grad = True\n\n def set_attrs(self):\n self.dtype = np.float16\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n\nclass TestReluNeg(TestRelu6):\n\n def setUp(self):\n self.set_mlu()\n self.op_type = \"relu6\"\n self.place = paddle.MLUPlace(0)\n\n self.init_dtype()\n np.random.seed(SEED)\n x = np.random.uniform(-10, -1, [10, 12]).astype(self.dtype)\n x[np.abs(x) < 0.005] = 0.02\n out = ref_relu6(x)\n\n self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(x)}\n self.attrs = {'threshold': 6.0}\n self.outputs = {'Out': out}\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n\n def init_dtype(self):\n self.dtype = np.float32\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n\nclass TestRelu6Net(unittest.TestCase):\n\n def _test(self, run_mlu=True):\n main_prog = paddle.static.Program()\n startup_prog = paddle.static.Program()\n main_prog.random_seed = SEED\n startup_prog.random_seed = SEED\n np.random.seed(SEED)\n\n a_np = np.random.random(size=(32, 32)).astype('float32')\n b_np = np.random.random(size=(32, 32)).astype('float32')\n label_np = np.random.randint(2, size=(32, 1)).astype('int64')\n\n with paddle.static.program_guard(main_prog, startup_prog):\n a = paddle.static.data(name=\"a\", shape=[32, 32], dtype='float32')\n b = paddle.static.data(name=\"b\", shape=[32, 32], dtype='float32')\n label = paddle.static.data(name=\"label\",\n shape=[32, 1],\n dtype='int64')\n\n sum = paddle.add(a, b)\n z = paddle.nn.functional.relu6(sum)\n\n fc_1 = fluid.layers.fc(input=z, size=128)\n prediction = fluid.layers.fc(input=fc_1, size=2, act='softmax')\n\n cost = fluid.layers.cross_entropy(input=prediction, label=label)\n loss = fluid.layers.reduce_mean(cost)\n sgd = fluid.optimizer.SGD(learning_rate=0.01)\n sgd.minimize(loss)\n\n if run_mlu:\n place = paddle.MLUPlace(0)\n else:\n place = paddle.CPUPlace()\n\n exe = paddle.static.Executor(place)\n exe.run(startup_prog)\n\n print(\"Start run on {}\".format(place))\n for epoch in range(100):\n\n pred_res, loss_res = exe.run(main_prog,\n feed={\n \"a\": a_np,\n \"b\": b_np,\n \"label\": label_np\n },\n fetch_list=[prediction, loss])\n if epoch % 10 == 0:\n print(\"Epoch {} | Prediction[0]: {}, Loss: {}\".format(\n epoch, pred_res[0], loss_res))\n\n return pred_res, loss_res\n\n def test_mlu(self):\n cpu_pred, cpu_loss = self._test(False)\n mlu_pred, mlu_loss = self._test(True)\n\n self.assertTrue(np.allclose(mlu_pred, cpu_pred))\n self.assertTrue(np.allclose(mlu_loss, cpu_loss))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2019 PaddlePaddle 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\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.framework import Parameter\nimport numpy as np\nfrom simple_nets import simple_fc_net\nimport random\nimport unittest\nimport os\n\nbatch_size = 32\n\nfeed_dict = {\n 'image':\n np.random.random([batch_size, 784]).astype('float32'),\n 'label':\n np.random.random_integers(low=0, high=9, size=[batch_size,\n 1]).astype('int64')\n}\n\n\nclass InplaceTestBase(unittest.TestCase):\n\n def initParameter(self):\n self.use_cuda = True\n self.fuse_all_optimizer_ops = False\n\n def setUp(self):\n paddle.enable_static()\n self.initParameter()\n if self.use_cuda and fluid.core.is_compiled_with_cuda():\n self.device_count = fluid.core.get_cuda_device_count()\n else:\n self.device_count = 4\n assert batch_size % self.device_count == 0\n\n def build_program_and_scope(self):\n self.place = fluid.CUDAPlace(0) if self.use_cuda else fluid.CPUPlace()\n paddle.seed(1)\n paddle.framework.random._manual_program_seed(1)\n startup_program = fluid.Program()\n main_program = fluid.Program()\n\n scope = fluid.Scope()\n with fluid.program_guard(main_program, startup_program):\n with fluid.unique_name.guard():\n loss = simple_fc_net()\n adam = fluid.optimizer.Adam(learning_rate=1e-3)\n adam.minimize(loss)\n\n with fluid.scope_guard(scope):\n exe = fluid.Executor(\n fluid.CUDAPlace(0) if self.use_cuda else fluid.CPUPlace(\n ))\n exe.run(startup_program)\n\n return main_program, scope, exe, loss\n\n def is_invalid_test(self):\n return self.use_cuda and not fluid.core.is_compiled_with_cuda()\n\n def get_all_vars(self, program):\n all_vars = program.global_block().vars\n all_vars_name = []\n for name, var in all_vars.items():\n if 0 not in var.shape and not var.persistable:\n all_vars_name.append(name)\n\n return all_vars_name\n\n def check_single_card_fetch_var(self):\n if self.is_invalid_test():\n return\n\n prog1, scope1, exe, loss1 = self.build_program_and_scope()\n scopes = []\n compiled_programs = []\n for memory_optimize in [False, True]:\n for enable_inplace in [False, True]:\n prog, scope, _, loss = self.build_program_and_scope()\n scopes.append(scope)\n build_strategy = fluid.BuildStrategy()\n build_strategy.memory_optimize = memory_optimize\n build_strategy.enable_inplace = enable_inplace\n build_strategy.fuse_all_optimizer_ops = self.fuse_all_optimizer_ops\n compiled_prog = fluid.CompiledProgram(prog).with_data_parallel(\n loss_name=loss.name,\n build_strategy=build_strategy,\n places=self.place)\n compiled_programs.append(compiled_prog)\n\n all_vars_name = self.get_all_vars(prog1)\n repeated_var_names = all_vars_name * 2\n random.shuffle(repeated_var_names) # add some random\n\n for fetch_var in repeated_var_names:\n for _ in range(4):\n with fluid.scope_guard(scope1):\n fetch_val1, = exe.run(prog1,\n feed=feed_dict,\n fetch_list=[fetch_var])\n\n for scope, compiled_prog in zip(scopes, compiled_programs):\n with fluid.scope_guard(scope):\n fetch_val2, = exe.run(compiled_prog,\n feed=feed_dict,\n fetch_list=[fetch_var])\n self.assertTrue(\n np.array_equal(fetch_val1, fetch_val2),\n \"error var name: {}, fetch_val1: {}, fetch_val2: {}\"\n .format(\n fetch_var,\n fetch_val1[~np.equal(fetch_val1, fetch_val2)],\n fetch_val2[~np.equal(fetch_val1, fetch_val2)]))\n\n def check_multi_card_fetch_var(self):\n if self.is_invalid_test():\n return\n\n prog1, scope1, exe, loss1 = self.build_program_and_scope()\n scopes = []\n compiled_programs = []\n\n if self.use_cuda:\n places = fluid.cuda_places()\n else:\n places = fluid.cpu_places(self.device_count)\n\n for memory_optimize in [False, True]:\n for enable_inplace in [False, True]:\n prog, scope, _, loss = self.build_program_and_scope()\n scopes.append(scope)\n build_strategy = fluid.BuildStrategy()\n build_strategy.memory_optimize = memory_optimize\n build_strategy.enable_inplace = enable_inplace\n build_strategy.fuse_all_optimizer_ops = self.fuse_all_optimizer_ops\n compiled_program = fluid.CompiledProgram(\n prog).with_data_parallel(loss_name=loss.name,\n build_strategy=build_strategy,\n places=places)\n compiled_programs.append(compiled_program)\n\n repeated_var_names = self.get_all_vars(prog1) * 2\n random.shuffle(repeated_var_names) # add some random\n\n for fetch_var in repeated_var_names:\n for _ in range(4):\n fetch_vals = []\n for scope, compiled_prog in zip(scopes, compiled_programs):\n with fluid.scope_guard(scope):\n fetch_val, = exe.run(compiled_prog,\n feed=feed_dict,\n fetch_list=[fetch_var])\n fetch_vals.append(fetch_val)\n\n for item in fetch_vals:\n self.assertTrue(np.array_equal(fetch_vals[0], item))\n self.assertTrue(\n np.array_equal(fetch_vals[0], item),\n \"error var name: {}, fetch_vals[0]: {}, item: {}\".\n format(fetch_var,\n fetch_vals[0][~np.equal(fetch_vals[0], item)],\n item[~np.equal(fetch_vals[0], item)]))\n\n\nclass CUDAInplaceTest(InplaceTestBase):\n\n def initParameter(self):\n self.use_cuda = True\n self.fuse_all_optimizer_ops = False\n\n def test_multi_card_fetch_var(self):\n self.check_multi_card_fetch_var()\n\n def test_single_card_fetch_var(self):\n self.check_single_card_fetch_var()\n\n\nclass CPUInplaceTest(InplaceTestBase):\n\n def initParameter(self):\n self.use_cuda = False\n self.fuse_all_optimizer_ops = False\n\n def test_multi_card_fetch_var(self):\n self.check_multi_card_fetch_var()\n\n def test_single_card_fetch_var(self):\n self.check_single_card_fetch_var()\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nfrom . import core\nfrom .data_feeder import DataToLoDTensorConverter\nimport numpy as np\n\n__all__ = ['create_lod_tensor', 'create_random_int_lodtensor']\n\n\ndef create_lod_tensor(data, recursive_seq_lens, place):\n \"\"\"\n Create a LoDTensor from a numpy array, list or existing LoDTensor.\n\n The implementation is as follows:\n\n 1. Check whether the length-based LoD, i.e., :code:`recursive_seq_lens`\n is valid.\n\n 2. Convert :code:`recursive_seq_lens` to a offset-based LoD.\n\n 3. Based on :code:`place` , copy the :code:`data` from a numpy array, list\n or existing LoDTensor to CPU or GPU device.\n\n 4. Set offset-based LoD to the output LoDTensor.\n\n Suppose we want to create a LoDTensor to hold data for word sequences,\n where each word is represented by an integer. If we want to create\n a LoDTensor to represent two sentences, one of 2 words, and one of 3 words.\n\n Then :code:`data` would be a numpy array of integers with shape (5, 1).\n :code:`recursive_seq_lens` would be [[2, 3]], indicating the word number\n in each sentence. This length-based :code:`recursive_seq_lens` [[2, 3]]\n would be converted to offset-based LoD [[0, 2, 5]] inside the function\n call.\n\n Please reference :ref:`user_guide_lod_tensor` for more details regarding LoD.\n\n Args:\n data (numpy.ndarray|list|LoDTensor): a numpy array, a list or ad LoDTensor\n holding the data to be copied.\n recursive_seq_lens (list[list[int]]): a list of lists indicating the\n length-based LoD info.\n place (CPUPlace|CUDAPlace): CPU or GPU place indicating where the data\n in the created LoDTensor will be stored.\n\n Returns:\n A LoDTensor with tensor data and recursive_seq_lens info.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n import numpy as np\n\n t = fluid.create_lod_tensor(np.ndarray([5, 30]), [[2, 3]], fluid.CPUPlace())\n \"\"\"\n if isinstance(data, core.LoDTensor):\n return create_lod_tensor(np.array(data), recursive_seq_lens, place)\n elif isinstance(data, list):\n # dtype and shape are not important here,\n # we only want to reuse code of DataToLoDTensorConverter\n converter = DataToLoDTensorConverter(place=place,\n lod_level=len(recursive_seq_lens),\n shape=[],\n dtype=core.VarDesc.VarType.FP32)\n\n new_recursive_seq_lens = []\n for seq in data:\n new_recursive_seq_lens.append(len(seq))\n converter.feed(seq)\n\n assert [\n new_recursive_seq_lens\n ] == recursive_seq_lens, \"data and recursive_seq_lens do not match\"\n\n arr = np.array(converter.data)\n\n # FIXME(zjl): the original logic of create_lod_tensor would append\n # 1 to the shape. Maybe it is not a right way? Currently, we only\n # follow the previous logic\n arr = arr.reshape(arr.shape + (1, ))\n tensor = core.LoDTensor()\n tensor.set(arr, place)\n tensor.set_recursive_sequence_lengths(recursive_seq_lens)\n return tensor\n elif isinstance(data, np.ndarray):\n tensor = core.LoDTensor()\n tensor.set(data, place)\n tensor.set_recursive_sequence_lengths(recursive_seq_lens)\n assert tensor.has_valid_recursive_sequence_lengths(\n ), \"the provided lod info is invalid\"\n return tensor\n else:\n raise TypeError(\n \"data should be either a LoDTensor, a Numpy array or a list\")\n\n\ndef create_random_int_lodtensor(recursive_seq_lens, base_shape, place, low,\n high):\n \"\"\"\n\t:api_attr: Static Graph\n\n Create a LoDTensor containing random integers.\n\n The implementation is as follows:\n\n 1. Obtain the shape of output LoDTensor based on :code:`recursive_seq_lens`\n and :code:`base_shape` . The first dimension of the shape is the total\n length of sequences, while the other dimensions are the same as\n :code:`base_shape` .\n\n 2. Create a numpy array of random integers, and parse the created numpy\n array as parameter :code:`data` of :ref:`api_fluid_create_lod_tensor` to\n create the output LoDTensor.\n\n Suppose we want to create a LoDTensor to hold data for 2 sequences, where\n the dimension of the sequences are [2, 30] and [3, 30] respectively.\n The :code:`recursive_seq_lens` would be [[2, 3]], and :code:`base_shape`\n would be [30] (the other dimensions excluding the sequence length).\n Therefore, the shape of the output LoDTensor would be [5, 30], where\n the first dimension 5 is the total lengths of the sequences, and the\n other dimensions are :code:`base_shape`.\n\n Args:\n recursive_seq_lens (list[list[int]]): a list of lists indicating the\n length-based LoD info.\n base_shape (list[int]): the shape of the output LoDTensor excluding\n the first dimension.\n place (CPUPlace|CUDAPlace): CPU or GPU place indicating where\n the data in the created LoDTensor will be stored.\n low (int): the lower bound of the random integers.\n high (int): the upper bound of the random integers.\n\n Returns:\n A LoDTensor with tensor data and recursive_seq_lens info, whose data\n is inside [low, high].\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n t = fluid.create_random_int_lodtensor(recursive_seq_lens=[[2, 3]],\n base_shape=[30], place=fluid.CPUPlace(), low=0, high=10)\n print(t.shape()) # [5, 30]\n \"\"\"\n assert isinstance(base_shape, list), \"base_shape should be a list\"\n # append the total number of basic elements to the front of its shape\n overall_shape = [sum(recursive_seq_lens[-1])] + base_shape\n # the range of integer data elements is [low, high]\n data = np.random.random_integers(low, high, overall_shape).astype(\"int64\")\n return create_lod_tensor(data, recursive_seq_lens, place)\n", "# -*-coding:utf-8-*-\n# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nimport paddle.fluid.core as core\nfrom paddle.fluid.op import Operator\nimport paddle.fluid.layers as layers\nimport paddle.fluid as fluid\nimport random\nimport six\nfrom sys import version_info\n\n\ndef create_tdm_travel():\n tree_travel = [[1, 3, 7, 14], [1, 3, 7, 15], [1, 3, 8, 16], [1, 3, 8, 17],\n [1, 4, 9, 18], [1, 4, 9, 19], [1, 4, 10, 20], [1, 4, 10, 21],\n [2, 5, 11, 22], [2, 5, 11, 23], [2, 5, 12, 24],\n [2, 5, 12, 25], [2, 6, 13, 0]]\n return tree_travel\n\n\ndef create_tdm_layer():\n tree_layer = [[1, 2], [3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13],\n [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]]\n return tree_layer\n\n\ntype_dict = {\n \"int32\": int(core.VarDesc.VarType.INT32),\n \"int64\": int(core.VarDesc.VarType.INT64)\n}\n\n\nclass TestTDMSamplerOp(OpTest):\n\n def setUp(self):\n self.__class__.op_type = \"tdm_sampler\"\n self.config()\n\n self.tree_travel = create_tdm_travel()\n self.tree_layer = create_tdm_layer()\n\n output_0 = self.x_shape[0]\n output_1 = len(self.neg_samples_num_list) + \\\n np.sum(self.neg_samples_num_list)\n self.output_shape = (output_0, output_1)\n self.layer_sample_nums = [1 + i for i in self.neg_samples_num_list]\n\n layer_node_num_list = [len(i) for i in self.tree_layer]\n tree_layer_offset_lod = [0]\n tree_layer_flat = []\n node_nums = 0\n for layer_idx, layer_node in enumerate(layer_node_num_list):\n tree_layer_flat += self.tree_layer[layer_idx]\n node_nums += layer_node\n tree_layer_offset_lod.append(node_nums)\n\n travel_np = np.array(self.tree_travel).astype(self.tree_dtype)\n layer_np = np.array(tree_layer_flat).astype(self.tree_dtype)\n layer_np = layer_np.reshape([-1, 1])\n\n self.x_np = np.random.randint(low=0, high=13,\n size=self.x_shape).astype(self.x_type)\n\n out = np.random.random(self.output_shape).astype(self.out_dtype)\n label = np.random.random(self.output_shape).astype(self.out_dtype)\n mask = np.random.random(self.output_shape).astype(self.out_dtype)\n\n self.attrs = {\n 'neg_samples_num_list': self.neg_samples_num_list,\n 'output_positive': True,\n 'layer_offset_lod': tree_layer_offset_lod,\n 'seed': 0,\n 'dtype': type_dict[self.out_dtype]\n }\n self.inputs = {'X': self.x_np, 'Travel': travel_np, 'Layer': layer_np}\n self.outputs = {'Out': out, 'Labels': label, 'Mask': mask}\n\n def config(self):\n \"\"\"set test shape & type\"\"\"\n self.neg_samples_num_list = [0, 0, 0, 0]\n self.x_shape = (10, 1)\n self.x_type = 'int32'\n self.tree_dtype = 'int32'\n self.out_dtype = 'int32'\n\n def test_check_output(self):\n places = self._get_places()\n for place in places:\n outs, fetch_list = self._calc_output(place)\n self.out = [np.array(out) for out in outs]\n\n x_res = self.out[fetch_list.index('Out')]\n label_res = self.out[fetch_list.index('Labels')]\n mask_res = self.out[fetch_list.index('Mask')]\n\n # check dtype\n if self.out_dtype == 'int32':\n assert x_res.dtype == np.int32\n assert label_res.dtype == np.int32\n assert mask_res.dtype == np.int32\n elif self.out_dtype == 'int64':\n assert x_res.dtype == np.int64\n assert label_res.dtype == np.int64\n assert mask_res.dtype == np.int64\n\n x_res = x_res.reshape(self.output_shape)\n label_res = label_res.reshape(self.output_shape)\n mask_res = mask_res.reshape(self.output_shape)\n\n layer_nums = len(self.neg_samples_num_list)\n for batch_ids, x_batch in enumerate(x_res):\n start_offset = 0\n positive_travel = []\n for layer_idx in range(layer_nums):\n end_offset = start_offset + self.layer_sample_nums[layer_idx]\n sampling_res = x_batch[start_offset:end_offset]\n sampling_res_list = sampling_res.tolist()\n positive_travel.append(sampling_res_list[0])\n\n label_sampling_res = label_res[batch_ids][\n start_offset:end_offset]\n mask_sampling_res = mask_res[batch_ids][start_offset:end_offset]\n\n # check unique\n if sampling_res_list[0] != 0:\n assert len(set(sampling_res_list)) == len(\n sampling_res_list\n ), \"len(set(sampling_res_list)): {}, len(sampling_res_list): {} , sample_res: {}, label_res:{}, mask_res: {}\".format(\n len(set(sampling_res_list)), len(sampling_res_list),\n sampling_res, label_sampling_res, mask_sampling_res)\n # check legal\n layer_node = self.tree_layer[layer_idx]\n layer_node.append(0)\n for sample in sampling_res_list:\n assert (\n sample in layer_node\n ), \"sample: {}, layer_node: {} , sample_res: {}, label_res: {}, mask_res:{}\".format(\n sample, layer_node, sampling_res, label_sampling_res,\n mask_sampling_res)\n\n # check label\n label_flag = 1\n if sampling_res[0] == 0:\n label_flag = 0\n assert label_sampling_res[0] == label_flag\n # check mask\n padding_index = np.where(sampling_res == 0)\n assert not np.sum(\n mask_sampling_res[padding_index]\n ), \"np.sum(mask_sampling_res[padding_index]): {} \".format(\n np.sum(mask_sampling_res[padding_index]))\n start_offset = end_offset\n # check travel legal\n assert self.tree_travel[int(\n self.x_np[batch_ids])] == positive_travel\n\n\nclass TestCase1(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test input int64\"\"\"\n self.neg_samples_num_list = [0, 0, 0, 0]\n self.x_shape = (10, 1)\n self.x_type = 'int64'\n self.tree_dtype = 'int64'\n self.out_dtype = 'int32'\n\n\nclass TestCase2(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test dtype int64\"\"\"\n self.neg_samples_num_list = [0, 0, 0, 0]\n self.x_shape = (10, 1)\n self.x_type = 'int32'\n self.tree_dtype = 'int32'\n self.out_dtype = 'int64'\n\n\nclass TestCase3(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test all dtype int64\"\"\"\n self.neg_samples_num_list = [0, 0, 0, 0]\n self.x_shape = (10, 1)\n self.x_type = 'int64'\n self.tree_dtype = 'int64'\n self.out_dtype = 'int64'\n\n\nclass TestCase4(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test one neg\"\"\"\n self.neg_samples_num_list = [1, 1, 1, 1]\n self.x_shape = (10, 1)\n self.x_type = 'int64'\n self.tree_dtype = 'int32'\n self.out_dtype = 'int64'\n\n\nclass TestCase5(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test normal neg\"\"\"\n self.neg_samples_num_list = [1, 2, 3, 4]\n self.x_shape = (10, 1)\n self.x_type = 'int64'\n self.tree_dtype = 'int32'\n self.out_dtype = 'int64'\n\n\nclass TestCase6(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test huge batchsize\"\"\"\n self.neg_samples_num_list = [1, 2, 3, 4]\n self.x_shape = (100, 1)\n self.x_type = 'int64'\n self.tree_dtype = 'int32'\n self.out_dtype = 'int64'\n\n\nclass TestCase7(TestTDMSamplerOp):\n\n def config(self):\n \"\"\"test full neg\"\"\"\n self.neg_samples_num_list = [1, 3, 6, 11]\n self.x_shape = (10, 1)\n self.x_type = 'int64'\n self.tree_dtype = 'int32'\n self.out_dtype = 'int64'\n\n\nclass TestTDMSamplerShape(unittest.TestCase):\n\n def test_shape(self):\n x = fluid.layers.data(name='x', shape=[1], dtype='int32', lod_level=1)\n tdm_tree_travel = create_tdm_travel()\n tdm_tree_layer = create_tdm_layer()\n layer_node_num_list = [len(i) for i in tdm_tree_layer]\n\n tree_layer_flat = []\n for layer_idx, layer_node in enumerate(layer_node_num_list):\n tree_layer_flat += tdm_tree_layer[layer_idx]\n\n travel_array = np.array(tdm_tree_travel).astype('int32')\n layer_array = np.array(tree_layer_flat).astype('int32')\n\n neg_samples_num_list = [1, 2, 3, 4]\n leaf_node_num = 13\n\n sample, label, mask = fluid.contrib.layers.tdm_sampler(\n x,\n neg_samples_num_list,\n layer_node_num_list,\n leaf_node_num,\n tree_travel_attr=fluid.ParamAttr(\n initializer=fluid.initializer.NumpyArrayInitializer(\n travel_array)),\n tree_layer_attr=fluid.ParamAttr(initializer=fluid.initializer.\n NumpyArrayInitializer(layer_array)),\n output_positive=True,\n output_list=True,\n seed=0,\n tree_dtype='int32',\n dtype='int32')\n\n place = fluid.CPUPlace()\n exe = fluid.Executor(place=place)\n exe.run(fluid.default_startup_program())\n\n feed = {\n 'x':\n np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10],\n [11], [12]]).astype('int32')\n }\n exe.run(feed=feed)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_data_feed()\n self.set_feed_attr()\n self.set_op_attrs()\n\n def set_data_feed(self):\n x = np.random.uniform(size=[3, 7])\n label = np.arange(3).reshape([3, 1])\n self.feed_fp32 = {\n \"x\": x.astype(np.float32),\n \"label\": label.astype(np.int64)\n }\n self.feed_fp16 = {\n \"x\": x.astype(np.float16),\n \"label\": label.astype(np.int32)\n }\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n\n def set_op_attrs(self):\n self.attrs = {\n 'soft_label': False,\n }\n\n @IPUOpTest.static_graph\n def build_model(self, on_ipu):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype=\"float32\")\n if on_ipu:\n label = paddle.static.data(name=self.feed_list[1],\n shape=self.feed_shape[1],\n dtype='int32')\n else:\n label = paddle.static.data(name=self.feed_list[1],\n shape=self.feed_shape[1],\n dtype='int64')\n out = paddle.fluid.layers.cross_entropy(input=x,\n label=label,\n **self.attrs)\n self.fetch_list = [out.name]\n\n def run_model(self, exec_mode):\n if self.is_ipu_mode(exec_mode):\n self.feed_fp32['label'] = self.feed_fp32['label'].astype(np.int32)\n self.run_op_test(exec_mode)\n\n def test(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model(self.is_ipu_mode(m))\n self.run_model(m)\n self.check()\n\n\nclass TestCase1(TestBase):\n\n def set_op_attrs(self):\n self.attrs = {\n 'soft_label': False,\n 'ignore_index': 1,\n }\n\n\nclass TestCase2(TestBase):\n\n def set_data_feed(self):\n x = np.random.uniform(size=[30, 70])\n label = np.arange(30).reshape([30, 1])\n self.feed_fp32 = {\n \"x\": x.astype(np.float32),\n \"label\": label.astype(np.int64)\n }\n self.feed_fp16 = {\n \"x\": x.astype(np.float16),\n \"label\": label.astype(np.int32)\n }\n\n\[email protected](\"soft_label=True is not supported\")\nclass TestCase3(TestBase):\n\n def set_op_attrs(self):\n self.attrs = {\n 'soft_label': True,\n }\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nimport paddle\nimport numpy as np\nimport random\nimport paddle.distributed as dist\nimport paddle.distributed.fleet as fleet\nfrom paddle.fluid import layers\nimport paddle.nn.functional as F\nfrom paddle.distributed.fleet.meta_parallel import PipelineLayer, LayerDesc\nfrom paddle.fluid.dygraph.layers import Layer\nimport paddle.nn as nn\n\n\ndef set_random_seed(seed, dp_id, rank_id):\n \"\"\"Set random seed for reproducability.\"\"\"\n random.seed(seed)\n np.random.seed(seed + dp_id)\n paddle.seed(seed + dp_id)\n\n\nbatch_size = 8\nlength = 8\nmicro_batch_size = 2\nvocab_size = 128\nhidden_size = 16\nd_model = hidden_size\ndim_feedforward = 4 * d_model\n\n\nclass EmbeddingNet(Layer):\n\n def __init__(self):\n super(EmbeddingNet, self).__init__()\n self.word_embeddings = nn.Embedding(vocab_size, hidden_size)\n self.position_embeddings = nn.Embedding(vocab_size, hidden_size)\n\n def forward(self, x):\n attention_mask = paddle.tensor.triu((paddle.ones(\n (length, length), dtype=\"float32\") * -1e9), 1)\n\n no_used = paddle.ones((3, 3), dtype=\"int32\")\n\n w_emb = self.word_embeddings(x)\n p_emb = self.position_embeddings(x)\n w_emb = w_emb + p_emb\n\n attention_mask.stop_gradient = True\n no_used.stop_gradient = True\n # need to fix bug of backward()\n return w_emb, attention_mask, no_used, p_emb\n\n\nclass TransformerNet(Layer):\n\n def __init__(self):\n super(TransformerNet, self).__init__()\n self.linear1 = nn.Linear(d_model, dim_feedforward)\n self.linear2 = nn.Linear(dim_feedforward, d_model)\n\n self.q_proj = nn.Linear(d_model, d_model)\n self.k_proj = nn.Linear(d_model, d_model)\n self.v_proj = nn.Linear(d_model, d_model)\n\n self.norm1 = nn.LayerNorm(d_model, epsilon=1e-5)\n\n def forward(self, x, mask):\n q = self.q_proj(x)\n k = self.k_proj(x)\n v = self.v_proj(x)\n product = layers.matmul(x=q, y=k, transpose_y=True, alpha=d_model**-0.5)\n\n weights = F.softmax(product + mask)\n # TODO(shenliang03) For save/load in PipeLineParallel, can’t support dropout temporarily.\n # weights = F.dropout(weights, 0.2)\n tgt = layers.matmul(weights, v)\n residual = tgt\n tgt = self.norm1(tgt)\n tgt = residual + tgt\n\n out = self.linear2(F.gelu(self.linear1(tgt), approximate=True))\n return out\n\n\nclass EmbeddingPipe(EmbeddingNet):\n\n def forward(self, x):\n return super().forward(x)\n\n\nclass TransformerNetPipe(TransformerNet):\n\n def forward(self, args):\n x, mask, no_used, p_emb = args[0], args[1], args[2], args[3]\n\n output = super().forward(x, mask)\n output = output + p_emb\n mask.stop_gradient = True\n return output, mask, no_used, p_emb\n\n\nclass CriterionPipe(Layer):\n\n def __init__(self):\n super(CriterionPipe, self).__init__()\n\n def forward(self, out, label):\n loss = out.mean()\n return loss\n\n\nclass ModelPipe(PipelineLayer):\n\n def __init__(self, topology):\n self.descs = []\n self.descs.append(LayerDesc(EmbeddingPipe))\n\n for x in range(6):\n self.descs.append(LayerDesc(TransformerNetPipe))\n\n self.descs.append(lambda x: x[0])\n\n super().__init__(layers=self.descs,\n loss_fn=CriterionPipe(),\n topology=topology,\n seg_method=\"layer:TransformerNetPipe\")\n\n\nclass TestDistPPTraning(unittest.TestCase):\n\n def setUp(self):\n strategy = fleet.DistributedStrategy()\n self.model_parallel_size = 1\n self.data_parallel_size = 1\n self.pipeline_parallel_size = 2\n strategy.hybrid_configs = {\n \"dp_degree\": self.data_parallel_size,\n \"mp_degree\": self.model_parallel_size,\n \"pp_degree\": self.pipeline_parallel_size,\n }\n strategy.pipeline_configs = {\n \"accumulate_steps\": batch_size // micro_batch_size,\n \"micro_batch_size\": micro_batch_size\n }\n fleet.init(is_collective=True, strategy=strategy)\n\n def test_pp_model(self):\n hcg = fleet.get_hybrid_communicate_group()\n word_size = hcg.get_model_parallel_world_size()\n dp_id = hcg.get_data_parallel_rank()\n pp_id = hcg.get_stage_id()\n rank_id = dist.get_rank()\n topology = hcg.topology()\n set_random_seed(1024, dp_id, rank_id)\n\n model = ModelPipe(topology)\n scheduler = paddle.optimizer.lr.PiecewiseDecay(boundaries=[2],\n values=[0.001, 0.002],\n verbose=True)\n optimizer = paddle.optimizer.SGD(learning_rate=scheduler,\n parameters=model.parameters())\n\n model = fleet.distributed_model(model)\n optimizer = fleet.distributed_optimizer(optimizer)\n\n for step_id in range(5):\n x_data = np.random.randint(0, vocab_size, size=[batch_size, length])\n x = paddle.to_tensor(x_data)\n x.stop_gradient = True\n\n e_loss = model.eval_batch([x, x], True)\n loss = model.train_batch([x, x], optimizer, scheduler)\n\n # TODO(shenliang03) add utest for loss\n if pp_id != 0:\n np.testing.assert_allclose(loss.numpy(), e_loss.numpy())\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport sys\n\nsys.path.append(\"..\")\nfrom op_test import OpTest\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler, Program, program_guard\nimport paddle\n\nfrom op_test_xpu import XPUOpTest\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\npaddle.enable_static()\n\n\nclass XPUTestAccuracyOp(XPUOpTestWrapper):\n\n def __init__(self):\n self.op_name = 'accuracy'\n self.use_dynamic_create_class = False\n\n class TestXPUAccuracyOp(XPUOpTest):\n\n def setUp(self):\n self.op_type = \"accuracy\"\n self.init_dtype()\n n = 8192\n infer = np.random.random((n, 1)).astype(self.dtype)\n indices = np.random.randint(0, 2, (n, 1)).astype('int64')\n label = np.random.randint(0, 2, (n, 1)).astype('int64')\n self.inputs = {'Out': infer, 'Indices': indices, \"Label\": label}\n num_correct = 0\n for rowid in range(n):\n for ele in indices[rowid]:\n if ele == label[rowid]:\n num_correct += 1\n break\n self.outputs = {\n 'Accuracy':\n np.array([num_correct / float(n)]).astype(self.dtype),\n 'Correct': np.array([num_correct]).astype(\"int32\"),\n 'Total': np.array([n]).astype(\"int32\")\n }\n self.attrs = {'use_xpu': True}\n\n def init_dtype(self):\n self.dtype = self.in_type\n\n def test_check_output(self):\n if paddle.is_compiled_with_xpu():\n place = paddle.XPUPlace(0)\n self.check_output_with_place(place)\n\n\nsupport_types = get_xpu_op_support_types('accuracy')\nfor stype in support_types:\n create_test_class(globals(), XPUTestAccuracyOp, stype)\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport math\nimport warnings\n\nimport numpy as np\nimport paddle\nfrom paddle import _C_ops\nfrom paddle.distribution import distribution\nfrom paddle.fluid import core\nfrom paddle.fluid.data_feeder import (check_dtype, check_type,\n check_variable_and_dtype, convert_dtype)\nfrom paddle.fluid.framework import _non_static_mode, in_dygraph_mode\nfrom paddle.fluid.layers import (control_flow, elementwise_add, elementwise_div,\n elementwise_mul, elementwise_sub, nn, ops,\n tensor)\nfrom paddle.tensor import arange, concat, gather_nd, multinomial\n\n\nclass Categorical(distribution.Distribution):\n r\"\"\"\n Categorical distribution is a discrete probability distribution that \n describes the possible results of a random variable that can take on \n one of K possible categories, with the probability of each category \n separately specified.\n\n The probability mass function (pmf) is:\n\n .. math::\n\n pmf(k; p_i) = \\prod_{i=1}^{k} p_i^{[x=i]}\n\n In the above equation:\n\n * :math:`[x=i]` : it evaluates to 1 if :math:`x==i` , 0 otherwise.\n\n Args:\n logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64.\n name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.distribution import Categorical\n\n paddle.seed(100) # on CPU device\n x = paddle.rand([6])\n print(x)\n # [0.5535528 0.20714243 0.01162981\n # 0.51577556 0.36369765 0.2609165 ]\n\n paddle.seed(200) # on CPU device\n y = paddle.rand([6])\n print(y)\n # [0.77663314 0.90824795 0.15685187\n # 0.04279523 0.34468332 0.7955718 ]\n\n cat = Categorical(x)\n cat2 = Categorical(y)\n\n paddle.seed(1000) # on CPU device\n cat.sample([2,3])\n # [[0, 0, 5],\n # [3, 4, 5]]\n\n cat.entropy()\n # [1.77528]\n\n cat.kl_divergence(cat2)\n # [0.071952]\n\n value = paddle.to_tensor([2,1,3])\n cat.probs(value)\n # [0.00608027 0.108298 0.269656]\n\n cat.log_prob(value)\n # [-5.10271 -2.22287 -1.31061]\n\n \"\"\"\n\n def __init__(self, logits, name=None):\n \"\"\"\n Args:\n logits(list|tuple|numpy.ndarray|Tensor): The logits input of categorical distribution. The data type is float32 or float64.\n name(str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n \"\"\"\n if not _non_static_mode():\n check_type(logits, 'logits',\n (np.ndarray, tensor.Variable, list, tuple),\n 'Categorical')\n\n self.name = name if name is not None else 'Categorical'\n self.dtype = 'float32'\n\n if self._validate_args(logits):\n self.logits = logits\n self.dtype = convert_dtype(logits.dtype)\n else:\n if isinstance(logits, np.ndarray) and str(\n logits.dtype) in ['float32', 'float64']:\n self.dtype = logits.dtype\n self.logits = self._to_tensor(logits)[0]\n if self.dtype != convert_dtype(self.logits.dtype):\n self.logits = tensor.cast(self.logits, dtype=self.dtype)\n dist_sum = paddle.sum(self.logits, axis=-1, keepdim=True)\n self._prob = self.logits / dist_sum\n\n def sample(self, shape):\n \"\"\"Generate samples of the specified shape.\n\n Args:\n shape (list): Shape of the generated samples.\n\n Returns:\n Tensor: A tensor with prepended dimensions shape.\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.distribution import Categorical\n\n paddle.seed(100) # on CPU device\n x = paddle.rand([6])\n print(x)\n # [0.5535528 0.20714243 0.01162981\n # 0.51577556 0.36369765 0.2609165 ]\n\n cat = Categorical(x)\n\n paddle.seed(1000) # on CPU device\n cat.sample([2,3])\n # [[0, 0, 5],\n # [3, 4, 5]]\n\n \"\"\"\n name = self.name + '_sample'\n if not _non_static_mode():\n check_type(shape, 'shape', (list), 'sample')\n\n num_samples = np.prod(np.array(shape))\n\n logits_shape = list(self.logits.shape)\n if len(logits_shape) > 1:\n sample_shape = shape + logits_shape[:-1]\n logits = paddle.reshape(\n self.logits, [np.prod(logits_shape[:-1]), logits_shape[-1]])\n else:\n sample_shape = shape\n logits = self.logits\n\n sample_index = multinomial(self._logits_to_probs(logits), num_samples,\n True)\n\n # multinomial sample shape is (logits.shape[:-1], num_samples), need to\n # tanspose to (num_samples, logits.shape[:-1])\n permute = list(range(sample_index.dim()))\n permute.insert(0, permute.pop(-1))\n sample_index = sample_index.transpose(permute)\n\n return paddle.reshape(sample_index, sample_shape, name=name)\n\n def kl_divergence(self, other):\n \"\"\"The KL-divergence between two Categorical distributions.\n\n Args:\n other (Categorical): instance of Categorical. The data type is float32.\n\n Returns:\n Tensor: kl-divergence between two Categorical distributions.\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.distribution import Categorical\n\n paddle.seed(100) # on CPU device\n x = paddle.rand([6])\n print(x)\n # [0.5535528 0.20714243 0.01162981\n # 0.51577556 0.36369765 0.2609165 ]\n\n paddle.seed(200) # on CPU device\n y = paddle.rand([6])\n print(y)\n # [0.77663314 0.90824795 0.15685187\n # 0.04279523 0.34468332 0.7955718 ]\n\n cat = Categorical(x)\n cat2 = Categorical(y)\n\n cat.kl_divergence(cat2)\n # [0.071952]\n\n \"\"\"\n name = self.name + '_kl_divergence'\n if not _non_static_mode():\n check_type(other, 'other', Categorical, 'kl_divergence')\n\n logits = self.logits - \\\n paddle.max(self.logits, axis=-1, keepdim=True)\n other_logits = other.logits - paddle.max(\n other.logits, axis=-1, keepdim=True)\n e_logits = ops.exp(logits)\n other_e_logits = ops.exp(other_logits)\n z = paddle.sum(e_logits, axis=-1, keepdim=True)\n other_z = paddle.sum(other_e_logits, axis=-1, keepdim=True)\n prob = e_logits / z\n kl = paddle.sum(\n prob *\n (logits - paddle.log(z) - other_logits + paddle.log(other_z)),\n axis=-1,\n keepdim=True,\n name=name)\n\n return kl\n\n def entropy(self):\n \"\"\"Shannon entropy in nats.\n\n Returns:\n Tensor: Shannon entropy of Categorical distribution. The data type is float32.\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.distribution import Categorical\n\n paddle.seed(100) # on CPU device\n x = paddle.rand([6])\n print(x)\n # [0.5535528 0.20714243 0.01162981\n # 0.51577556 0.36369765 0.2609165 ]\n\n cat = Categorical(x)\n\n cat.entropy()\n # [1.77528]\n\n \"\"\"\n name = self.name + '_entropy'\n logits = self.logits - \\\n paddle.max(self.logits, axis=-1, keepdim=True)\n e_logits = ops.exp(logits)\n z = paddle.sum(e_logits, axis=-1, keepdim=True)\n prob = e_logits / z\n\n neg_entropy = paddle.sum(prob * (logits - paddle.log(z)), axis=-1)\n entropy = paddle.scale(neg_entropy, scale=-1.0, name=name)\n return entropy\n\n def probs(self, value):\n \"\"\"Probabilities of the given category (``value``).\n\n If ``logits`` is 2-D or higher dimension, the last dimension will be regarded as \n category, and the others represents the different distributions.\n At the same time, if ``vlaue`` is 1-D Tensor, ``value`` will be broadcast to the \n same number of distributions as ``logits``.\n If ``value`` is not 1-D Tensor, ``value`` should have the same number distributions\n with ``logits. That is, ``value[:-1] = logits[:-1]``.\n\n Args:\n value (Tensor): The input tensor represents the selected category index.\n\n Returns:\n Tensor: probability according to the category index.\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.distribution import Categorical\n\n paddle.seed(100) # on CPU device\n x = paddle.rand([6])\n print(x)\n # [0.5535528 0.20714243 0.01162981\n # 0.51577556 0.36369765 0.2609165 ]\n\n cat = Categorical(x)\n\n value = paddle.to_tensor([2,1,3])\n cat.probs(value)\n # [0.00608027 0.108298 0.269656]\n\n \"\"\"\n name = self.name + '_probs'\n if len(self._prob.shape) == 1: # batch_shape is empty\n return paddle.gather(self._prob,\n value.reshape([-1], name=name),\n name=name).reshape(value.shape, name=name)\n else:\n if len(value.shape) == 1:\n return paddle.take_along_axis(\n self._prob,\n paddle.reshape(value,\n (len(self._prob.shape) - 1) * [1] + [-1],\n name=name),\n axis=-1)\n else:\n return paddle.take_along_axis(self._prob, value, axis=-1)\n\n def log_prob(self, value):\n \"\"\"Log probabilities of the given category. Refer to ``probs`` method.\n\n Args:\n value (Tensor): The input tensor represents the selected category index.\n\n Returns:\n Tensor: Log probability.\n\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.distribution import Categorical\n\n paddle.seed(100) # on CPU device\n x = paddle.rand([6])\n print(x)\n # [0.5535528 0.20714243 0.01162981\n # 0.51577556 0.36369765 0.2609165 ]\n\n cat = Categorical(x)\n\n value = paddle.to_tensor([2,1,3])\n cat.log_prob(value)\n # [-5.10271 -2.22287 -1.31061]\n\n \"\"\"\n name = self.name + '_log_prob'\n\n return paddle.log(self.probs(value), name=name)\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport os\n\nos.environ[\"FLAGS_enable_eager_mode\"] = \"0\"\nimport math\nimport time\nimport unittest\nimport tempfile\n\nimport numpy as np\n\nimport paddle\n\nfrom predictor_utils import PredictorTools\n\nSEED = 2020\nIMAGENET1000 = 1281167\nbase_lr = 0.001\nmomentum_rate = 0.9\nl2_decay = 1e-4\n# NOTE: Reduce batch_size from 8 to 2 to avoid unittest timeout.\nbatch_size = 2\nepoch_num = 1\nplace = paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda() \\\n else paddle.CPUPlace()\n\nprogram_translator = paddle.jit.ProgramTranslator()\n\nif paddle.is_compiled_with_cuda():\n paddle.fluid.set_flags({'FLAGS_cudnn_deterministic': True})\n\n\ndef optimizer_setting(parameter_list=None):\n optimizer = paddle.optimizer.Momentum(\n learning_rate=base_lr,\n momentum=momentum_rate,\n weight_decay=paddle.regularizer.L2Decay(l2_decay),\n parameters=parameter_list)\n\n return optimizer\n\n\nclass ConvBNLayer(paddle.nn.Layer):\n\n def __init__(self,\n num_channels,\n num_filters,\n filter_size,\n stride=1,\n groups=1,\n act=None):\n super(ConvBNLayer, self).__init__()\n\n self._conv = paddle.nn.Conv2D(in_channels=num_channels,\n out_channels=num_filters,\n kernel_size=filter_size,\n stride=stride,\n padding=(filter_size - 1) // 2,\n groups=groups,\n bias_attr=False)\n\n self._batch_norm = paddle.nn.BatchNorm(num_filters, act=act)\n\n def forward(self, inputs):\n y = self._conv(inputs)\n y = self._batch_norm(y)\n\n return y\n\n\nclass BottleneckBlock(paddle.nn.Layer):\n\n def __init__(self, num_channels, num_filters, stride, shortcut=True):\n super(BottleneckBlock, self).__init__()\n\n self.conv0 = ConvBNLayer(num_channels=num_channels,\n num_filters=num_filters,\n filter_size=1,\n act='relu')\n self.conv1 = ConvBNLayer(num_channels=num_filters,\n num_filters=num_filters,\n filter_size=3,\n stride=stride,\n act='relu')\n self.conv2 = ConvBNLayer(num_channels=num_filters,\n num_filters=num_filters * 4,\n filter_size=1,\n act=None)\n\n if not shortcut:\n self.short = ConvBNLayer(num_channels=num_channels,\n num_filters=num_filters * 4,\n filter_size=1,\n stride=stride)\n\n self.shortcut = shortcut\n\n self._num_channels_out = num_filters * 4\n\n def forward(self, inputs):\n y = self.conv0(inputs)\n conv1 = self.conv1(y)\n conv2 = self.conv2(conv1)\n\n if self.shortcut:\n short = inputs\n else:\n short = self.short(inputs)\n\n y = paddle.add(x=short, y=conv2)\n\n layer_helper = paddle.fluid.layer_helper.LayerHelper(self.full_name(),\n act='relu')\n return layer_helper.append_activation(y)\n\n\nclass ResNet(paddle.nn.Layer):\n\n def __init__(self, layers=50, class_dim=102):\n super(ResNet, self).__init__()\n\n self.layers = layers\n supported_layers = [50, 101, 152]\n assert layers in supported_layers, \\\n \"supported layers are {} but input layer is {}\".format(supported_layers, layers)\n\n if layers == 50:\n depth = [3, 4, 6, 3]\n elif layers == 101:\n depth = [3, 4, 23, 3]\n elif layers == 152:\n depth = [3, 8, 36, 3]\n num_channels = [64, 256, 512, 1024]\n num_filters = [64, 128, 256, 512]\n\n self.conv = ConvBNLayer(num_channels=3,\n num_filters=64,\n filter_size=7,\n stride=2,\n act='relu')\n self.pool2d_max = paddle.fluid.dygraph.Pool2D(pool_size=3,\n pool_stride=2,\n pool_padding=1,\n pool_type='max')\n\n self.bottleneck_block_list = []\n for block in range(len(depth)):\n shortcut = False\n for i in range(depth[block]):\n bottleneck_block = self.add_sublayer(\n 'bb_%d_%d' % (block, i),\n BottleneckBlock(num_channels=num_channels[block]\n if i == 0 else num_filters[block] * 4,\n num_filters=num_filters[block],\n stride=2 if i == 0 and block != 0 else 1,\n shortcut=shortcut))\n self.bottleneck_block_list.append(bottleneck_block)\n shortcut = True\n\n self.pool2d_avg = paddle.fluid.dygraph.Pool2D(pool_size=7,\n pool_type='avg',\n global_pooling=True)\n\n self.pool2d_avg_output = num_filters[len(num_filters) - 1] * 4 * 1 * 1\n\n stdv = 1.0 / math.sqrt(2048 * 1.0)\n\n self.out = paddle.nn.Linear(\n in_features=self.pool2d_avg_output,\n out_features=class_dim,\n weight_attr=paddle.ParamAttr(\n initializer=paddle.nn.initializer.Uniform(-stdv, stdv)))\n\n @paddle.jit.to_static\n def forward(self, inputs):\n y = self.conv(inputs)\n y = self.pool2d_max(y)\n for bottleneck_block in self.bottleneck_block_list:\n y = bottleneck_block(y)\n y = self.pool2d_avg(y)\n y = paddle.reshape(y, shape=[-1, self.pool2d_avg_output])\n pred = self.out(y)\n pred = paddle.nn.functional.softmax(pred)\n\n return pred\n\n\ndef reader_decorator(reader):\n\n def __reader__():\n for item in reader():\n img = np.array(item[0]).astype('float32').reshape(3, 224, 224)\n label = np.array(item[1]).astype('int64').reshape(1)\n yield img, label\n\n return __reader__\n\n\nclass TestResnet(unittest.TestCase):\n\n def setUp(self):\n self.temp_dir = tempfile.TemporaryDirectory()\n\n self.model_save_dir = os.path.join(self.temp_dir.name, \"./inference\")\n self.model_save_prefix = os.path.join(self.temp_dir.name,\n \"./inference/resnet_v2\")\n self.model_filename = \"resnet_v2\" + paddle.fluid.dygraph.io.INFER_MODEL_SUFFIX\n self.params_filename = \"resnet_v2\" + paddle.fluid.dygraph.io.INFER_PARAMS_SUFFIX\n self.dy_state_dict_save_path = os.path.join(self.temp_dir.name,\n \"./resnet_v2.dygraph\")\n\n def tearDown(self):\n self.temp_dir.cleanup()\n\n def do_train(self, to_static):\n \"\"\"\n Tests model decorated by `dygraph_to_static_output` in static mode. For users, the model is defined in dygraph mode and trained in static mode.\n \"\"\"\n paddle.disable_static(place)\n np.random.seed(SEED)\n paddle.seed(SEED)\n paddle.framework.random._manual_program_seed(SEED)\n\n train_reader = paddle.batch(reader_decorator(\n paddle.dataset.flowers.train(use_xmap=False)),\n batch_size=batch_size,\n drop_last=True)\n data_loader = paddle.io.DataLoader.from_generator(capacity=5,\n iterable=True)\n data_loader.set_sample_list_generator(train_reader)\n\n resnet = ResNet()\n optimizer = optimizer_setting(parameter_list=resnet.parameters())\n\n for epoch in range(epoch_num):\n total_loss = 0.0\n total_acc1 = 0.0\n total_acc5 = 0.0\n total_sample = 0\n\n for batch_id, data in enumerate(data_loader()):\n start_time = time.time()\n img, label = data\n\n pred = resnet(img)\n loss = paddle.nn.functional.cross_entropy(input=pred,\n label=label)\n avg_loss = paddle.mean(x=loss)\n acc_top1 = paddle.metric.accuracy(input=pred, label=label, k=1)\n acc_top5 = paddle.metric.accuracy(input=pred, label=label, k=5)\n\n avg_loss.backward()\n optimizer.minimize(avg_loss)\n resnet.clear_gradients()\n\n total_loss += avg_loss\n total_acc1 += acc_top1\n total_acc5 += acc_top5\n total_sample += 1\n\n end_time = time.time()\n if batch_id % 2 == 0:\n print( \"epoch %d | batch step %d, loss %0.3f, acc1 %0.3f, acc5 %0.3f, time %f\" % \\\n ( epoch, batch_id, total_loss.numpy() / total_sample, \\\n total_acc1.numpy() / total_sample, total_acc5.numpy() / total_sample, end_time-start_time))\n if batch_id == 10:\n if to_static:\n paddle.jit.save(resnet, self.model_save_prefix)\n else:\n paddle.fluid.dygraph.save_dygraph(\n resnet.state_dict(), self.dy_state_dict_save_path)\n # avoid dataloader throw abort signaal\n data_loader._reset()\n break\n paddle.enable_static()\n\n return total_loss.numpy()\n\n def predict_dygraph(self, data):\n program_translator.enable(False)\n paddle.disable_static(place)\n resnet = ResNet()\n\n model_dict, _ = paddle.fluid.dygraph.load_dygraph(\n self.dy_state_dict_save_path)\n resnet.set_dict(model_dict)\n resnet.eval()\n\n pred_res = resnet(\n paddle.to_tensor(data=data,\n dtype=None,\n place=None,\n stop_gradient=True))\n\n ret = pred_res.numpy()\n paddle.enable_static()\n return ret\n\n def predict_static(self, data):\n exe = paddle.static.Executor(place)\n [inference_program, feed_target_names,\n fetch_targets] = paddle.static.load_inference_model(\n self.model_save_dir,\n executor=exe,\n model_filename=self.model_filename,\n params_filename=self.params_filename)\n\n pred_res = exe.run(inference_program,\n feed={feed_target_names[0]: data},\n fetch_list=fetch_targets)\n\n return pred_res[0]\n\n def predict_dygraph_jit(self, data):\n paddle.disable_static(place)\n resnet = paddle.jit.load(self.model_save_prefix)\n resnet.eval()\n\n pred_res = resnet(data)\n\n ret = pred_res.numpy()\n paddle.enable_static()\n return ret\n\n def predict_analysis_inference(self, data):\n output = PredictorTools(self.model_save_dir, self.model_filename,\n self.params_filename, [data])\n out = output()\n return out\n\n def train(self, to_static):\n program_translator.enable(to_static)\n return self.do_train(to_static)\n\n def verify_predict(self):\n image = np.random.random([1, 3, 224, 224]).astype('float32')\n dy_pre = self.predict_dygraph(image)\n st_pre = self.predict_static(image)\n dy_jit_pre = self.predict_dygraph_jit(image)\n predictor_pre = self.predict_analysis_inference(image)\n self.assertTrue(np.allclose(dy_pre, st_pre),\n msg=\"dy_pre:\\n {}\\n, st_pre: \\n{}.\".format(\n dy_pre, st_pre))\n self.assertTrue(np.allclose(dy_jit_pre, st_pre),\n msg=\"dy_jit_pre:\\n {}\\n, st_pre: \\n{}.\".format(\n dy_jit_pre, st_pre))\n self.assertTrue(np.allclose(predictor_pre, st_pre),\n msg=\"predictor_pre:\\n {}\\n, st_pre: \\n{}.\".format(\n predictor_pre, st_pre))\n\n def test_resnet(self):\n static_loss = self.train(to_static=True)\n dygraph_loss = self.train(to_static=False)\n self.assertTrue(np.allclose(static_loss, dygraph_loss),\n msg=\"static_loss: {} \\n dygraph_loss: {}\".format(\n static_loss, dygraph_loss))\n self.verify_predict()\n\n def test_in_static_mode_mkldnn(self):\n paddle.fluid.set_flags({'FLAGS_use_mkldnn': True})\n try:\n if paddle.fluid.core.is_compiled_with_mkldnn():\n self.train(to_static=True)\n finally:\n paddle.fluid.set_flags({'FLAGS_use_mkldnn': False})\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\n\nimport paddle\nimport paddle.nn as nn\n\npaddle.enable_static()\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom paddle.fluid.tests.unittests.op_test import OpTest\n\n\ndef conv2dtranspose_forward_naive(input_, filter_, attrs):\n padding_algorithm = attrs['padding_algorithm']\n if padding_algorithm not in [\"SAME\", \"VALID\", \"EXPLICIT\"]:\n raise ValueError(\"Unknown Attr(padding_algorithm): '%s'. \"\n \"It can only be 'SAME' or 'VALID'.\" %\n str(padding_algorithm))\n\n if attrs['data_format'] == 'NHWC':\n input_ = np.transpose(input_, [0, 3, 1, 2])\n in_n, in_c, in_h, in_w = input_.shape\n f_c, f_out_c, f_h, f_w = filter_.shape\n groups = attrs['groups']\n assert in_c == f_c\n out_c = f_out_c * groups\n sub_in_c = in_c // groups\n\n stride, pad, dilations = attrs['strides'], attrs['paddings'], attrs[\n 'dilations']\n\n # update pad and dilation\n def _get_padding_with_SAME(input_shape, kernel_size, kernel_stride):\n padding = []\n for input_size, filter_size, stride_size in zip(input_shape,\n kernel_size,\n kernel_stride):\n out_size = int((input_size + stride_size - 1) / stride_size)\n pad_sum = np.max(\n ((out_size - 1) * stride_size + filter_size - input_size, 0))\n pad_0 = int(pad_sum / 2)\n pad_1 = int(pad_sum - pad_0)\n padding.append(pad_0)\n padding.append(pad_1)\n return padding\n\n ksize = filter_.shape[2:4]\n if padding_algorithm == \"VALID\":\n pad = [0, 0, 0, 0]\n elif padding_algorithm == \"SAME\":\n dilations = [1, 1]\n input_data_shape = input_.shape[2:4]\n pad = _get_padding_with_SAME(input_data_shape, ksize, stride)\n\n pad_h_0, pad_h_1 = pad[0], pad[0]\n pad_w_0, pad_w_1 = pad[1], pad[1]\n if len(pad) == 4:\n pad_h_0, pad_h_1 = pad[0], pad[1]\n pad_w_0, pad_w_1 = pad[2], pad[3]\n\n d_bolck_h = dilations[0] * (f_h - 1) + 1\n d_bolck_w = dilations[1] * (f_w - 1) + 1\n out_h = (in_h - 1) * stride[0] + d_bolck_h\n out_w = (in_w - 1) * stride[1] + d_bolck_w\n if 'output_size' in attrs:\n output_size = attrs['output_size']\n out_h = output_size[0] + pad_h_0 + pad_h_1\n out_w = output_size[1] + pad_w_0 + pad_w_1\n out_pad_h = 0\n out_pad_w = 0\n if 'output_padding' in attrs:\n out_pad_h = attrs['output_padding'][0]\n out_pad_w = attrs['output_padding'][1]\n out = np.zeros((in_n, out_c, out_h + out_pad_h, out_w + out_pad_w),\n dtype=input_.dtype)\n\n for n in range(in_n):\n for i in range(in_h):\n for j in range(in_w):\n for g in range(groups):\n input_masked = input_[n, g * sub_in_c:(g + 1) * sub_in_c, i,\n j] # (c)\n input_masked = np.reshape(input_masked, (sub_in_c, 1, 1))\n input_masked = np.tile(input_masked, (1, f_h, f_w))\n\n for k in range(f_out_c):\n tmp_out = np.sum(\n input_masked *\n filter_[g * sub_in_c:(g + 1) * sub_in_c, k, :, :],\n axis=0)\n i1, i2 = i * stride[0], i * stride[0] + d_bolck_h\n j1, j2 = j * stride[1], j * stride[1] + d_bolck_w\n out[n, g * f_out_c + k, i1:i2:dilations[0],\n j1:j2:dilations[1]] += tmp_out\n\n out = out[:, :, pad_h_0:out_h - pad_h_1 + out_pad_h,\n pad_w_0:out_w - pad_w_1 + out_pad_w]\n if attrs['data_format'] == 'NHWC':\n out = np.transpose(out, [0, 2, 3, 1])\n return out\n\n\nclass TestConv2DTransposeOp(OpTest):\n\n def setUp(self):\n # init as conv transpose\n self.dtype = np.float32\n self.set_mlu()\n self.need_check_grad = True\n self.is_test = False\n self.use_cudnn = False\n self.use_mkldnn = False\n self.output_size = None\n self.output_padding = []\n self.data_format = \"NCHW\"\n self.pad = [0, 0]\n self.padding_algorithm = \"EXPLICIT\"\n self.init_op_type()\n self.init_test_case()\n\n input_ = np.random.random(self.input_size).astype(self.dtype)\n filter_ = np.random.random(self.filter_size).astype(self.dtype)\n\n self.inputs = {'Input': input_, 'Filter': filter_}\n self.attrs = {\n 'strides': self.stride,\n 'paddings': self.pad,\n 'padding_algorithm': self.padding_algorithm,\n 'groups': self.groups,\n 'dilations': self.dilations,\n 'use_cudnn': self.use_cudnn,\n 'is_test': self.is_test,\n 'use_mkldnn': self.use_mkldnn,\n 'data_format': self.data_format\n }\n if self.output_size is not None:\n self.attrs['output_size'] = self.output_size\n\n if len(self.output_padding) > 0:\n self.attrs['output_padding'] = self.output_padding\n\n output = conv2dtranspose_forward_naive(input_, filter_,\n self.attrs).astype(self.dtype)\n\n self.outputs = {'Output': output}\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad_no_input(self):\n if self.need_check_grad:\n self.check_grad_with_place(self.place, ['Filter'],\n 'Output',\n max_relative_error=0.02,\n no_grad_set=set(['Input']))\n\n def test_check_grad_no_filter(self):\n if self.need_check_grad:\n self.check_grad_with_place(self.place, ['Input'],\n 'Output',\n no_grad_set=set(['Filter']))\n\n def test_check_grad(self):\n if self.need_check_grad:\n self.check_grad_with_place(self.place,\n set(['Input', 'Filter']),\n 'Output',\n max_relative_error=0.02)\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def init_op_type(self):\n self.op_type = \"conv2d_transpose\"\n\n\nclass TestWithSymmetricPad(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithAsymmetricPad(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithSAMEPad(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.stride = [2, 1]\n self.dilations = [1, 2]\n self.groups = 1\n self.input_size = [2, 3, 6, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 4, 3]\n self.padding_algorithm = 'SAME'\n\n\nclass TestWithVALIDPad(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n self.padding_algorithm = 'VALID'\n\n\nclass TestWithGroups(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 4, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 3, 3, 3]\n\n\nclass TestWithStride(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithDilation(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [2, 2]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n\nclass TestWithEvenUpsample(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_size = [14, 14]\n self.input_size = [2, 3, 7, 7] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 5, 5]\n\n\nclass TestWithEvenUpsampleOutputPadding(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_padding = [1, 1]\n self.input_size = [2, 3, 7, 7] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 5, 5]\n\n\nclass Test_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithSymmetricPad_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithAsymmetricPad_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 0, 1, 2]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithGroups_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 5, 5, 4] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 3, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithStride_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [2, 2]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NCHW\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithDilation_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [2, 2]\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestWithEvenUpsample_NHWC(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_size = [14, 14]\n self.input_size = [2, 7, 7, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 5, 5]\n self.data_format = 'NHWC'\n\n\nclass TestWithEvenUpsample_NHWC_output_padding(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_padding = [1, 1]\n self.input_size = [2, 7, 7, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 5, 5]\n self.data_format = 'NHWC'\n\n\nclass TestMLU_FP16(TestConv2DTransposeOp):\n\n def init_test_case(self):\n self.dtype = np.float16\n self.set_mlu()\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.groups = 1\n self.dilations = [1, 1]\n self.input_size = [2, 3, 5, 5] # NCHW\n f_c = self.input_size[1]\n self.filter_size = [f_c, 6, 3, 3]\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def init_op_type(self):\n self.need_check_grad = False\n self.op_type = \"conv2d_transpose\"\n\n def test_check_output(self):\n self.check_output_with_place(self.place, atol=1e-2)\n\n\nclass TestMLU_NHWC_FP16(TestMLU_FP16):\n\n def init_test_case(self):\n self.dtype = np.float16\n self.pad = [0, 0]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 1\n self.input_size = [2, 5, 5, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestMLUWithGroups_NHWC_FP16(TestMLU_FP16):\n\n def init_test_case(self):\n self.dtype = np.float16\n self.pad = [1, 1]\n self.stride = [1, 1]\n self.dilations = [1, 1]\n self.groups = 2\n self.input_size = [2, 5, 5, 4] # NCHW\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 3, 3, 3]\n self.data_format = 'NHWC'\n\n\nclass TestMLUWithEvenUpsample_NHWC_FP16(TestMLU_FP16):\n\n def init_test_case(self):\n self.dtype = np.float16\n self.pad = [2, 2]\n self.stride = [2, 2]\n self.groups = 1\n self.dilations = [1, 1]\n self.output_size = [14, 14]\n self.input_size = [2, 7, 7, 3] # NHWC\n f_c = self.input_size[-1]\n self.filter_size = [f_c, 6, 5, 5]\n self.data_format = 'NHWC'\n\n\nclass TestConv2DTransposeAPI(unittest.TestCase):\n\n def setUp(self):\n self.set_mlu()\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def test_case1(self):\n data1 = fluid.layers.data(name='data1',\n shape=[3, 5, 5],\n dtype='float32')\n data2 = fluid.layers.data(name='data2',\n shape=[5, 5, 3],\n dtype='float32')\n out1 = fluid.layers.conv2d_transpose(input=data1,\n groups=1,\n num_filters=6,\n filter_size=3,\n data_format='NCHW')\n out2 = fluid.layers.conv2d_transpose(input=data2,\n groups=1,\n num_filters=6,\n filter_size=3,\n data_format='NHWC')\n out3 = fluid.layers.conv2d_transpose(input=data1,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding=[[0, 0], [1, 1], [1, 1],\n [0, 0]],\n data_format='NHWC')\n out4 = fluid.layers.conv2d_transpose(input=data1,\n groups=3,\n num_filters=6,\n filter_size=3,\n padding=[[0, 0], [0, 0], [2, 1],\n [0, 0]],\n data_format='NCHW')\n out5 = fluid.layers.conv2d_transpose(input=data2,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding='SAME',\n data_format='NCHW')\n out6 = fluid.layers.conv2d_transpose(input=data1,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding='VALID',\n data_format='NHWC')\n out7 = fluid.layers.conv2d_transpose(input=data1,\n groups=1,\n num_filters=6,\n output_size=[7, 7],\n padding=[0, 0],\n data_format='NHWC')\n\n data1_np = np.random.random((2, 3, 5, 5)).astype(\"float32\")\n data2_np = np.random.random((2, 5, 5, 3)).astype(\"float32\")\n\n exe = fluid.Executor(self.place)\n exe.run(fluid.default_startup_program())\n results = exe.run(fluid.default_main_program(),\n feed={\n \"data1\": data1_np,\n \"data2\": data2_np\n },\n fetch_list=[out1, out2, out3, out4, out5, out6, out7],\n return_numpy=True)\n self.assertIsNotNone(results[0])\n self.assertIsNotNone(results[1])\n self.assertIsNotNone(results[2])\n self.assertIsNotNone(results[3])\n self.assertIsNotNone(results[4])\n self.assertIsNotNone(results[5])\n self.assertIsNotNone(results[6])\n\n\nclass TestConv2DTransposeOpException(unittest.TestCase):\n\n def setUp(self):\n self.set_mlu()\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def test_exception(self):\n data = fluid.layers.data(name='data', shape=[3, 5, 5], dtype=\"float32\")\n\n def attr_data_format():\n out = fluid.layers.conv2d_transpose(input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n data_format=\"NCDHW\")\n\n self.assertRaises(ValueError, attr_data_format)\n\n def attr_padding_str():\n out = fluid.layers.conv2d_transpose(input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding='Vald')\n\n self.assertRaises(ValueError, attr_padding_str)\n\n def attr_padding_list():\n out = fluid.layers.conv2d_transpose(input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding=[[1, 1], [1, 1], [0, 0],\n [0, 0]])\n\n self.assertRaises(ValueError, attr_padding_list)\n\n def attr_padding_with_data_format():\n out = fluid.layers.conv2d_transpose(input=data,\n groups=1,\n num_filters=6,\n filter_size=3,\n padding=[[1, 1], [0, 0], [0, 0],\n [1, 1]],\n data_format='NHWC')\n\n self.assertRaises(ValueError, attr_padding_with_data_format)\n\n error_input = fluid.layers.data(name='error_data',\n shape=[1],\n dtype=\"float32\")\n\n def error_input_size():\n out = fluid.layers.conv2d_transpose(input=error_input,\n groups=1,\n num_filters=6,\n filter_size=3)\n\n self.assertRaises(ValueError, error_input_size)\n\n def error_groups():\n out = fluid.layers.conv2d_transpose(input=data,\n groups=0,\n num_filters=6,\n filter_size=3,\n data_format='NHWC')\n\n self.assertRaises(ValueError, error_groups)\n\n\nclass TestConv2DTransposeRepr(unittest.TestCase):\n\n def setUp(self):\n self.set_mlu()\n\n def set_mlu(self):\n self.__class__.use_mlu = True\n self.place = paddle.device.MLUPlace(0)\n\n def test_case(self):\n paddle.disable_static()\n x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.)\n conv = nn.Conv2DTranspose(4, 6, (3, 3), output_padding=1, stride=2)\n print(conv)\n y_var = conv(x_var)\n y_np = y_var.numpy()\n self.assertIsNotNone(y_np)\n paddle.enable_static()\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_data_feed()\n self.set_feed_attr()\n self.set_op_attrs()\n\n def set_data_feed(self):\n x = np.random.uniform(size=[1, 3, 2, 2])\n y = np.random.uniform(size=[1, 3, 2, 2])\n self.feed_fp32 = {\"x\": x.astype(np.float32), \"y\": y.astype(np.float32)}\n self.feed_fp16 = {\"x\": x.astype(np.float16), \"y\": y.astype(np.float16)}\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n self.feed_dtype = [x.dtype for x in self.feed_fp32.values()]\n\n def set_op_attrs(self):\n self.attrs = {}\n\n @IPUOpTest.static_graph\n def build_model(self):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype='float32')\n y = paddle.static.data(name=self.feed_list[1],\n shape=self.feed_shape[1],\n dtype='float32')\n out = paddle.fluid.layers.sum([x, y], **self.attrs)\n self.fetch_list = [out.name]\n\n def run_model(self, exec_mode):\n self.run_op_test(exec_mode)\n\n def test(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model()\n self.run_model(m)\n self.check()\n\n\nclass TestCase1(TestBase):\n\n def set_data_feed(self):\n x = np.random.uniform(size=[1, 3, 2, 2])\n y = np.random.uniform(size=[1, 3, 2, 2])\n z = np.random.uniform(size=[1, 3, 2, 2])\n self.feed_fp32 = {\n \"x\": x.astype(np.float32),\n \"y\": y.astype(np.float32),\n \"z\": z.astype(np.float32)\n }\n self.feed_fp16 = {\n \"x\": x.astype(np.float16),\n \"y\": y.astype(np.float16),\n \"z\": z.astype(np.float16)\n }\n\n @IPUOpTest.static_graph\n def build_model(self):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype='float32')\n y = paddle.static.data(name=self.feed_list[1],\n shape=self.feed_shape[1],\n dtype='float32')\n z = paddle.static.data(name=self.feed_list[2],\n shape=self.feed_shape[2],\n dtype='float32')\n out = paddle.fluid.layers.sum([x, y, z], **self.attrs)\n self.fetch_list = [out.name]\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "#Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport unittest\nimport numpy as np\nimport paddle\nimport paddle.fluid as fluid\nimport paddle.fluid.layers as layers\nimport paddle.fluid.core as core\nfrom paddle.static import program_guard, Program\nfrom op_test import OpTest\n\n\nclass TestMVOp(OpTest):\n\n def setUp(self):\n self.op_type = \"mv\"\n self.python_api = paddle.mv\n self.init_config()\n self.inputs = {'X': self.x, 'Vec': self.vec}\n self.outputs = {'Out': np.dot(self.x, self.vec)}\n\n def test_check_output(self):\n self.check_output(check_eager=True)\n\n def test_check_grad(self):\n self.check_grad(['X', 'Vec'], 'Out', check_eager=True)\n\n def init_config(self):\n self.x = np.random.random((2, 100)).astype(\"float64\")\n self.vec = np.random.random((100)).astype(\"float64\")\n\n\nclass TestMVAPI(unittest.TestCase):\n\n def test_dygraph_api_out(self):\n paddle.disable_static()\n\n self.x_data = np.random.random((5, 100)).astype(\"float64\")\n self.x = paddle.to_tensor(self.x_data)\n self.vec_data = np.random.random((100)).astype(\"float64\")\n self.vec = paddle.to_tensor(self.vec_data)\n z = paddle.mv(self.x, self.vec)\n np_z = z.numpy()\n z_expected = np.array(np.dot(self.x_data, self.vec_data))\n self.assertTrue(np.allclose(np_z, z_expected))\n\n paddle.enable_static()\n\n def test_static_graph(self):\n for x_stop_gradient in [False, True]:\n for vec_stop_gradient in [False, True]:\n\n paddle.enable_static()\n\n train_program = Program()\n startup_program = Program()\n\n self.input_x = np.random.rand(5, 100).astype(\"float64\")\n self.input_vec = np.random.rand(100).astype(\"float64\")\n\n with program_guard(train_program, startup_program):\n data_x = paddle.static.data(\"x\",\n shape=[5, 100],\n dtype=\"float64\")\n data_vec = paddle.static.data(\"vec\",\n shape=[100],\n dtype=\"float64\")\n\n data_x.stop_gradient = x_stop_gradient\n data_vec.stop_gradient = vec_stop_gradient\n\n result_vec = paddle.mv(data_x, data_vec)\n\n self.place = paddle.CPUPlace()\n exe = paddle.static.Executor(self.place)\n res, = exe.run(feed={\n \"x\": self.input_x,\n \"vec\": self.input_vec\n },\n fetch_list=[result_vec])\n z_expected = np.array(np.dot(self.input_x, self.input_vec))\n self.assertTrue(np.allclose(res, z_expected))\n\n\nclass TestMVError(unittest.TestCase):\n\n def test_input(self):\n\n def test_shape():\n paddle.enable_static()\n\n self.input_x = np.random.rand(5, 100).astype(\"float64\")\n self.input_vec = np.random.rand(100).astype(\"float64\")\n\n data_x = paddle.static.data(\"x\", shape=[5, 100], dtype=\"float64\")\n data_vec = paddle.static.data(\"vec\",\n shape=[100, 2],\n dtype=\"float64\")\n result_vec = paddle.mv(data_x, data_vec)\n\n self.assertRaises(ValueError, test_shape)\n\n\nif __name__ == '__main__':\n paddle.enable_static()\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport numpy as np\nimport unittest\nimport sys\n\nsys.path.append(\"..\")\n\nfrom paddle.fluid import Program, program_guard\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nimport paddle\nfrom op_test import OpTest, skip_check_grad_ci\n\npaddle.enable_static()\n\n\nclass TestElementwiseAddOp(OpTest):\n\n def setUp(self):\n self.set_npu()\n self.op_type = \"elementwise_add\"\n self.place = paddle.NPUPlace(0)\n self.init_dtype()\n self.init_input_output()\n self.init_kernel_type()\n self.init_axis()\n\n self.inputs = {\n 'X': OpTest.np_dtype_to_fluid_dtype(self.x),\n 'Y': OpTest.np_dtype_to_fluid_dtype(self.y)\n }\n self.attrs = {'axis': self.axis, 'use_mkldnn': self.use_mkldnn}\n self.outputs = {'Out': self.out}\n\n def set_npu(self):\n self.__class__.use_npu = True\n\n def init_kernel_type(self):\n self.use_mkldnn = False\n\n def init_input_output(self):\n self.x = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)\n self.y = np.random.uniform(0.1, 1, [13, 17]).astype(self.dtype)\n self.out = np.add(self.x, self.y)\n\n def init_dtype(self):\n self.dtype = np.float32\n\n def init_axis(self):\n self.axis = -1\n\n def test_check_output(self):\n self.check_output_with_place(self.place)\n\n def test_check_grad_normal(self):\n if self.dtype == np.int64:\n return\n\n if self.dtype == np.float16:\n self.check_grad_with_place(\n self.place,\n ['X', 'Y'],\n 'Out',\n max_relative_error=0.15,\n )\n else:\n self.check_grad_with_place(\n self.place,\n ['X', 'Y'],\n 'Out',\n max_relative_error=0.006,\n )\n\n def test_check_grad_ingore_x(self):\n if self.dtype == np.int64:\n return\n\n if self.dtype == np.float16:\n self.check_grad_with_place(\n self.place,\n ['Y'],\n 'Out',\n no_grad_set=set(\"X\"),\n max_relative_error=0.92,\n )\n else:\n self.check_grad_with_place(\n self.place,\n ['Y'],\n 'Out',\n no_grad_set=set(\"X\"),\n max_relative_error=0.006,\n )\n\n def test_check_grad_ingore_y(self):\n if self.dtype == np.int64:\n return\n\n if self.dtype == np.float16:\n self.check_grad_with_place(\n self.place,\n ['X'],\n 'Out',\n no_grad_set=set(\"Y\"),\n max_relative_error=0.8,\n )\n else:\n self.check_grad_with_place(\n self.place,\n ['X'],\n 'Out',\n no_grad_set=set(\"Y\"),\n max_relative_error=0.006,\n )\n\n\nclass TestFP16ElementwiseAddOp(TestElementwiseAddOp):\n\n def init_dtype(self):\n self.dtype = np.float16\n\n\nclass TestINT64ElementwiseAddOp(TestElementwiseAddOp):\n\n def init_dtype(self):\n self.dtype = np.int64\n\n\n@skip_check_grad_ci(\n reason=\"[skip shape check] Use y_shape(1) to test broadcast.\")\nclass TestElementwiseAddOp_scalar(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 4).astype(self.dtype)\n self.y = np.random.rand(1).astype(self.dtype)\n self.out = self.x + self.y\n\n\n@skip_check_grad_ci(\n reason=\"[skip shape check] Use y_shape(1) to test broadcast.\")\nclass TestFP16ElementwiseAddOp_scalar(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 4).astype(self.dtype)\n self.y = np.random.rand(1).astype(self.dtype)\n self.out = self.x + self.y\n\n\n@skip_check_grad_ci(\n reason=\"[skip shape check] Use y_shape(1,1) to test broadcast.\")\nclass TestElementwiseAddOp_scalar2(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 4).astype(self.dtype)\n self.y = np.random.rand(1, 1).astype(self.dtype)\n self.out = self.x + self.y\n\n\n@skip_check_grad_ci(\n reason=\"[skip shape check] Use y_shape(1,1) to test broadcast.\")\nclass TestFP16ElementwiseAddOp_scalar2(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 4).astype(self.dtype)\n self.y = np.random.rand(1, 1).astype(self.dtype)\n self.out = self.x + self.y\n\n\nclass TestAddAPI(unittest.TestCase):\n\n def test_name(self):\n with paddle.static.program_guard(paddle.static.Program()):\n x = paddle.static.data(name=\"x\", shape=[2, 3], dtype=\"float32\")\n y = paddle.static.data(name='y', shape=[2, 3], dtype='float32')\n\n y_1 = paddle.add(x, y, name='add_res')\n self.assertEqual(('add_res' in y_1.name), True)\n\n def test_static(self):\n with paddle.static.program_guard(paddle.static.Program()):\n\n x_np = np.array([2, 3, 4]).astype('float32')\n y_np = np.array([1, 5, 2]).astype('float32')\n\n x = paddle.static.data(name=\"x\", shape=[3], dtype='float32')\n y = paddle.static.data(name=\"y\", shape=[3], dtype='float32')\n\n x_reshape = paddle.reshape(x, [3, 1])\n y_reshape = paddle.reshape(y, [3, 1])\n z = paddle.add(x_reshape, y_reshape)\n z = paddle.reshape(z, shape=[3])\n\n place = paddle.NPUPlace(0)\n exe = paddle.static.Executor(place)\n x_value, y_value, z_value = exe.run(feed={\n \"x\": x_np,\n \"y\": y_np\n },\n fetch_list=[x, y, z])\n\n z_expected = np.array([3., 8., 6.])\n self.assertEqual(\n (x_value == x_np).all(),\n True,\n msg=\"x_value = {}, but expected {}\".format(x_value, x_np))\n self.assertEqual(\n (y_value == y_np).all(),\n True,\n msg=\"y_value = {}, but expected {}\".format(y_value, y_np))\n self.assertEqual(\n (z_value == z_expected).all(),\n True,\n msg=\"z_value = {}, but expected {}\".format(z_value, z_expected))\n\n\nclass TestAddError(unittest.TestCase):\n\n def test_errors(self):\n with paddle.static.program_guard(paddle.static.Program()):\n # the input of elementwise_add must be Variable.\n x1 = fluid.create_lod_tensor(np.array([-1, 3, 5, 5]),\n [[1, 1, 1, 1]], fluid.NPUPlace(0))\n y1 = fluid.create_lod_tensor(np.array([-1, 3, 5, 5]),\n [[1, 1, 1, 1]], fluid.NPUPlace(0))\n self.assertRaises(TypeError, paddle.add, x1, y1)\n\n # the input dtype must be float16 or float32 or float64 or int32 or int64\n x2 = paddle.static.data(name='x2',\n shape=[3, 4, 5, 6],\n dtype=\"uint8\")\n y2 = paddle.static.data(name='y2',\n shape=[3, 4, 5, 6],\n dtype=\"uint8\")\n self.assertRaises(TypeError, paddle.add, x2, y2)\n\n\nclass TestElementwiseAddOp_Vector(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.random((100, )).astype(self.dtype)\n self.y = np.random.random((100, )).astype(self.dtype)\n self.out = np.add(self.x, self.y)\n\n\nclass TestFP16ElementwiseAddOp_Vector(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.random((100, )).astype(self.dtype)\n self.y = np.random.random((100, )).astype(self.dtype)\n self.out = np.add(self.x, self.y)\n\n\nclass TestElementwiseAddOp_broadcast_0(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 2, 3).astype(self.dtype)\n self.y = np.random.rand(100).astype(self.dtype)\n self.out = self.x + self.y.reshape(100, 1, 1)\n\n def init_axis(self):\n self.axis = 0\n\n\nclass TestFP16ElementwiseAddOp_broadcast_0(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 2, 3).astype(self.dtype)\n self.y = np.random.rand(100).astype(self.dtype)\n self.out = self.x + self.y.reshape(100, 1, 1)\n\n def init_axis(self):\n self.axis = 0\n\n\nclass TestElementwiseAddOp_broadcast_1(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 100, 3).astype(self.dtype)\n self.y = np.random.rand(100).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 100, 1)\n\n def init_axis(self):\n self.axis = 1\n\n\nclass TestFP16ElementwiseAddOp_broadcast_1(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 100, 3).astype(self.dtype)\n self.y = np.random.rand(100).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 100, 1)\n\n def init_axis(self):\n self.axis = 1\n\n\nclass TestElementwiseAddOp_broadcast_2(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 100).astype(self.dtype)\n self.y = np.random.rand(100).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 1, 100)\n\n\nclass TestFP16ElementwiseAddOp_broadcast_2(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 100).astype(self.dtype)\n self.y = np.random.rand(100).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 1, 100)\n\n\nclass TestElementwiseAddOp_broadcast_3(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 10, 12, 1).astype(self.dtype)\n self.y = np.random.rand(10, 12).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 10, 12, 1)\n\n def init_axis(self):\n self.axis = 1\n\n\nclass TestFP16ElementwiseAddOp_broadcast_3(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 10, 12, 3).astype(self.dtype)\n self.y = np.random.rand(10, 12).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 10, 12, 1)\n\n def init_axis(self):\n self.axis = 1\n\n\nclass TestElementwiseAddOp_broadcast_4(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 2, 1, 2).astype(self.dtype)\n self.y = np.random.rand(100, 1).astype(self.dtype)\n self.out = self.x + self.y.reshape(100, 1, 1, 1)\n\n def init_axis(self):\n self.axis = 0\n\n\nclass TestFP16ElementwiseAddOp_broadcast_4(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 2, 1, 2).astype(self.dtype)\n self.y = np.random.rand(100, 1).astype(self.dtype)\n self.out = self.x + self.y.reshape(100, 1, 1, 1)\n\n def init_axis(self):\n self.axis = 0\n\n\nclass TestElementwiseAddOp_broadcast_5(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(10, 3, 12).astype(self.dtype)\n self.y = np.random.rand(10, 1, 12).astype(self.dtype)\n self.out = self.x + self.y\n\n\nclass TestFP16ElementwiseAddOp_broadcast_5(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(10, 3, 12).astype(self.dtype)\n self.y = np.random.rand(10, 1, 12).astype(self.dtype)\n self.out = self.x + self.y\n\n\nclass TestElementwiseAddOp_broadcast_6(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 12, 3, 5).astype(self.dtype)\n self.y = np.random.rand(2, 12, 1, 5).astype(self.dtype)\n self.out = self.x + self.y\n\n\nclass TestElementwiseAddOp_broadcast_7(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(1, 1, 20, 5).astype(self.dtype)\n self.y = np.random.rand(20, 5, 1, 1).astype(self.dtype)\n self.out = self.x + self.y\n\n\nclass TestFP16ElementwiseAddOp_broadcast_6(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 12, 3, 5).astype(self.dtype)\n self.y = np.random.rand(2, 12, 1, 5).astype(self.dtype)\n self.out = self.x + self.y\n\n\nclass TestElementwiseAddOp_rowwise_add_0(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 10, 12).astype(self.dtype)\n self.y = np.random.rand(10, 12).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 10, 12)\n\n def init_axis(self):\n self.axis = 1\n\n\nclass TestFP16ElementwiseAddOp_rowwise_add_0(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 10, 12).astype(self.dtype)\n self.y = np.random.rand(10, 12).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 10, 12)\n\n def init_axis(self):\n self.axis = 1\n\n\n@skip_check_grad_ci(\n reason=\"[skip shape check] Use y_shape(1) to test broadcast.\")\nclass TestElementwiseAddOp_rowwise_add_1(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 1).astype(self.dtype)\n self.y = np.random.rand(1).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 1)\n\n def init_axis(self):\n self.axis = 1\n\n\n@skip_check_grad_ci(\n reason=\"[skip shape check] Use y_shape(1) to test broadcast.\")\nclass TestFP16ElementwiseAddOp_rowwise_add_1(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 1).astype(self.dtype)\n self.y = np.random.rand(1).astype(self.dtype)\n self.out = self.x + self.y.reshape(1, 1)\n\n def init_axis(self):\n self.axis = 1\n\n\nclass TestElementwiseAddOp_channelwise_add(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 2, 3).astype(self.dtype)\n self.y = np.random.rand(100, 1, 1).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = -1\n\n\nclass TestFP16ElementwiseAddOp_channelwise_add(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(100, 2, 3).astype(self.dtype)\n self.y = np.random.rand(100, 1, 1).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = -1\n\n\nclass TestElementwiseAddOp_commonuse_add1(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 100).astype(self.dtype)\n self.y = np.random.rand(1, 1, 100).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = -1\n\n\nclass TestElementwiseFP16AddOp_commonuse_add1(TestFP16ElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(2, 3, 100).astype(self.dtype)\n self.y = np.random.rand(1, 1, 100).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = -1\n\n\nclass TestElementwiseAddOp_commonuse_add2(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(10, 3, 1, 4).astype(self.dtype)\n self.y = np.random.rand(10, 1, 12, 1).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = -1\n\n\nclass TestElementwiseAddOp_xsize_lessthan_ysize_add(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(10, 12).astype(self.dtype)\n self.y = np.random.rand(2, 2, 10, 12).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = 2\n\n\nclass TestElementwiseAddOp_same_shape_ysize_large(TestElementwiseAddOp):\n\n def init_input_output(self):\n self.x = np.random.rand(10, 1, 12).astype(self.dtype)\n self.y = np.random.rand(10, 2, 12).astype(self.dtype)\n self.out = self.x + self.y\n\n def init_axis(self):\n self.axis = 0\n\n\nclass TestElementwiseAddOpError(unittest.TestCase):\n\n def test_errors(self):\n with program_guard(Program(), Program()):\n # the input of elementwise_add must be Variable.\n x1 = fluid.create_lod_tensor(np.array([-1, 3, 5, 5]),\n [[1, 1, 1, 1]], fluid.NPUPlace(0))\n y1 = fluid.create_lod_tensor(np.array([-1, 3, 5, 5]),\n [[1, 1, 1, 1]], fluid.NPUPlace(0))\n self.assertRaises(TypeError, fluid.layers.elementwise_add, x1, y1)\n\n # the input dtype of elementwise_add must be float16 or float32 or float64 or int32 or int64\n # float16 only can be set on GPU place\n x2 = fluid.layers.data(name='x2', shape=[3, 4, 5, 6], dtype=\"uint8\")\n y2 = fluid.layers.data(name='y2', shape=[3, 4, 5, 6], dtype=\"uint8\")\n self.assertRaises(TypeError, fluid.layers.elementwise_add, x2, y2)\n\n\nclass TestAddApi(unittest.TestCase):\n\n def _executed_api(self, x, y, name=None):\n return paddle.add(x, y, name)\n\n def test_name(self):\n with fluid.program_guard(fluid.Program()):\n x = fluid.data(name=\"x\", shape=[2, 3], dtype=\"float32\")\n y = fluid.data(name='y', shape=[2, 3], dtype='float32')\n\n y_1 = self._executed_api(x, y, name='add_res')\n self.assertEqual(('add_res' in y_1.name), True)\n\n def test_declarative(self):\n with fluid.program_guard(fluid.Program()):\n\n def gen_data():\n return {\n \"x\": np.array([2, 3, 4]).astype('float32'),\n \"y\": np.array([1, 5, 2]).astype('float32')\n }\n\n x = fluid.data(name=\"x\", shape=[3], dtype='float32')\n y = fluid.data(name=\"y\", shape=[3], dtype='float32')\n z = self._executed_api(x, y)\n\n place = fluid.NPUPlace(0)\n exe = fluid.Executor(place)\n z_value = exe.run(feed=gen_data(), fetch_list=[z.name])\n z_expected = np.array([3., 8., 6.])\n self.assertEqual((z_value == z_expected).all(), True)\n\n def test_dygraph(self):\n with fluid.dygraph.guard(paddle.NPUPlace(0)):\n np_x = np.array([2, 3, 4]).astype('float32')\n np_y = np.array([1, 5, 2]).astype('float32')\n x = fluid.dygraph.to_variable(np_x)\n y = fluid.dygraph.to_variable(np_y)\n z = self._executed_api(x, y)\n np_z = z.numpy()\n z_expected = np.array([3., 8., 6.])\n self.assertEqual((np_z == z_expected).all(), True)\n\n\nclass TestAddInplaceApi(TestAddApi):\n\n def _executed_api(self, x, y, name=None):\n return x.add_(y, name)\n\n\nclass TestAddInplaceBroadcastSuccess(unittest.TestCase):\n\n def init_data(self):\n self.x_numpy = np.random.rand(2, 3, 4).astype('float')\n self.y_numpy = np.random.rand(3, 4).astype('float')\n\n def test_broadcast_success(self):\n paddle.disable_static(place=paddle.NPUPlace(0))\n self.init_data()\n x = paddle.to_tensor(self.x_numpy)\n y = paddle.to_tensor(self.y_numpy)\n inplace_result = x.add_(y)\n numpy_result = self.x_numpy + self.y_numpy\n self.assertEqual((inplace_result.numpy() == numpy_result).all(), True)\n paddle.enable_static()\n\n\nclass TestAddInplaceBroadcastSuccess2(TestAddInplaceBroadcastSuccess):\n\n def init_data(self):\n self.x_numpy = np.random.rand(1, 2, 3, 1).astype('float')\n self.y_numpy = np.random.rand(3, 1).astype('float')\n\n\nclass TestAddInplaceBroadcastSuccess3(TestAddInplaceBroadcastSuccess):\n\n def init_data(self):\n self.x_numpy = np.random.rand(2, 3, 1, 5).astype('float')\n self.y_numpy = np.random.rand(1, 3, 1, 5).astype('float')\n\n\nclass TestAddInplaceBroadcastError(unittest.TestCase):\n\n def init_data(self):\n self.x_numpy = np.random.rand(3, 4).astype('float')\n self.y_numpy = np.random.rand(2, 3, 4).astype('float')\n\n def test_broadcast_errors(self):\n paddle.disable_static(place=paddle.NPUPlace(0))\n self.init_data()\n x = paddle.to_tensor(self.x_numpy)\n y = paddle.to_tensor(self.y_numpy)\n\n def broadcast_shape_error():\n x.add_(y)\n\n self.assertRaises(ValueError, broadcast_shape_error)\n paddle.enable_static()\n\n\nclass TestAddInplaceBroadcastError2(TestAddInplaceBroadcastError):\n\n def init_data(self):\n self.x_numpy = np.random.rand(2, 1, 4).astype('float')\n self.y_numpy = np.random.rand(2, 3, 4).astype('float')\n\n\nclass TestAddInplaceBroadcastError3(TestAddInplaceBroadcastError):\n\n def init_data(self):\n self.x_numpy = np.random.rand(5, 2, 1, 4).astype('float')\n self.y_numpy = np.random.rand(2, 3, 4).astype('float')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom trt_layer_auto_scan_test import TrtLayerAutoScanTest\nfrom program_config import TensorConfig, ProgramConfig\nimport numpy as np\nimport paddle.inference as paddle_infer\nfrom functools import partial\nfrom typing import List, Dict, Any\nimport unittest\n\n\nclass TrtConvertYoloBoxHeadTest(TrtLayerAutoScanTest):\n\n def sample_program_configs(self):\n\n def generate_input(attrs: List[Dict[str, Any]], batch, shape):\n gen_shape = shape.copy()\n gen_shape.insert(0, batch)\n return np.random.uniform(0, 1, gen_shape).astype(\"float32\")\n\n input_shape = [[255, 19, 19], [255, 38, 38], [255, 76, 76]]\n anchors = [[116, 90, 156, 198, 373, 326], [30, 61, 62, 45, 59, 119],\n [10, 13, 16, 30, 33, 23]]\n class_num = 80\n for batch in [1, 4]:\n for i in range(len(anchors)):\n attrs_dict = {\n \"anchors\": anchors[i],\n \"class_num\": class_num,\n }\n ops_config = [{\n \"op_type\": \"yolo_box_head\",\n \"op_inputs\": {\n \"X\": [\"yolo_box_head_input\"],\n },\n \"op_outputs\": {\n \"Out\": [\"yolo_box_head_output\"],\n },\n \"op_attrs\": attrs_dict\n }]\n ops = self.generate_op_config(ops_config)\n program_config = ProgramConfig(\n ops=ops,\n weights={},\n inputs={\n \"yolo_box_head_input\":\n TensorConfig(data_gen=partial(\n generate_input, attrs_dict, batch, input_shape[i]))\n },\n outputs=[\"yolo_box_head_output\"])\n\n yield program_config\n\n def sample_predictor_configs(\n self, program_config) -> (paddle_infer.Config, List[int], float):\n # for static_shape\n self.trt_param.precision = paddle_infer.PrecisionType.Float32\n yield self.create_inference_config(), [1, 2], 1e-5\n\n def test(self):\n self.run_test()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\n\nimport numpy as np\nimport contextlib\n\nimport paddle\nimport paddle.fluid as fluid\n\nfrom paddle import Model, set_device\nfrom paddle.static import InputSpec as Input\nfrom paddle.nn.layer.loss import CrossEntropyLoss\nfrom paddle.metric import Accuracy\nfrom paddle.vision.models import LeNet\nfrom paddle.vision.datasets import MNIST\n\n\nclass MnistDataset(MNIST):\n\n def __init__(self, mode, return_label=True):\n super(MnistDataset, self).__init__(mode=mode)\n self.return_label = return_label\n\n def __getitem__(self, idx):\n img = np.reshape(self.images[idx], [1, 28, 28])\n if self.return_label:\n return img, np.array(self.labels[idx]).astype('int64')\n return img,\n\n def __len__(self):\n return len(self.images)\n\n\ndef compute_accuracy(pred, gt):\n pred = np.argmax(pred, -1)\n gt = np.array(gt)\n\n correct = pred[:, np.newaxis] == gt\n\n return np.sum(correct) / correct.shape[0]\n\n\[email protected](not fluid.is_compiled_with_cuda(),\n 'CPU testing is not supported')\nclass TestDistTraning(unittest.TestCase):\n\n def test_dynamic_multiple_gpus(self):\n device = set_device('gpu')\n\n im_shape = (-1, 1, 28, 28)\n batch_size = 128\n\n inputs = [Input(im_shape, 'float32', 'image')]\n labels = [Input([None, 1], 'int64', 'label')]\n\n model = Model(LeNet(), inputs, labels)\n optim = fluid.optimizer.Momentum(learning_rate=0.001,\n momentum=.9,\n parameter_list=model.parameters())\n model.prepare(optim, CrossEntropyLoss(), Accuracy())\n\n train_dataset = MnistDataset(mode='train')\n val_dataset = MnistDataset(mode='test')\n test_dataset = MnistDataset(mode='test', return_label=False)\n\n cbk = paddle.callbacks.ProgBarLogger(50)\n model.fit(train_dataset,\n val_dataset,\n epochs=2,\n batch_size=batch_size,\n callbacks=cbk)\n\n eval_result = model.evaluate(val_dataset, batch_size=batch_size)\n\n output = model.predict(test_dataset,\n batch_size=batch_size,\n stack_outputs=True)\n\n np.testing.assert_equal(output[0].shape[0], len(test_dataset))\n\n acc = compute_accuracy(output[0], val_dataset.labels)\n\n np.testing.assert_allclose(acc, eval_result['acc'])\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division\n\nimport os\nimport sys\nimport six\nimport time\nimport unittest\nimport multiprocessing\nimport numpy as np\n\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.io import Dataset, BatchSampler, DataLoader\n\nEPOCH_NUM = 3\nBATCH_SIZE = 8\nIMAGE_SIZE = 32\nSAMPLE_NUM = 100\nCLASS_NUM = 10\n\n\nclass RandomDataset(Dataset):\n\n def __init__(self, sample_num, class_num):\n self.sample_num = sample_num\n self.class_num = class_num\n\n def __getitem__(self, idx):\n np.random.seed(idx)\n image = np.random.random([IMAGE_SIZE]).astype('float32')\n label = np.random.randint(0, self.class_num - 1, (1, )).astype('int64')\n return image, label\n\n def __len__(self):\n return self.sample_num\n\n\ndef simple_fc_net_static():\n startup_prog = fluid.Program()\n main_prog = fluid.Program()\n startup_prog.random_seed = 1\n main_prog.random_seed = 1\n\n with fluid.unique_name.guard():\n with fluid.program_guard(main_prog, startup_prog):\n image = fluid.data(name='image',\n shape=[None, IMAGE_SIZE],\n dtype='float32')\n label = fluid.data(name='label', shape=[None, 1], dtype='int64')\n hidden = image\n param_attr = fluid.ParamAttr(initializer=fluid.initializer.Constant(\n value=0.8))\n bias_attr = fluid.ParamAttr(initializer=fluid.initializer.Constant(\n value=0.5))\n for hidden_size in [10, 20, 30]:\n hidden = fluid.layers.fc(hidden,\n size=hidden_size,\n act='tanh',\n param_attr=param_attr,\n bias_attr=bias_attr)\n\n predict_label = fluid.layers.fc(hidden,\n size=CLASS_NUM,\n act='softmax',\n param_attr=param_attr,\n bias_attr=bias_attr)\n loss = fluid.layers.reduce_mean(\n fluid.layers.cross_entropy(input=predict_label, label=label))\n\n optimizer = fluid.optimizer.Adam()\n optimizer.minimize(loss)\n return startup_prog, main_prog, image, label, loss\n\n\ndef prepare_places(with_data_parallel, with_cpu=False, with_gpu=True):\n places = []\n if with_cpu:\n places.append([fluid.CPUPlace()])\n if with_data_parallel:\n places.append([fluid.CPUPlace()] * 2)\n\n if with_gpu and fluid.core.is_compiled_with_cuda():\n tmp = fluid.cuda_places()[:2]\n assert len(tmp) > 0, \"no gpu detected\"\n if with_data_parallel and len(tmp) > 1:\n places.append(tmp)\n places.append([tmp[0]])\n return places\n\n\nclass TestStaticDataLoader(unittest.TestCase):\n\n def run_main(self, num_workers, places, persistent_workers, use_pe=True):\n scope = fluid.Scope()\n with fluid.scope_guard(scope):\n startup_prog, main_prog, image, label, loss = simple_fc_net_static()\n\n dataset = RandomDataset(SAMPLE_NUM, CLASS_NUM)\n dataloader = DataLoader(dataset,\n feed_list=[image, label],\n places=places,\n num_workers=num_workers,\n batch_size=BATCH_SIZE,\n return_list=False,\n drop_last=True,\n persistent_workers=persistent_workers)\n assert len(dataloader) == int(SAMPLE_NUM / BATCH_SIZE)\n\n exe = fluid.Executor(place=places[0])\n exe.run(startup_prog)\n\n if use_pe:\n prog = fluid.CompiledProgram(main_prog)\n if len(places) > 1:\n prog = prog.with_data_parallel(loss_name=loss.name,\n places=places)\n else:\n prog = main_prog\n\n step_list = []\n loss_list = []\n start_t = time.time()\n for _ in six.moves.range(EPOCH_NUM):\n step = 0\n for d in dataloader:\n assert len(d) == len(places), \"{} != {}\".format(\n len(d), len(places))\n for i, item in enumerate(d):\n image = item['image']\n label = item['label']\n assert image.shape() == [BATCH_SIZE, IMAGE_SIZE]\n assert label.shape() == [BATCH_SIZE, 1]\n assert image._place()._equals(places[i])\n assert label._place()._equals(places[i])\n L, = exe.run(program=prog,\n feed=d,\n fetch_list=[loss],\n use_program_cache=True)\n loss_list.append(np.mean(L))\n step += 1\n step_list.append(step)\n\n end_t = time.time()\n ret = {\n \"time\": end_t - start_t,\n \"step\": step_list,\n \"loss\": np.array(loss_list)\n }\n print(\"time cost\", ret['time'], 'step_list', ret['step'])\n return ret\n\n def test_main(self):\n for p in prepare_places(True):\n for persistent_workers in [True, False]:\n results = []\n for num_workers in [0, 2]:\n print(self.__class__.__name__, p, num_workers,\n persistent_workers)\n sys.stdout.flush()\n ret = self.run_main(num_workers=num_workers,\n places=p,\n persistent_workers=persistent_workers)\n results.append(ret)\n diff = np.max(\n np.abs(results[0]['loss'] - results[1]['loss']) /\n np.abs(results[0]['loss']))\n self.assertLess(diff, 1e-2)\n\n\nclass TestStaticDataLoaderReturnList(unittest.TestCase):\n\n def run_single_place(self, num_workers):\n scope = fluid.Scope()\n image = fluid.data(name='image',\n shape=[None, IMAGE_SIZE],\n dtype='float32')\n label = fluid.data(name='label', shape=[None, 1], dtype='int64')\n with fluid.scope_guard(scope):\n dataset = RandomDataset(SAMPLE_NUM, CLASS_NUM)\n dataloader = DataLoader(dataset,\n feed_list=[image, label],\n num_workers=num_workers,\n batch_size=BATCH_SIZE,\n drop_last=True,\n return_list=True)\n\n for d in dataloader:\n assert isinstance(d, list)\n assert len(d) == 2\n assert not isinstance(d[0], list)\n assert not isinstance(d[1], list)\n\n def run_multi_place(self, num_workers):\n scope = fluid.Scope()\n image = fluid.data(name='image',\n shape=[None, IMAGE_SIZE],\n dtype='float32')\n label = fluid.data(name='label', shape=[None, 1], dtype='int64')\n with fluid.scope_guard(scope):\n dataset = RandomDataset(SAMPLE_NUM, CLASS_NUM)\n dataloader = DataLoader(dataset,\n feed_list=[image, label],\n num_workers=num_workers,\n batch_size=BATCH_SIZE,\n places=[fluid.CPUPlace()] * 2,\n drop_last=True,\n return_list=True)\n\n for d in dataloader:\n assert isinstance(d, list)\n assert len(d) == 2\n assert isinstance(d[0], list)\n assert isinstance(d[1], list)\n\n def test_main(self):\n paddle.enable_static()\n for num_workers in [0, 2]:\n self.run_single_place(num_workers)\n self.run_multi_place(num_workers)\n\n\nclass RandomBatchedDataset(Dataset):\n\n def __init__(self, sample_num, class_num):\n self.sample_num = int(sample_num / BATCH_SIZE)\n self.class_num = class_num\n\n def __getitem__(self, idx):\n np.random.seed(idx)\n images = []\n labels = []\n for _ in range(BATCH_SIZE):\n image = np.random.random([IMAGE_SIZE]).astype('float32')\n label = np.random.randint(0, self.class_num - 1,\n (1, )).astype('int64')\n images.append(image)\n labels.append(label)\n return np.stack(images, axis=0), np.stack(labels, axis=0)\n\n def __len__(self):\n return self.sample_num\n\n\nclass TestStaticDataLoaderWithBatchedDataset(TestStaticDataLoader):\n\n def run_main(self, num_workers, places, persistent_workers):\n scope = fluid.Scope()\n with fluid.scope_guard(scope):\n startup_prog, main_prog, image, label, loss = simple_fc_net_static()\n\n dataset = RandomBatchedDataset(SAMPLE_NUM, CLASS_NUM)\n dataloader = DataLoader(dataset,\n feed_list=[image, label],\n places=places,\n num_workers=num_workers,\n batch_size=None,\n return_list=False,\n drop_last=True,\n persistent_workers=persistent_workers)\n assert len(dataloader) == int(SAMPLE_NUM / BATCH_SIZE)\n\n exe = fluid.Executor(place=places[0])\n exe.run(startup_prog)\n\n prog = fluid.CompiledProgram(main_prog)\n if len(places) > 1:\n prog = prog.with_data_parallel(loss_name=loss.name,\n places=places)\n\n step_list = []\n loss_list = []\n start_t = time.time()\n for _ in six.moves.range(EPOCH_NUM):\n step = 0\n for d in dataloader:\n assert len(d) == len(places), \"{} != {}\".format(\n len(d), len(places))\n for i, item in enumerate(d):\n image = item['image']\n label = item['label']\n assert image.shape() == [BATCH_SIZE, IMAGE_SIZE]\n assert label.shape() == [BATCH_SIZE, 1]\n assert image._place()._equals(places[i])\n assert label._place()._equals(places[i])\n L, = exe.run(program=prog,\n feed=d,\n fetch_list=[loss],\n use_program_cache=True)\n loss_list.append(np.mean(L))\n step += 1\n step_list.append(step)\n\n end_t = time.time()\n ret = {\n \"time\": end_t - start_t,\n \"step\": step_list,\n \"loss\": np.array(loss_list)\n }\n print(\"time cost\", ret['time'], 'step_list', ret['step'])\n return ret\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2018 PaddlePaddle 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.\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport unittest\nimport tempfile\n\nimport numpy as np\n\nfrom test_dist_base import TestDistBase, RUN_STEP\n\nimport os\n\nflag_name = os.path.splitext(__file__)[0]\n\n\nclass TestDistSaveLoadDense2x2(TestDistBase):\n\n def _setup_config(self):\n self._sync_mode = True\n self._enforce_place = \"CPU\"\n\n def check_with_place(self,\n model_file,\n delta=1e-3,\n check_error_log=False,\n need_envs={},\n log_name=\"\"):\n required_envs = {\n \"PATH\": os.getenv(\"PATH\", \"\"),\n \"PYTHONPATH\": os.getenv(\"PYTHONPATH\", \"\"),\n \"LD_LIBRARY_PATH\": os.getenv(\"LD_LIBRARY_PATH\", \"\"),\n \"http_proxy\": \"\"\n }\n\n required_envs.update(need_envs)\n\n if check_error_log:\n required_envs[\"GLOG_vmodule\"] = \\\n \"fused_all_reduce_op_handle=10,all_reduce_op_handle=10,alloc_continuous_space_op=10,fuse_all_reduce_op_pass=10,alloc_continuous_space_for_grad_pass=10,fast_threaded_ssa_graph_executor=10\"\n required_envs[\"GLOG_logtostderr\"] = \"1\"\n\n model_dir = tempfile.mkdtemp()\n\n local_env = {}\n local_env[\"SAVE\"] = \"1\"\n local_env[\"MODEL_DIR\"] = model_dir\n local_env.update(required_envs)\n\n cluster_env = {}\n cluster_env[\"LOAD\"] = \"1\"\n cluster_env[\"MODEL_DIR\"] = model_dir\n cluster_env.update(required_envs)\n\n local_var = self._run_local(model_file, local_env, check_error_log)\n tr0_var, tr1_var = self._run_cluster(model_file,\n cluster_env,\n check_error_log,\n log_name=flag_name)\n\n shutil.rmtree(model_dir)\n\n local_np = np.array(local_var)\n train0_np = np.array(tr0_var)\n train1_np = np.array(tr1_var)\n\n np.testing.assert_almost_equal(local_np, train0_np, decimal=2)\n np.testing.assert_almost_equal(local_np, train1_np, decimal=2)\n np.testing.assert_almost_equal(train0_np, train1_np, decimal=2)\n\n def test_dist(self):\n need_envs = {\n \"IS_DISTRIBUTED\": '0',\n \"IS_SPARSE\": '0',\n 'IS_SELF_CONTAINED_LR': '1',\n 'SAVE_MODE': 'LOCAL',\n }\n self.check_with_place(\"dist_save_load.py\",\n delta=0,\n check_error_log=False,\n need_envs=need_envs)\n\n\nclass TestDistSaveLoadWithPServerStateDense2x2(TestDistBase):\n\n def _setup_config(self):\n self._sync_mode = True\n self._enforce_place = \"CPU\"\n\n def check_with_place(self,\n model_file,\n delta=1e-3,\n check_error_log=False,\n need_envs={},\n log_name=\"\"):\n required_envs = {\n \"PATH\": os.getenv(\"PATH\", \"\"),\n \"PYTHONPATH\": os.getenv(\"PYTHONPATH\", \"\"),\n \"LD_LIBRARY_PATH\": os.getenv(\"LD_LIBRARY_PATH\", \"\"),\n \"http_proxy\": \"\"\n }\n\n required_envs.update(need_envs)\n\n if check_error_log:\n required_envs[\"GLOG_vmodule\"] = \\\n \"fused_all_reduce_op_handle=10,all_reduce_op_handle=10,alloc_continuous_space_op=10,fuse_all_reduce_op_pass=10,alloc_continuous_space_for_grad_pass=10,fast_threaded_ssa_graph_executor=10\"\n required_envs[\"GLOG_logtostderr\"] = \"1\"\n\n model_dir = tempfile.mkdtemp()\n\n save_env = {}\n save_env[\"SAVE_MODE\"] = \"DIST\"\n save_env[\"SAVE\"] = \"1\"\n save_env[\"MODEL_DIR\"] = model_dir\n save_env.update(required_envs)\n\n tr0_var_1, tr1_var_1 = self._run_cluster(model_file,\n save_env,\n check_error_log,\n log_name=flag_name)\n\n load_env = {}\n load_env[\"LOAD\"] = \"1\"\n load_env[\"MODEL_DIR\"] = model_dir\n load_env.update(required_envs)\n tr0_var_2, tr1_var_2 = self._run_cluster(model_file,\n load_env,\n check_error_log,\n log_name=flag_name)\n\n shutil.rmtree(model_dir)\n\n train0_1_np = np.array(tr0_var_1)\n train1_1_np = np.array(tr1_var_1)\n train0_2_np = np.array(tr0_var_2)\n train1_2_np = np.array(tr1_var_2)\n\n np.testing.assert_almost_equal(train0_1_np, train0_2_np, decimal=2)\n np.testing.assert_almost_equal(train1_1_np, train1_2_np, decimal=2)\n\n def test_dist(self):\n need_envs = {\n \"IS_DISTRIBUTED\": '0',\n \"IS_SPARSE\": '0',\n 'IS_SELF_CONTAINED_LR': '1',\n 'SAVE_MODE': 'DIST',\n 'OPTIMIZER': 'ADAM',\n 'SKIP_STEPS': str(np.random.randint(2, 6))\n }\n self.check_with_place(\"dist_save_load.py\",\n delta=0,\n check_error_log=True,\n need_envs=need_envs,\n log_name=flag_name)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\n\nimport paddle\nimport paddle.nn.functional as F\n\nfrom paddle.incubate.optimizer.functional.bfgs import minimize_bfgs\nfrom paddle.fluid.framework import _test_eager_guard\n\nnp.random.seed(123)\n\n\ndef test_static_graph(func, x0, line_search_fn='strong_wolfe', dtype='float32'):\n dimension = x0.shape[0]\n paddle.enable_static()\n main = paddle.static.Program()\n startup = paddle.static.Program()\n with paddle.static.program_guard(main, startup):\n X = paddle.static.data(name='x', shape=[dimension], dtype=dtype)\n Y = minimize_bfgs(func, X, line_search_fn=line_search_fn, dtype=dtype)\n\n exe = paddle.static.Executor()\n exe.run(startup)\n return exe.run(main, feed={'x': x0}, fetch_list=[Y])\n\n\ndef test_static_graph_H0(func, x0, H0, dtype='float32'):\n paddle.enable_static()\n main = paddle.static.Program()\n startup = paddle.static.Program()\n with paddle.static.program_guard(main, startup):\n X = paddle.static.data(name='x', shape=[x0.shape[0]], dtype=dtype)\n H = paddle.static.data(name='h',\n shape=[H0.shape[0], H0.shape[1]],\n dtype=dtype)\n Y = minimize_bfgs(func,\n X,\n initial_inverse_hessian_estimate=H,\n dtype=dtype)\n\n exe = paddle.static.Executor()\n exe.run(startup)\n return exe.run(main, feed={'x': x0, 'h': H0}, fetch_list=[Y])\n\n\ndef test_dynamic_graph(func,\n x0,\n H0=None,\n line_search_fn='strong_wolfe',\n dtype='float32'):\n paddle.disable_static()\n x0 = paddle.to_tensor(x0)\n if H0 is not None:\n H0 = paddle.to_tensor(H0)\n return minimize_bfgs(func,\n x0,\n initial_inverse_hessian_estimate=H0,\n line_search_fn=line_search_fn,\n dtype=dtype)\n\n\nclass TestBfgs(unittest.TestCase):\n\n def test_quadratic_nd(self):\n for dimension in [1, 10]:\n minimum = np.random.random(size=[dimension]).astype('float32')\n scale = np.exp(np.random.random(size=[dimension]).astype('float32'))\n\n def func(x):\n minimum_ = paddle.assign(minimum)\n scale_ = paddle.assign(scale)\n return paddle.sum(\n paddle.multiply(scale_, (F.square_error_cost(x, minimum_))))\n\n x0 = np.random.random(size=[dimension]).astype('float32')\n results = test_static_graph(func=func, x0=x0)\n self.assertTrue(np.allclose(minimum, results[2]))\n\n results = test_dynamic_graph(func=func, x0=x0)\n self.assertTrue(np.allclose(minimum, results[2].numpy()))\n\n def test_inf_minima(self):\n extream_point = np.array([-1, 2]).astype('float32')\n\n def func(x):\n # df = 3(x - 1.01)(x - 0.99)\n # f = x^3 - 3x^2 + 3*1.01*0.99x\n return x * x * x / 3.0 - (\n extream_point[0] + extream_point[1]\n ) * x * x / 2 + extream_point[0] * extream_point[1] * x\n\n x0 = np.array([-1.7]).astype('float32')\n results = test_static_graph(func, x0)\n self.assertFalse(results[0][0])\n\n def test_multi_minima(self):\n\n def func(x):\n # df = 12(x + 1.1)(x - 0.2)(x - 0.8)\n # f = 3*x^4+0.4*x^3-5.46*x^2+2.112*x\n # minimum = -1.1 or 0.8.\n # All these minima may be reached from appropriate starting points.\n return 3 * x**4 + 0.4 * x**3 - 5.64 * x**2 + 2.112 * x\n\n x0 = np.array([0.82], dtype='float64')\n\n results = test_static_graph(func, x0, dtype='float64')\n self.assertTrue(np.allclose(0.8, results[2]))\n\n def func_rosenbrock(self):\n # The Rosenbrock function is a standard optimization test case.\n a = np.random.random(size=[1]).astype('float32')\n minimum = [a.item(), (a**2).item()]\n b = np.random.random(size=[1]).astype('float32')\n\n def func(position):\n # f(x, y) = (a - x)^2 + b (y - x^2)^2\n # minimum = (a, a^2)\n x, y = position[0], position[1]\n c = (a - x)**2 + b * (y - x**2)**2\n # the return cant be np array[1], or in jacobin will cause flat error\n return c[0]\n\n x0 = np.random.random(size=[2]).astype('float32')\n\n results = test_dynamic_graph(func, x0)\n self.assertTrue(np.allclose(minimum, results[2]))\n\n def test_rosenbrock(self):\n with _test_eager_guard():\n self.func_rosenbrock()\n self.func_rosenbrock()\n\n def test_exception(self):\n\n def func(x):\n return paddle.dot(x, x)\n\n x0 = np.random.random(size=[2]).astype('float32')\n H0 = np.array([[2.0, 0.0], [0.0, 0.9]]).astype('float32')\n\n # test initial_inverse_hessian_estimate is good\n results = test_static_graph_H0(func, x0, H0, dtype='float32')\n self.assertTrue(np.allclose([0., 0.], results[2]))\n self.assertTrue(results[0][0])\n\n # test initial_inverse_hessian_estimate is bad\n H1 = np.array([[1.0, 2.0], [2.0, 1.0]]).astype('float32')\n self.assertRaises(ValueError, test_dynamic_graph, func, x0, H0=H1)\n\n # test line_search_fn is bad\n self.assertRaises(NotImplementedError,\n test_static_graph,\n func,\n x0,\n line_search_fn='other')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle 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\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_data_feed()\n self.set_feed_attr()\n self.set_op_attrs()\n\n @property\n def fp16_enabled(self):\n return False\n\n def set_data_feed(self):\n data = np.random.uniform(size=[1, 3, 3, 3]).astype('float32')\n self.feed_fp32 = {\"x\": data.astype(np.float32)}\n self.feed_fp16 = {\"x\": data.astype(np.float16)}\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed_fp32.values()]\n self.feed_list = list(self.feed_fp32.keys())\n self.feed_dtype = [x.dtype for x in self.feed_fp32.values()]\n\n def set_op_attrs(self):\n self.attrs = {}\n\n @IPUOpTest.static_graph\n def build_model(self):\n x = paddle.static.data(name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype=self.feed_dtype[0])\n out = paddle.fluid.layers.conv2d(x, num_filters=3, filter_size=3)\n out = paddle.fluid.layers.Print(out, **self.attrs)\n\n if self.is_training:\n loss = paddle.mean(out)\n adam = paddle.optimizer.Adam(learning_rate=1e-2)\n adam.minimize(loss)\n self.fetch_list = [loss.name]\n else:\n self.fetch_list = [out.name]\n\n def run_model(self, exec_mode):\n self.run_op_test(exec_mode)\n\n def test(self):\n for m in IPUOpTest.ExecutionMode:\n if not self.skip_mode(m):\n self.build_model()\n self.run_model(m)\n\n\nclass TestCase1(TestBase):\n\n def set_op_attrs(self):\n self.attrs = {\"message\": \"input_data\"}\n\n\nclass TestTrainCase1(TestBase):\n\n def set_op_attrs(self):\n # \"forward\" : print forward\n # \"backward\" : print forward and backward\n # \"both\": print forward and backward\n self.attrs = {\"message\": \"input_data2\", \"print_phase\": \"both\"}\n\n def set_training(self):\n self.is_training = True\n self.epoch = 2\n\n\[email protected](\"attrs are not supported\")\nclass TestCase2(TestBase):\n\n def set_op_attrs(self):\n self.attrs = {\n \"first_n\": 10,\n \"summarize\": 10,\n \"print_tensor_name\": True,\n \"print_tensor_type\": True,\n \"print_tensor_shape\": True,\n \"print_tensor_layout\": True,\n \"print_tensor_lod\": True\n }\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2020 PaddlePaddle 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\nimport unittest\nimport numpy as np\nimport random\nfrom op_test import OpTest\nimport paddle.fluid as fluid\nfrom paddle.fluid import Program, program_guard\nfrom op_test import OpTest, skip_check_grad_ci\nimport paddle.fluid.core as core\n\n\ndef gen_input_help(input, rank_offset, max_rank, max_size):\n input_row, input_col = input.shape\n max_ins = np.max((max_size, input_row))\n input_help = np.zeros((max_ins * max_rank * input_col))\n ins_rank = np.zeros((max_ins, 1))\n ins_rank.fill(-1)\n\n output_col = max_rank * input_col\n output_row = input_row\n\n for idx in range(output_col * output_row):\n output_col_idx = idx % output_col\n output_row_idx = int(idx / output_col)\n k = int(output_col_idx / input_col)\n faster = rank_offset[output_row_idx, 2 * k + 1] - 1\n\n if output_col_idx == 0:\n ins_rank[output_row_idx] = rank_offset[output_row_idx, 0]\n\n if rank_offset[output_row_idx, 0] - 1 < 0 or faster < 0:\n continue\n\n rank_input_col_idx = output_col_idx % input_col\n index = rank_offset[output_row_idx, 2 * k + 2]\n input_help[idx] = input[index, rank_input_col_idx]\n input_help = input_help.reshape([max_ins, max_rank * input_col])\n\n return input_help, ins_rank\n\n\ndef gen_param_help(input, rank_offset, param, max_rank):\n input_row, input_col = input.shape\n rank_offset_row, rank_offset_col = rank_offset.shape\n param_row, param_col = param.shape\n\n block_matrix_row = input_col * max_rank\n\n output_param_row = block_matrix_row * input_row\n output_param_col = param_col\n\n output_param = np.zeros((output_param_row * output_param_col, ))\n\n for idx in range(output_param_row * output_param_col):\n output_col_idx = idx % output_param_col\n output_row_idx = int(idx / output_param_col)\n ins_idx = int(output_row_idx / block_matrix_row)\n start_offset = output_row_idx % block_matrix_row\n k = int(start_offset / input_col)\n k_offset = start_offset % input_col\n\n lower = rank_offset[ins_idx, 0] - 1\n faster = rank_offset[ins_idx, 2 * k + 1] - 1\n if lower < 0 or faster < 0:\n continue\n start = lower * max_rank + faster\n ori_idx = start * param_col * input_col + k_offset * param_col + output_col_idx\n output_param[idx] = param[int(ori_idx / param_col), ori_idx % param_col]\n\n output_param = output_param.reshape([output_param_row, output_param_col])\n return output_param\n\n\ndef np_rank_attention(input, rank_offset, rank_para, max_rank, max_size):\n input_row, input_col = input.shape\n rank_offset_row, rank_offset_col = rank_offset.shape\n rank_para_row, rank_para_col = rank_para.shape\n\n assert (input_row == rank_offset_row)\n assert (max_rank == ((rank_offset_col - 1) / 2))\n assert (rank_para_row == max_rank * max_rank * input_col)\n\n input_help, ins_rank = gen_input_help(input, rank_offset, max_rank,\n max_size)\n param_help = gen_param_help(input, rank_offset, rank_para, max_rank)\n block_matrix_row = input_col * max_rank\n\n res = np.zeros((input_row, rank_para_col))\n for ins in range(input_row):\n res[ins, :] = \\\n np.dot(input_help[ins, :],\n param_help[int(block_matrix_row * ins):int(block_matrix_row * (ins+1)),:])\n return res, input_help, param_help, ins_rank\n\n\ndef gen_rank_offset(pv_nums, max_rank):\n all_ins_num = 0\n pv_rank_msg = []\n for _ in range(pv_nums):\n ins_pv = np.random.randint(1, max_rank + 2) # 1~4\n rank_list = list(range(1, ins_pv + 1))\n random.shuffle(rank_list)\n all_ins_num = all_ins_num + ins_pv\n pv_rank_msg.append(rank_list)\n\n rank_offset = np.zeros((all_ins_num, max_rank * 2 + 1)).astype(\"int32\")\n rank_offset.fill(-1)\n index = 0\n for pv_number in range(len(pv_rank_msg)):\n pv_ins = pv_rank_msg[pv_number]\n ad_num = len(pv_ins)\n index_start = index\n\n for j in range(ad_num):\n rank = -1\n if pv_ins[j] <= max_rank:\n rank = pv_ins[j]\n rank_offset[index, 0] = rank\n\n if rank > 0:\n for k in range(ad_num):\n fast_rank = -1\n if pv_ins[k] <= max_rank:\n fast_rank = pv_ins[k]\n if fast_rank > 0:\n m = fast_rank - 1\n rank_offset[index, 2 * m + 1] = pv_ins[k]\n rank_offset[index, 2 * m + 2] = index_start + k\n index = index + 1\n return all_ins_num, rank_offset\n\n\nclass TestRankAttentionOpComplex(OpTest):\n\n def config(self):\n self.pv_num = 100\n self.x_feat = 10\n self.y_feat = 15\n self.max_rank = 3\n self.dtype = \"float64\"\n\n def setUp(self):\n self.op_type = \"rank_attention\"\n self.config()\n ins_num, rank_offset = gen_rank_offset(self.pv_num, self.max_rank)\n input = np.random.random((ins_num, self.x_feat)).astype(self.dtype)\n rank_para_shape = [\n self.max_rank * self.max_rank * self.x_feat, self.y_feat\n ]\n rank_para = np.random.random(rank_para_shape).astype(self.dtype)\n np_out, np_input_help, np_param_help, np_ins_rank = np_rank_attention(\n input, np.array(rank_offset), rank_para, self.max_rank,\n self.pv_num * 7)\n self.inputs = {\n \"X\": input,\n \"RankOffset\": np.array(rank_offset).astype(\"int32\"),\n \"RankParam\": rank_para\n }\n self.attrs = {'MaxRank': self.max_rank, 'MaxSize': self.pv_num * 7}\n self.outputs = {\n \"Out\": np_out,\n \"InputHelp\": np_input_help,\n \"InsRank\": np_ins_rank\n }\n\n def test_check_output_gpu(self):\n if core.is_compiled_with_cuda():\n self.check_output_with_place(core.CUDAPlace(0))\n\n def test_check_grad_gpu(self):\n if core.is_compiled_with_cuda():\n self.check_grad_with_place(core.CUDAPlace(0), [\"RankParam\"], \"Out\")\n\n\nclass TestRankAttentionOpCpu(OpTest):\n\n def config(self):\n self.pv_num = 100\n self.x_feat = 10\n self.y_feat = 15\n self.max_rank = 3\n self.dtype = \"float64\"\n\n def setUp(self):\n self.op_type = \"rank_attention\"\n self.config()\n ins_num, rank_offset = gen_rank_offset(self.pv_num, self.max_rank)\n input = np.random.random((ins_num, self.x_feat)).astype(self.dtype)\n rank_para_shape = [\n self.max_rank * self.max_rank * self.x_feat, self.y_feat\n ]\n rank_para = np.random.random(rank_para_shape).astype(self.dtype)\n np_out, np_input_help, np_param_help, np_ins_rank = np_rank_attention(\n input, np.array(rank_offset), rank_para, self.max_rank,\n self.pv_num * 7)\n self.inputs = {\n \"X\": input,\n \"RankOffset\": np.array(rank_offset).astype(\"int32\"),\n \"RankParam\": rank_para\n }\n self.attrs = {'MaxRank': self.max_rank, 'MaxSize': self.pv_num * 7}\n self.outputs = {\n \"Out\": np_out,\n \"InputHelp\": np_input_help,\n \"InsRank\": np_ins_rank\n }\n\n def test_check_output_cpu(self):\n try:\n self.check_output_with_place(place=core.CPUPlace())\n except:\n print(\"do not support cpu test, skip\")\n\n def test_check_grad_cpu(self):\n try:\n self.check_grad_with_place(core.CPUPlace(), [\"RankParam\"], \"Out\")\n except:\n print(\"do not support cpu test, skip\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2022 PaddlePaddle 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\nimport sys\n\nsys.path.append(\"..\")\n\nimport unittest\nimport paddle\nimport random\nimport numpy as np\nimport paddle.fluid as fluid\nfrom functools import partial\nfrom paddle.framework import core\n\nfrom op_test_xpu import XPUOpTest\n\nfrom xpu.get_test_cover_info import create_test_class, get_xpu_op_support_types, XPUOpTestWrapper\n\n\ndef adamw_step(inputs, attributes):\n param = inputs['Param']\n grad = inputs['Grad']\n moment1 = inputs['Moment1']\n moment2 = inputs['Moment2']\n lr = inputs['LearningRate']\n beta1_pow = inputs['Beta1Pow']\n beta2_pow = inputs['Beta2Pow']\n\n epsilon = attributes['epsilon']\n\n if 'lr_ratio' in attributes:\n lr = lr * attributes['lr_ratio']\n\n if attributes[\"with_decay\"]:\n coeff = attributes[\"coeff\"]\n decay = 1.0 - lr * coeff\n param2 = param * decay\n param = param2.copy()\n\n if 'beta1' in attributes:\n beta1 = attributes['beta1']\n else:\n beta1 = inputs['Beta1Tensor'][0]\n if 'beta2' in attributes:\n beta2 = attributes['beta2']\n else:\n beta2 = inputs['Beta2Tensor'][0]\n\n moment1_out = beta1 * moment1 + (1 - beta1) * grad\n moment2_out = beta2 * moment2 + (1 - beta2) * np.square(grad)\n lr_t = lr * np.sqrt(1 - beta2_pow) / (1 - beta1_pow)\n param_out = param - lr_t * (moment1_out / (np.sqrt(moment2_out) + epsilon))\n return param_out, moment1_out, moment2_out\n\n\ndef simple_lr_setting(param, decay_rate, n_layers):\n if \"fc_0\" in param.name or \"linear_1\" in param.name:\n depth = int(param.name.split(\"_\")[2]) + 1\n elif \"fc_1\" in param.name or \"linear_2\" in param.name:\n depth = int(param.name.split(\"_\")[2]) + 2\n else:\n depth = 0\n\n return decay_rate**(n_layers + 2 - depth)\n\n\nclass XPUTestAdamwOp1(XPUOpTestWrapper):\n\n def __init__(self):\n self.op_name = 'adamw'\n self.use_dynamic_create_class = False\n\n class TestAdamW(XPUOpTest):\n\n def setUp(self):\n #Test AdamW Op with supplied attributes\n self.op_type = \"adamw\"\n self.init_shape()\n self.dtype = self.in_type_str\n param = np.random.uniform(-1, 1, self.shape).astype(self.dtype)\n grad = np.random.uniform(-1, 1, self.shape).astype(self.dtype)\n moment1 = np.random.uniform(-1, 1, self.shape).astype(self.dtype)\n # The second moment is positive\n moment2 = np.random.random(self.shape).astype(self.dtype)\n\n learning_rate = 0.004\n beta1 = 0.78\n beta2 = 0.836\n epsilon = 1e-4\n beta1_pow = beta1**10\n beta2_pow = beta2**10\n\n self.inputs = {\n 'Param': param,\n 'Grad': grad,\n 'Moment1': moment1,\n 'Moment2': moment2,\n 'LearningRate': np.array([learning_rate]).astype(self.dtype),\n 'Beta1Pow': np.array([beta1_pow]).astype(self.dtype),\n 'Beta2Pow': np.array([beta2_pow]).astype(self.dtype)\n }\n\n self.attrs = {\n 'epsilon': epsilon,\n 'beta1': beta1,\n 'beta2': beta2,\n \"coeff\": 0.5,\n \"with_decay\": True\n }\n\n param_out, moment1_out, \\\n moment2_out = adamw_step(self.inputs, self.attrs)\n\n self.outputs = {\n 'Moment1Out': moment1_out,\n 'Moment2Out': moment2_out,\n 'ParamOut': param_out,\n 'Beta1PowOut': np.array([beta1_pow]).astype(self.dtype) * beta1,\n 'Beta2PowOut': np.array([beta2_pow]).astype(self.dtype) * beta2\n }\n\n def init_shape(self):\n self.shape = [102, 105]\n\n def test_check_output(self):\n paddle.enable_static()\n self.check_output_with_place(place=paddle.XPUPlace(0))\n\n class TestAdamW2(TestAdamW):\n\n def init_shape(self):\n self.shape = [\n 1000,\n ]\n\n class TestAdamW3(TestAdamW):\n\n def init_shape(self):\n self.shape = [200, 3000]\n\n\nclass XPUTestAdamwOp2(XPUOpTestWrapper):\n\n def __init__(self):\n self.op_name = 'adamw'\n self.use_dynamic_create_class = False\n\n class TestAdamWOp(unittest.TestCase):\n\n def test_adamw_op_dygraph(self):\n paddle.disable_static()\n value = np.arange(26).reshape(2, 13).astype(self.in_type_str)\n a = paddle.to_tensor(value)\n linear = paddle.nn.Linear(13, 5)\n adam = paddle.optimizer.AdamW(\n learning_rate=0.01,\n parameters=linear.parameters(),\n apply_decay_param_fun=lambda name: True,\n weight_decay=0.01)\n\n for _ in range(2):\n out = linear(a)\n out.backward()\n adam.step()\n adam.clear_gradients()\n\n def test_adamw_op_coverage(self):\n paddle.disable_static()\n value = np.arange(26).reshape(2, 13).astype(self.in_type_str)\n a = paddle.to_tensor(value)\n linear = paddle.nn.Linear(13, 5)\n adam = paddle.optimizer.AdamW(\n learning_rate=0.0,\n parameters=linear.parameters(),\n apply_decay_param_fun=lambda name: True,\n weight_decay=0.01)\n assert (adam.__str__() is not None)\n\n def test_adamw_op(self):\n paddle.enable_static()\n place = fluid.XPUPlace(0)\n shape = [2, 3, 8, 8]\n exe = fluid.Executor(place)\n train_prog = fluid.Program()\n startup = fluid.Program()\n with fluid.program_guard(train_prog, startup):\n with fluid.unique_name.guard():\n data = fluid.data(name=\"data\", shape=shape)\n conv = fluid.layers.conv2d(data, 8, 3)\n loss = paddle.mean(conv)\n\n beta1 = fluid.layers.create_global_var(\n shape=[1],\n value=0.85,\n dtype=self.in_type_str,\n persistable=True)\n beta2 = fluid.layers.create_global_var(\n shape=[1],\n value=0.95,\n dtype=self.in_type_str,\n persistable=True)\n betas = [beta1, beta2]\n opt = paddle.optimizer.AdamW(learning_rate=1e-5,\n beta1=beta1,\n beta2=beta2,\n weight_decay=0.01,\n epsilon=1e-8)\n opt.minimize(loss)\n\n exe.run(startup)\n data_np = np.random.random(shape).astype(self.in_type_str)\n rets = exe.run(train_prog,\n feed={\"data\": data_np},\n fetch_list=[loss])\n assert rets[0] is not None\n paddle.disable_static()\n\n def test_adamw_op_invalid_input(self):\n paddle.disable_static()\n linear = paddle.nn.Linear(10, 10)\n with self.assertRaises(ValueError):\n adam = paddle.optimizer.AdamW(0.1,\n beta1=-1,\n parameters=linear.parameters())\n with self.assertRaises(ValueError):\n adam = paddle.optimizer.AdamW(0.1,\n beta2=-1,\n parameters=linear.parameters())\n with self.assertRaises(ValueError):\n adam = paddle.optimizer.AdamW(0.1,\n epsilon=-1,\n parameters=linear.parameters())\n\n class TestAdamWOpGroup(TestAdamWOp):\n\n def test_adamw_op_dygraph(self):\n paddle.disable_static()\n value = np.arange(26).reshape(2, 13).astype(self.in_type_str)\n a = paddle.to_tensor(value)\n linear_1 = paddle.nn.Linear(13, 5)\n linear_2 = paddle.nn.Linear(5, 3)\n adam = paddle.optimizer.AdamW(\n learning_rate=0.01,\n parameters=[{\n 'params': linear_1.parameters()\n }, {\n 'params': linear_2.parameters(),\n 'weight_decay': 0.001\n }],\n apply_decay_param_fun=lambda name: True,\n weight_decay=0.01)\n\n for _ in range(2):\n out = linear_1(a)\n out = linear_2(out)\n out.backward()\n adam.step()\n adam.clear_gradients()\n\n class TestAdamWOpGroupWithLR(TestAdamWOp):\n\n def test_adamw_op_dygraph(self):\n paddle.disable_static()\n value = np.arange(26).reshape(2, 13).astype(self.in_type_str)\n a = paddle.to_tensor(value)\n linear_1 = paddle.nn.Linear(13, 5)\n linear_2 = paddle.nn.Linear(5, 3)\n adam = paddle.optimizer.AdamW(\n learning_rate=paddle.optimizer.lr.PiecewiseDecay(\n boundaries=[3, 6], values=[0.1, 0.2, 0.3]),\n parameters=[{\n 'params': linear_1.parameters(),\n 'learning_rate': 0.1,\n }, {\n 'params': linear_2.parameters(),\n 'weight_decay': 0.001,\n }],\n apply_decay_param_fun=lambda name: True,\n weight_decay=0.01)\n\n for _ in range(2):\n out = linear_1(a)\n out = linear_2(out)\n out.backward()\n adam.step()\n adam.clear_gradients()\n\n\nsupport_types = get_xpu_op_support_types('adamw')\nfor stype in support_types:\n create_test_class(globals(), XPUTestAdamwOp1, stype)\n create_test_class(globals(), XPUTestAdamwOp2, stype)\n\nif __name__ == \"__main__\":\n paddle.enable_static()\n unittest.main()\n" ]
[ [ "numpy.random.random", "numpy.random.seed", "numpy.tile", "numpy.ones", "numpy.array", "numpy.random.randint" ], [ "numpy.array" ], [ "numpy.random.randn", "numpy.random.randint" ], [ "numpy.random.uniform" ], [ "numpy.random.rand", "numpy.array", "numpy.allclose" ], [ "numpy.random.seed", "numpy.testing.assert_allclose" ], [ "numpy.allclose" ], [ "numpy.mod", "numpy.random.uniform", "numpy.random.random" ], [ "numpy.argmax", "numpy.random.random", "numpy.random.seed" ], [ "numpy.array", "numpy.random.random", "numpy.array_equal" ], [ "numpy.random.random", "numpy.prod" ], [ "numpy.random.uniform" ], [ "numpy.asarray", "numpy.random.randn", "numpy.random.seed" ], [ "numpy.zeros", "numpy.allclose", "numpy.random.seed" ], [ "numpy.log", "numpy.sqrt", "numpy.asarray", "numpy.random.normal", "numpy.random.uniform", "numpy.array", "numpy.random.randint" ], [ "numpy.random.uniform" ], [ "numpy.arange", "numpy.amax", "numpy.allclose" ], [ "numpy.random.random" ], [ "numpy.arange", "numpy.array", "numpy.random.random" ], [ "numpy.split", "numpy.random.random", "numpy.allclose", "numpy.unique", "numpy.random.rand", "numpy.array", "numpy.zeros" ], [ "numpy.reshape", "numpy.array" ], [ "numpy.split", "numpy.array" ], [ "numpy.random.seed" ], [ "numpy.random.random", "numpy.array_equal", "numpy.random.seed", "numpy.array", "numpy.random.randint" ], [ "numpy.random.uniform" ], [ "numpy.maximum", "numpy.abs", "numpy.allclose", "numpy.random.seed", "numpy.random.random", "numpy.copy", "numpy.random.uniform", "numpy.random.randint" ], [ "numpy.random.random", "numpy.equal", "numpy.array_equal", "numpy.random.random_integers" ], [ "numpy.array", "numpy.random.random_integers" ], [ "numpy.random.random", "numpy.array", "numpy.where", "numpy.sum", "numpy.random.randint" ], [ "numpy.random.uniform", "numpy.arange" ], [ "numpy.random.seed", "numpy.random.randint" ], [ "numpy.array", "numpy.random.random", "numpy.random.randint" ], [ "numpy.array", "numpy.prod" ], [ "numpy.array", "numpy.random.random", "numpy.allclose", "numpy.random.seed" ], [ "numpy.random.random", "numpy.reshape", "numpy.tile", "numpy.max", "numpy.transpose", "numpy.zeros", "numpy.sum" ], [ "numpy.random.uniform" ], [ "numpy.random.rand", "numpy.dot", "numpy.random.random", "numpy.allclose" ], [ "numpy.random.random", "numpy.random.uniform", "numpy.random.rand", "numpy.add", "numpy.array" ], [ "numpy.random.uniform" ], [ "numpy.reshape", "numpy.argmax", "numpy.testing.assert_allclose", "numpy.array", "numpy.sum" ], [ "numpy.random.random", "numpy.abs", "numpy.random.seed", "numpy.stack", "numpy.mean", "numpy.array", "numpy.random.randint" ], [ "numpy.testing.assert_almost_equal", "numpy.array", "numpy.random.randint" ], [ "numpy.array", "numpy.random.random", "numpy.allclose", "numpy.random.seed" ], [ "numpy.random.uniform" ], [ "numpy.random.random", "numpy.max", "numpy.array", "numpy.zeros", "numpy.random.randint" ], [ "numpy.square", "numpy.random.random", "numpy.sqrt", "numpy.arange", "numpy.random.uniform", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Yvette1993/spinningup
[ "5094cf291fa24cf93d58b4507dab56dafe73dac1" ]
[ "envs/cell_place_gym/native/acp_state.py" ]
[ "import numpy as np\n\nfrom cell_place_gym.native.acp_placement import *\n\nclass acp_placement_state (object):\n\n def __init__ (self, place):\n self.place = place\n self.design = place.design\n l_inst_count = len (self.design.instances)\n # Non-Placed Nets Matrix\n self.c_matrix = np.zeros (shape = (l_inst_count, l_inst_count))\n # Placed Nets Matrix\n self.n_matrix = np.zeros (shape = (l_inst_count, l_inst_count))\n\n def get_state (self):\n nets = self.design.nets\n self.c_matrix [:,:] = 0\n self.n_matrix [:,:] = 0\n for n in nets:\n src = n.net_source\n src_id = src.get_inst_id ()\n src_placed = src.is_placed ()\n src_position = src.get_position ()\n for dst in n.net_dests:\n dst_id = dst.get_inst_id ()\n dst_placed = dst.is_placed ()\n dst_position = dst.get_position ()\n if src_placed and dst_placed:\n self.n_matrix [src_id][dst_id] = 1\n else:\n self.n_matrix [src_id][dst_id] = 1\n return\n" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Adri1bo/HEMS_API
[ "dca26e55696f9f2e36f29968a8c3a90871d6bc16" ]
[ "forecaster.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 7 17:58:57 2020\r\n\r\n@author: adria.bove\r\n\"\"\"\r\n\r\nfrom BBDD import BBDD\r\nimport analytics\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport datetime as dt\r\n\r\nclass consumption:\r\n def __init__(self, nom):\r\n self.nom_BBDD=nom\r\n \r\n def forecaster(self,timestamp):\r\n self.timestamp=str(timestamp)\r\n # get the df\r\n this_BBDD=BBDD(self.nom_BBDD)\r\n a=pd.Series(dtype='float64')\r\n \r\n \r\n \r\n \r\n k=0\r\n list_weekdays=[(dt.datetime.now()+dt.timedelta(days=i+k)).weekday() for i in range(5)]\r\n for weekday in list_weekdays:\r\n df=this_BBDD.extract_weekday(weekday)\r\n \r\n #send it to the mean_day function que farà el dia tipus\r\n \r\n a=a.append(self.mean_day(df,k))\r\n k=k+1\r\n \r\n del(a[0])\r\n a['dt']=a.index\r\n a = a.reset_index(drop=True)\r\n \r\n self.store_data(a,'loads_forecast')\r\n \r\n return a\r\n \r\n def mean_day(self,df,k): #amb el weekday he de fer millor de date_range i fer-lo sobre el valor del timer\r\n df['timer'] = df.dt.apply(self.massive_rounder,groupsize=1,groups=int(60))\r\n \r\n df = df.rename(columns={'P_load [kW]': 'P_load'})\r\n df.P_load=pd.to_numeric(df.P_load)\r\n mean_DAY=df.groupby('timer').P_load.mean()\r\n mean_DAY=mean_DAY.to_frame()\r\n \r\n start_date=dt.datetime.combine(dt.date.today(), dt.datetime.min.time())#+dt.timedelta(days=1)\r\n mean_DAY['dta']=mean_DAY.index\r\n mean_DAY.dta=mean_DAY.dta.apply(lambda x: dt.timedelta(minutes=x) + start_date + dt.timedelta(days=k))\r\n mean_DAY.index=mean_DAY.dta\r\n del(mean_DAY['dta'])\r\n \r\n new_mean_DAY=mean_DAY.resample(self.timestamp+'T').pad()\r\n \r\n return new_mean_DAY\r\n\r\n \r\n def massive_rounder(self, element, groupsize, groups):\r\n \r\n for i in range(groups):\r\n if element.time().minute < (groupsize*(range(groups)[i]+1)):\r\n return range(groups)[i] + element.time().hour*groups\r\n \r\n \r\n def store_data(self,data,name):\r\n this_BBDD=BBDD(name)\r\n this_BBDD.store_data(data) \r\n \r\n\r\nif __name__ == '__main__':\r\n consumption_forecast=consumption('grid_BBDD')\r\n b=consumption_forecast.forecaster(timestamp=15)\r\n plt.plot(-b.P_load)" ]
[ [ "matplotlib.pyplot.plot", "pandas.to_numeric", "pandas.Series" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
ARAN1218/RealEstateRentPrediction_AI
[ "da537f3204fa1bc80a499a03b2fd015926ccc755" ]
[ "improved-ver1/6.Real_Estate_Own_Data_Prediction_improved1.py" ]
[ "#必要なライブラリをインポート\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.preprocessing import LabelEncoder\n\n\n#numpyのリスト表示制限を解除しておく\nnp.set_printoptions(threshold=np.inf)\n\n\n#既に学習データとREDP関数を用いてAIが作成されているものとする\n#model = RERL(df_l)\n\n\n#住所と路線と間取りはラベルエンコーディングの都合により学習データ/テストデータにあったものしか使えない為、予め確保しておいた使える要素を表示させる\n#上記の3つの要素はこの中から選んでもらう\n#このプログラムは別のセルで起動させると見やすい\nprint(adressC,'\\n','\\n',stationC,'\\n','\\n',layoutC)\n\n\n#(学習した範囲内の)任意のデータを入力して賃料を予測できる関数\n#Real_Estate_Own_Data_Prediction\ndef REODP(address,station,access,mc_fees,k_fees,s_fees,area,layout,age):\n #入力したデータを辞書d_tryに格納する\n d_try = {\n '住所':address,\n '路線':station,\n '交通':access,\n '管理共益費':mc_fees,\n '礼金':k_fees,\n '敷金':s_fees,\n '専有面積':area,\n '間取り':layout,\n '築年数':age\n }\n \n #辞書d_tryをデータフレームdf_tryに変換する\n df_try = pd.DataFrame(d_try,index=['own'])\n \n #入力情報の確認用\n display(df_try)\n \n #ラベルエンコーディングを行い、文字列を数値化する\n df_try.住所 = LE1.transform(df_try.住所)\n df_try.路線 = LE2.transform(df_try.路線)\n df_try.間取り = LE3.transform(df_try.間取り)\n \n #データ型をfloat64で統一する\n df_try = df_try.astype('float64')\n \n #予測結果(少数第二位まで)を表示する\n df_try = xgb.DMatrix(df_try)\n return print('予想賃料:',round(float(model.predict(df_try)),2),'万円')\n\n\n#REODP(住所, 路線, 交通, 管理共益費, 礼金, 敷金, 専有面積, 間取り, 築年数)\n#データ型に気をつける\n#住所と路線と間取りはラベルエンコーディングの都合により学習データ/テストデータにあったものしか使えない為、上で表示させた要素から選ぶこと\nREODP(address=''\n ,station=''\n ,access=0\n ,mc_fees=0\n ,k_fees=0\n ,s_fees=0\n ,area=0\n ,layout=''\n ,age=0\n )\n" ]
[ [ "numpy.set_printoptions", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Lifebrain/p025_education_brain
[ "507cca3514b8ddbf65df7a047dba5bae1295badf" ]
[ "02_ukb/src/01_data_preparation/02_qdec_table/01_creat_qdec_table.py" ]
[ "#!/usr/bin/env python3\n# Purpose: Create qdec table\n\nimport pandas as pd\nimport numpy as np\nimport glob\nimport os.path as op\nimport os\n\ndata_csv = op.join(os.environ['TABULAR_DATA_DIR'],'data.csv')\n\noutput_file = op.join(os.environ['QDEC_DATA_DIR'],'qdec.table.dat')\n\nfs_dir = \"/cluster/projects/p23/data/open_datasets/ukb_long/bids/derivatives/freesurfer.7.1.0/recon\"\n\ndf = pd.read_csv(data_csv)\n\ndef extract_fs_long_dir(id,timepoint):\n \"\"\" Extract fs long dir based on id and timepoint \"\"\"\n\n search = glob.glob(op.join(fs_dir,\"*\"+str(id)+\"*\"+str(timepoint+1)+\"*\"+\".long.*\"))\n\n try:\n return op.basename(search[0])\n except:\n return np.nan\n\n\ndf['fs_long_dir'] = df[['eid','mr_timepoint']].apply(lambda x: extract_fs_long_dir(x.eid,x.mr_timepoint), axis=1)\ndf = df.dropna()\n\ndf['fsid'] = df['fs_long_dir'].apply(lambda x: x.split(\".long.\")[0])\ndf['fsid_base'] = df['fs_long_dir'].apply(lambda x: x.split(\".long.\")[1])\ndf['edu_coded'] = df['education'].apply(lambda x: 1 if x==1 else 0)\ndf['sex'] = df['sex'].apply(lambda x: int(x))\n\ndf[['fsid','fsid_base','int','bl_age','sex','edu_coded']].to_csv(output_file, sep=\" \", index=False)" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
amiyapatanaik/U-Time
[ "a9ed4892da77d165a71dbfef1d069d782c909757", "a9ed4892da77d165a71dbfef1d069d782c909757" ]
[ "utime/callbacks/callbacks.py", "utime/train/trainer.py" ]
[ "import numpy as np\nimport pandas as pd\nfrom carbontracker.tracker import CarbonTracker\nfrom tensorflow.keras.callbacks import Callback\nfrom utime.utils import get_memory_usage\nfrom mpunet.utils import highlighted\nfrom mpunet.logging import ScreenLogger\nfrom collections import defaultdict\nfrom datetime import timedelta\n\n\nclass Validation(Callback):\n \"\"\"\n Validation computation callback.\n\n Samples a number of validation batches from a deepsleep\n ValidationMultiSequence object\n and computes for all tasks:\n - Batch-wise validation loss\n - Batch-wise metrics as specified in model.metrics_tensors\n - Epoch-wise pr-class and average precision\n - Epoch-wise pr-class and average recall\n - Epoch-wise pr-class and average dice coefficients\n ... and adds all results to the log dict\n\n Note: The purpose of this callback over the default tf.keras evaluation\n mechanism is to calculate certain metrics over the entire epoch of data as\n opposed to averaged batch-wise computations.\n \"\"\"\n def __init__(self,\n val_sequence,\n max_val_studies_per_dataset=20,\n logger=None, verbose=True):\n \"\"\"\n Args:\n val_sequence: A deepsleep ValidationMultiSequence object\n logger: An instance of a MultiPlanar Logger that prints to\n screen and/or file\n verbose: Print progress to screen - OBS does not use Logger\n \"\"\"\n super().__init__()\n self.logger = logger or ScreenLogger()\n self.sequences = val_sequence.sequences\n self.verbose = verbose\n self.max_studies = max_val_studies_per_dataset\n self.n_classes = val_sequence.n_classes\n self.IDs = val_sequence.IDs\n self.print_round = 3\n self.log_round = 4\n\n def _compute_counts(self, pred, true, ignore_class=None):\n # Argmax and CM elements\n pred = pred.argmax(-1).ravel()\n true = true.ravel()\n\n if ignore_class:\n mask = np.where(true != ignore_class)\n true = true[mask]\n pred = pred[mask]\n\n # Compute relevant CM elements\n # We select the number following the largest class integer when\n # y != pred, then bincount and remove the added dummy class\n tps = np.bincount(np.where(true == pred, true, self.n_classes),\n minlength=self.n_classes+1)[:-1].astype(np.uint64)\n rel = np.bincount(true, minlength=self.n_classes).astype(np.uint64)\n sel = np.bincount(pred, minlength=self.n_classes).astype(np.uint64)\n return tps, rel, sel\n\n def predict(self):\n # Get tensors to run and their names\n metrics = self.model.loss_functions + self.model.metrics\n metrics_names = self.model.metrics_names\n self.model.reset_metrics()\n assert len(metrics_names) == len(metrics)\n\n # Prepare arrays for CM summary stats\n true_pos, relevant, selected, metrics_results = {}, {}, {}, {}\n for id_, sequence in zip(self.IDs, self.sequences):\n # Add count arrays to the result dictionaries\n true_pos[id_] = np.zeros(shape=(self.n_classes,), dtype=np.uint64)\n relevant[id_] = np.zeros(shape=(self.n_classes,), dtype=np.uint64)\n selected[id_] = np.zeros(shape=(self.n_classes,), dtype=np.uint64)\n\n # Get validation sleep study loader\n n_val = min(len(sequence.dataset_queue), self.max_studies)\n study_iterator = sequence.dataset_queue.get_study_iterator(n_val)\n\n # Predict and evaluate on all studies\n per_study_metrics = defaultdict(list)\n for i, sleep_study_context in enumerate(study_iterator):\n if self.verbose:\n s = \" {}Validation subject: {}/{}\".format(f\"[{id_}] \"\n if id_ else \"\",\n i+1,\n n_val)\n print(s, end=\"\\r\", flush=True)\n\n with sleep_study_context as ss:\n x, y = sequence.get_single_study_full_seq(ss.identifier,\n reshape=True)\n pred = self.model.predict_on_batch(x)\n\n # Compute counts\n tps, rel, sel = self._compute_counts(pred=pred.numpy(),\n true=y,\n ignore_class=5)\n true_pos[id_] += tps\n relevant[id_] += rel\n selected[id_] += sel\n\n # Run all metrics\n for metric, name in zip(metrics, metrics_names):\n per_study_metrics[name].append(metric(y, pred).numpy())\n\n # Compute mean metrics for the dataset\n metrics_results[id_] = {}\n for metric, name in zip(metrics, metrics_names):\n metrics_results[id_][name] = np.mean(per_study_metrics[name])\n self.model.reset_metrics()\n self.logger(\"\")\n self.logger(\"\")\n return true_pos, relevant, selected, metrics_results\n\n @staticmethod\n def _compute_dice(tp, rel, sel):\n # Get data masks (to avoid div. by zero warnings)\n # We set precision, recall, dice to 0 in for those particular cls.\n sel_mask = sel > 0\n rel_mask = rel > 0\n\n # prepare arrays\n precisions = np.zeros(shape=tp.shape, dtype=np.float32)\n recalls = np.zeros_like(precisions)\n dices = np.zeros_like(precisions)\n\n # Compute precisions, recalls\n precisions[sel_mask] = tp[sel_mask] / sel[sel_mask]\n recalls[rel_mask] = tp[rel_mask] / rel[rel_mask]\n\n # Compute dice\n intrs = (2 * precisions * recalls)\n union = (precisions + recalls)\n dice_mask = union > 0\n dices[dice_mask] = intrs[dice_mask] / union[dice_mask]\n\n return precisions, recalls, dices\n\n def _print_val_results(self, precisions, recalls, dices, metrics, epoch,\n name, classes):\n # Log the results\n # We add them to a pd dataframe just for the pretty print output\n index = [\"cls %i\" % i for i in classes]\n metric_keys, metric_vals = map(list, list(zip(*metrics.items())))\n col_order = metric_keys + [\"precision\", \"recall\", \"dice\"]\n nan_arr = np.empty(shape=len(precisions))\n nan_arr[:] = np.nan\n value_dict = {\"precision\": precisions,\n \"recall\": recalls,\n \"dice\": dices}\n value_dict.update({key: nan_arr for key in metrics})\n val_results = pd.DataFrame(value_dict,\n index=index).loc[:, col_order] # ensure order\n # Transpose the results to have metrics in rows\n val_results = val_results.T\n # Add mean and set in first row\n means = metric_vals + [precisions.mean(), recalls.mean(), dices.mean()]\n val_results[\"mean\"] = means\n cols = list(val_results.columns)\n cols.insert(0, cols.pop(cols.index('mean')))\n val_results = val_results.loc[:, cols]\n\n # Print the df to screen\n self.logger(highlighted((\"[%s] Validation Results for \"\n \"Epoch %i\" % (name, epoch)).lstrip(\" \")))\n print_string = val_results.round(self.print_round).to_string()\n self.logger(print_string.replace(\"NaN\", \"---\") + \"\\n\")\n\n def on_epoch_end(self, epoch, logs={}):\n self.logger(\"\\n\")\n # Predict and get CM\n TPs, relevant, selected, metrics = self.predict()\n for id_ in self.IDs:\n tp, rel, sel = TPs[id_], relevant[id_], selected[id_]\n precisions, recalls, dices = self._compute_dice(tp=tp, sel=sel, rel=rel)\n classes = np.arange(len(dices))\n\n # Add to log\n n = (id_ + \"_\") if len(self.IDs) > 1 else \"\"\n logs[f\"{n}val_dice\"] = dices.mean().round(self.log_round)\n logs[f\"{n}val_precision\"] = precisions.mean().round(self.log_round)\n logs[f\"{n}val_recall\"] = recalls.mean().round(self.log_round)\n for m_name, value in metrics[id_].items():\n logs[f\"{n}val_{m_name}\"] = value.round(self.log_round)\n\n if self.verbose:\n self._print_val_results(precisions=precisions,\n recalls=recalls,\n dices=dices,\n metrics=metrics[id_],\n epoch=epoch,\n name=id_,\n classes=classes)\n\n if len(self.IDs) > 1:\n # Print cross-dataset mean values\n if self.verbose:\n self.logger(highlighted(f\"[ALL DATASETS] Means Across Classes\"\n f\" for Epoch {epoch}\"))\n fetch = (\"val_dice\", \"val_precision\", \"val_recall\")\n m_fetch = tuple([\"val_\" + s for s in self.model.metrics_names])\n to_print = {}\n for f in fetch + m_fetch:\n scores = [logs[\"%s_%s\" % (name, f)] for name in self.IDs]\n res = np.mean(scores)\n logs[f] = res.round(self.log_round) # Add to log file\n to_print[f.split(\"_\")[-1]] = list(scores) + [res]\n if self.verbose:\n df = pd.DataFrame(to_print)\n df.index = self.IDs + [\"mean\"]\n self.logger(df.round(self.print_round))\n self.logger(\"\")\n\n\nclass MemoryConsumption(Callback):\n def __init__(self, max_gib=None, round_=2, logger=None, set_limit=False):\n self.max_gib = max_gib\n self.logger = logger\n self.round_ = round_\n if set_limit:\n import resource\n _, hard = resource.getrlimit(resource.RLIMIT_AS)\n resource.setrlimit(resource.RLIMIT_AS,\n (self._gib_to_bytes(max_gib), hard))\n self.logger(\"Setting memory limit to {} GiB\".format(max_gib))\n\n @staticmethod\n def _gib_to_bytes(gib):\n return gib * (1024 ** 3)\n\n @staticmethod\n def _bytes_to_gib(bytes):\n return bytes / (1024 ** 3)\n\n def on_epoch_end(self, epoch, logs={}):\n mem_bytes = get_memory_usage()\n mem_gib = round(self._bytes_to_gib(mem_bytes), self.round_)\n logs['memory_usage_gib'] = mem_gib\n if self.max_gib and mem_gib >= self.max_gib:\n self.logger.warn(\"Stopping training from callback 'MemoryConsumption'! \"\n \"Total memory consumption of {} GiB exceeds limitation\"\n \" (self.max_gib = {}) \".format(mem_gib, self.max_gib))\n self.model.stop_training = True\n\n\nclass MaxTrainingTime(Callback):\n def __init__(self, max_minutes, log_name='train_time_total', logger=None):\n \"\"\"\n TODO\n Args:\n \"\"\"\n super().__init__()\n self.max_minutes = int(max_minutes)\n self.log_name = log_name\n self.logger = logger or ScreenLogger()\n\n def on_epoch_end(self, epochs, logs={}):\n \"\"\"\n TODO\n\n Args:\n epochs:\n logs:\n\n Returns:\n\n \"\"\"\n train_time_str = logs.get(self.log_name, None)\n if not train_time_str:\n self.logger.warn(\"Did not find log entry '{}' (needed in callback \"\n \"'MaxTrainingTime')\".format(self.log_name))\n return\n train_time_m = timedelta(\n days=int(train_time_str[:2]),\n hours=int(train_time_str[4:6]),\n minutes=int(train_time_str[8:10]),\n seconds=int(train_time_str[12:14])\n ).total_seconds() / 60\n if train_time_m >= self.max_minutes:\n # Stop training\n self.warn(\"Stopping training from callback 'MaxTrainingTime'! \"\n \"Total training length of {} minutes exceeded (now {}) \"\n \"\".format(self.max_minutes, train_time_m))\n self.model.stop_training = True\n\n\nclass CarbonUsageTracking(Callback):\n \"\"\"\n tf.keras Callback for the Carbontracker package.\n See https://github.com/lfwa/carbontracker.\n \"\"\"\n def __init__(self, epochs, add_to_logs=True, monitor_epochs=-1,\n epochs_before_pred=-1, devices_by_pid=True, **additional_tracker_kwargs):\n \"\"\"\n Accepts parameters as per CarbonTracker.__init__\n Sets other default values for key parameters.\n\n Args:\n add_to_logs: bool, Add total_energy_kwh and total_co2_g to the keras logs after each epoch\n For other arguments, please refer to CarbonTracker.__init__\n \"\"\"\n super().__init__()\n self.tracker = None\n self.add_to_logs = bool(add_to_logs)\n self.parameters = {\"epochs\": epochs,\n \"monitor_epochs\": monitor_epochs,\n \"epochs_before_pred\": epochs_before_pred,\n \"devices_by_pid\": devices_by_pid}\n self.parameters.update(additional_tracker_kwargs)\n\n def on_train_end(self, logs={}):\n \"\"\" Ensure actual consumption is reported \"\"\"\n self.tracker.stop()\n\n def on_epoch_begin(self, epoch, logs={}):\n \"\"\" Start tracking this epoch \"\"\"\n if self.tracker is None:\n # At this point all CPUs should be discoverable\n self.tracker = CarbonTracker(**self.parameters)\n self.tracker.epoch_start()\n\n def on_epoch_end(self, epoch, logs={}):\n \"\"\" End tracking this epoch \"\"\"\n self.tracker.epoch_end()\n if self.add_to_logs:\n energy_kwh = self.tracker.tracker.total_energy_per_epoch().sum()\n co2eq_g = self.tracker._co2eq(energy_kwh)\n logs[\"total_energy_kwh\"] = round(energy_kwh, 6)\n logs[\"total_co2_g\"] = round(co2eq_g, 6)\n", "\"\"\"\nThe Trainer class prepares and launches training of a model.\nMost importantly, it compiles the tf.keras Model object with according to the\nspecified optimizer, loss and metrics and implements the .fit method for\ntraining the model given a set of parameters and (non-initialized) callbacks.\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.python.framework.errors_impl import (ResourceExhaustedError,\n InternalError)\nfrom mpunet.callbacks import (init_callback_objects,\n remove_validation_callbacks)\nfrom mpunet.logging import ScreenLogger\nfrom mpunet.callbacks import (DividerLine, LearningCurve)\nfrom mpunet.utils import ensure_list_or_tuple\nfrom mpunet.train.utils import (ensure_sparse,\n init_losses,\n init_metrics,\n init_optimizer)\nfrom utime.callbacks import Validation, MemoryConsumption\nfrom utime.train.utils import get_steps\n\n\ndef ignore_class_wrapper(loss_func, n_pred_classes, logger):\n \"\"\"\n For a model that outputs K classes, this wrapper removes entries in the\n true/pred pairs for which the true label is of integer value K.\n\n TODO\n \"\"\"\n @tf.function\n def wrapper(true, pred):\n true.set_shape(pred.get_shape()[:-1] + [1])\n true = tf.reshape(true, [-1])\n pred = tf.reshape(pred, [-1, n_pred_classes])\n mask = tf.where(tf.not_equal(true, n_pred_classes), tf.ones_like(true), tf.zeros_like(true))\n mask = tf.cast(mask, tf.bool)\n true = tf.boolean_mask(true, mask, axis=0)\n pred = tf.boolean_mask(pred, mask, axis=0)\n return loss_func(true, pred)\n logger(\"Regarding loss func: {}. \"\n \"Model outputs {} classes; Ignoring class with \"\n \"integer values {}\".format(loss_func, n_pred_classes,\n n_pred_classes))\n return wrapper\n\n\nclass Trainer(object):\n \"\"\"\n Handles initialization and logging of model fitting sessions.\n \"\"\"\n def __init__(self, model, org_model=None, logger=None):\n \"\"\"\n Init. simply accepts a model and stores it.\n Optionally, an 'org_model' (original model) may be passed and stored\n as well. This is for training multi-GPU models prepared by the\n tf.keras.utils.multi_gpu_model utility, which returns a new, split\n model for training (passed as 'model' parameter here). For properly\n saving the model parameter, however, it is recommended to use the\n original, non-split model (here passed as 'org_model').\n\n Args:\n model: (tf.keras Model) Initialized model to train\n org_model: (tf.keras Model) Optional single-GPU version for the\n passed 'model' parameter.\n logger: (Logger) Optional Logger instance\n \"\"\"\n self.model = model\n self.logger = logger if logger is not None else ScreenLogger()\n\n # Extra reference to original (non multiple-GPU) model\n # May also be set from a script at a later time (before self.fit call)\n self.org_model = org_model\n\n def compile_model(self, optimizer, loss, metrics, reduction,\n check_sparse=False, optimizer_kwargs={}, loss_kwargs={}, **kwargs):\n \"\"\"\n Compile the stored tf.keras Model instance stored in self.model\n Sets the loss function, optimizer and metrics\n\n Args:\n optimizer: (string) The name of a tf.keras.optimizers Optimizer\n optimizer_kwargs: (dict) Key-word arguments passed to the Optimizer\n loss: (string) The name of a tf.keras.losses or\n MultiPlanarUnet loss function\n metrics: (list) List of tf.keras.metrics or\n MultiPlanarUNet metrics.\n reduction TODO\n check_sparse: TODO\n **kwargs: (dict) Key-word arguments passed to losses\n and/or metrics that accept such.\n \"\"\"\n # Make sure sparse metrics and loss are specified as sparse\n metrics = ensure_list_or_tuple(metrics)\n losses = ensure_list_or_tuple(loss)\n if check_sparse:\n ensure_sparse(metrics+losses)\n\n # Initialize optimizer, loss(es) and metric(s) from tf.keras or MultiPlanarUNet\n optimizer = init_optimizer(optimizer, self.logger, **optimizer_kwargs)\n losses = init_losses(losses, self.logger, **kwargs)\n for i, loss in enumerate(losses):\n try:\n losses[i] = loss(reduction=reduction, **loss_kwargs)\n except (ValueError, TypeError):\n raise TypeError(\"All loss functions must currently be \"\n \"callable and accept the 'reduction' \"\n \"parameter specifying a \"\n \"tf.keras.losses.Reduction type. If you \"\n \"specified a keras loss function such as \"\n \"'sparse_categorical_crossentropy', change \"\n \"this to its corresponding loss class \"\n \"'SparseCategoricalCrossentropy'. If \"\n \"you implemented a custom loss function, \"\n \"please raise an issue on GitHub.\")\n else:\n # Mask out class 5: TODO: Make optional\n losses[i] = ignore_class_wrapper(losses[i], self.model.n_classes, self.logger)\n metrics = init_metrics(metrics, self.logger, **kwargs)\n\n # Compile the model\n self.model.compile(optimizer=optimizer, loss=losses, metrics=metrics)\n self.logger(\"Optimizer: %s\" % optimizer)\n self.logger(\"Loss funcs: %s\" % losses)\n self.logger(\"Metrics: %s\" % init_metrics)\n return self\n\n def fit(self, batch_size, **fit_kwargs):\n \"\"\"\n Fit the stored tf.keras Model (self.model) on a set of data.\n\n The 'fit' method is a wrapper around the hidden '_fit' method. It\n handles KeyboardInterrupts (--> stopping training prematurely), TF\n GPU memory errors (--> batch_size is reduced by 2 and training\n restarted), and other exceptions (--> error logged and training\n terminated).\n\n Please refer to the self._fit method for 'fit_kwargs' argument details.\n\n Args:\n batch_size: (int) The initial batch size to run training with\n fit_kwargs: (dict) Keyword arguments passed to self._fit\n \"\"\"\n fitting = True\n while fitting:\n try:\n self._fit(batch_size=batch_size, **fit_kwargs)\n fitting = False\n except (ResourceExhaustedError, InternalError):\n # Reduce batch size\n batch_size -= 2\n self.logger(\"\\n\\n[MEMORY ERROR] Reducing batch size \"\n \"by 2 (now %i)\" % batch_size)\n if batch_size < 1:\n self.logger(\"[ERROR] Batch size negative or zero!\")\n fitting = False\n except KeyboardInterrupt:\n fitting = False\n except Exception as e:\n self.logger(e)\n raise e\n self.logger.print_calling_method = True\n self.logger(\"Training stopped.\")\n return self.model\n\n def _fit(self,\n train,\n val,\n batch_size,\n n_epochs,\n callbacks,\n train_samples_per_epoch,\n verbose=1,\n init_epoch=0,\n **unused):\n \"\"\"\n Args:\n train: (Sequence) The training Sequence object\n val (Sequence, None) The validation Sequence object or None if no\n validation is to be performed\n batch_size: (int) The batch size to use for training\n n_epochs: (int) Number of epochs to train for\n callbacks: (list) List of uninitialized callback kwargs.\n train_samples_per_epoch: (int) Number of training samples to sample\n before an epoch is determined over.\n verbose: (int/bool) Verbosity level passed to keras.fit_generator\n init_epoch: (int) The initial epoch\n use_multiprocessing: (bool) Whether to use multiprocessing instead\n of multithreading.\n \"\"\"\n train.batch_size = batch_size\n train_steps = get_steps(train_samples_per_epoch, train)\n self.logger(\"Using {} steps per train epoch\".format(train_steps))\n\n if val is None:\n # No validation to be performed, remove callbacks that might need\n # validation data to function properly\n remove_validation_callbacks(callbacks, self.logger)\n else:\n val.batch_size = batch_size\n # Add validation callback\n # Important: Should be first in callbacks list as other CBs may\n # depend on the validation metrics/loss\n validation = Validation(val, logger=self.logger, verbose=verbose)\n callbacks = [validation] + callbacks\n\n # Add various callbacks for plotting learning curves etc.\n callbacks.append(MemoryConsumption(max_gib=45, logger=self.logger))\n callbacks.append(LearningCurve(logger=self.logger))\n # callbacks.append(CarbonUsageTracking(epochs=n_epochs, add_to_logs=False))\n callbacks.append(DividerLine(self.logger))\n\n # Get initialized callback objects\n callbacks, cb_dict = init_callback_objects(callbacks, self.logger)\n\n # If ModelCheckPointClean is used, set the original model to store\n # the correct weights when using multi-GPU models\n cb = cb_dict.get(\"ModelCheckPointClean\")\n if cb:\n cb.org_model = self.org_model\n\n # Temporary memory leak fix\n import tensorflow as tf\n dtypes, shapes = list(zip(*map(lambda x: (x.dtype, x.shape), train[0])))\n train = tf.data.Dataset.from_generator(train, dtypes, shapes)\n\n # Fit the model\n self.logger.active_log_file = \"training\"\n self.logger.print_calling_method = False\n self.model.fit(\n train,\n steps_per_epoch=train_steps,\n epochs=n_epochs,\n callbacks=callbacks,\n initial_epoch=init_epoch,\n use_multiprocessing=False,\n workers=3,\n max_queue_size=10,\n shuffle=False, # Determined by the chosen Sequence class\n verbose=verbose\n )\n" ]
[ [ "pandas.DataFrame", "numpy.mean", "numpy.bincount", "numpy.zeros_like", "numpy.where", "numpy.zeros" ], [ "tensorflow.boolean_mask", "tensorflow.not_equal", "tensorflow.cast", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.zeros_like", "tensorflow.data.Dataset.from_generator" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
aditya9126/pipelines-azureml
[ "0c747f12e02ee3d3976746663bd1da0ab5935887" ]
[ "models/diabetes/train.py" ]
[ "# new update\n\nimport pickle\nimport os\nimport numpy as np\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.linear_model import Ridge\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split\nfrom azureml.core.run import Run\n\nfrom utils import mylib\n\nos.makedirs('./outputs', exist_ok=True)\n\nX, y = load_diabetes(return_X_y=True)\n\nrun = Run.get_context()\n\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=0.2,\n random_state=0)\ndata = {\"train\": {\"X\": X_train, \"y\": y_train},\n \"test\": {\"X\": X_test, \"y\": y_test}}\n\n# list of numbers from 0.0 to 1.0 with a 0.05 interval\nalphas = mylib.get_alphas()\n\nfor alpha in alphas:\n # Use Ridge algorithm to create a regression model\n reg = Ridge(alpha=alpha)\n reg.fit(data[\"train\"][\"X\"], data[\"train\"][\"y\"])\n\n preds = reg.predict(data[\"test\"][\"X\"])\n mse = mean_squared_error(preds, data[\"test\"][\"y\"])\n run.log('alpha', alpha)\n run.log('mse', mse)\n\n # Save model in the outputs folder so it automatically get uploaded when running on AML Compute\n model_file_name = 'ridge_{0:.2f}.pkl'.format(alpha)\n with open(os.path.join('./outputs/', model_file_name), 'wb') as file:\n pickle.dump(reg, file)\n\n print('alpha is {0:.2f}, and mse is {1:0.2f}'.format(alpha, mse))\n" ]
[ [ "sklearn.linear_model.Ridge", "sklearn.model_selection.train_test_split", "sklearn.datasets.load_diabetes", "sklearn.metrics.mean_squared_error" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pasindubawantha/just-copy
[ "919b1723c87cadc5946f891da53f4abc7d50ff6e" ]
[ "AC_Network.py" ]
[ "import tensorflow as tf\nimport tensorflow.contrib.slim as slim\n#import tensorflow.nn as slim\nimport numpy as np\nfrom helpers import *\n\nclass AC_Network():\n def __init__(self,s_size,a_size,scope,trainer,s_shape):\n with tf.variable_scope(scope):\n #Input and visual encoding layers\n self.inputs = tf.placeholder(shape=[None,s_size],dtype=tf.float32)\n self.imageIn = tf.reshape(self.inputs,shape=[-1,s_shape[0],s_shape[1],s_shape[2]])\n self.conv1 = slim.conv2d(activation_fn=tf.nn.elu,\n inputs=self.imageIn,num_outputs=16,\n kernel_size=[8,8],stride=[4,4],padding='VALID')\n self.conv2 = slim.conv2d(activation_fn=tf.nn.elu,\n inputs=self.conv1,num_outputs=32,\n kernel_size=[4,4],stride=[2,2],padding='VALID')\n hidden = slim.fully_connected(slim.flatten(self.conv2),256,activation_fn=tf.nn.elu)\n \n #Recurrent network for temporal dependencies\n lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(256,state_is_tuple=True)\n \n c_init = np.zeros((1, lstm_cell.state_size.c), np.float32)\n h_init = np.zeros((1, lstm_cell.state_size.h), np.float32)\n self.state_init = [c_init, h_init]\n \n c_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.c])\n h_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.h])\n self.state_in = (c_in, h_in)\n\n rnn_in = tf.expand_dims(hidden, [0])\n step_size = tf.shape(self.imageIn)[:1]\n state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in)\n\n lstm_outputs, lstm_state = tf.nn.dynamic_rnn(\n lstm_cell, rnn_in, initial_state=state_in, sequence_length=step_size,\n time_major=False)\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n rnn_out = tf.reshape(lstm_outputs, [-1, 256])\n \n #Output layers for policy and value estimations\n self.policy = slim.fully_connected(rnn_out,a_size,\n activation_fn=tf.nn.softmax,\n weights_initializer=normalized_columns_initializer(0.01),\n biases_initializer=None)\n self.value = slim.fully_connected(rnn_out,1,\n activation_fn=None,\n weights_initializer=normalized_columns_initializer(1.0),\n biases_initializer=None)\n\n #Only the worker network need ops for loss functions and gradient updating.\n if scope != 'global':\n self.actions = tf.placeholder(shape=[None],dtype=tf.int32)\n self.actions_onehot = tf.one_hot(self.actions,a_size,dtype=tf.float32)\n self.target_v = tf.placeholder(shape=[None],dtype=tf.float32)\n self.advantages = tf.placeholder(shape=[None],dtype=tf.float32)\n\n self.responsible_outputs = tf.reduce_sum(self.policy * self.actions_onehot, [1])\n\n #Loss functions\n self.value_loss = 0.5 * tf.reduce_sum(tf.square(self.target_v - tf.reshape(self.value,[-1])))\n self.entropy = - tf.reduce_sum(self.policy * tf.log(self.policy))\n self.policy_loss = -tf.reduce_sum(tf.log(self.responsible_outputs)*self.advantages)\n self.loss = 0.5 * self.value_loss + self.policy_loss - self.entropy * 0.01\n\n #Get gradients from local network using local losses\n local_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)\n self.gradients = tf.gradients(self.loss,local_vars)\n self.var_norms = tf.global_norm(local_vars)\n self.grads,self.grad_norms = tf.clip_by_global_norm(self.gradients,40.0)\n \n #Apply local gradients to global network\n self.global_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, 'global')\n self.apply_grads = trainer.apply_gradients(zip(self.grads,self.global_vars))" ]
[ [ "tensorflow.nn.rnn_cell.BasicLSTMCell", "tensorflow.nn.dynamic_rnn", "tensorflow.nn.rnn_cell.LSTMStateTuple", "tensorflow.shape", "tensorflow.get_collection", "tensorflow.reduce_sum", "tensorflow.reshape", "tensorflow.gradients", "tensorflow.placeholder", "tensorflow.expand_dims", "tensorflow.clip_by_global_norm", "tensorflow.contrib.slim.flatten", "tensorflow.contrib.slim.conv2d", "tensorflow.one_hot", "tensorflow.variable_scope", "tensorflow.log", "numpy.zeros", "tensorflow.global_norm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
jishnujayakumar/meta-dataset
[ "fac43975e7e8931bd9c9a9171268758e26469646", "fac43975e7e8931bd9c9a9171268758e26469646" ]
[ "meta_dataset/analysis/select_best_model.py", "meta_dataset/data/sur_decoder.py" ]
[ "# coding=utf-8\n# Copyright 2021 The Meta-Dataset 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# Lint as: python2, python3\nr\"\"\"A script for choosing the best variant of a model automatically.\n\nIt takes as input the root directory of all experiments, and a list of names of\ndirectories in that root, each storing the data of an experiment with multiple\nvariants accross which we want to select the best. Each experiment directory\nshould contain a directoy named 'summaries' that hosts subdirectories for the\ndifferent runs with each one containing event files. These event files are read\nto figure out which is best in terms of mean validation accuracy, and at which\nstep of that run this best value occurs in.\n\nFor each of the experiment directories provided, the output information is saved\nin a 'best.pklz' file in that directory. This file contains a dict with keys\n'best_variant', 'best_valid_acc', and 'best_update_num' where the name of the\nvariant is simply the name of the sub-directory corresponding to that variant.\n\nExample directory structure (after the script is ran):\nRoot contains: 'Exp1', 'Exp2'.\n Exp1 contains: 'checkpoints', 'summaries', and best.pklz\n summaries contains: '1', '2', '3', ..., '20'\n '1' contains event files\n '2' contains event files\n ...\n '20' contains event files\n\nSample command:\n# pylint: disable=line-too-long\npython -m meta_dataset.analysis.select_best_model \\\n --alsologtostderr \\\n --all_experiments_root=<experiments_root> \\\n --experiment_dir_basenames=baseline_imagenet_icml2019_1/3602170,baselinefinetune_imagenet_icml2019_1/3581340\n# pylint: enable=line-too-long\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\n\nfrom absl import logging\nimport numpy as np\nfrom six.moves import range\nfrom six.moves import zip\nimport six.moves.cPickle as pkl\nimport tensorflow.compat.v1 as tf\n\nFLAGS = tf.flags.FLAGS\n\ntf.flags.DEFINE_string(\n 'all_experiments_root',\n '',\n 'The overall experiments directory root.')\n\ntf.flags.DEFINE_string(\n 'experiment_dir_basenames', ''\n 'baseline_imagenet_icml2019_1/3602170,'\n 'baselinefinetune_imagenet_icml2019_1/3581340',\n 'A comma-separated list of directory basenames. Adding each basename as a '\n 'suffix to FLAGS.all_experiments_root forms a path that stores the data of '\n 'an experiment with multiple variants accross which we want to select the '\n 'best. Each such path is expected to host a directory named \"summaries\" '\n 'that contains subdirectories for the different runs with each such '\n 'subdirectory containing event files.')\n\n# TODO(etriantafillou): This assumes the variants to omit are the same for all\n# experiments that model selection will be ran for which doesn't make much\n# sense. Maybe just remove this altogether?\ntf.flags.DEFINE_string(\n 'restrict_to_variants', '', 'A comma-separated list of '\n 'variants to restrict to for model selection. This is '\n 'useful for example for finding the best out of all '\n 'variants that use a specific embedding or image size.')\n\ntf.flags.DEFINE_string(\n 'restrict_to_variants_by_range', '', 'A comma-separated list of '\n 'two integers that represent the start and end range (both inclusive) '\n 'of variant ids to restrict to.')\n\ntf.flags.DEFINE_string(\n 'description', 'best', 'The description for the output. The output will '\n 'then be named as description.pklz and description.txt. For example, this '\n 'can be used to reflect that some variants were omitted.')\n\n# The following two flags assume that the parameters of the experiments have\n# been logged (they attempt to read from them). If this is not the case, the\n# restrict_to_variants flag should be used instead.\ntf.flags.DEFINE_string(\n 'restrict_to_architectures', '', 'The comma-separated names of the '\n 'embedding networks to restrict to for model selection.')\n\ntf.flags.DEFINE_enum(\n 'restrict_to_pretrained_source', '', ['', 'scratch', 'imagenet'],\n 'The name of a pretrained_source to '\n 'restrict to for model selection.')\n\ntf.flags.DEFINE_integer(\n 'smooth_window', 1, 'rolling average window to be '\n 'applied before the best model selection. '\n 'Set 1 for no smoothing.')\n\nVALIDATION_ACCURACY_TAGS = (\n 'valid_acc/mean',\n 'mean valid acc',\n 'mean acc', # TODO(doersch): rather unclear tag written by trainer.py\n)\n\n\ndef get_value_from_params_dir(params_dir, param_names):\n \"\"\"Gets the first found value from `param_names` in `params_dir`.\"\"\"\n\n def _load_params(param_name, params_file, loader, mode):\n with tf.io.gfile.GFile(params_file, mode) as f:\n params = loader(f)\n logging.info('Found params file %s', params_file)\n return params[param_name]\n\n for param_name in param_names:\n try:\n try:\n return _load_params(param_name, os.path.join(params_dir, 'params.json'),\n json.load, 'r')\n except tf.errors.NotFoundError:\n logging.info('%s does not exist in %s', 'params.json', params_dir)\n\n try:\n return _load_params(param_name, os.path.join(params_dir, 'params.pkl'),\n pkl.load, 'rb')\n except tf.errors.NotFoundError:\n logging.info('%s does not exist in %s', 'params.pkl', params_dir)\n\n except KeyError:\n pass\n\n raise ValueError('Did not find any of the following keys: %s' % param_names)\n\n\ndef get_paths_to_events(root_dir,\n restrict_to_architectures,\n restrict_to_pretrained_source,\n restrict_to_variants=None):\n \"\"\"Returns a dict that maps each variant name to its event file.\n\n The name of the variant is the basename of the directory where it's stored.\n Assumes the following directory organization root_dir contains a sub-directory\n for every variant where event files can be found.\n\n There may be more than one event file for each variant, e.g. a new one will be\n created upon restarting an experiment that was pre-empted. So later event\n files contain the summaries for larger values of 'step'. We need all of them\n for determining the global 'best'.\n\n Args:\n root_dir: A str. The root directory of experiments of all models variants.\n restrict_to_architectures: A list of names of architectures to restrict to\n when choosing the best variant.\n restrict_to_pretrained_source: A string. The pretrained_source to restrict\n to when choosing the best variant.\n restrict_to_variants: Optionally, a set of variant names to restrict to.\n \"\"\"\n params_dir = os.path.join(root_dir, 'params')\n summary_dir = os.path.join(root_dir, 'summaries')\n logging.info('Looking for parameters in params_dir: %s', params_dir)\n logging.info('Looking for summaries in summary_dir: %s', summary_dir)\n\n def get_variant_architecture(name):\n \"\"\"Return the architecture of the given variant if recorded; o/w None.\"\"\"\n variant_params_dir = os.path.join(params_dir, name)\n architecture = get_value_from_params_dir(\n variant_params_dir,\n (\n '_gin.Learner.embedding_fn',\n # The following are for backwards compatibility.\n '_gin.Trainer.embedding_network',\n '_gin.LearnerConfig.embedding_network',\n ))\n\n return architecture\n\n def get_variant_pretrained_source(name):\n \"\"\"Return the pretrained src of the given variant if recorded; o/w None.\"\"\"\n variant_params_dir = os.path.join(params_dir, name)\n pretrained_source = get_value_from_params_dir(\n variant_params_dir, '_gin.Trainer.pretrained_source')\n\n if not pretrained_source:\n # Backwards compatibility.\n pretrained_source = get_value_from_params_dir(\n variant_params_dir, '_gin.LearnerConfig.pretrained_source')\n\n return pretrained_source\n\n def keep_variant(name):\n \"\"\"Determine if the variant in directory name should be considered.\"\"\"\n value_error_msg = (\n 'Requested to restrict to an architecture or '\n 'pretrained_source but the given experiment does not '\n 'have its params recorded. Looked in: {}'.format(params_dir))\n\n if restrict_to_architectures:\n architecture = get_variant_architecture(name)\n if architecture is None:\n raise ValueError(value_error_msg)\n valid_architecture = (not restrict_to_architectures or\n architecture in restrict_to_architectures)\n\n if restrict_to_pretrained_source:\n pretrained_source = get_variant_pretrained_source(name)\n if pretrained_source is None:\n raise ValueError(value_error_msg)\n valid_pretrained_source = (\n not restrict_to_pretrained_source or\n pretrained_source == restrict_to_pretrained_source)\n\n valid_variant_name = True\n if restrict_to_variants is not None:\n valid_variant_name = name in restrict_to_variants\n\n return (valid_architecture and valid_pretrained_source and\n valid_variant_name)\n\n variant_names = [\n fname for fname in tf.io.gfile.listdir(summary_dir)\n if tf.io.gfile.isdir(os.path.join(summary_dir, fname))\n ]\n\n if not variant_names:\n # Maybe there are no variants, and we are already in the directory that\n # contains the summaries. In this case, we consider that the current\n # directory (.) is the only variant.\n variant_names = ['.']\n\n # Further filter variant names based on the given restrictions.\n variant_names = [name for name in variant_names if keep_variant(name)]\n\n if not variant_names:\n raise ValueError('Found no subdirectories in {}. Was expecting a '\n 'subdirectory per variant.'.format(summary_dir))\n variant_paths = [\n os.path.join(summary_dir, variant_dir) for variant_dir in variant_names\n ]\n\n event_paths = {}\n for variant_path, variant_name in zip(variant_paths, variant_names):\n event_filenames = [\n f_name for f_name in tf.io.gfile.listdir(variant_path)\n if f_name.startswith('events.out.tfevents')\n ]\n\n if len(event_filenames) < 1:\n logging.warn('Skipping empty variant %s.', variant_path)\n logging.info(\n 'Was expecting at least one event file '\n 'in directory %s. Instead, found %d.', variant_path,\n len(event_filenames))\n continue\n event_paths[variant_name] = [\n os.path.join(variant_path, event_filename)\n for event_filename in event_filenames\n ]\n\n logging.info('Found event files for variants: %s', list(event_paths.keys()))\n return event_paths\n\n\n# TODO(crisnv): add smooth_type='uniform' that defines the smooth policy\ndef moving_average(x, smooth_window):\n \"\"\"Returns a smoothed version of x.\n\n This smoothes the x array according to the smooth_window parameter.\n\n Args:\n x: The array to smooth.\n smooth_window: An integer that defines the neighborhood to be used in\n smoothing.\n \"\"\"\n conv_filter = getattr(moving_average, 'conv_filter', None)\n if conv_filter is None or (moving_average.conv_filter_size != smooth_window):\n moving_average.conv_filter = np.ones((smooth_window,)) / smooth_window\n moving_average.conv_filter_size = smooth_window\n # if smooth_window is even, pad accordingly to keep stream size\n x = np.pad(x, (smooth_window // 2, smooth_window - 1 - (smooth_window // 2)),\n 'reflect')\n return np.convolve(x, moving_average.conv_filter, mode='valid')\n\n\ndef extract_best_from_event_file(event_path, smooth_window, log_details=False):\n \"\"\"Returns the best accuracy and the step it occurs in in the given events.\n\n This searches the summaries written in a given event file, which may be only a\n subset of the total summaries of a run, since the summaries of a run are\n sometimes split into multiple event files.\n\n Args:\n event_path: A string. The path to an event file.\n smooth_window: An integer that defines the neighborhood to be used in\n smoothing before the argmax (use <=1 for no smoothing)\n log_details: A boolean. Whether to log details regarding skipped event paths\n in which locating the validation accuracy tag failed.\n \"\"\"\n steps, valid_accs = [], []\n try:\n for event in tf.train.summary_iterator(event_path):\n step = event.step\n for value in event.summary.value:\n if any(\n valid_tag in value.tag for valid_tag in VALIDATION_ACCURACY_TAGS):\n steps.append(step)\n valid_accs.append(value.simple_value)\n except tf.errors.DataLossError:\n if log_details:\n tf.logging.info(\n 'Omitting events from event_path {} because '\n 'tf.train.summary_iterator(event_path) failed.'.format(event_path))\n return 0, 0\n if not valid_accs:\n # Could happen if there is no DataLossError above but for some reason\n # there is no validation accuracy tag found in the summary values.\n tf.logging.info(\n 'Did not find any validation accuracy tags ({}) in event_path {}'\n .format(' or '.join(VALIDATION_ACCURACY_TAGS), event_path))\n return 0, 0\n if smooth_window > 1:\n valid_accs = moving_average(valid_accs, smooth_window)\n argmax_ind = np.argmax(valid_accs)\n best_acc = valid_accs[argmax_ind]\n best_step = steps[argmax_ind]\n if log_details:\n tf.logging.info('Successfully read event_path {} with best_acc {}'.format(\n event_path, best_acc))\n return best_acc, best_step\n\n\ndef extract_best_from_variant(event_paths, smooth_window):\n \"\"\"Returns the best accuracy and the step it occurs in for the given run.\n\n Args:\n event_paths: A list of strings. The event files of the given run.\n smooth_window: An integer that defines the neighborhood to be used in\n smoothing before the argmax (use <=1 for no smoothing)\n\n Raises:\n RuntimeError: No 'valid' event file for the given variant ('valid' here\n refers to an event file that has a validation accuracy tag).\n \"\"\"\n best_step = best_acc = -1\n for event_path in event_paths:\n best_acc_, best_step_ = extract_best_from_event_file(\n event_path, smooth_window)\n if best_acc_ > best_acc:\n best_acc = best_acc_\n best_step = best_step_\n if best_acc <= 0:\n raise RuntimeError('Something went wrong with the summary event reading.')\n return best_acc, best_step\n\n\ndef main(argv):\n del argv\n experiment_paths = [\n os.path.join(FLAGS.all_experiments_root, basename)\n for basename in FLAGS.experiment_dir_basenames.split(',')\n ]\n # Perform model selection for each provided experiment root.\n for root_experiment_dir in experiment_paths:\n stars_string = '\\n**************************************\\n'\n architecture_string = ''\n if FLAGS.restrict_to_architectures:\n architecture_string = ' out of the {} variants'.format(\n FLAGS.restrict_to_architectures)\n logging.info('%sSelecting the best variant for: %s%s.%s', stars_string,\n root_experiment_dir, architecture_string, stars_string)\n\n if FLAGS.restrict_to_variants_by_range and FLAGS.restrict_to_variants:\n raise ValueError('Please provide only one of '\n 'FLAGS.restrict_to_variants_by_range and '\n 'FLAGS.restrict_to_variants, not both.')\n\n restrict_to_variants = None\n if FLAGS.restrict_to_variants_by_range:\n start, end = FLAGS.restrict_to_variants_by_range.split(',')\n start, end = int(start), int(end)\n restrict_to_variants = set(\n [str(variant_id) for variant_id in range(start, end + 1)])\n if FLAGS.restrict_to_variants:\n restrict_to_variants = set(FLAGS.restrict_to_variants.split(','))\n\n restrict_to_architectures = []\n if FLAGS.restrict_to_architectures:\n restrict_to_architectures = FLAGS.restrict_to_architectures.split(',')\n\n smooth_window = FLAGS.smooth_window\n event_paths = get_paths_to_events(\n root_experiment_dir,\n restrict_to_architectures,\n FLAGS.restrict_to_pretrained_source,\n restrict_to_variants=restrict_to_variants)\n # Read the event file of each variant to find the highest mean validation\n # accuracy reached with it.\n best_variant = ''\n best_valid_acc = -1\n best_step = -1\n for variant_name, event_path in event_paths.items():\n best_valid_acc_, best_step_ = extract_best_from_variant(\n event_path, smooth_window)\n if best_valid_acc_ > best_valid_acc:\n best_variant = variant_name\n best_valid_acc = best_valid_acc_\n best_step = best_step_\n\n output_dict = {\n 'best_variant': best_variant,\n 'best_valid_acc': best_valid_acc,\n 'best_update_num': best_step\n }\n\n # Create a more informative description if necessary.\n description = FLAGS.description\n if FLAGS.restrict_to_architectures and FLAGS.description == 'best':\n description += '_{}'.format(FLAGS.restrict_to_architectures)\n\n if (FLAGS.restrict_to_pretrained_source and FLAGS.description == 'best'):\n if FLAGS.restrict_to_pretrained_source == 'scratch':\n description += '_trained_from_scratch'\n else:\n description += '_pretrained_on_{}'.format(\n FLAGS.restrict_to_pretrained_source)\n if FLAGS.smooth_window > 1:\n description += '_smoothed_by_window_{}'.format(smooth_window)\n\n output_path_pklz = os.path.join(root_experiment_dir,\n '{}.pklz'.format(description))\n with tf.io.gfile.GFile(output_path_pklz, 'wb') as f:\n pkl.dump(output_dict, f, protocol=pkl.HIGHEST_PROTOCOL)\n\n # Also write this info as a .txt file for easier reading.\n output_path_txt = os.path.join(root_experiment_dir,\n '{}.txt'.format(description))\n with tf.io.gfile.GFile(output_path_txt, 'w') as f:\n f.write(\n 'best_variant: {}\\nbest_valid_acc: {}\\nbest_update_num: {}\\n'.format(\n best_variant, best_valid_acc, best_step))\n logging.info(\n 'Best variant: %s. Best valid acc: %s. Best update num: %d. '\n 'Just wrote this info to %s and %s', best_variant, best_valid_acc,\n best_step, output_path_pklz, output_path_txt)\n\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.INFO)\n tf.app.run(main)\n", "# coding=utf-8\n# Copyright 2021 The Meta-Dataset 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\"\"\"Module responsible for decoding images as in SUR (Dvornik et al).\n\nMIT License\n\nCopyright (c) 2021 Nikita Dvornik\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport gin.tf\nimport tensorflow.compat.v1 as tf\n\n\[email protected]\nclass SURDataAugmentation(object):\n \"\"\"Configurations for performing data augmentation.\"\"\"\n\n def __init__(self, enable_jitter, jitter_amount, enable_gaussian_noise,\n gaussian_noise_std, enable_random_flip, enable_random_brightness,\n random_brightness_delta, enable_random_contrast,\n random_contrast_delta, enable_random_hue, random_hue_delta,\n enable_random_saturation, random_saturation_delta):\n \"\"\"Initializes a DataAugmentation.\"\"\"\n self.enable_jitter = enable_jitter\n self.jitter_amount = jitter_amount\n self.enable_gaussian_noise = enable_gaussian_noise\n self.gaussian_noise_std = gaussian_noise_std\n self.enable_random_flip = enable_random_flip\n self.enable_random_brightness = enable_random_brightness\n self.random_brightness_delta = random_brightness_delta\n self.enable_random_contrast = enable_random_contrast\n self.random_contrast_delta = random_contrast_delta\n self.enable_random_hue = enable_random_hue\n self.random_hue_delta = random_hue_delta\n self.enable_random_saturation = enable_random_saturation\n self.random_saturation_delta = random_saturation_delta\n\n\[email protected]\nclass SURImageDecoder(object):\n \"\"\"Image decoder.\"\"\"\n out_type = tf.float32\n\n def __init__(self, image_size=None, data_augmentation=None):\n \"\"\"Class constructor.\n\n Args:\n image_size: int, desired image size. The extracted image will be resized\n to `[image_size, image_size]`.\n data_augmentation: A DataAugmentation object with parameters for\n perturbing the images.\n \"\"\"\n\n self.image_size = image_size\n self.data_augmentation = data_augmentation\n\n def __call__(self, example_string):\n \"\"\"Processes a single example string.\n\n Extracts and processes the image, and ignores the label. We assume that the\n image has three channels.\n Args:\n example_string: str, an Example protocol buffer.\n\n Returns:\n image_rescaled: the image, resized to `image_size x image_size` and\n rescaled to [-1, 1]. Note that Gaussian data augmentation may cause values\n to go beyond this range.\n \"\"\"\n image_string = tf.parse_single_example(\n example_string,\n features={\n 'image': tf.FixedLenFeature([], dtype=tf.string),\n 'label': tf.FixedLenFeature([], tf.int64)\n })['image']\n image_decoded = tf.image.decode_image(image_string, channels=3)\n image_decoded.set_shape([None, None, 3])\n image_resized = tf.image.resize_images(\n image_decoded, [self.image_size, self.image_size],\n method=tf.image.ResizeMethod.BILINEAR,\n align_corners=True)\n image = tf.cast(image_resized, tf.float32)\n\n if self.data_augmentation is not None:\n if self.data_augmentation.enable_random_brightness:\n delta = self.data_augmentation.random_brightness_delta\n image = tf.image.random_brightness(image, delta)\n\n if self.data_augmentation.enable_random_saturation:\n delta = self.data_augmentation.random_saturation_delta\n image = tf.image.random_saturation(image, 1 - delta, 1 + delta)\n\n if self.data_augmentation.enable_random_contrast:\n delta = self.data_augmentation.random_contrast_delta\n image = tf.image.random_contrast(image, 1 - delta, 1 + delta)\n\n if self.data_augmentation.enable_random_hue:\n delta = self.data_augmentation.random_hue_delta\n image = tf.image.random_hue(image, delta)\n\n if self.data_augmentation.enable_random_flip:\n image = tf.image.random_flip_left_right(image)\n\n image = 2 * (image / 255.0 - 0.5) # Rescale to [-1, 1].\n\n if self.data_augmentation is not None:\n if self.data_augmentation.enable_gaussian_noise:\n image = image + tf.random_normal(\n tf.shape(image)) * self.data_augmentation.gaussian_noise_std\n\n if self.data_augmentation.enable_jitter:\n j = self.data_augmentation.jitter_amount\n paddings = tf.constant([[j, j], [j, j], [0, 0]])\n image = tf.pad(image, paddings, 'REFLECT')\n image = tf.image.random_crop(image,\n [self.image_size, self.image_size, 3])\n\n return image\n" ]
[ [ "numpy.convolve", "numpy.pad", "tensorflow.compat.v1.io.gfile.listdir", "tensorflow.compat.v1.train.summary_iterator", "tensorflow.compat.v1.flags.DEFINE_string", "tensorflow.compat.v1.io.gfile.GFile", "numpy.ones", "numpy.argmax", "tensorflow.compat.v1.flags.DEFINE_enum", "tensorflow.compat.v1.flags.DEFINE_integer", "tensorflow.compat.v1.app.run" ], [ "tensorflow.compat.v1.image.resize_images", "tensorflow.compat.v1.image.random_crop", "tensorflow.compat.v1.image.random_saturation", "tensorflow.compat.v1.image.random_hue", "tensorflow.compat.v1.FixedLenFeature", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.image.random_brightness", "tensorflow.compat.v1.image.random_contrast", "tensorflow.compat.v1.image.random_flip_left_right", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.image.decode_image", "tensorflow.compat.v1.pad", "tensorflow.compat.v1.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sdrobert/pydrobert-pytorch
[ "7abad0dbb2e80b4267aebcee492aa9fd7d83ea3f", "7abad0dbb2e80b4267aebcee492aa9fd7d83ea3f" ]
[ "tests/test_data.py", "src/pydrobert/torch/command_line.py" ]
[ "# Copyright 2021 Sean Robertson\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 os\n\nfrom itertools import repeat\nfrom io import StringIO\n\n\nimport pytest\nimport torch\nimport torch.utils.data\nimport pydrobert.torch.data as data\n\nfrom pydrobert.torch import INDEX_PAD_VALUE\n\n\[email protected]\[email protected](\"left\", [0, 1, 100])\[email protected](\"right\", [0, 1, 100])\[email protected](\"T\", [1, 5, 10])\ndef test_extract_window(left, right, T):\n signal = torch.arange(T).view(-1, 1).expand(-1, 10)\n for frame_idx in range(T):\n window = data.extract_window(signal, frame_idx, left, right)\n left_pad = max(left - frame_idx, 0)\n right_pad = max(frame_idx + right + 1 - T, 0)\n assert tuple(window.shape) == (1 + left + right, 10)\n if left_pad:\n assert torch.all(window[:left_pad] == torch.tensor([0]))\n if right_pad:\n assert torch.all(window[-right_pad:] == torch.tensor([T - 1]))\n assert torch.all(\n window[left_pad : 1 + left + right - right_pad]\n == torch.arange(\n frame_idx - left + left_pad, frame_idx + right - right_pad + 1\n )\n .view(-1, 1)\n .expand(-1, 10)\n )\n\n\[email protected]\[email protected](\"num_utts\", [1, 2, 10])\[email protected](\"file_prefix\", [\"prefix_\", \"\"])\[email protected](\"eos\", [1000, None])\[email protected](\"sos\", [2000, None])\[email protected](\"feat_dtype\", [torch.float, torch.int])\ndef test_valid_spect_data_set(\n temp_dir, num_utts, file_prefix, populate_torch_dir, sos, eos, feat_dtype\n):\n feats, _, _, _, _, utt_ids = populate_torch_dir(\n temp_dir,\n num_utts,\n file_prefix=file_prefix,\n include_ali=False,\n include_ref=False,\n feat_dtype=feat_dtype,\n )\n # note that this'll just resave the same features if there's no file\n # prefix. If there is, these ought to be ignored by the data set\n populate_torch_dir(\n temp_dir, num_utts, include_ali=False, include_ref=False, feat_dtype=feat_dtype\n )\n if not os.path.isdir(os.path.join(temp_dir, \"feat\", \"fake\")):\n os.makedirs(os.path.join(temp_dir, \"feat\", \"fake\"))\n torch.save(\n torch.randint(100, (10, 5), dtype=feat_dtype),\n os.path.join(temp_dir, \"feat\", \"fake\", file_prefix + \"fake.pt\"),\n )\n data_set = data.SpectDataSet(temp_dir, file_prefix=file_prefix, eos=eos)\n assert not data_set.has_ali and not data_set.has_ref\n assert len(utt_ids) == len(data_set.utt_ids)\n assert all(utt_a == utt_b for (utt_a, utt_b) in zip(utt_ids, data_set.utt_ids))\n assert all(\n ali_b is None and ref_b is None and torch.allclose(feat_a, feat_b)\n for (feat_a, (feat_b, ali_b, ref_b)) in zip(feats, data_set)\n )\n feats, alis, refs, _, _, utt_ids = populate_torch_dir(\n temp_dir, num_utts, file_prefix=file_prefix, feat_dtype=feat_dtype\n )\n if sos is not None:\n sos_sym = torch.full((3,), -1, dtype=torch.long)\n sos_sym[0] = sos\n sos_sym = sos_sym.unsqueeze(0)\n refs = [torch.cat([sos_sym, x]) for x in refs]\n if eos is not None:\n eos_sym = torch.full((3,), -1, dtype=torch.long)\n eos_sym[0] = eos\n eos_sym = eos_sym.unsqueeze(0)\n refs = [torch.cat([x, eos_sym]) for x in refs]\n data_set = data.SpectDataSet(temp_dir, file_prefix=file_prefix, sos=sos, eos=eos)\n assert data_set.has_ali and data_set.has_ref\n assert len(utt_ids) == len(data_set.utt_ids)\n assert all(utt_a == utt_b for (utt_a, utt_b) in zip(utt_ids, data_set.utt_ids))\n assert all(\n torch.all(ali_a == ali_b)\n and torch.all(ref_a == ref_b)\n and feat_a.dtype == feat_b.dtype\n and torch.allclose(feat_a, feat_b)\n for ((feat_a, ali_a, ref_a), (feat_b, ali_b, ref_b)) in zip(\n zip(feats, alis, refs), data_set\n )\n )\n subset_ids = data_set.utt_ids[: num_utts // 2]\n data_set = data.SpectDataSet(\n temp_dir, file_prefix=file_prefix, subset_ids=set(subset_ids), sos=sos, eos=eos\n )\n assert all(utt_a == utt_b for (utt_a, utt_b) in zip(subset_ids, data_set.utt_ids))\n assert all(\n torch.all(ali_a == ali_b)\n and torch.all(ref_a == ref_b)\n and torch.allclose(feat_a, feat_b)\n for ((feat_a, ali_a, ref_a), (feat_b, ali_b, ref_b)) in zip(\n zip(feats[: num_utts // 2], alis[: num_utts // 2], refs[: num_utts // 2]),\n data_set,\n )\n )\n\n\[email protected]\ndef test_spect_data_set_warnings(temp_dir):\n torch.manual_seed(1)\n feat_dir = os.path.join(temp_dir, \"feat\")\n ali_dir = os.path.join(temp_dir, \"ali\")\n os.makedirs(feat_dir)\n os.makedirs(ali_dir)\n torch.save(torch.rand(3, 3), os.path.join(feat_dir, \"a.pt\"))\n torch.save(torch.rand(4, 3), os.path.join(feat_dir, \"b.pt\"))\n torch.save(torch.randint(10, (4,), dtype=torch.long), os.path.join(ali_dir, \"b.pt\"))\n torch.save(torch.randint(10, (5,), dtype=torch.long), os.path.join(ali_dir, \"c.pt\"))\n data_set = data.SpectDataSet(temp_dir, warn_on_missing=False)\n assert data_set.has_ali\n assert data_set.utt_ids == (\"b\",)\n with pytest.warns(UserWarning) as warnings:\n data_set = data.SpectDataSet(temp_dir)\n assert len(warnings) == 2\n assert any(str(x.message) == \"Missing ali for uttid: 'a'\" for x in warnings)\n assert any(str(x.message) == \"Missing feat for uttid: 'c'\" for x in warnings)\n\n\ndef test_spect_data_write_pdf(temp_dir, device):\n torch.manual_seed(1)\n feat_dir = os.path.join(temp_dir, \"feat\")\n os.makedirs(feat_dir)\n torch.save(torch.rand(3, 3), os.path.join(feat_dir, \"a.pt\"))\n data_set = data.SpectDataSet(temp_dir)\n z = torch.randint(10, (4, 5), dtype=torch.long)\n if device == \"cuda\":\n data_set.write_pdf(\"b\", z.cuda())\n else:\n data_set.write_pdf(\"b\", z)\n zp = torch.load(os.path.join(temp_dir, \"pdfs\", \"b.pt\"))\n assert isinstance(zp, torch.FloatTensor)\n assert torch.allclose(zp, z.float())\n data_set.write_pdf(0, torch.rand(10, 4))\n assert os.path.exists(os.path.join(temp_dir, \"pdfs\", \"a.pt\"))\n data_set.write_pdf(\"c\", z, pdfs_dir=os.path.join(temp_dir, \"foop\"))\n assert os.path.exists(os.path.join(temp_dir, \"foop\", \"c.pt\"))\n\n\[email protected](\"eos\", [None, -1])\[email protected](\"sos\", [None, -2])\ndef test_spect_data_write_hyp(temp_dir, device, sos, eos):\n torch.manual_seed(1)\n feat_dir = os.path.join(temp_dir, \"feat\")\n os.makedirs(feat_dir)\n torch.save(torch.rand(3, 3), os.path.join(feat_dir, \"a.pt\"))\n data_set = data.SpectDataSet(temp_dir, sos=sos, eos=eos)\n z = torch.randint(10, (4, 3), dtype=torch.float)\n zz = z\n if sos:\n zz = torch.cat([torch.full_like(zz, sos), zz])\n if eos:\n zz = torch.cat([zz, torch.full_like(z, eos)])\n if device == \"cuda\":\n data_set.write_hyp(\"b\", zz.cuda())\n else:\n data_set.write_hyp(\"b\", zz)\n zp = torch.load(os.path.join(temp_dir, \"hyp\", \"b.pt\"))\n assert isinstance(zp, torch.LongTensor)\n assert torch.all(zp == z.long())\n data_set.write_hyp(0, torch.randint(10, (11, 3)))\n assert os.path.exists(os.path.join(temp_dir, \"hyp\", \"a.pt\"))\n data_set.write_hyp(\"c\", z, hyp_dir=os.path.join(temp_dir, \"foop\"))\n assert os.path.exists(os.path.join(temp_dir, \"foop\", \"c.pt\"))\n\n\[email protected]\[email protected](\"eos\", [None, 10000])\ndef test_spect_data_set_validity(temp_dir, eos):\n torch.manual_seed(1)\n feat_dir = os.path.join(temp_dir, \"feat\")\n ali_dir = os.path.join(temp_dir, \"ali\")\n ref_dir = os.path.join(temp_dir, \"ref\")\n feats_a_pt = os.path.join(feat_dir, \"a.pt\")\n feats_b_pt = os.path.join(feat_dir, \"b.pt\")\n ali_a_pt = os.path.join(ali_dir, \"a.pt\")\n ali_b_pt = os.path.join(ali_dir, \"b.pt\")\n ref_a_pt = os.path.join(ref_dir, \"a.pt\")\n ref_b_pt = os.path.join(ref_dir, \"b.pt\")\n os.makedirs(feat_dir)\n os.makedirs(ali_dir)\n os.makedirs(ref_dir)\n torch.save(torch.rand(10, 4), feats_a_pt)\n torch.save(torch.rand(4, 4), feats_b_pt)\n torch.save(torch.randint(10, (10,), dtype=torch.long), ali_a_pt)\n torch.save(torch.randint(10, (4,), dtype=torch.long), ali_b_pt)\n torch.save(\n torch.cat(\n [\n torch.randint(10, (11, 1), dtype=torch.long),\n torch.full((11, 2), -1, dtype=torch.long),\n ],\n -1,\n ),\n ref_a_pt,\n )\n torch.save(torch.tensor([[0, 3, 4], [1, 1, 2]]), ref_b_pt)\n data_set = data.SpectDataSet(temp_dir, eos=eos)\n data.validate_spect_data_set(data_set)\n torch.save(torch.rand(4, 4).long(), feats_b_pt)\n with pytest.raises(ValueError, match=\"not the same tensor type\"):\n data.validate_spect_data_set(data_set)\n torch.save(\n torch.rand(\n 4,\n ),\n feats_b_pt,\n )\n with pytest.raises(ValueError, match=\"does not have two dimensions\"):\n data.validate_spect_data_set(data_set)\n torch.save(torch.rand(4, 3), feats_b_pt)\n with pytest.raises(ValueError, match=\"has second dimension of size 3.*\"):\n data.validate_spect_data_set(data_set)\n torch.save(torch.rand(4, 4), feats_b_pt)\n data.validate_spect_data_set(data_set)\n torch.save(torch.randint(10, (4,)).int(), ali_b_pt)\n with pytest.raises(ValueError, match=\"is not a long tensor\"):\n data.validate_spect_data_set(data_set)\n with pytest.warns(UserWarning):\n data.validate_spect_data_set(data_set, True) # will fix bad type\n data.validate_spect_data_set(data_set) # fine after correction\n torch.save(torch.randint(10, (4, 1), dtype=torch.long), ali_b_pt)\n with pytest.raises(ValueError, match=\"does not have one dimension\"):\n data.validate_spect_data_set(data_set)\n torch.save(torch.randint(10, (3,), dtype=torch.long), ali_b_pt)\n with pytest.raises(ValueError, match=\"does not have the same first\"):\n data.validate_spect_data_set(data_set)\n torch.save(torch.randint(10, (4,), dtype=torch.long), ali_b_pt)\n data.validate_spect_data_set(data_set)\n torch.save(torch.Tensor([[0, 1, 2]]).int(), ref_b_pt)\n with pytest.raises(ValueError, match=\"is not a long tensor\"):\n data.validate_spect_data_set(data_set)\n with pytest.warns(UserWarning):\n data.validate_spect_data_set(data_set, True) # convert to long\n data.validate_spect_data_set(data_set)\n torch.save(torch.tensor([[0, -1, 2], [1, 1, 2]]), ref_b_pt)\n with pytest.raises(ValueError, match=\"invalid boundaries\"):\n data.validate_spect_data_set(data_set)\n with pytest.warns(UserWarning):\n data.validate_spect_data_set(data_set, True) # will remove end bound\n data.validate_spect_data_set(data_set)\n torch.save(torch.tensor([[0, 0, 1], [1, 3, 5]]), ref_b_pt)\n with pytest.raises(ValueError, match=\"invalid boundaries\"):\n data.validate_spect_data_set(data_set)\n with pytest.warns(UserWarning):\n data.validate_spect_data_set(data_set, True) # will trim 5 to 4\n data.validate_spect_data_set(data_set)\n torch.save(torch.tensor([[0, 0, 1], [1, 4, 5]]), ref_b_pt)\n with pytest.raises(ValueError, match=\"invalid boundaries\"):\n data.validate_spect_data_set(data_set, True) # will not trim b/c causes s == e\n torch.save(torch.tensor([1, 2, 3]), ref_b_pt)\n with pytest.raises(ValueError, match=\"were 2D\"):\n data.validate_spect_data_set(data_set)\n torch.save(torch.tensor([10, 4, 2, 5]), ref_a_pt)\n data.validate_spect_data_set(data_set)\n\n\[email protected]\ndef test_validate_spect_data_set_cuda(temp_dir):\n torch.manual_seed(29)\n feat_dir = os.path.join(temp_dir, \"feat\")\n ali_dir = os.path.join(temp_dir, \"ali\")\n ref_dir = os.path.join(temp_dir, \"ref\")\n feats_pt = os.path.join(feat_dir, \"a.pt\")\n ali_pt = os.path.join(ali_dir, \"a.pt\")\n ref_pt = os.path.join(ref_dir, \"a.pt\")\n os.makedirs(feat_dir)\n os.makedirs(ali_dir)\n os.makedirs(ref_dir)\n torch.save(torch.rand(10, 5), feats_pt)\n torch.save(torch.randint(10, (10,), dtype=torch.long), ali_pt)\n torch.save(torch.tensor([1, 2, 3]), ref_pt)\n data_set = data.SpectDataSet(temp_dir)\n data.validate_spect_data_set(data_set)\n torch.save(torch.rand(10, 5).cuda(), feats_pt)\n with pytest.raises(ValueError, match=\"cuda\"):\n data.validate_spect_data_set(data_set)\n with pytest.warns(UserWarning):\n data.validate_spect_data_set(data_set, True) # to CPU\n data.validate_spect_data_set(data_set)\n torch.save(torch.rand(10, 5).cuda(), feats_pt)\n torch.save(torch.randint(10, (10,), dtype=torch.long).cuda(), ali_pt)\n torch.save(torch.tensor([1, 2, 3]).cuda(), ref_pt)\n with pytest.raises(ValueError, match=\"cuda\"):\n data.validate_spect_data_set(data_set)\n with pytest.warns(UserWarning):\n data.validate_spect_data_set(data_set, True) # to CPU\n data.validate_spect_data_set(data_set)\n\n\[email protected]\[email protected](\"processes\", [0, 2])\ndef test_read_trn(processes):\n trn = StringIO()\n trn.write(\n \"\"\"\\\nhere is a simple example (a)\nnothing should go wrong (b)\n\"\"\"\n )\n trn.seek(0)\n act = data.read_trn(trn, processes=processes, chunk_size=1)\n assert act == [\n (\"a\", [\"here\", \"is\", \"a\", \"simple\", \"example\"]),\n (\"b\", [\"nothing\", \"should\", \"go\", \"wrong\"]),\n ]\n trn.seek(0)\n trn.write(\n \"\"\"\\\nhere is an { example /with} some alternates (a)\n} and /here/ is {something really / {really}} (stupid) { ignore this (b)\n(c)\na11 (d)\n\"\"\"\n )\n trn.seek(0)\n act = data.read_trn(trn, warn=False, processes=processes)\n assert act == [\n (\n \"a\",\n [\n \"here\",\n \"is\",\n \"an\",\n ([[\"example\"], [\"with\"]], -1, -1),\n \"some\",\n \"alternates\",\n ],\n ),\n (\n \"b\",\n [\n \"}\",\n \"and\",\n \"/here/\",\n \"is\",\n ([[\"something\", \"really\"], [[[\"really\"]]]], -1, -1),\n \"(stupid)\",\n ],\n ),\n (\"c\", []),\n (\"d\", [\"a11\"]),\n ]\n\n\[email protected]\ndef test_read_ctm():\n ctm = StringIO()\n ctm.write(\n \"\"\"\\\nutt1 A 0.0 0.1 a\nutt1 A 0.5 0.1 c ;; ctm files should always be ordered, but we tolerate\n ;; different orders\nutt2 B 0.1 1.0 d\nutt1 B 0.4 0.3 b\n;; utt2 A 0.2 1.0 f\n\"\"\"\n )\n ctm.seek(0)\n act = data.read_ctm(ctm)\n assert act == [\n (\"utt1\", [(\"a\", 0.0, 0.1), (\"b\", 0.4, 0.7), (\"c\", 0.5, 0.6)]),\n (\"utt2\", [(\"d\", 0.1, 1.1)]),\n ]\n ctm.seek(0)\n act = data.read_ctm(\n ctm, {(\"utt1\", \"A\"): \"foo\", (\"utt1\", \"B\"): \"bar\", (\"utt2\", \"B\"): \"baz\"}\n )\n assert act == [\n (\"foo\", [(\"a\", 0.0, 0.1), (\"c\", 0.5, 0.6)]),\n (\"baz\", [(\"d\", 0.1, 1.1)]),\n (\"bar\", [(\"b\", 0.4, 0.7)]),\n ]\n with pytest.raises(ValueError):\n ctm.write(\"utt3 -0.1 1.0 woop\\n\")\n ctm.seek(0)\n data.read_ctm(ctm)\n\n\[email protected]\ndef test_write_trn():\n trn = StringIO()\n transcripts = [\n (\"a\", [\"again\", \"a\", \"simple\", \"example\"]),\n (\"b\", [\"should\", \"get\", \"right\", \"no\", \"prob\"]),\n ]\n data.write_trn(transcripts, trn)\n trn.seek(0)\n assert (\n \"\"\"\\\nagain a simple example (a)\nshould get right no prob (b)\n\"\"\"\n == trn.read()\n )\n trn.seek(0)\n trn.truncate()\n transcripts = [\n (\n \" c \",\n [\n (\"unnecessary\", -1, -1),\n ([[\"complexity\", [[\"can\"]]], [\"also\", \"be\"]], 10, 4),\n \"handled\",\n ],\n ),\n (\"d\", []),\n (\"e\", [\"a11\"]),\n ]\n data.write_trn(transcripts, trn)\n trn.seek(0)\n assert (\n \"\"\"\\\nunnecessary { complexity { can } / also be } handled ( c )\n(d)\na11 (e)\n\"\"\"\n == trn.read()\n )\n\n\[email protected]\ndef test_write_ctm():\n ctm = StringIO()\n transcripts = [\n (\n \"c\",\n [\n (\"here\", 0.1, 0.2),\n (\"are\", 0.3, 0.5),\n (\"some\", 0.2, 0.4),\n (\"unordered\", 0.5, 0.5),\n (\"tokens\", 10.0, 1000),\n ],\n ),\n (\"b\", []),\n (\"a\", [(\"hullo\", 0.0, 10.0111)]),\n ]\n data.write_ctm(transcripts, ctm)\n ctm.seek(0)\n assert (\n \"\"\"\\\na A 0.0 10.0111 hullo\nc A 0.1 0.1 here\nc A 0.2 0.2 some\nc A 0.3 0.2 are\nc A 0.5 0.0 unordered\nc A 10.0 990.0 tokens\n\"\"\"\n == ctm.read()\n )\n ctm.seek(0)\n ctm.truncate()\n data.write_ctm(\n transcripts,\n ctm,\n {\"a\": (\"last\", \"A\"), \"b\": (\"middle\", \"B\"), \"c\": (\"first\", \"C\")},\n )\n ctm.seek(0)\n assert (\n \"\"\"\\\nfirst C 0.1 0.1 here\nfirst C 0.2 0.2 some\nfirst C 0.3 0.2 are\nfirst C 0.5 0.0 unordered\nfirst C 10.0 990.0 tokens\nlast A 0.0 10.0111 hullo\n\"\"\"\n == ctm.read()\n )\n transcripts.append((\"foo\", [(\"a\", 0.1, 0.2), (\"b\", 0.2, 0.1)]))\n with pytest.raises(ValueError):\n data.write_ctm(transcripts, ctm)\n\n\[email protected]\[email protected](\n \"transcript,token2id,unk,skip_frame_times,exp\",\n [\n ([], None, None, False, torch.LongTensor(0, 3)),\n (\n [1, 2, 3, 4],\n None,\n None,\n True,\n torch.LongTensor([1, 2, 3, 4]),\n ),\n (\n [1, (\"a\", 4, 10), \"a\", 3],\n {\"a\": 2},\n None,\n False,\n torch.LongTensor([[1, -1, -1], [2, 4, 10], [2, -1, -1], [3, -1, -1]]),\n ),\n (\n [\"foo\", 1, \"bar\"],\n {\"foo\": 0, \"baz\": 3},\n \"baz\",\n False,\n torch.LongTensor([[0, -1, -1], [3, -1, -1], [3, -1, -1]]),\n ),\n ],\n)\ndef test_transcript_to_token(transcript, token2id, unk, skip_frame_times, exp):\n act = data.transcript_to_token(\n transcript, token2id, unk=unk, skip_frame_times=skip_frame_times\n )\n assert torch.all(exp == act)\n transcript = [\"foo\"] + transcript\n with pytest.raises(Exception):\n data.transcript_to_token(transcript, token2id)\n\n\[email protected]\ndef test_transcript_to_token_frame_shift():\n trans = [(12, 0.5, 0.81), 420, (1, 2.1, 2.2), (3, 2.8, 2.815), (12, 2.9, 3.0025)]\n # normal case: frame shift 10ms. Frame happens every hundredth of a second,\n # so multiply by 100. Half-frames should round up; quarter-frames down\n tok = data.transcript_to_token(trans, frame_shift_ms=10)\n assert torch.allclose(\n tok,\n torch.LongTensor(\n [[12, 50, 81], [420, -1, -1], [1, 210, 220], [3, 280, 282], [12, 290, 300]]\n ),\n )\n # raw case @ 8000Hz sample rate. \"Frame\" is every sample. frames/msec =\n # 1000 / sample_rate_hz = 1 / 8.\n tok = data.transcript_to_token(trans, frame_shift_ms=1 / 8)\n assert torch.allclose(\n tok,\n torch.LongTensor(\n [\n [12, 4000, 6480],\n [420, -1, -1],\n [1, 16800, 17600],\n [3, 22400, 22520],\n [12, 23200, 24020],\n ]\n ),\n )\n\n\[email protected]\[email protected](\n \"tok,id2token,exp\",\n [\n (torch.LongTensor(0, 3), None, []),\n (\n torch.LongTensor([[1, -1, -1], [2, -1, -1], [3, -1, -1], [4, -1, -1]]),\n None,\n [1, 2, 3, 4],\n ),\n (\n torch.LongTensor([[1, 3, 4], [3, 4, 5], [2, -1, -1]]),\n {1: \"a\", 2: \"b\"},\n [(\"a\", 3, 4), (3, 4, 5), \"b\"],\n ),\n (torch.tensor(range(10)), None, list(range(10))),\n (torch.tensor(range(5)).unsqueeze(-1), None, list(range(5))),\n ],\n)\ndef test_token_to_transcript(tok, id2token, exp):\n act = data.token_to_transcript(tok, id2token)\n assert exp == act\n\n\[email protected]\ndef test_token_to_transcript_frame_shift():\n tok = torch.LongTensor([[1, -1, 10], [2, 1000, 2000], [3, 12345, 678910]])\n # standard case: 10ms frame shift\n # 10ms per frame means divide frame number by 100\n trans = data.token_to_transcript(tok, frame_shift_ms=10)\n assert trans == [1, (2, 10.0, 20.0), (3, 123.45, 6789.10)]\n # raw case: 8000 samples / sec = 8 samples / msec so frame shift is 1 / 8\n trans = data.token_to_transcript(tok, frame_shift_ms=1 / 8)\n assert trans == [\n 1,\n (2, 1000 / 8000, 2000 / 8000),\n (3, 12345 / 8000, 678910 / 8000),\n ]\n\n\[email protected]\[email protected](\"reverse\", [True, False])\ndef test_context_window_data_set(temp_dir, reverse):\n torch.manual_seed(1)\n feat_dir = os.path.join(temp_dir, \"feat\")\n os.makedirs(feat_dir)\n a = torch.rand(2, 10)\n torch.save(a, os.path.join(feat_dir, \"a.pt\"))\n data_set = data.ContextWindowDataSet(temp_dir, 1, 1, reverse=reverse)\n windowed, _ = data_set[0]\n assert tuple(windowed.shape) == (2, 3, 10)\n if reverse:\n # [[a1, a0, a0], [a1, a1, a0]]\n assert torch.allclose(a[0], windowed[0, 1:])\n assert torch.allclose(a[1], windowed[0, 0])\n assert torch.allclose(a[0], windowed[1, 2])\n assert torch.allclose(a[1], windowed[1, :2])\n else:\n # [[a0, a0, a1], [a0, a1, a1]]\n assert torch.allclose(a[0], windowed[0, :2])\n assert torch.allclose(a[1], windowed[0, 2])\n assert torch.allclose(a[0], windowed[1, 0])\n assert torch.allclose(a[1], windowed[1, 1:])\n\n\[email protected]\ndef test_epoch_random_sampler(temp_dir):\n data_source = torch.utils.data.TensorDataset(torch.arange(100))\n sampler = data.EpochRandomSampler(data_source, base_seed=1)\n samples_ep0 = tuple(sampler)\n samples_ep1 = tuple(sampler)\n assert samples_ep0 != samples_ep1\n assert sorted(samples_ep0) == list(range(100))\n assert sorted(samples_ep1) == list(range(100))\n assert samples_ep0 == tuple(sampler.get_samples_for_epoch(0))\n assert samples_ep1 == tuple(sampler.get_samples_for_epoch(1))\n sampler = data.EpochRandomSampler(data_source, init_epoch=10, base_seed=1)\n assert samples_ep0 == tuple(sampler.get_samples_for_epoch(0))\n assert samples_ep1 == tuple(sampler.get_samples_for_epoch(1))\n # should be reproducible if we set torch manual seed\n torch.manual_seed(5)\n sampler = data.EpochRandomSampler(data_source)\n samples_ep0 = tuple(sampler)\n torch.manual_seed(5)\n sampler = data.EpochRandomSampler(data_source)\n assert samples_ep0 == tuple(sampler)\n\n\[email protected]\[email protected](\n \"feat_sizes\",\n [((3, 5, 4), (4, 5, 4), (1, 5, 4)), ((2, 10, 5),) * 10],\n ids=[\"short\", \"long\"],\n)\[email protected](\"include_ali\", [True, False])\ndef test_context_window_seq_to_batch(feat_sizes, include_ali):\n torch.manual_seed(1)\n feats = tuple(torch.rand(*x) for x in feat_sizes)\n if include_ali:\n alis = tuple(torch.randint(10, (x[0],), dtype=torch.long) for x in feat_sizes)\n else:\n alis = repeat(None)\n seq = zip(feats, alis)\n batch_feats, batch_ali = data.context_window_seq_to_batch(seq)\n assert torch.allclose(torch.cat(feats), batch_feats)\n if include_ali:\n assert torch.all(torch.cat(alis) == batch_ali)\n else:\n assert batch_ali is None\n\n\[email protected]\[email protected](\"include_ali\", [True, False])\[email protected](\n \"include_ref,include_frame_shift\", [(True, True), (True, False), (False, None)]\n)\[email protected](\"batch_first\", [True, False])\ndef test_spect_seq_to_batch(include_ali, include_ref, batch_first, include_frame_shift):\n torch.manual_seed(1)\n feat_sizes = tuple(\n torch.randint(1, 30, (1,)).item()\n for _ in range(torch.randint(3, 10, (1,)).item())\n )\n feats = tuple(torch.randn(x, 5) for x in feat_sizes)\n if include_ali:\n alis = tuple(torch.randint(100, (x,), dtype=torch.long) for x in feat_sizes)\n else:\n alis = repeat(None)\n if include_ref:\n ref_sizes = tuple(\n torch.randint(1, 30, (1,)).item() for _ in range(len(feat_sizes))\n )\n extra_dim = (3,) if include_frame_shift else tuple()\n refs = tuple(\n torch.randint(100, (x,) + extra_dim, dtype=torch.long) for x in ref_sizes\n )\n else:\n ref_sizes = repeat(None)\n refs = repeat(None)\n (\n batch_feats,\n batch_ali,\n batch_ref,\n batch_feat_sizes,\n batch_ref_sizes,\n ) = data.spect_seq_to_batch(zip(feats, alis, refs), batch_first=batch_first)\n feat_sizes, feats, alis, refs, ref_sizes = zip(\n *sorted(zip(feat_sizes, feats, alis, refs, ref_sizes), key=lambda x: -x[0])\n )\n assert torch.all(torch.tensor(feat_sizes) == batch_feat_sizes)\n if not batch_first:\n batch_feats = batch_feats.transpose(0, 1)\n if include_ali:\n batch_ali = batch_ali.transpose(0, 1)\n if include_ref:\n batch_ref = batch_ref.transpose(0, 1)\n assert all(\n torch.allclose(a[: b.shape[0]], b)\n and torch.allclose(a[b.shape[0] :], torch.tensor([0.0]))\n for (a, b) in zip(batch_feats, feats)\n )\n if include_ali:\n assert all(\n torch.all(a[: b.shape[0]] == b)\n and torch.all(a[b.shape[0] :] == torch.tensor([INDEX_PAD_VALUE]))\n for (a, b) in zip(batch_ali, alis)\n )\n else:\n assert batch_ali is None\n if include_ref:\n assert torch.all(torch.tensor(ref_sizes) == batch_ref_sizes)\n assert all(\n torch.all(a[: b.shape[0]] == b)\n and torch.all(a[b.shape[0] :] == torch.tensor([INDEX_PAD_VALUE]))\n for (a, b) in zip(batch_ref, refs)\n )\n else:\n assert batch_ref is None\n assert batch_ref_sizes is None\n\n\[email protected]\[email protected](\"eos\", [None, -1])\[email protected](\"sos\", [None, -2])\[email protected](\"split_params\", [True, False])\[email protected](\"include_frame_shift\", [True, False])\[email protected](\"feat_dtype\", [torch.float, torch.int])\ndef test_spect_training_data_loader(\n temp_dir,\n populate_torch_dir,\n sos,\n eos,\n split_params,\n include_frame_shift,\n feat_dtype,\n):\n torch.manual_seed(40)\n num_utts, batch_size, num_filts = 20, 5, 11\n populate_torch_dir(\n temp_dir,\n num_utts,\n num_filts=num_filts,\n include_frame_shift=include_frame_shift,\n feat_dtype=feat_dtype,\n )\n if split_params:\n params = data.DataSetParams(batch_size=batch_size)\n data_params = data.SpectDataParams(sos=sos, eos=eos)\n else:\n params = data.SpectDataSetParams(batch_size=batch_size, sos=sos, eos=eos)\n data_params = None\n # check missing either ali or ref gives None in batches\n data_loader = data.SpectTrainingDataLoader(\n temp_dir, params, data_params=data_params, ali_subdir=None, seed=2\n )\n assert next(iter(data_loader))[1] is None\n data_loader = data.SpectTrainingDataLoader(\n temp_dir, params, data_params=data_params, ref_subdir=None, seed=2\n )\n assert next(iter(data_loader))[2] is None\n assert next(iter(data_loader))[4] is None\n data_loader = data.SpectTrainingDataLoader(\n temp_dir, params, data_params=data_params, seed=2\n )\n\n def _get_epoch(sort):\n ep_feats, ep_ali, ep_ref = [], [], []\n ep_feat_sizes, ep_ref_sizes = [], []\n max_T = 0\n max_R = 0\n batch_first = data_loader.batch_first\n for b_feats, b_ali, b_ref, b_feat_sizes, b_ref_sizes in data_loader:\n if not batch_first:\n b_feats = b_feats.transpose(0, 1)\n b_ali = b_ali.transpose(0, 1)\n b_ref = b_ref.transpose(0, 1)\n max_T = max(max_T, b_feat_sizes[0])\n R_star = max(b_ref_sizes)\n max_R = max(max_R, R_star)\n assert b_feats.shape[0] == batch_size\n assert b_ali.shape[0] == batch_size\n assert b_ref.shape[0] == batch_size\n assert b_feats.shape[-1] == num_filts\n assert b_feats.shape[1] == b_feat_sizes[0]\n assert b_ali.shape[1] == b_feat_sizes[0]\n assert b_ref.shape[1] == R_star\n assert b_ref.dim() == (3 if include_frame_shift else 2)\n ep_feats += tuple(b_feats)\n ep_ali += tuple(b_ali)\n ep_ref += tuple(b_ref)\n ep_feat_sizes += tuple(b_feat_sizes)\n ep_ref_sizes += tuple(b_ref_sizes)\n assert len(ep_feats) == num_utts\n assert len(ep_ali) == num_utts\n for i in range(num_utts):\n ep_feats[i] = torch.nn.functional.pad(\n ep_feats[i], (0, 0, 0, max_T - ep_ali[i].shape[0])\n )\n ep_ali[i] = torch.nn.functional.pad(\n ep_ali[i], (0, max_T - ep_ali[i].shape[0]), value=INDEX_PAD_VALUE\n )\n if include_frame_shift:\n ep_ref[i] = torch.nn.functional.pad(\n ep_ref[i],\n (0, 0, 0, max_R - ep_ref[i].shape[0]),\n value=INDEX_PAD_VALUE,\n )\n else:\n ep_ref[i] = torch.nn.functional.pad(\n ep_ref[i], (0, max_R - ep_ref[i].shape[0]), value=INDEX_PAD_VALUE\n )\n if sort:\n ep_feats, ep_ali, ep_ref, ep_feat_sizes, ep_ref_sizes = zip(\n *sorted(\n zip(ep_feats, ep_ali, ep_ref, ep_feat_sizes, ep_ref_sizes),\n key=lambda x: (-x[3], -x[4], x[0][0, 0]),\n )\n )\n return ep_feats, ep_ali, ep_ref, ep_feat_sizes, ep_ref_sizes\n\n def _compare_epochs(ep_a, ep_b, same):\n a_feats, a_ali, a_ref, a_feat_sizes, a_ref_sizes = ep_a\n b_feats, b_ali, b_ref, b_feat_sizes, b_ref_sizes = ep_b\n a_feats, b_feats = torch.stack(a_feats), torch.stack(b_feats)\n a_ali, b_ali = torch.stack(a_ali), torch.stack(b_ali)\n a_ref, b_ref = torch.stack(a_ref), torch.stack(b_ref)\n if same:\n assert a_feat_sizes == b_feat_sizes\n assert a_ref_sizes == b_ref_sizes\n assert torch.allclose(a_feats, b_feats)\n assert torch.all(a_ali == b_ali)\n assert torch.all(a_ref == b_ref)\n else:\n assert a_feat_sizes != b_feat_sizes\n assert a_ref_sizes != b_ref_sizes\n assert not torch.allclose(a_feats, b_feats)\n assert torch.any(a_ali != b_ali)\n assert torch.any(a_ref != b_ref)\n\n ep0 = _get_epoch(False)\n ep1 = _get_epoch(False)\n _compare_epochs(ep0, ep1, False) # could be same by fluke\n _compare_epochs(_get_epoch(True), _get_epoch(True), True)\n data_loader.epoch = 1\n _compare_epochs(ep1, _get_epoch(False), True)\n # XXX(sdrobert): warning spit out on CI if num_workers > 2\n data_loader = data.SpectTrainingDataLoader(\n temp_dir, params, data_params=data_params, num_workers=2, seed=2\n )\n _compare_epochs(ep0, _get_epoch(False), True)\n _compare_epochs(ep1, _get_epoch(False), True)\n data_loader.batch_first = False\n data_loader.epoch = 0\n _compare_epochs(ep0, _get_epoch(False), True)\n _compare_epochs(ep1, _get_epoch(False), True)\n\n\[email protected]\[email protected](\"eos\", [None, -1])\[email protected](\"sos\", [None, -2])\[email protected](\"split_params\", [True, False])\[email protected](\"include_frame_shift\", [True, False])\[email protected](\"feat_dtype\", [torch.float, torch.int])\ndef test_spect_evaluation_data_loader(\n temp_dir,\n populate_torch_dir,\n sos,\n eos,\n split_params,\n include_frame_shift,\n feat_dtype,\n):\n torch.manual_seed(41)\n feat_dir = os.path.join(temp_dir, \"feat\")\n ali_dir = os.path.join(temp_dir, \"ali\")\n os.makedirs(feat_dir)\n os.makedirs(ali_dir)\n batch_size = 5\n if split_params:\n params = data.DataSetParams(batch_size=batch_size)\n data_params = data.SpectDataParams(sos=sos, eos=eos)\n else:\n params = data.SpectDataSetParams(batch_size=batch_size, sos=sos, eos=eos)\n data_params = None\n feats, ali, ref, feat_sizes, ref_sizes, utt_ids = populate_torch_dir(\n temp_dir, 20, include_frame_shift=include_frame_shift, feat_dtype=feat_dtype\n )\n if sos is not None:\n if include_frame_shift:\n sos_sym = torch.full((3,), -1, dtype=torch.long)\n sos_sym[0] = sos\n sos_sym = sos_sym.unsqueeze(0)\n else:\n sos_sym = torch.full((1,), sos, dtype=torch.long)\n ref = [torch.cat([sos_sym, x], 0) for x in ref]\n ref_sizes = [x + 1 for x in ref_sizes]\n if eos is not None:\n if include_frame_shift:\n eos_sym = torch.full((3,), eos, dtype=torch.long)\n eos_sym[0] = eos\n eos_sym = eos_sym.unsqueeze(0)\n else:\n eos_sym = torch.full((1,), eos, dtype=torch.long)\n ref = [torch.cat([x, eos_sym], 0) for x in ref]\n ref_sizes = [x + 1 for x in ref_sizes]\n # check that ali and ref can be missing\n data_loader = data.SpectEvaluationDataLoader(\n temp_dir, params, data_params=data_params, ali_subdir=None, ref_subdir=None\n )\n assert next(iter(data_loader))[1:3] == (None, None)\n assert next(iter(data_loader))[4] is None\n data_loader = data.SpectEvaluationDataLoader(\n temp_dir, params, data_params=data_params\n )\n\n def _compare_data_loader():\n batch_first = data_loader.batch_first\n assert len(data_loader) == 4\n cur_idx = 0\n for (\n b_feats,\n b_ali,\n b_ref,\n b_feat_sizes,\n b_ref_sizes,\n b_utt_ids,\n ) in data_loader:\n if not batch_first:\n b_feats = b_feats.transpose(0, 1)\n b_ali = b_ali.transpose(0, 1)\n b_ref = b_ref.transpose(0, 1)\n R_star = max(b_ref_sizes)\n assert tuple(b_feats.shape) == (5, b_feat_sizes[0], 5)\n assert tuple(b_ali.shape) == (5, b_feat_sizes[0])\n if include_frame_shift:\n assert tuple(b_ref.shape) == (5, R_star, 3)\n else:\n assert tuple(b_ref.shape) == (5, R_star)\n # sort the sub-section of the master list by feature size\n s_feats, s_ali, s_ref, s_feat_sizes, s_ref_sizes, s_utt_ids = zip(\n *sorted(\n zip(\n feats[cur_idx : cur_idx + 5],\n ali[cur_idx : cur_idx + 5],\n ref[cur_idx : cur_idx + 5],\n feat_sizes[cur_idx : cur_idx + 5],\n ref_sizes[cur_idx : cur_idx + 5],\n utt_ids[cur_idx : cur_idx + 5],\n ),\n key=lambda x: -x[3],\n )\n )\n assert b_utt_ids == s_utt_ids\n assert tuple(b_feat_sizes) == s_feat_sizes\n assert tuple(b_ref_sizes) == s_ref_sizes\n for a, b in zip(b_feats, s_feats):\n assert torch.allclose(a[: b.shape[0]], b)\n assert torch.allclose(\n a[b.shape[0] :], torch.tensor([0], dtype=feat_dtype)\n )\n for a, b in zip(b_ali, s_ali):\n assert torch.all(a[: b.shape[0]] == b)\n assert torch.all(a[b.shape[0] :] == torch.tensor([INDEX_PAD_VALUE]))\n for a, b in zip(b_ref, s_ref):\n assert torch.all(a[: b.shape[0]] == b)\n assert torch.all(a[b.shape[0] :] == torch.tensor([INDEX_PAD_VALUE]))\n cur_idx += 5\n\n _compare_data_loader()\n _compare_data_loader() # order should not change\n data_loader = data.SpectEvaluationDataLoader(\n temp_dir, params, data_params=data_params, num_workers=2\n )\n _compare_data_loader() # order should still not change\n data_loader.batch_first = False\n _compare_data_loader()\n\n\[email protected]\[email protected](\"split_params\", [True, False])\ndef test_window_training_data_loader(temp_dir, populate_torch_dir, split_params):\n populate_torch_dir(temp_dir, 5, num_filts=2)\n seed, batch_size, context_left, context_right = 2, 5, 1, 1\n if split_params:\n params = data.DataSetParams(batch_size=batch_size, drop_last=True)\n data_params = data.ContextWindowDataParams(\n context_left=context_left, context_right=context_right\n )\n else:\n params = data.ContextWindowDataSetParams(\n context_left=context_left,\n context_right=context_right,\n batch_size=batch_size,\n drop_last=True,\n )\n data_params = None\n data_loader = data.ContextWindowTrainingDataLoader(\n temp_dir, params, data_params=data_params, seed=seed\n )\n total_windows_ep0 = 0\n for feat, ali in data_loader:\n windows = feat.shape[0]\n assert tuple(feat.shape) == (windows, 3, 2)\n assert tuple(ali.shape) == (windows,)\n total_windows_ep0 += windows\n assert total_windows_ep0 >= batch_size\n feats_ep1_a, alis_ep1_a = [], []\n total_windows_ep1 = 0\n for feats, alis in data_loader:\n windows = feat.shape[0]\n assert tuple(feat.shape) == (windows, 3, 2)\n assert tuple(ali.shape) == (windows,)\n feats_ep1_a.append(feats)\n alis_ep1_a.append(alis)\n total_windows_ep1 += windows\n assert total_windows_ep0 == total_windows_ep1\n data_loader = data.ContextWindowTrainingDataLoader(\n temp_dir,\n params,\n init_epoch=1,\n data_params=data_params,\n num_workers=2,\n seed=seed,\n )\n feats_ep1_b, alis_ep1_b = [], []\n for feats, alis in data_loader:\n feats_ep1_b.append(feats)\n alis_ep1_b.append(alis)\n assert all(\n torch.allclose(feats_a, feats_b)\n for (feats_a, feats_b) in zip(feats_ep1_a, feats_ep1_b)\n )\n assert all(\n torch.all(alis_a == alis_b) for (alis_a, alis_b) in zip(alis_ep1_a, alis_ep1_b)\n )\n data_loader.epoch = 1\n feats_ep1_c, alis_ep1_c = [], []\n for feats, alis in data_loader:\n feats_ep1_c.append(feats)\n alis_ep1_c.append(alis)\n assert all(\n torch.allclose(feats_a, feats_c)\n for (feats_a, feats_c) in zip(feats_ep1_a, feats_ep1_c)\n )\n assert all(\n torch.all(alis_a == alis_c) for (alis_a, alis_c) in zip(alis_ep1_a, alis_ep1_c)\n )\n\n\[email protected]\[email protected](\"split_params\", [True, False])\ndef test_window_evaluation_data_loader(temp_dir, populate_torch_dir, split_params):\n torch.manual_seed(1)\n feat_dir = os.path.join(temp_dir, \"feat\")\n ali_dir = os.path.join(temp_dir, \"ali\")\n os.makedirs(feat_dir)\n os.makedirs(ali_dir)\n if split_params:\n params = data.DataSetParams(batch_size=5)\n data_params = data.ContextWindowDataParams(context_left=1, context_right=1)\n else:\n params = data.ContextWindowDataSetParams(\n context_left=1, context_right=1, batch_size=5\n )\n data_params = None\n feats, alis, _, feat_sizes, _, utt_ids = populate_torch_dir(\n temp_dir, 20, include_ref=False\n )\n\n def _compare_data_loader(data_loader):\n assert len(data_loader) == 4\n cur_idx = 0\n for b_feats, b_alis, b_feat_sizes, b_utt_ids in data_loader:\n assert tuple(b_feats.shape[1:]) == (3, 5)\n assert b_feats.shape[0] == sum(b_feat_sizes)\n assert tuple(b_utt_ids) == tuple(utt_ids[cur_idx : cur_idx + 5])\n assert torch.allclose(\n b_feats[:, 1], torch.cat(feats[cur_idx : cur_idx + 5])\n )\n assert torch.all(b_alis == torch.cat(alis[cur_idx : cur_idx + 5]))\n cur_idx += 5\n\n data_loader = data.ContextWindowEvaluationDataLoader(\n temp_dir, params, data_params=data_params, ali_subdir=None\n )\n # check batching works when alignments are empty\n assert next(iter(data_loader))[1] is None\n data_loader = data.ContextWindowEvaluationDataLoader(\n temp_dir, params, data_params=data_params\n )\n _compare_data_loader(data_loader)\n _compare_data_loader(data_loader) # order should not change\n data_loader = data.ContextWindowEvaluationDataLoader(\n temp_dir, params, data_params=data_params, num_workers=2\n )\n _compare_data_loader(data_loader) # order should still not change\n\n\[email protected]\ndef test_pydrobert_param_optuna_hooks():\n poptuna = pytest.importorskip(\"pydrobert.param.optuna\")\n optuna = pytest.importorskip(\"optuna\")\n for class_ in (\n data.DataSetParams,\n data.SpectDataSetParams,\n data.ContextWindowDataParams,\n data.ContextWindowDataSetParams,\n ):\n assert issubclass(class_, poptuna.TunableParameterized)\n global_dict = {\n \"data_set\": data.DataSetParams(),\n \"spect_data\": data.SpectDataParams(),\n \"spect_data_set\": data.SpectDataSetParams(),\n \"context_window_data\": data.ContextWindowDataParams(),\n \"context_window_data_set\": data.ContextWindowDataSetParams(),\n }\n assert {\n \"data_set.batch_size\",\n \"spect_data.eos\",\n \"spect_data_set.batch_size\",\n \"context_window_data.reverse\",\n \"context_window_data_set.batch_size\",\n } - poptuna.get_param_dict_tunable(global_dict) == {\"spect_data.eos\"}\n\n def objective(trial):\n param_dict = poptuna.suggest_param_dict(trial, global_dict)\n return param_dict[\"data_set\"].batch_size\n\n sampler = optuna.samplers.RandomSampler(seed=5)\n study = optuna.create_study(sampler=sampler)\n study.optimize(objective, n_trials=10)\n assert (\n not {\n \"data_set.batch_size\",\n \"spect_data_set.batch_size\",\n \"context_window_data.reverse\",\n \"context_window_data_set.batch_size\",\n }\n - set(study.best_params)\n )\n assert study.best_params[\"data_set.batch_size\"] < 7\n", "# Copyright 2021 Sean Robertson\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 os\nimport sys\nimport argparse\nimport math\nfrom typing import Optional, Sequence\nimport warnings\nimport itertools\n\nfrom collections import defaultdict, OrderedDict\n\nimport torch\nimport pydrobert.torch.data as data\nimport pydrobert.torch.util as util\n\n__author__ = \"Sean Robertson\"\n__email__ = \"[email protected]\"\n__license__ = \"Apache 2.0\"\n__copyright__ = \"Copyright 2019 Sean Robertson\"\n__all__ = [\n \"compute_torch_token_data_dir_error_rates\",\n \"ctm_to_torch_token_data_dir\",\n \"get_torch_spect_data_dir_info\",\n \"torch_token_data_dir_to_ctm\",\n \"torch_token_data_dir_to_trn\",\n \"trn_to_torch_token_data_dir\",\n]\n\n\ndef _get_torch_spect_data_dir_info_parse_args(args):\n parser = argparse.ArgumentParser(description=get_torch_spect_data_dir_info.__doc__,)\n parser.add_argument(\"dir\", type=str, help=\"The torch data directory\")\n parser.add_argument(\n \"out_file\",\n nargs=\"?\",\n type=argparse.FileType(\"w\"),\n default=sys.stdout,\n help=\"The file to write to. If unspecified, stdout\",\n )\n parser.add_argument(\n \"--file-prefix\", default=\"\", help=\"The file prefix indicating a torch data file\"\n )\n parser.add_argument(\n \"--file-suffix\",\n default=\".pt\",\n help=\"The file suffix indicating a torch data file\",\n )\n parser.add_argument(\n \"--feat-subdir\", default=\"feat\", help=\"Subdirectory where features are stored\"\n )\n parser.add_argument(\n \"--ali-subdir\", default=\"ali\", help=\"Subdirectory where alignments are stored\"\n )\n parser.add_argument(\n \"--ref-subdir\",\n default=\"ref\",\n help=\"Subdirectory where reference token sequences are stored\",\n )\n\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--strict\",\n action=\"store_true\",\n default=False,\n help=\"If set, validate the data directory before collecting info. The \"\n \"process is described in pydrobert.torch.data.validate_spect_data_set\",\n )\n group.add_argument(\n \"--fix\",\n action=\"store_true\",\n default=False,\n help=\"If set, validate the data directory before collecting info, potentially \"\n \"fixing small errors in the directory. The process is described in \"\n \"pydrobert.torch.validate_spect_data_set\",\n )\n\n return parser.parse_args(args)\n\n\ndef get_torch_spect_data_dir_info(args: Optional[Sequence[str]] = None) -> None:\n \"\"\"Write info about the specified SpectDataSet data dir\n\n A torch :class:`pydrobert.torch.data.SpectDataSet` data dir is of the\n form::\n\n dir/\n feat/\n <file_prefix><utt1><file_suffix>\n <file_prefix><utt2><file_suffix>\n ...\n [ali/\n <file_prefix><utt1><file_suffix>\n <file_prefix><utt1><file_suffix>\n ...\n ]\n [ref/\n <file_prefix><utt1><file_suffix>\n <file_prefix><utt1><file_suffix>\n ...\n ]\n\n Where ``feat`` contains float :class:`torch.Tensor`s of shape ``(N, F)``, where\n ``N`` is the number of frames (variable) and ``F`` is the number of filters (fixed),\n ``ali``, if there, contains long :class:`torch.Tensor`s of shape ``(N,)`` indicating\n the appropriate class labels (likely pdf-ids for discriminative training in an\n DNN-HMM), and ``ref``, if there, contains long :class:`torch.Tensor`s of shape\n ``(R, 3)`` indicating a sequence of reference tokens where element indexed by ``[i,\n 0]`` is a token id, ``[i, 1]`` is the inclusive start frame of the token (or a\n negative value if unknown), and ``[i, 2]`` is the exclusive end frame of the token.\n\n This command writes the following space-delimited key-value pairs to an\n output file in sorted order:\n\n 1. \"max_ali_class\", the maximum inclusive class id found over ``ali/``\n (if available, ``-1`` if not)\n 2. \"max_ref_class\", the maximum inclussive class id found over ``ref/``\n (if available, ``-1`` if not)\n 3. \"num_utterances\", the total number of listed utterances\n 4. \"num_filts\", ``F``\n 5. \"total_frames\", ``sum(N)`` over the data dir\n 6. \"count_<i>\", the number of instances of the class \"<i>\" that appear in ``ali``\n (if available). If \"count_<i>\" is a valid key, then so are \"count_<0 to i>\".\n \"count_<i>\" is left-padded with zeros to ensure that the keys remain in the same\n order in the table as the class indices. The maximum ``i`` will be equal to\n ``maximum_ali_class``\n\n Note that the output can be parsed as a `Kaldi <http://kaldi-asr.org/>`__ text table\n of integers.\n \"\"\"\n try:\n options = _get_torch_spect_data_dir_info_parse_args(args)\n except SystemExit as ex:\n return ex.code\n if not os.path.isdir(options.dir):\n print(\"'{}' is not a directory\".format(options.dir), file=sys.stderr)\n return 1\n data_set = data.SpectDataSet(\n options.dir,\n file_prefix=options.file_prefix,\n file_suffix=options.file_suffix,\n feat_subdir=options.feat_subdir,\n ali_subdir=options.ali_subdir,\n ref_subdir=options.ref_subdir,\n )\n if options.strict or options.fix:\n data.validate_spect_data_set(data_set, options.fix)\n info_dict = {\n \"num_utterances\": len(data_set),\n \"total_frames\": 0,\n \"max_ali_class\": -1,\n \"max_ref_class\": -1,\n }\n counts = dict()\n for feat, ali, ref in data_set:\n info_dict[\"num_filts\"] = feat.size()[1]\n info_dict[\"total_frames\"] += feat.size()[0]\n if ali is not None:\n for class_idx in ali:\n class_idx = class_idx.item()\n if class_idx < 0:\n raise ValueError(\"Got a negative ali class idx\")\n info_dict[\"max_ali_class\"] = max(class_idx, info_dict[\"max_ali_class\"])\n counts[class_idx] = counts.get(class_idx, 0) + 1\n if ref is not None:\n ref = ref[..., 0]\n if ref.min().item() < 0:\n raise ValueError(\"Got a negative ref class idx\")\n info_dict[\"max_ref_class\"] = max(\n info_dict[\"max_ref_class\"], ref.max().item()\n )\n if info_dict[\"max_ali_class\"] == 0:\n info_dict[\"count_0\"] = counts[0]\n elif info_dict[\"max_ali_class\"] > 0:\n count_fmt_str = \"count_{{:0{}d}}\".format(\n int(math.log10(info_dict[\"max_ali_class\"])) + 1\n )\n for class_idx in range(info_dict[\"max_ali_class\"] + 1):\n info_dict[count_fmt_str.format(class_idx)] = counts.get(class_idx, 0)\n info_list = sorted(info_dict.items())\n for key, value in info_list:\n options.out_file.write(\"{} {}\\n\".format(key, value))\n if options.out_file != sys.stdout:\n options.out_file.close()\n return 0\n\n\ndef _trn_to_torch_token_data_dir_parse_args(args):\n parser = argparse.ArgumentParser(description=trn_to_torch_token_data_dir.__doc__,)\n parser.add_argument(\"trn\", type=argparse.FileType(\"r\"), help=\"The input trn file\")\n parser.add_argument(\n \"token2id\",\n type=argparse.FileType(\"r\"),\n help=\"A file containing mappings from tokens (e.g. words or phones) \"\n \"to unique IDs. Each line has the format ``<token> <id>``. The flag \"\n \"``--swap`` can be used to swap the expected ordering (i.e. \"\n \"``<id> <token>``)\",\n )\n parser.add_argument(\n \"dir\",\n help=\"The directory to store token sequences to. If the directory \"\n \"does not exist, it will be created\",\n )\n parser.add_argument(\n \"--alt-handler\",\n default=\"error\",\n choices=(\"error\", \"first\"),\n help='How to handle transcription alternates. If \"error\", error if '\n 'the \"trn\" file contains alternates. If \"first\", always treat the '\n \"alternate as canon\",\n )\n parser.add_argument(\n \"--file-prefix\", default=\"\", help=\"The file prefix indicating a torch data file\"\n )\n parser.add_argument(\n \"--file-suffix\",\n default=\".pt\",\n help=\"The file suffix indicating a torch data file\",\n )\n parser.add_argument(\n \"--swap\",\n action=\"store_true\",\n default=False,\n help=\"If set, swaps the order of key and value in `token2id`\",\n )\n parser.add_argument(\n \"--unk-symbol\",\n default=None,\n help=\"If set, will map out-of-vocabulary tokens to this symbol\",\n )\n parser.add_argument(\n \"--num-workers\",\n type=int,\n default=torch.multiprocessing.cpu_count(),\n help=\"The number of workers to spawn to process the data. 0 is serial.\"\n \" Defaults to the cpu count\",\n )\n parser.add_argument(\n \"--chunk-size\",\n type=int,\n default=1000,\n help=\"The number of lines that a worker will process at once. Impacts \"\n \"speed and memory consumption.\",\n )\n size_group = parser.add_mutually_exclusive_group()\n size_group.add_argument(\n \"--skip-frame-times\",\n action=\"store_true\",\n default=False,\n help=\"If true, will store token tensors of shape (R,) instead of \"\n \"(R, 3), foregoing segment start and end times (which trn does not \"\n \"have).\",\n )\n size_group.add_argument(\n \"--feat-sizing\",\n action=\"store_true\",\n default=False,\n help=\"If true, will store token tensors of shape (R, 1) instead of \"\n \"(R, 3), foregoing segment start and end times (which trn does not \"\n \"have). The extra dimension will allow data in this directory to be \"\n \"loaded as features in a SpectDataSet.\",\n )\n return parser.parse_args(args)\n\n\ndef _parse_token2id(file, swap, return_swap):\n ret = dict()\n ret_swapped = dict()\n for line_no, line in enumerate(file):\n line = line.strip()\n if not line:\n continue\n ls = line.split()\n if len(ls) != 2 or not ls[1 - int(swap)].lstrip(\"-\").isdigit():\n raise ValueError(\n \"Cannot parse line {} of {}\".format(line_no + 1, file.name)\n )\n key, value = ls\n key, value = (int(key), value) if swap else (key, int(value))\n if key in ret:\n warnings.warn(\n '{} line {}: \"{}\" already exists. Mapping will be ambiguous'\n \"\".format(file.name, line_no + 1, key)\n )\n if value in ret_swapped:\n warnings.warn(\n '{} line {}: \"{}\" already exists. Mapping will be ambiguous'\n \"\".format(file.name, line_no + 1, value)\n )\n ret[key] = value\n ret_swapped[value] = key\n return ret_swapped if return_swap else ret\n\n\ndef _save_transcripts_to_dir_worker(\n token2id,\n file_prefix,\n file_suffix,\n dir_,\n frame_shift_ms,\n unk,\n skip_frame_times,\n feat_sizing,\n queue,\n first_timeout=30,\n rest_timeout=10,\n):\n transcripts = queue.get(True, first_timeout)\n while transcripts is not None:\n for utt_id, transcript in transcripts:\n tok = data.transcript_to_token(\n transcript,\n token2id,\n frame_shift_ms,\n unk,\n skip_frame_times or feat_sizing,\n )\n if feat_sizing:\n tok = tok.unsqueeze(-1)\n path = os.path.join(dir_, file_prefix + utt_id + file_suffix)\n torch.save(tok, path)\n transcripts = queue.get(True, rest_timeout)\n\n\ndef _save_transcripts_to_dir(\n transcripts,\n token2id,\n file_prefix,\n file_suffix,\n dir_,\n frame_shift_ms=None,\n unk=None,\n skip_frame_times=False,\n feat_sizing=False,\n num_workers=0,\n chunk_size=1000,\n):\n if not os.path.isdir(dir_):\n os.makedirs(dir_)\n if num_workers:\n queue = torch.multiprocessing.Queue(num_workers)\n try:\n with torch.multiprocessing.Pool(\n num_workers,\n _save_transcripts_to_dir_worker,\n (\n token2id,\n file_prefix,\n file_suffix,\n dir_,\n frame_shift_ms,\n unk,\n skip_frame_times,\n feat_sizing,\n queue,\n ),\n ) as pool:\n chunk = tuple(itertools.islice(transcripts, chunk_size))\n while len(chunk):\n queue.put(chunk)\n chunk = tuple(itertools.islice(transcripts, chunk_size))\n for _ in range(num_workers):\n queue.put(None)\n pool.close()\n pool.join()\n except AttributeError: # 2.7\n pool = torch.multiprocessing.Pool(\n num_workers,\n _save_transcripts_to_dir_worker,\n (\n token2id,\n file_prefix,\n file_suffix,\n dir_,\n frame_shift_ms,\n unk,\n skip_frame_times,\n queue,\n ),\n )\n try:\n chunk = tuple(itertools.islice(transcripts, chunk_size))\n while len(chunk):\n queue.put(chunk)\n chunk = tuple(itertools.islice(transcripts, chunk_size))\n for _ in range(num_workers):\n queue.put(None)\n pool.close()\n pool.join()\n finally:\n pool.terminate()\n else:\n for utt_id, transcript in transcripts:\n tok = data.transcript_to_token(\n transcript,\n token2id,\n frame_shift_ms,\n unk,\n skip_frame_times or feat_sizing,\n )\n if feat_sizing:\n tok = tok.unsqueeze(-1)\n path = os.path.join(dir_, file_prefix + utt_id + file_suffix)\n torch.save(tok, path)\n\n\ndef trn_to_torch_token_data_dir(args: Optional[Sequence[str]] = None) -> None:\n \"\"\"Convert a NIST \"trn\" file to the specified SpectDataSet data dir\n\n A \"trn\" file is the standard transcription file without alignment information used\n in the `sclite <http://www1.icsi.berkeley.edu/Speech/docs/sctk-1.2/sclite.htm>`__\n toolkit. It has the format::\n\n here is a transcription (utterance_a)\n here is another (utterance_b)\n\n This command reads in a \"trn\" file and writes its contents as token sequences\n compatible with the ``ref/`` directory of a\n :class:`pydrobert.torch.data.SpectDataSet`. See the command\n :func:`get_torch_spect_data_dir_info` (command line \"get-torch-spect-data-dir-info\")\n for more information on a :class:`pydrobert.torch.data.SpectDataSet`\n \"\"\"\n try:\n options = _trn_to_torch_token_data_dir_parse_args(args)\n except SystemExit as ex:\n return ex.code\n token2id = _parse_token2id(options.token2id, options.swap, options.swap)\n if options.unk_symbol is not None and options.unk_symbol not in token2id:\n print(\n 'Unk symbol \"{}\" is not in token2id'.format(options.unk_symbol),\n file=sys.stderr,\n )\n return 1\n # we're going to do all the threading on the tensor creation part of\n # things\n transcripts = data.read_trn_iter(options.trn)\n\n def error_handling_iter():\n for utt_id, transcript in transcripts:\n old_transcript = transcript[:]\n transcript[:] = []\n while len(old_transcript):\n x = old_transcript.pop(0)\n if len(x) == 3 and x[1] == -1:\n x = x[0]\n if isinstance(x, str):\n transcript.append(x)\n elif options.alt_handler == \"error\":\n raise ValueError('Cannot handle alternate in \"{}\"'.format(utt_id))\n else: # first\n x[0].extend(old_transcript)\n old_transcript = x[0]\n yield utt_id, transcript\n\n _save_transcripts_to_dir(\n error_handling_iter(),\n token2id,\n options.file_prefix,\n options.file_suffix,\n options.dir,\n unk=options.unk_symbol,\n skip_frame_times=options.skip_frame_times,\n feat_sizing=options.feat_sizing,\n num_workers=options.num_workers,\n chunk_size=options.chunk_size,\n )\n return 0\n\n\ndef _torch_token_data_dir_to_trn_parse_args(args):\n parser = argparse.ArgumentParser(description=torch_token_data_dir_to_trn.__doc__)\n parser.add_argument(\"dir\", help=\"The directory to read token sequences from\")\n parser.add_argument(\n \"id2token\",\n type=argparse.FileType(\"r\"),\n help=\"A file containing the mappings from unique IDs to tokens (e.g. \"\n \"words or phones). Each line has the format ``<id> <token>``. The \"\n \"flag ``--swap`` can be used to swap the expected ordering (i.e. \"\n \"``<token> <id>``)\",\n )\n parser.add_argument(\n \"trn\",\n type=argparse.FileType(\"w\"),\n help='The \"trn\" file to write transcriptions to',\n )\n parser.add_argument(\n \"--file-prefix\", default=\"\", help=\"The file prefix indicating a torch data file\"\n )\n parser.add_argument(\n \"--file-suffix\",\n default=\".pt\",\n help=\"The file suffix indicating a torch data file\",\n )\n parser.add_argument(\n \"--swap\",\n action=\"store_true\",\n default=False,\n help=\"If set, swaps the order of key and value in `id2token`\",\n )\n parser.add_argument(\n \"--num-workers\",\n type=int,\n default=torch.multiprocessing.cpu_count(),\n help=\"The number of workers to spawn to process the data. 0 is serial.\"\n \" Defaults to the cpu count\",\n )\n return parser.parse_args(args)\n\n\nclass _TranscriptDataSet(torch.utils.data.Dataset):\n def __init__(\n self, dir_, id2token, file_prefix, file_suffix, frame_shift_ms, strip_timing\n ):\n super(_TranscriptDataSet, self).__init__()\n fpl = len(file_prefix)\n neg_fsl = -len(file_suffix)\n self.utt_ids = sorted(\n x[fpl:neg_fsl]\n for x in os.listdir(dir_)\n if x.startswith(file_prefix) and x.endswith(file_suffix)\n )\n self.dir_ = dir_\n self.file_prefix = file_prefix\n self.file_suffix = file_suffix\n self.id2token = id2token\n self.frame_shift_ms = frame_shift_ms\n self.strip_timing = strip_timing\n\n def __getitem__(self, index):\n utt_id = self.utt_ids[index]\n tok = torch.load(\n os.path.join(self.dir_, self.file_prefix + utt_id + self.file_suffix)\n )\n transcript = data.token_to_transcript(tok, self.id2token, self.frame_shift_ms)\n for idx in range(len(transcript)):\n token = transcript[idx]\n if isinstance(token, tuple):\n token = token[0]\n if self.strip_timing:\n transcript[idx] = token\n if isinstance(token, int) and self.id2token is not None:\n assert token not in self.id2token\n raise ValueError(\n 'Utterance \"{}\": ID \"{}\" could not be found in id2token'\n \"\".format(utt_id, token)\n )\n return utt_id, transcript\n\n def __len__(self):\n return len(self.utt_ids)\n\n\ndef _noop_collate(x):\n return x[0]\n\n\ndef _load_transcripts_from_data_dir(\n dir_,\n id2token,\n file_prefix,\n file_suffix,\n frame_shift_ms=None,\n strip_timing=False,\n num_workers=0,\n):\n ds = _TranscriptDataSet(\n dir_, id2token, file_prefix, file_suffix, frame_shift_ms, strip_timing\n )\n dl = torch.utils.data.DataLoader(\n ds, batch_size=1, num_workers=num_workers, collate_fn=_noop_collate\n )\n for utt_ids, transcripts in dl:\n yield utt_ids, transcripts\n del dl, ds\n\n\ndef torch_token_data_dir_to_trn(args: Optional[Sequence[str]] = None) -> None:\n \"\"\"Convert a SpectDataSet token data dir to a NIST trn file\n\n A \"trn\" file is the standard transcription file without alignment information used\n in the `sclite <http://www1.icsi.berkeley.edu/Speech/docs/sctk-1.2/sclite.htm>`_\n toolkit. It has the format::\n\n here is a transcription (utterance_a)\n here is another (utterance_b)\n\n This command scans the contents of a directory like ``ref/`` in a\n :class:`pydrobert.torch.data.SpectDataSet` and converts each such file into a\n transcription. Each such transcription is then written to a \"trn\" file. See the\n command :func:`get_torch_spect_data_dir_info` (command line\n \"get-torch-spect-data-dir-info\") for more information on a\n :class:`pydrobert.torch.data.SpectDataSet`.\n \"\"\"\n try:\n options = _torch_token_data_dir_to_trn_parse_args(args)\n except SystemExit as ex:\n return ex.code\n if not os.path.isdir(options.dir):\n print('\"{}\" is not a directory'.format(options.dir), file=sys.stderr)\n return 1\n id2token = _parse_token2id(options.id2token, not options.swap, options.swap)\n transcripts = _load_transcripts_from_data_dir(\n options.dir,\n id2token,\n options.file_prefix,\n options.file_suffix,\n strip_timing=True,\n num_workers=options.num_workers,\n )\n data.write_trn(transcripts, options.trn)\n return 0\n\n\ndef _ctm_to_torch_token_data_dir_parse_args(args):\n parser = argparse.ArgumentParser(description=ctm_to_torch_token_data_dir.__doc__)\n parser.add_argument(\n \"ctm\",\n type=argparse.FileType(\"r\"),\n help='The \"ctm\" file to read token segments from',\n )\n parser.add_argument(\n \"token2id\",\n type=argparse.FileType(\"r\"),\n help=\"A file containing mappings from tokens (e.g. words or phones) \"\n \"to unique IDs. Each line has the format ``<token> <id>``. The flag \"\n \"``--swap`` can be used to swap the expected ordering (i.e. \"\n \"``<id> <token>``)\",\n )\n parser.add_argument(\n \"dir\",\n help=\"The directory to store token sequences to. If the \"\n \"directory does not exist, it will be created\",\n )\n parser.add_argument(\n \"--file-prefix\", default=\"\", help=\"The file prefix indicating a torch data file\"\n )\n parser.add_argument(\n \"--file-suffix\",\n default=\".pt\",\n help=\"The file suffix indicating a torch data file\",\n )\n parser.add_argument(\n \"--swap\",\n action=\"store_true\",\n default=False,\n help=\"If set, swaps the order of key and value in `token2id`\",\n )\n parser.add_argument(\n \"--frame-shift-ms\",\n type=float,\n default=10.0,\n help=\"The number of milliseconds that have passed between consecutive \"\n \"frames. Used to convert between time in seconds and frame index. If your \"\n \"features are the raw sample, set this to 1000 / sample_rate_hz\",\n )\n utt_group = parser.add_mutually_exclusive_group()\n utt_group.add_argument(\n \"--wc2utt\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file mapping wavefile name and channel combinations (e.g. \"\n \"``utt_1 A``) to utterance IDs. Each line of the file has the format \"\n '``<wavefile_name> <channel> <utt_id>``. If neither \"--wc2utt\" nor '\n '\"--utt2wc\" has been specied, the wavefile name will be treated as '\n \"the utterance ID\",\n )\n utt_group.add_argument(\n \"--utt2wc\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file mapping utterance IDs to wavefile name and channel \"\n \"combinations (e.g. ``utt_1 A``). Each line of the file has the \"\n 'format ``<utt_id> <wavefile_name> <channel>``. If neither \"--wc2utt\" '\n 'nor \"--utt2wc\" has been specied, the wavefile name will be treated '\n \"as the utterance ID\",\n )\n parser.add_argument(\n \"--unk-symbol\",\n default=None,\n help=\"If set, will map out-of-vocabulary tokens to this symbol\",\n )\n return parser.parse_args(args)\n\n\ndef _parse_wc2utt(file, swap, return_swap):\n ret = dict()\n ret_swapped = dict()\n for line_no, line in enumerate(file):\n line = line.strip()\n if not line:\n continue\n ls = line.split()\n if len(ls) != 3:\n raise ValueError(\n \"Cannot parse line {} of {}\".format(line_no + 1, file.name),\n )\n first, mid, last = ls\n key, value = ((mid, last), first) if swap else ((first, mid), last)\n if key in ret:\n warnings.warn(\n '{} line {}: \"{}\" already exists. Mapping will be '\n \"\".format(file.name, line_no + 1, key)\n )\n if value in ret_swapped:\n warnings.warn(\n '{} line {}: \"{}\" already exists. Mapping will be '\n \"\".format(file.name, line_no + 1, value)\n )\n ret[key] = value\n ret_swapped[value] = key\n return ret_swapped if return_swap else ret\n\n\ndef ctm_to_torch_token_data_dir(args: Optional[Sequence[str]] = None) -> None:\n \"\"\"Convert a NIST \"ctm\" file to a SpectDataSet token data dir\n\n A \"ctm\" file is a transcription file with token alignments (a.k.a. a time-marked\n conversation file) used in the `sclite\n <http://www1.icsi.berkeley.edu/Speech/docs/sctk-1.2/sclite.htm>`_ toolkit. Here is\n the format::\n\n utt_1 A 0.2 0.1 hi\n utt_1 A 0.3 1.0 there ;; comment\n utt_2 A 0.0 1.0 next\n utt_3 A 0.1 0.4 utterance\n\n Where the first number specifies the token start time (in seconds) and the second\n the duration.\n\n This command reads in a \"ctm\" file and writes its contents as token sequences\n compatible with the ``ref/`` directory of a\n :class:`pydrobert.torch.data.SpectDataSet`. See the command\n :func:`get_torch_spect_data_dir_info` (command line \"get-torch-spect-data-dir-info\")\n for more information on a :class:`pydrobert.torch.data.SpectDataSet`\n \"\"\"\n try:\n options = _ctm_to_torch_token_data_dir_parse_args(args)\n except SystemExit as ex:\n return ex.code\n token2id = _parse_token2id(options.token2id, options.swap, options.swap)\n if options.unk_symbol is not None and options.unk_symbol not in token2id:\n print(\n 'Unk symbol \"{}\" is not in token2id'.format(options.unk_symbol),\n file=sys.stderr,\n )\n return 1\n if options.wc2utt:\n wc2utt = _parse_wc2utt(options.wc2utt, False, False)\n elif options.utt2wc:\n wc2utt = _parse_wc2utt(options.utt2wc, True, False)\n else:\n wc2utt = None\n transcripts = data.read_ctm(options.ctm, wc2utt)\n _save_transcripts_to_dir(\n transcripts,\n token2id,\n options.file_prefix,\n options.file_suffix,\n options.dir,\n options.frame_shift_ms,\n options.unk_symbol,\n )\n return 0\n\n\ndef _torch_token_data_dir_to_ctm_parse_args(args):\n parser = argparse.ArgumentParser(description=torch_token_data_dir_to_ctm.__doc__)\n parser.add_argument(\"dir\", help=\"The directory to read token sequences from\")\n parser.add_argument(\n \"id2token\",\n type=argparse.FileType(\"r\"),\n help=\"A file containing mappings from unique IDs to tokens (e.g. \"\n \"words or phones). Each line has the format ``<id> <token>``. The \"\n \"``--swap`` can be used to swap the expected ordering (i.e. \"\n \"``<token> <id>``)\",\n )\n parser.add_argument(\n \"ctm\",\n type=argparse.FileType(\"w\"),\n help='The \"ctm\" file to write token segments to',\n )\n parser.add_argument(\n \"--file-prefix\", default=\"\", help=\"The file prefix indicating a torch data file\"\n )\n parser.add_argument(\n \"--file-suffix\",\n default=\".pt\",\n help=\"The file suffix indicating a torch data file\",\n )\n parser.add_argument(\n \"--swap\",\n action=\"store_true\",\n default=False,\n help=\"If set, swaps the order of key and value in `id2token`\",\n )\n parser.add_argument(\n \"--frame-shift-ms\",\n type=float,\n default=10.0,\n help=\"The number of milliseconds that have passed between consecutive \"\n \"frames. Used to convert between time in seconds and frame index. If your \"\n \"features are the raw samples, set this to 1000 / sample_rate_hz\",\n )\n utt_group = parser.add_mutually_exclusive_group()\n utt_group.add_argument(\n \"--wc2utt\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file mapping wavefile name and channel combinations (e.g. \"\n \"``utt_1 A``) to utterance IDs. Each line of the file has the format \"\n \"``<wavefile_name> <channel> <utt_id>``\",\n )\n utt_group.add_argument(\n \"--utt2wc\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file mapping utterance IDs to wavefile name and channel \"\n \"combinations (e.g. ``utt_1 A``). Each line of the file has the \"\n \"format ``<utt_id> <wavefile_name> <channel>``\",\n )\n utt_group.add_argument(\n \"--channel\",\n default=\"A\",\n help='If neither \"--wc2utt\" nor \"--utt2wc\" is specified, utterance '\n \"IDs are treated as wavefile names and are given the value of this \"\n \"flag as a channel\",\n )\n return parser.parse_args(args)\n\n\ndef torch_token_data_dir_to_ctm(args: Optional[Sequence[str]] = None) -> None:\n \"\"\"Convert a SpectDataSet token data directory to a NIST \"ctm\" file\n\n A \"ctm\" file is a transcription file with token alignments (a.k.a. a time-marked\n conversation file) used in the `sclite\n <http://www1.icsi.berkeley.edu/Speech/docs/sctk-1.2/sclite.htm>`__ toolkit. Here is\n the format::\n\n utt_1 A 0.2 0.1 hi\n utt_1 A 0.3 1.0 there ;; comment\n utt_2 A 0.0 1.0 next\n utt_3 A 0.1 0.4 utterance\n\n Where the first number specifies the token start time (in seconds) and the second\n the duration.\n\n This command scans the contents of a directory like ``ref/`` in a\n :class:`pydrobert.torch.data.SpectDataSet` and converts each such file into a\n transcription. Every token in a given transcription must have information about its\n duration. Each such transcription is then written to the \"ctm\" file. See the command\n :func:`get_torch_spect_data_dir_info` (command line \"get-torch-spect-data-dir-info\")\n for more information on a :class:`pydrobert.torch.data.SpectDataSet`\n \"\"\"\n try:\n options = _torch_token_data_dir_to_ctm_parse_args(args)\n except SystemExit as ex:\n return ex.code\n id2token = _parse_token2id(options.id2token, not options.swap, options.swap)\n if options.wc2utt:\n utt2wc = _parse_wc2utt(options.wc2utt, False, True)\n elif options.utt2wc:\n utt2wc = _parse_wc2utt(options.utt2wc, True, True)\n else:\n utt2wc = options.channel\n transcripts = _load_transcripts_from_data_dir(\n options.dir,\n id2token,\n options.file_prefix,\n options.file_suffix,\n options.frame_shift_ms,\n )\n data.write_ctm(transcripts, options.ctm, utt2wc)\n return 0\n\n\ndef _compute_torch_token_data_dir_parse_args(args):\n parser = argparse.ArgumentParser(\n description=compute_torch_token_data_dir_error_rates.__doc__\n )\n parser.add_argument(\n \"dir\",\n help=\"If the `hyp` argument is not specified, this is the \"\n \"parent directory of two subdirectories, ``ref/`` and ``hyp/``, which \"\n \"contain the reference and hypothesis transcripts, respectively. If \"\n \"the ``--hyp`` argument is specified, this is the reference \"\n \"transcript directory\",\n )\n parser.add_argument(\n \"hyp\", nargs=\"?\", default=None, help=\"The hypothesis transcript directory\",\n )\n parser.add_argument(\n \"out\",\n nargs=\"?\",\n type=argparse.FileType(\"w\"),\n default=sys.stdout,\n help=\"Where to print the error rate to. Defaults to stdout\",\n )\n parser.add_argument(\n \"--id2token\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file containing mappings from unique IDs to tokens (e.g. \"\n \"words or phones). Each line has the format ``<id> <token>``. The \"\n \"``--swap`` flag can be used to swap the expected ordering (i.e. \"\n \"``<token> <id>``). ``--id2token`` can be used to collapse unique IDs \"\n \"together. Also, ``--ignore`` will contain a list of strings instead \"\n \"of IDs\",\n )\n parser.add_argument(\n \"--replace\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file containing pairs of elements per line. The first is the \"\n \"element to replace, the second what to replace it with. If \"\n \"``--id2token`` is specified, the file should contain tokens. If \"\n \"``--id2token`` is not specified, the file should contain IDs \"\n \"(integers). This is processed before ``--ignore``\",\n )\n parser.add_argument(\n \"--ignore\",\n type=argparse.FileType(\"r\"),\n default=None,\n help=\"A file containing a whitespace-delimited list of elements to \"\n \"ignore in both the reference and hypothesis transcripts. If \"\n \"``--id2token`` is specified, the file should contain tokens. If \"\n \"``--id2token`` is not specified, the file should contain IDs \"\n \"(integers). This is processed after ``--replace``\",\n )\n parser.add_argument(\n \"--file-prefix\", default=\"\", help=\"The file prefix indicating a torch data file\"\n )\n parser.add_argument(\n \"--file-suffix\",\n default=\".pt\",\n help=\"The file suffix indicating a torch data file\",\n )\n parser.add_argument(\n \"--swap\",\n action=\"store_true\",\n default=False,\n help=\"If set, swaps the order of key and value in `id2token`\",\n )\n parser.add_argument(\n \"--warn-missing\",\n action=\"store_true\",\n default=False,\n help=\"If set, warn and exclude any utterances that are missing either \"\n \"a reference or hypothesis transcript. The default is to error\",\n )\n parser.add_argument(\n \"--distances\",\n action=\"store_true\",\n default=False,\n help=\"If set, return the average distance per utterance instead of the total \"\n \"errors over the number of reference tokens\",\n )\n parser.add_argument(\n \"--per-utt\",\n action=\"store_true\",\n default=False,\n help=\"If set, return lines of ``<utt_id> <error_rate>`` denoting the \"\n \"per-utterance error rates instead of the average\",\n )\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=100,\n help=\"The number of error rates to compute at once. Reduce if you \"\n \"run into memory errors\",\n )\n parser.add_argument(\n \"--quiet\",\n action=\"store_true\",\n default=False,\n help=\"Suppress warnings which arise from edit distance computations\",\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--costs\",\n nargs=3,\n type=float,\n metavar=(\"INS\", \"DEL\", \"SUB\"),\n default=(1.0, 1.0, 1.0),\n help=\"The costs of an insertion, deletion, and substitution, respectively\",\n )\n group.add_argument(\n \"--nist-costs\",\n action=\"store_true\",\n default=False,\n help=\"Use NIST (sclite, score) default costs for insertions, deletions, and \"\n \"substitutions (3/3/4)\",\n )\n return parser.parse_args(args)\n\n\ndef compute_torch_token_data_dir_error_rates(\n args: Optional[Sequence[str]] = None,\n) -> None:\n \"\"\"Compute error rates between reference and hypothesis token data dirs\n\n This is a very simple script that computes and prints the error rates between the\n ``ref/`` (reference/gold standard) token sequences and ``hyp/``\n (hypothesis/generated) token sequences in a\n :class:`pydrobert.torch.data.SpectDataSet` directory. Consult the Wikipedia article\n on the `Levenshtein distance <https://en.wikipedia.org/wiki/Levenshtein_distance>`__\n for more info on error rates. The error rate for the entire partition will be\n calculated as the total number of insertions, deletions, and substitutions made in\n all transcriptions divided by the sum of lengths of reference transcriptions.\n\n Error rates are printed as ratios, not by \"percentage.\"\n\n While convenient and accurate, this script has very few features. Consider pairing\n the command ``torch-token-data-dir-to-trn`` with `sclite\n <http://www1.icsi.berkeley.edu/Speech/docs/sctk-1.2/sclite.htm>`__ instead.\n\n Warnings\n --------\n The error rates reported by this command have changed since version ``v0.3.0`` of\n ``pydrobert-pytorch`` when the insertion, deletion, and substitution costs do not\n all equal 1. Consult the documentation of :func:`error_rate` for more information.\n\n Many tasks will ignore some tokens (e.g. silences) or collapse others (e.g. phones).\n Please consult a standard recipe (such as those in `Kaldi\n <http://kaldi-asr.org/>`__) before performing these computations.\n \"\"\"\n try:\n options = _compute_torch_token_data_dir_parse_args(args)\n except SystemExit as ex:\n return ex.code\n if options.nist_costs:\n options.costs = (3.0, 3.0, 4.0)\n if options.hyp:\n ref_dir, hyp_dir = options.dir, options.hyp\n else:\n ref_dir = os.path.join(options.dir, \"ref\")\n hyp_dir = os.path.join(options.dir, \"hyp\")\n if not os.path.isdir(ref_dir):\n print('\"{}\" is not a directory'.format(ref_dir), file=sys.stderr)\n return 1\n if not os.path.isdir(hyp_dir):\n print('\"{}\" is not a directory'.format(hyp_dir), file=sys.stderr)\n return 1\n if options.id2token:\n id2token = _parse_token2id(options.id2token, not options.swap, options.swap)\n else:\n id2token = None\n replace = dict()\n if options.replace:\n for line in options.replace:\n replaced, replacement = line.strip().split()\n if id2token is None:\n try:\n replaced, replacement = int(replaced), int(replacement)\n except ValueError:\n raise ValueError(\n 'If --id2token is not set, all elements in \"{}\" must '\n \"be integers\".format(options.replace.name)\n )\n replace[replaced] = replacement\n if options.ignore:\n ignore = set(options.ignore.read().strip().split())\n if id2token is None:\n try:\n ignore = {int(x) for x in ignore}\n except ValueError:\n raise ValueError(\n 'If --id2token is not set, all elements in \"{}\" must be '\n \"integers\".format(options.ignore.name)\n )\n else:\n ignore = set()\n ref_transcripts = list(\n _load_transcripts_from_data_dir(\n ref_dir,\n id2token,\n options.file_prefix,\n options.file_suffix,\n strip_timing=True,\n )\n )\n hyp_transcripts = list(\n _load_transcripts_from_data_dir(\n hyp_dir,\n id2token,\n options.file_prefix,\n options.file_suffix,\n strip_timing=True,\n )\n )\n idx = 0\n while idx < max(len(ref_transcripts), len(hyp_transcripts)):\n missing_ref = missing_hyp = False\n if idx == len(ref_transcripts):\n missing_hyp = True\n elif idx == len(hyp_transcripts):\n missing_ref = True\n elif ref_transcripts[idx][0] < hyp_transcripts[idx][0]:\n missing_ref = True\n elif hyp_transcripts[idx][0] < ref_transcripts[idx][0]:\n missing_hyp = True\n if missing_hyp or missing_ref:\n if missing_hyp:\n fmt_tup = hyp_dir, hyp_transcripts[idx][0], ref_dir\n del hyp_transcripts[idx]\n else:\n fmt_tup = ref_dir, ref_transcripts[idx][0], hyp_dir\n del ref_transcripts[idx]\n msg = (\n 'Directory \"{}\" contains utterance \"{}\" which directory \"{}\" '\n \"does not contain\"\n ).format(*fmt_tup)\n if options.warn_missing:\n warnings.warn(msg + \". Skipping\")\n else:\n raise ValueError(msg)\n else:\n idx += 1\n assert len(ref_transcripts) == len(hyp_transcripts)\n idee_, eos, padding = [0], -1, -2\n\n def get_idee():\n v = idee_[0]\n idee_[0] += 1\n return v\n\n token2id = defaultdict(get_idee)\n error_rates = OrderedDict()\n tot_errs = 0\n total_ref_tokens = 0.0\n while len(ref_transcripts):\n batch_ref_transcripts = [\n (\n utt,\n [\n token2id[replace.get(t, t)]\n for t in transcript\n if replace.get(t, t) not in ignore\n ],\n )\n for (utt, transcript) in ref_transcripts[: options.batch_size]\n ]\n batch_hyp_transcripts = [\n (\n utt,\n [\n token2id[replace.get(t, t)]\n for t in transcript\n if replace.get(t, t) not in ignore\n ],\n )\n for (utt, transcript) in hyp_transcripts[: options.batch_size]\n ]\n ref_transcripts = ref_transcripts[options.batch_size :]\n hyp_transcripts = hyp_transcripts[options.batch_size :]\n ref = torch.nn.utils.rnn.pad_sequence(\n [\n torch.tensor(transcript + [eos])\n for _, transcript in batch_ref_transcripts\n ],\n padding_value=padding,\n )\n hyp = torch.nn.utils.rnn.pad_sequence(\n [\n torch.tensor(transcript + [eos])\n for _, transcript in batch_hyp_transcripts\n ],\n padding_value=padding,\n )\n ers = util.error_rate(\n ref,\n hyp,\n eos=eos,\n include_eos=False,\n ins_cost=options.costs[0],\n del_cost=options.costs[1],\n sub_cost=options.costs[2],\n norm=False,\n warn=not options.quiet,\n )\n for (utt_id, transcript), er in zip(batch_ref_transcripts, ers):\n error_rates[utt_id] = er.item() / (\n 1 if options.distances else len(transcript)\n )\n tot_errs += er.item()\n total_ref_tokens += len(transcript)\n if options.per_utt:\n for utt_id, er in list(error_rates.items()):\n options.out.write(\"{} {}\\n\".format(utt_id, er))\n else:\n options.out.write(\n \"{}\\n\".format(\n tot_errs / (len(error_rates) if options.distances else total_ref_tokens)\n )\n )\n" ]
[ [ "torch.all", "torch.LongTensor", "torch.randint", "torch.full", "torch.cat", "torch.Tensor", "torch.manual_seed", "torch.randn", "torch.tensor", "torch.any", "torch.full_like", "torch.rand", "torch.arange", "torch.stack", "torch.allclose", "torch.nn.functional.pad" ], [ "torch.multiprocessing.Queue", "torch.utils.data.DataLoader", "torch.multiprocessing.cpu_count", "torch.tensor", "torch.multiprocessing.Pool", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lidongyv/Monocular-depth-esitimation-with-region-support-cvpr
[ "7715c91b9c9f88de5c0233923c3a073edf9b2ca8", "7715c91b9c9f88de5c0233923c3a073edf9b2ca8" ]
[ "back of code/RSCFN/rsden/models/rsn_cluster # without 0 fuse cluster.py", "back of code/RSCFN/rsden/loader/NYU2-20181023212211.py" ]
[ "# -*- coding: utf-8 -*-\n# @Author: lidong\n# @Date: 2018-03-20 18:01:52\n# @Last Modified by: yulidong\n# @Last Modified time: 2018-11-06 20:45:11\n\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport math\nfrom math import ceil\nfrom torch.autograd import Variable\nfrom rsden.cluster_loss import *\nfrom rsden import caffe_pb2\nfrom rsden.models.utils import *\nimport time\ncuda_id=3\ngroup_dim=1\ndef mean_shift(feature,mean,bandwidth):\n #feature shape c h w\n for t in range(10):\n #print(t)\n dis=feature-mean\n dis=torch.norm(dis,dim=0)\n mask=torch.where(dis<bandwidth,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n mean=torch.sum((feature*mask).view(feature.shape[0],feature.shape[1]*feature.shape[2]),dim=1)/torch.sum(mask)\n mean=mean.view([feature.shape[0],1,1])\n return mean\ndef get_mask(feature,mean,bandwidth):\n mean=mean.view([mean.shape[0],1,1])\n dis=feature-mean\n dis=torch.norm(dis,dim=0)\n mask=torch.where(dis<bandwidth,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id))\n #pixels=mask.nonzero()\n return mask.float()\n\n\ndef re_label(mask,area,bandwidth):\n index=torch.sum(area)\n print(index)\n count=torch.tensor(0).float().cuda(cuda_id)\n for i in range(area.shape[0]):\n mask[i,:,:]=torch.where(mask[i,:,:]>0,mask[i,:,:]+count,mask[i,:,:])\n count+=area[i]\n segment=torch.where(mask>0,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n final=torch.sum(mask,dim=0)/torch.sum(segment,dim=0)\n final=torch.squeeze(final)\n final=final/255\n return mask,area,final\ndef refine_mask(mask):\n pixels=mask.nonzero()\n if torch.sum(mask)<400:\n return mask\n minx=torch.min(pixels[:,0])\n maxx=torch.max(pixels[:,0])\n miny=torch.min(pixels[:,1])\n maxy=torch.max(pixels[:,1])\n for i in range(1,torch.ceil((maxx-minx).float()/80).int()+1):\n for j in range(1,torch.ceil((maxy-miny).float()/80).int()+1):\n if torch.sum(mask[minx+80*(i-1):minx+80*i,miny+80*(j-1):miny+80*j])>400:\n mask[minx+80*(i-1):minx+80*i,miny+80*(j-1):miny+80*j]*=i*j\n areas=torch.unique(mask).sort()[0]\n for i in range(1,len(areas)):\n mask=torch.where(mask==areas[i],-torch.ones(1).float().cuda(cuda_id)*i,mask)\n mask=-mask\n return mask.float()\ndef fuse_mask(n_mask,r_mask):\n base=torch.where(n_mask>0,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n areas=torch.max(n_mask)\n #for i in range(1,torch.max(r_mask).long()+1):\n i=1\n shift=torch.where(r_mask==i,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n non_overlap=torch.where(base-shift==-1,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n overlap=shift-non_overlap\n if torch.sum(non_overlap)/torch.sum(shift)>0.4:\n areas+=1\n n_mask=torch.where(non_overlap==1,areas,n_mask)\n base=torch.where(n_mask>0,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n #print(areas)\n else:\n area_num=torch.argmax(torch.bincount(torch.where(overlap.long()==1,n_mask.long(),torch.tensor(0).cuda(cuda_id)).view(-1))[1:]).float()+1\n n_mask=torch.where(non_overlap==1,area_num,n_mask)\n base=torch.where(n_mask>0,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n #print(areas)\n# areas_nums=torch.tensor(1).float().cuda(cuda_id)\n# for i in range(1,torch.max(n_mask).long()+1):\n# region=torch.where(n_mask==i,torch.tensor(1).cuda(cuda_id),torch.tensor(0).cuda(cuda_id)).float()\n# pixels=region.nonzero()\n# if pixels.shape[0]>0:\n# minx=torch.min(pixels[:,0])\n# maxx=torch.max(pixels[:,0])\n# miny=torch.min(pixels[:,1])\n# maxy=torch.max(pixels[:,1])\n# for i in range(1,torch.ceil((maxx-minx).float()/80).int()+1):\n# for j in range(1,torch.ceil((maxy-miny).float()/80).int()+1):\n# if torch.sum(region[minx+80*(i-1):minx+80*i,miny+80*(j-1):miny+80*j])>400:\n# region[minx+80*(i-1):minx+80*i,miny+80*(j-1):miny+80*j]*=i*j\n# areas=torch.unique(region).sort()[0]\n# for i in range(1,len(areas)):\n# region=torch.where(region==areas[i],-areas_nums,region)\n# areas_nums+=1\n# n_mask=torch.where(n_mask==i,region,n_mask)\n# n_mask=-n_mask\n\n return n_mask\n\ndef fast_cluster(feature,bandwidth=0.16):\n masks=[]\n areas=[]\n segments=[]\n #start_time=time.time()\n for i in range(feature.shape[0]):\n n_mask=0\n n_feature=feature[i,...]\n label=torch.zeros(n_feature.shape[1],n_feature.shape[2]).cuda(cuda_id).float()\n check=0\n count=0\n while(torch.min(label)==0):\n candidate=torch.where(label==0,torch.tensor(1).float().cuda(cuda_id),torch.tensor(0).float().cuda(cuda_id)).nonzero()\n #print(len(candidate))\n seed=torch.randint(len(candidate),(1,))[0].long()\n mean=n_feature[:,candidate[seed][0].long(),candidate[seed][1].long()].view(n_feature.shape[0],1,1)\n mean=mean_shift(n_feature, mean, bandwidth)\n t_masks=get_mask(n_feature, mean, bandwidth)\n #print(len(candidate),n_mask)\n label=label+t_masks\n if n_mask==0:\n #r_masks=refine_mask(t_masks)\n n_masks=t_masks\n n_mask=torch.max(n_masks)\n \n else:\n #r_masks=refine_mask(t_masks)\n n_masks=fuse_mask(n_masks,t_masks)\n n_mask=torch.max(n_masks)\n #print(torch.max(n_masks))\n if len(candidate)==check:\n count+=1\n else:\n check=len(candidate)\n if count>3:\n bandwidth=bandwidth*1.1\n count=0\n if n_mask==50:\n bandwidth=bandwidth*1.1\n if n_mask==60:\n bandwidth=bandwidth*1.1 \n # if n_mask==70:\n # bandwidth=bandwidth*1.1\n # if n_mask==100:\n # bandwidth=bandwidth*1.1\n if n_mask>70:\n #n_masks=fuse_mask(n_masks,torch.where(label==0,torch.tensor(1).float().cuda(cuda_id),torch.tensor(0).float().cuda(cuda_id)))\n break\n #print(time.time()-start_time)\n return n_masks\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n pad=nn.ReplicationPad2d(1)\n padding=0\n conv_mod = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=padding, bias=False)\n return nn.Sequential(pad,conv_mod)\n \n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.gn1 = nn.GroupNorm(group_dim,planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.gn2 = nn.GroupNorm(group_dim,planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.gn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.gn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n # print(residual.shape)\n # print(out.shape)\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.gn1 = nn.GroupNorm(group_dim,planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.gn2 = nn.GroupNorm(group_dim,planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.gn3 = nn.GroupNorm(group_dim,planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.gn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.gn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.gn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n\n out += residual\n out = self.relu(out)\n\n return out\nclass rsn_cluster(nn.Module):\n\n\n def __init__(self, \n n_classes=64, \n block_config=[3, 16, 3, 3], \n input_size= (480, 640), \n version='scene'):\n\n super(rsn_cluster, self).__init__()\n self.inplanes = 64\n layers=[4, 10, 5, 5]\n block=BasicBlock\n # Encoder\n self.conv1=conv2DGroupNormRelu(3, 32, k_size=3,\n padding=1, stride=1, bias=False)\n self.conv2=conv2DGroupNormRelu(32, 64, k_size=3,\n padding=1, stride=1, bias=False) \n self.layer1 = self._make_layer(block, 64, layers[0],stride=1)\n\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 256, layers[3], stride=1)\n # self.layer5 = conv2DGroupNormRelu(in_channels=128, k_size=3, n_filters=256,\n # padding=1, stride=1, bias=False,group_dim=group_dim)\n\n\n # Pyramid Pooling Module\n #we need to modify the padding to keep the diminsion\n #remove 1 ,because the error of bn\n self.pyramid_pooling = pyramidPoolingGroupNorm(256, [[30,40],[12,16],[3,4],[1,1]],group_dim=group_dim)\n #self.global_pooling = globalPooling(256, 1)\n # Final conv layers\n #self.cbr_final = conv2DBatchNormRelu(512, 256, 3, 1, 1, False)\n #self.dropout = nn.Dropout2d(p=0.1, inplace=True)\n self.fuse0 = conv2DGroupNormRelu(in_channels=512, k_size=3, n_filters=256,\n padding=1, stride=1, bias=False,group_dim=group_dim) \n self.fuse1 = conv2DGroupNormRelu(in_channels=256, k_size=3, n_filters=128,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n #we need to replace the upsampling unit with nearest and deconv2d\n self.deconv1 = deconv2DGroupNormRelu(in_channels=128, n_filters=128, k_size=4, \n stride=2, padding=1,output_padding=0, bias=False,group_dim=group_dim)\n self.fuse2 = conv2DGroupNormRelu(in_channels=256, k_size=3, n_filters=192,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.deconv2 = deconv2DGroupNormRelu(in_channels=192, n_filters=192, k_size=4, \n stride=2, padding=1,output_padding=0, bias=False,group_dim=group_dim)\n self.fuse3 = conv2DGroupNormRelu(in_channels=256, k_size=3, n_filters=256,\n padding=1, stride=1, bias=False,group_dim=group_dim) \n self.inplanes = 257\n self.regress1 = self._make_layer(block,128, 4, stride=1)\n\n self.regress2 = conv2DGroupNormRelu(in_channels=128, k_size=3, n_filters=64,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.regress3 = conv2DGroupNormRelu(in_channels=64, k_size=3, n_filters=32,\n padding=1, stride=1, bias=False,group_dim=group_dim) \n self.regress4 = conv2DRelu(in_channels=32, k_size=3, n_filters=1,\n padding=1, stride=1, bias=False)\n self.class0= conv2DGroupNormRelu(in_channels=258, k_size=1, n_filters=128,\n padding=0, stride=1, bias=False,group_dim=group_dim)\n self.class1= conv2DGroupNormRelu(in_channels=128, k_size=3, n_filters=64,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.class2= conv2DRelu(in_channels=64, k_size=3, n_filters=64,\n padding=1, stride=1, bias=False)\n self.class3= conv2DRelu(in_channels=64, k_size=3, n_filters=32,\n padding=1, stride=1, bias=False) \n self.class4= conv2D(in_channels=32, k_size=1, n_filters=16,\n padding=0, stride=1, bias=False)\n # self.outrefine1=conv2DGroupNormRelu(in_channels=514, k_size=1, n_filters=128,\n # padding=0, stride=1, bias=False,group_dim=group_dim)\n # self.outrefine2=conv2DGroupNormRelu(in_channels=128, k_size=1, n_filters=64,\n # padding=0, stride=1, bias=False,group_dim=group_dim)\n # self.outrefine3=conv2DRelu(in_channels=64, k_size=3, n_filters=32,\n # padding=1, stride=1, bias=False)\n # self.outrefine4= conv2D(in_channels=32, k_size=1, n_filters=1,\n # padding=0, stride=1, bias=False)\n self.inrefine1=conv2DGroupNormRelu(in_channels=513, k_size=3, n_filters=128,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.inrefine2=conv2DGroupNormRelu(in_channels=128, k_size=3, n_filters=64,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.inrefine3=conv2DGroupNormRelu(in_channels=64, k_size=3, n_filters=32,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.inrefine4= conv2DRelu(in_channels=32, k_size=1, n_filters=16,\n padding=0, stride=1, bias=False)\n self.inrefine5= conv2D(in_channels=16, k_size=1, n_filters=1,\n padding=0, stride=1, bias=False)\n self.reliable1=conv2DGroupNormRelu(in_channels=513, k_size=3, n_filters=128,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.reliable2=conv2DGroupNormRelu(in_channels=128, k_size=3, n_filters=64,\n padding=1, stride=1, bias=False,group_dim=group_dim)\n self.reliable3= conv2DGroupNormRelu(in_channels=64, k_size=1, n_filters=32,\n padding=0, stride=1, bias=False,group_dim=group_dim) \n self.reliable4= conv2DGroupNormRelu(in_channels=32, k_size=1, n_filters=16,\n padding=0, stride=1, bias=False)\n self.reliable5= conv2D(in_channels=16, k_size=1, n_filters=1,\n padding=0, stride=1, bias=False)\n\n self.output=nn.ReLU(inplace=True)\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.GroupNorm):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.ConvTranspose2d):\n m.weight.data.fill_(1)\n\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.ReplicationPad2d(0),\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False,padding=0),\n nn.GroupNorm(group_dim,planes * block.expansion),\n )\n\n layers = []\n \n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n #print(self.inplanes)\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n def forward(self, x,segments,labels,flag,task):\n #print(x.shape)\n location_map=torch.cat([(torch.arange(x.shape[-1])/x.shape[-1]).unsqueeze(0).expand(x.shape[-2],x.shape[-1]).unsqueeze(0), \\\n (torch.arange(x.shape[-2])/x.shape[-2]).unsqueeze(0).transpose(1,0).expand(x.shape[-2],x.shape[-1]).unsqueeze(0)],0).unsqueeze(0).float().cuda(cuda_id)\n #x=torch.cat([x,location_map],1)\n zero=torch.zeros(1).cuda(cuda_id)\n one=torch.ones(1).cuda(cuda_id)\n x = self.conv1(x)\n x=self.conv2(x)\n x1 = self.layer1(x)\n #half resolution\n x2 = self.layer2(x1)\n #print(x.shape)\n x = self.layer3(x2)\n #print(x.shape)\n x = self.layer4(x)\n #print(x.shape)\n # H, W -> H/2, W/2 \n x = self.pyramid_pooling(x)\n\n #x = self.cbr_final(x)\n #x = self.dropout(x)\n x = self.fuse0(x)\n x = self.fuse1(x)\n #print(x.shape)\n x = self.deconv1(x)\n #print(x.shape,x2.shape)\n x = self.fuse2(torch.cat((x,x2),1))\n x = self.deconv2(x)\n #print(x.shape)\n x_share = self.fuse3(torch.cat((x,x1),1))\n\n # x=self.regress1(x_share)\n # #print(x.shape)\n # x=self.regress2(x)\n # x=self.regress3(x)\n # depth=self.regress4(x)\n\n # accurate_depth=depth\n # return depth,accurate_depth\n #clustering feature\n\n #accurate_depth=depth*reliable\n \n if flag==0:\n x_fuse=torch.cat([x_share,location_map],1)\n y=self.class0(x_fuse)\n y=self.class1(y)\n y=self.class2(y)\n y=self.class3(y)\n y=self.class4(y)\n with torch.no_grad():\n masks=fast_cluster(y).view(1,1,x_share.shape[-2],x_share.shape[-1])\n #masks=segments.view(1,1,x_share.shape[-2],x_share.shape[-1])\n x=self.regress1(torch.cat([x_share,masks],1))\n #x=self.regress1(torch.cat([x_share,masks],1))\n #print(x.shape)\n x=self.regress2(x)\n x=self.regress3(x)\n depth=self.regress4(x)\n with torch.no_grad():\n #masks=fast_cluster(y).view_as(depth)\n #masks=segments.view_as(depth)\n labels=labels.view_as(depth)\n #coarse depth\n coarse_depth=depth+0\n coarse_feature=x_share+0\n mean_features=torch.zeros(1,x_share.shape[1],torch.max(masks).long()+1).cuda(cuda_id)\n mean_depth=torch.zeros(torch.max(masks).long()+1).cuda(cuda_id)\n #print(torch.max(masks))\n for i in range(1,torch.max(masks).int()+1):\n index_r=torch.where(masks==i,one,zero)\n mean_d=torch.sum(index_r*depth)/torch.sum(index_r)\n mean_depth[i]=mean_d\n coarse_depth=torch.where(masks==i,mean_d,coarse_depth)\n mean_f=torch.sum((index_r*x_share).view(x_share.shape[0],x_share.shape[1],-1),dim=-1)/torch.sum(index_r)\n #print(mean_f.shape,mean_features[...,i].shape)\n mean_features[...,i]=mean_f\n coarse_feature=torch.where(masks==i,mean_f.view(x_share.shape[0],x_share.shape[1],1,1),coarse_feature)\n\n # #refine outer\n # outer_feature=torch.zeros(1,2*x_share.shape[1]+2,torch.max(masks).long()+1,torch.max(masks).long()+1).cuda(cuda_id)\n # for i in range(torch.min(masks).int(),torch.max(masks).int()+1):\n # for j in range(torch.min(masks).int(),torch.max(masks).int()+1):\n # if i!=j:\n # #print(outer_feature[...,i,j].shape,mean_depth[i].view(1,1).shape,mean_features[...,i].shape)\n # outer_feature[...,i,j]=torch.cat([mean_depth[i].view(1,1),mean_features[...,i],mean_depth[j].view(1,1),mean_features[...,j]],dim=-1)\n\n # outer=self.outrefine1(outer_feature)\n # outer=self.outrefine2(outer)\n # outer=self.outrefine3(outer)\n # outer_variance=self.outrefine4(outer)\n # outer_depth=torch.zeros(torch.max(masks).long()+1).cuda(cuda_id)\n # # #mean_depth_map=coarse_depth+0\n # #with torch.no_grad():\n # for i in range(torch.min(masks).int(),torch.max(masks).int()+1):\n # outer_depth[i]=(torch.sum(mean_depth*outer_variance[...,i,:])+mean_depth[i])/torch.sum(outer_variance[...,i,:]+1)\n # #outer_depth[i]=(torch.sum(mean_depth*outer_variance[...,i,:])+mean_depth[i])\n # coarse_depth=torch.where(masks==i,outer_depth[i],coarse_depth)+0\n #refine inner\n #coarse_depth=self.output(coarse_depth)\n inner_feature= torch.cat([coarse_depth,x_share,coarse_feature],1)\n inner=self.inrefine1(inner_feature)\n inner=self.inrefine2(inner)\n inner=self.inrefine3(inner)\n inner=self.inrefine4(inner)\n inner_variance=self.inrefine5(inner)\n\n reliable_feature= torch.cat([depth,x_share,coarse_feature],1)\n reliable=self.inrefine1(reliable_feature)\n reliable=self.inrefine2(reliable)\n reliable=self.inrefine3(reliable)\n reliable=self.inrefine4(reliable)\n reliable_variance=self.inrefine5(reliable)\n # #inner_variance[:,0,...]=inner_variance[:,0,...]/torch.max(inner_variance[:,0,...])\n # reliable_to_depth=(inner_variance[:,0,...]/torch.max(inner_variance[:,0,...])).unsqueeze(1)\n # variance_on_cosrse=inner_variance[:,1,...].unsqueeze(1)\n # #print(inner_variance.shape)\n # accurate_depth=depth*reliable_to_depth+(coarse_depth*variance_on_cosrse)*(1-reliable_to_depth)\n loss_var,loss_dis,loss_reg = cluster_loss(y,segments.long(),device_id=cuda_id)\n loss_var=loss_var.reshape((y.shape[0],1))\n loss_dis=loss_dis.reshape((y.shape[0],1))\n loss_reg=loss_reg.reshape((y.shape[0],1))\n accurate_depth=self.output(inner_variance+coarse_depth)\n depth=self.output(reliable_variance+depth)\n accurate_depth=torch.where(masks>0,(depth+accurate_depth)/2,depth)\n #print(torch.mean(depth).item(),torch.mean(coarse_depth).item())\n return masks,accurate_depth,loss_var,loss_dis,loss_reg\n else:\n if task=='train':\n with torch.no_grad():\n masks=fast_cluster(y).view_as(depth)\n print(torch.max(masks))\n\n loss_var,loss_dis,loss_reg = cluster_loss(y,segments.long())\n loss_var=loss_var.reshape((y.shape[0],1))\n loss_dis=loss_dis.reshape((y.shape[0],1))\n loss_reg=loss_reg.reshape((y.shape[0],1))\n return depth,masks,loss_var,loss_dis,loss_reg\n elif task=='test':\n\n loss_var,loss_dis,loss_reg = cluster_loss(y,segments.long())\n loss_var=loss_var.reshape((y.shape[0],1))\n loss_dis=loss_dis.reshape((y.shape[0],1))\n loss_reg=loss_reg.reshape((y.shape[0],1))\n return depth,loss_var,loss_dis,loss_reg\n elif task=='eval':\n\n x_fuse=torch.cat([x_share,location_map],1)\n masks=segments.view_as(depth)\n #coarse depth\n coarse_depth=depth+0\n coarse_feature=x_fuse+0\n mean_features=torch.zeros(1,x_fuse.shape[1],torch.max(masks).long()+1).cuda(cuda_id)\n mean_depth=torch.zeros(torch.max(masks).long()+1).cuda(cuda_id)\n \n for i in range(torch.min(masks).int(),torch.max(masks).int()+1):\n index_r=torch.where(masks==i,one,zero)\n mean_d=torch.sum(index_r*depth)/torch.sum(index_r)\n mean_depth[i]=mean_d+0\n coarse_depth=torch.where(masks==i,mean_depth[i],coarse_depth)\n mean_f=torch.sum((index_r*x_fuse).view(x_fuse.shape[0],x_fuse.shape[1],-1),dim=-1)/torch.sum(index_r)\n #print(mean_f.shape,mean_features[...,i].shape)\n mean_features[...,i]=mean_f\n coarse_feature=torch.where(masks==i,mean_f.view(x_fuse.shape[0],x_fuse.shape[1],1,1),coarse_feature)\n\n #refine outer\n # outer_feature=torch.zeros(1,2*x_fuse.shape[1]+2,torch.max(masks).long()-torch.min(masks).long()+1,torch.max(masks).long()-torch.min(masks).long()+1).cuda(cuda_id)\n # for i in range(torch.min(masks).int(),torch.max(masks).int()+1):\n # for j in range(torch.min(masks).int(),torch.max(masks).int()+1):\n # if i!=j:\n # #print(outer_feature[...,i,j].shape,mean_depth[i].view(1,1).shape,mean_features[...,i].shape)\n # outer_feature[...,i,j]=torch.cat([mean_depth[i].view(1,1),mean_features[...,i],mean_depth[j].view(1,1),mean_features[...,j]],dim=-1)\n\n # outer=self.outrefine1(outer_feature)\n # outer=self.outrefine2(outer)\n # outer=self.outrefine3(outer)\n # outer_variance=self.outrefine4(outer)\n # outer_depth=torch.zeros(torch.max(masks).long()-torch.min(masks).long()+1).cuda(cuda_id)\n # #mean_depth_map=coarse_depth+0\n # # print(torch.min(masks))\n # # print(torch.sum(torch.where(masks==0,torch.ones(1).cuda(cuda_id),torch.zeros(1).cuda(cuda_id))))\n # for i in range(torch.min(masks).int(),torch.max(masks).int()+1):\n # outer_depth[i]=(torch.sum(mean_depth*outer_variance[...,i,:])+mean_depth[i])/(torch.sum(outer_variance[...,i,:])+1)\n # #outer_depth[i]=(torch.sum(mean_depth*outer_variance[...,i,:])+mean_depth[i])\n # coarse_depth=torch.where(masks==i,outer_depth[i],coarse_depth)+0\n #print(torch.max(coarse_depth),torch.mean(mean_depth),torch.mean(outer_depth),torch.max(outer_variance))\n #mean_depth_map=coarse_depth+0\n #refine inner\n inner_feature= torch.cat([coarse_depth,x_fuse-coarse_feature],1)\n\n #print('inner_feature',torch.max(inner_feature).item())\n inner=self.inrefine1(inner_feature)\n #print('inner_1',torch.max(inner).item())\n inner=self.inrefine2(inner)\n #print('inner_2',torch.max(inner).item())\n inner=self.inrefine3(inner)\n #print('inner_3',torch.max(inner).item())\n inner=self.inrefine4(inner)\n inner_variance=self.inrefine5(inner)\n accurate_depth=inner_variance\n\n # inner_feature= torch.cat([depth,x_share],1)\n # relialbe=self.reliable1(inner_feature)\n # relialbe=self.reliable2(relialbe)\n # relialbe=self.reliable3(relialbe)\n # relialbe=self.reliable4(relialbe)\n # relialbe=self.reliable5(relialbe)\n # accurate_depth=relialbe\n # print('inner_variance',torch.max(inner_variance).item())\n # inner_variance[:,0,...]=inner_variance[:,0,...]/torch.max(inner_variance[:,0,...])\n # reliable_to_depth=(torch.exp(-relialbe[:,0,...])).unsqueeze(1)\n # reliable_to_coarse=(torch.exp(-inner_variance[:,0,...])).unsqueeze(1)\n # variance_on_depth=relialbe[:,1,...].unsqueeze(1)\n # variance_on_cosrse=inner_variance[:,1,...].unsqueeze(1)\n # print('reliable_depth: %.2f reliable_coarse: %.2f variance_depth %.2f variance_coarse %.2f'%(torch.mean(reliable_to_depth).item(), \\\n # torch.mean(reliable_to_coarse).item(),torch.mean(variance_on_depth).item(),torch.mean(variance_on_cosrse).item()))\n # #print('variance %.2f'%(torch.mean(inner_variance).item()))\n # relialbe_weights=reliable_to_coarse+reliable_to_depth\n # # #print(inner_variance.shape)\n # accurate_depth=(depth*variance_on_depth*reliable_to_coarse+coarse_depth*variance_on_cosrse*reliable_to_coarse)/ \\\n # (torch.where(relialbe_weights==0,torch.ones(1).cuda(cuda_id),relialbe_weights))\n # refined_depth=depth*variance_on_depth\n # coarse_depth=coarse_depth*variance_on_cosrse\n # accurate_depth=(coarse_depth*reliable_to_coarse+refined_depth*(1-reliable_to_coarse))\n # accurate_depth=refined_depth*reliable_to_depth\n # print('depth',torch.max(depth).item())\n # print('coarse',torch.max(coarse_depth).item())\n # print('accurate',torch.max(accurate_depth).item())\n # loss_var,loss_dis,loss_reg = cluster_loss(y,segments.long())\n # loss_var=loss_var.reshape((y.shape[0],1))\n # loss_dis=loss_dis.reshape((y.shape[0],1))\n # loss_reg=loss_reg.reshape((y.shape[0],1))\n\n # accurate_depth=inner_variance\n # simple refinement\n # x_fuse=x_share+depth.expand_as(x_share)\n # inner=self.inrefine1(x_fuse)\n # inner=self.inrefine2(inner)\n # inner=self.inrefine3(inner)\n # inner=self.inrefine4(inner)\n # accurate_depth=self.inrefine5(inner)\n accurate_depth=depth\n return depth,accurate_depth\n \n\n\n", "# -*- coding: utf-8 -*-\n# @Author: yulidong\n# @Date: 2018-04-25 23:06:40\n# @Last Modified by: yulidong\n# @Last Modified time: 2018-10-23 21:19:50\n\n\nimport os\nimport torch\nimport numpy as np\nimport scipy.misc as m\nimport cv2\nfrom torch.utils import data\nfrom python_pfm import *\nfrom rsden.utils import recursive_glob\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nclass NYU2(data.Dataset):\n def __init__(self, root, split=\"train\", is_transform=True, img_size=(480,640),task='depth'):\n \"\"\"__init__\n\n :param root:\n :param split:\n :param is_transform:\n :param img_size:\n \"\"\"\n self.root = root\n self.split = split\n self.num=0\n self.is_transform = is_transform\n self.n_classes = 64 # 0 is reserved for \"other\"\n self.img_size = img_size if isinstance(img_size, tuple) else (480, 640)\n self.mean = np.array([104.00699, 116.66877, 122.67892])\n self.path=os.path.join(self.root,self.split)\n self.files=os.listdir(self.path)\n self.files.sort(key=lambda x:int(x[:-4]))\n if len(self.files)<1:\n raise Exception(\"No files for %s found in %s\" % (split, self.path))\n\n print(\"Found %d in %s images\" % (len(self.files), self.path))\n self.task=task\n if task=='depth':\n self.d=3\n self.r=5\n else:\n self.d=5\n self.r=7\n if task=='all':\n self.d=3\n self.r=7 \n if task=='visualize':\n self.d=3\n self.r=5 \n if task=='region':\n self.d=3\n self.r=7\n self.m=6 \n def __len__(self):\n \"\"\"__len__\"\"\"\n return len(self.files)\n\n def __getitem__(self, index):\n \"\"\"__getitem__\n\n :param index:\n \"\"\"\n data=np.load(os.path.join(self.path,self.files[index]))\n if self.task=='visualize':\n data=data[0,:,:,:]\n #print(data.shape)\n img = data[:,:,0:3]\n #img=img[:,:,::-1]\n #dis=readPFM(disparity_path)\n #dis=np.array(dis[0], dtype=np.uint8)\n\n depth = data[:,:,self.d]\n #depth=np.load(os.path.join('/home/lidong/Documents/datasets/nyu/nyu2/all',self.files[index]))[:,:,3]\n region=data[:,:,self.r]\n region=np.reshape(region,[1,region.shape[0],region.shape[1]])\n segments = data[:,:,self.m]\n #segments=np.load(os.path.join('/home/lidong/Documents/datasets/nyu/nyu2/all',self.files[index]))[:,:,4]\n #print(segments.shape)\n segments=np.reshape(segments,[1,segments.shape[0],segments.shape[1]])\n if self.task=='visualize':\n rgb=img\n img, depth,region,segments = self.transform(img, depth,region,segments)\n return img, depth,segments,data\n\n if self.is_transform:\n img, depth,region,segments = self.transform(img, depth,region,segments)\n\n return img, depth,region,segments\n\n def transform(self, img, depth,region,segments):\n \"\"\"transform\n\n :param img:\n :param depth:\n \"\"\"\n img = img[:,:,:]\n #print(img.shape)\n img = img.astype(np.float32)\n # Resize scales images from 0 to 255, thus we need\n # to divide by 255.0\n #img = torch.from_numpy(img).float()\n depth = torch.from_numpy(depth).float().unsqueeze(0).unsqueeze(0)\n segments=torch.from_numpy(segments).float().unsqueeze(0)\n region=torch.from_numpy(region).float().unsqueeze(0)\n #img = img.astype(float) / 255.0\n # NHWC -> NCHW\n #img = img.transpose(1,2,0)\n totensor=transforms.ToTensor()\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n img=totensor(img)\n img=normalize(img).unsqueeze(0)\n #print(img.shape,depth.shape)\n #depth=depth[0,:,:]\n #depth = depth.astype(float)/32\n #depth = np.round(depth)\n #depth = m.imresize(depth, (self.img_size[0], self.img_size[1]), 'nearest', mode='F')\n #depth = depth.astype(int)\n #depth=np.reshape(depth,[1,depth.shape[0],depth.shape[1]])\n #classes = np.unique(depth)\n #print(classes)\n #depth = depth.transpose(2,0,1)\n #if not np.all(classes == np.unique(depth)):\n # print(\"WARN: resizing segmentss yielded fewer classes\")\n\n #if not np.all(classes < self.n_classes):\n # raise ValueError(\"Segmentation map contained invalid class values\")\n # img=F.interpolate(img,scale_factor=1/4,mode='nearest').squeeze()\n # #print(depth.shape)\n # depth=F.interpolate(depth,scale_factor=1/4,mode='nearest').squeeze()\n # region=F.interpolate(region,scale_factor=1/4,mode='nearest').squeeze()\n # segments=F.interpolate(segments,scale_factor=1/4,mode='nearest').squeeze()\n img=img.squeeze()\n #print(depth.shape)\n depth=depth.squeeze()\n region=region.squeeze()\n segments=segments.squeeze()\n #print(region.shape,segments.shape)\n return img, depth,region,segments\n" ]
[ [ "torch.nn.Sequential", "torch.norm", "torch.ones", "torch.max", "torch.cat", "torch.zeros", "torch.min", "torch.nn.Conv2d", "torch.sum", "torch.tensor", "torch.unique", "torch.no_grad", "torch.where", "torch.arange", "torch.nn.GroupNorm", "torch.nn.ReLU", "torch.squeeze", "torch.nn.ReplicationPad2d" ], [ "numpy.reshape", "numpy.array", "torch.from_numpy" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sdss/apogee
[ "e134409dc14b20f69e68a0d4d34b2c1b5056a901", "e134409dc14b20f69e68a0d4d34b2c1b5056a901", "5112ea30a83d2ea308e552b985ff3584734d9df1" ]
[ "python/apogee/aspcap/teff.py", "python/apogee/apred/target.py", "external/doppler/doppler/cannongrid_cubic_norm_training.py" ]
[ "# routines for calibrating/comparing effective temperatures with photometric sample\n\nfrom apogee.utils import apload\nfrom apogee.utils import apselect\nfrom astropy.io import fits, ascii\nfrom tools import match\nfrom tools import plots\nfrom tools import fit\nfrom apogee.utils import bitmask\nfrom apogee.aspcap import err\nimport pdb\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport matplotlib\n\ndef bindata(xdata,ydata,bins,median=True) :\n \"\"\"\n Given xdata, ydata, and bins in x, returns mean of ydata in each of the bins\n \"\"\"\n mean=bins*0.\n for i in range(len(bins)-1) :\n j=np.where((xdata>bins[i]) & (xdata<bins[i+1]))[0]\n if median :\n mean[i]=np.median(ydata[j])\n else :\n mean[i]=ydata[j].mean() \n return mean\n\ndef ghb(allstar,glatmin=30.,ebvmax=0.03,trange=[3750,5500],loggrange=[-1,6],mhrange=[-2.5,0.75],alpha=False,out='teffcomp',yr=[-500,500],\n calib=False,dr13=False,grid=None,cmap='rainbow',doerr=True) :\n \"\"\"\n Compares allstar ASPCPAP Teff with photometric Teff from GHB for sample of stars with GLAT>glatmin and SFD_EBV<ebvmax,\n does fits\n\n Args:\n allstar : allStar structure\n\n Keyword args:\n glatmin (float) : minimum GLAT for sample (default=30)\n ebvmax (float) : maximum SFD_EBV for sample (default=0.03)\n dwarf (bool) : use dwarfs and dwarf GHB (default = False)\n \"\"\"\n\n # select data to use\n badtarg=['YOUNG','EMBEDDED','EXTENDED','M31','M33','EMISSION','RRLYR','DSPH','MAGCLOUD']\n\n # plots using Berger isochrone Teff for infomational purposes\n if calib : param='PARAM'\n else : param = 'FPARAM'\n berger=fits.open(os.environ['APOGEE_DIR']+'/data/calib/teff_berger.fits')[1].data\n gd=apselect.select(allstar,badval=['STAR_BAD'],badstar=['MULTIPLE_SUSPECT'],badtarg=badtarg,raw=True)\n i1,i2=match.match(allstar['APOGEE_ID'][gd],berger['APOGEE_ID'])\n fig,ax=plots.multi(1,1,figsize=(12,6))\n plots.plotc(ax,allstar[param][gd[i1],3],allstar[param][gd[i1],0]-berger['TEFF'][i2],allstar[param][gd[i1],0],\n xt='[M/H]',yt='ASPCAP-Berger',zt='Teff',xr=[-3,1],yr=[-500,500],zr=[4500,7000],colorbar=True)\n ax.grid()\n fig.savefig(out+'_berger_mh.png')\n plt.close()\n fig,ax=plots.multi(1,1,figsize=(12,6))\n plots.plotc(ax,allstar[param][gd[i1],0],allstar[param][gd[i1],1],allstar[param][gd[i1],0]-berger['TEFF'][i2],\n xt='Teff',yt='log ',zt='ASPCAP-Berger',xr=[8000,3000],yr=[6,-1],zr=[-250,250],colorbar=True)\n ax.grid()\n fig.savefig(out+'_berger_hr.png')\n plt.close()\n\n gd=apselect.select(allstar,badval=['STAR_BAD'],badstar=['MULTIPLE_SUSPECT'],badtarg=badtarg,teff=trange,mh=mhrange,logg=loggrange,raw=True)\n allstar=allstar[gd]\n #if dr13 :\n # j=np.where((abs(allstar['GLAT'])>glatmin)&(allstar['SFD_EBV']<ebvmax))[0]\n #else :\n j=np.where((abs(allstar['GLAT'])>glatmin)&(allstar['SFD_EBV']>-0.01)&(allstar['SFD_EBV']<ebvmax)&(abs(allstar['J'])<90)&(abs(allstar['K'])<90))[0]\n\n # remove second gen GC stars\n #if not dr13 :\n gcstars = ascii.read(os.environ['APOGEE_DIR']+'/data/calib/gc_szabolcs.dat')\n bd=np.where(gcstars['pop'] != 1)[0]\n j = [x for x in j if allstar[x]['APOGEE_ID'] not in gcstars['id'][bd]]\n\n allstar=allstar[j]\n\n ghb,dtdjk=cte_ghb(allstar['J']-allstar['K'],allstar['FPARAM'][:,3],dwarf=False)\n ghb_dwarf,dtdjk_dwarf=cte_ghb(allstar['J']-allstar['K'],allstar['FPARAM'][:,3],dwarf=True)\n # use dwarf relation for dwarfs\n dw=np.where(allstar['FPARAM'][:,1] > 3.8)[0]\n ghb[dw]=ghb_dwarf[dw]\n dtdjk[dw]=dtdjk_dwarf[dw]\n gd=np.where(abs(allstar['FPARAM'][:,0]-ghb) < 500)[0]\n ghb=ghb[gd]\n dtdjk=dtdjk[gd]\n allstar=allstar[gd]\n print('Teff calibration, number of stars: ', len(allstar))\n\n if calib : \n param='PARAM'\n teff=allstar[param][:,0]\n logg=allstar[param][:,1]\n mh=allstar[param][:,3]\n am=allstar[param][:,6]\n elif grid is None :\n param='FPARAM'\n teff=allstar[param][:,0]\n logg=allstar[param][:,1]\n mh=allstar[param][:,3]\n am=allstar[param][:,6]\n else :\n param='FPARAM_CLASS'\n teff=allstar[param][:,grid,0]\n logg=allstar[param][:,grid,1]\n mh=allstar[param][:,grid,3]\n am=allstar[param][:,grid,6]\n out=out+'_grid{:1d}'.format(grid)\n \n # HR digram plot of differences \n fig,ax=plots.multi(1,1,figsize=(12,6))\n plots.plotc(ax,teff,logg,teff-ghb, xt='Teff',yt='log ',zt='ASPCAP-GHB',xr=[8000,3000],yr=[6,-1],zr=[-250,250],colorbar=True)\n ax.grid()\n fig.savefig(out+'_ghb_hr.png')\n plt.close()\n\n # plot Teff difference against metallicity, color-code by temperature\n fig,ax=plots.multi(1,1,hspace=0.001,wspace=0.001,figsize=(12,6))\n xr=[-3.0,1.0]\n zr=trange\n if dr13: zr=[3500,5500]\n binsize=0.25\n bins=np.arange(-2.5,0.75,binsize)\n # diff color-coded by gravity as f([M/H])\n\n if alpha :\n plots.plotc(ax,mh,teff-ghb,am,zr=[-0.1,0.4],xr=xr,yr=yr,xt='[M/H]',yt='ASPCAP-photometric Teff',\n colorbar=True,zt=r'[$\\alpha$/M]',rasterized=True,cmap=cmap)\n else :\n plots.plotc(ax,mh,teff-ghb,teff,xr=xr,yr=yr,xt='[M/H]',yt='ASPCAP-photometric Teff',\n colorbar=True,zt='$T_{eff}$',rasterized=True,zr=trange,cmap=cmap)\n ax.grid()\n mean=bindata(mh,teff-ghb,bins,median=False)\n if not dr13: plots.plotp(ax,bins+binsize/2.,mean,marker='o',size=40)\n mean=bindata(mh,teff-ghb,bins,median=True)\n if not dr13: plots.plotp(ax,bins+binsize/2.,mean,marker='o',size=40,color='b')\n ax.text(0.1,0.9,'E(B-V)<{:6.2f}'.format(ebvmax),transform=ax.transAxes)\n gd=np.where(np.isfinite(mean))[0]\n tefit = fit.fit1d(bins[gd]+binsize/2.,mean[gd],degree=2,reject=0)\n # 1D quadratic fit as a function of metallicity\n allfit = fit.fit1d(mh,teff-ghb,ydata=teff,degree=2,reject=0)\n fig2,ax2=plots.multi(1,1)\n tefit2 = fit.fit2d(mh,teff,teff-ghb,reject=0,plot=ax2,zr=[-500,200],xt='[M/H]',yt=['Teff'],zt='$\\Delta Teff$')\n #pfit = fit.fit2d(allstar[param][:,3],allstar[param][:,0],allstar[param][:,0]-ghb,plot=ax[0,0],zr=[-500,200],xt='[M/H]',yt=['Teff'],zt='$\\Delta Teff$')\n #ejk=np.clip(np.sqrt(allstar['J_ERR']**2+allstar['K_ERR']**2),0.,0.02)\n #errpar = err.errfit(teff,allstar['SNR'],mh,teff-tefit(mh)-ghb,title='Teff',out=out+'_phot',zr=[0,250],meanerr=abs(dtdjk)*ejk)\n if doerr: \n errpar = err.errfit(teff,allstar['SNR'],mh,teff-tefit(mh)-ghb,title='Teff',out=out,zr=[0,150])\n else: errpar=0.\n\n x=np.linspace(-3,1,200)\n rms = (teff-tefit(mh)-ghb).std()\n if dr13: \n plots.plotl(ax,x,-36.17+95.97*x-15.09*x**2,color='k')\n print(allfit)\n else :\n plots.plotl(ax,x,tefit(x),color='k')\n ax.text(0.98,0.9,'rms: {:6.1f}'.format(rms),transform=ax.transAxes,ha='right')\n\n cmap = matplotlib.cm.get_cmap(cmap)\n for t in np.arange(trange[0],trange[1],500.) :\n rgba=cmap((t-trange[0])/(trange[1]-trange[0]))\n y=x*0.+t\n plots.plotl(ax,x,tefit2(x,y),color=rgba)\n\n plots._data_x = mh\n plots._data_y = teff-ghb\n plots._data = allstar\n plots.event(fig)\n\n # separate fits for low/hi alpha/M if requested\n if alpha :\n gdlo=apselect.select(allstar,badval=['STAR_BAD'],teff=trange,mh=mhrange,logg=[0,3.8],alpha=[-0.1,0.1],raw=True)\n mean=bindata(mh[gdlo],teff[gdlo]-ghb[gdlo],bins)\n plots.plotp(ax,bins,mean,marker='o',size=40,color='g')\n tmpfit = fit.fit1d(mh[gdlo],teff[gdlo]-ghb[gdlo],ydata=teff[gdlo],degree=2)\n plots.plotl(ax,x,tmpfit(x))\n print('low alpha: ', len(gdlo))\n\n gdhi=apselect.select(allstar,badval=['STAR_BAD'],teff=trange,mh=mhrange,logg=[0,3.8],alpha=[0.1,0.5],raw=True)\n mean=bindata(mh[gdhi],teff[gdhi]-ghb[gdhi],bins)\n plots.plotp(ax,bins,mean,marker='o',size=40,color='b')\n tmpfit = fit.fit1d(mh[gdhi],teff[gdhi]-ghb[gdhi],ydata=teff[gdhi],degree=2)\n plots.plotl(ax,x,tmpfit(x))\n print('hi alpha: ', len(gdhi))\n\n fig.tight_layout()\n fig.savefig(out+'.png')\n plt.close()\n plt.rc('font',size=14)\n plt.rc('axes',titlesize=14)\n plt.rc('axes',labelsize=14)\n fig.savefig(out+'.pdf')\n plt.close()\n\n # auxiliary plots with different color-codings\n try:\n meanfib=allstar['MEANFIB']\n except:\n meanfib=teff*0.\n fig,ax=plots.multi(2,2,hspace=0.001,wspace=0.001,figsize=(12,8))\n plots.plotc(ax[0,0],mh,teff-ghb,logg,zr=[0,5],xr=xr,yr=yr,xt='[M/H]',yt='ASPCAP-photometric Teff',colorbar=True,zt='log g',size=2)\n plots.plotc(ax[0,1],mh,teff-ghb,meanfib,zr=[0,300],xr=xr,yr=yr,xt='[M/H]',yt='ASPCAP-photometric Teff',colorbar=True,zt='mean fiber',size=2)\n pfit = fit.fit1d(mh,teff-ghb,ydata=teff,plot=ax[1,0],zr=[-500,200],xt='[M/H]',yt='$\\Delta Teff$',xr=[-2.7,0.9],yr=[3500,5000],colorbar=True,zt='Teff')\n pfit = fit.fit1d(teff,teff-ghb,ydata=mh,plot=ax[1,1],zr=[-500,200],xt='Teff',yt='$\\Delta Teff$',xr=trange,yr=[-2.5,0.5],colorbar=True,zt='[M/H]')\n fig.tight_layout()\n fig.savefig(out+'_b.png')\n plt.close()\n\n # do some test 2D and 1D fits and plots \n #fig,ax=plots.multi(2,2,hspace=0.5,wspace=0.001)\n #ax[0,1].xaxis.set_visible(False)\n #ax[0,1].yaxis.set_visible(False)\n #pfit = fit.fit2d(allstar[param][:,3],allstar[param][:,0],allstar[param][:,0]-ghb,plot=ax[0,0],zr=[-500,200],xt='[M/H]',yt=['Teff'],zt='$\\Delta Teff$')\n #pfit = fit.fit1d(allstar[param][:,3],allstar[param][:,0]-ghb,ydata=allstar[param][:,0],plot=ax[1,0],zr=[-500,200],xt='[M/H]',yt='$\\Delta Teff$',xr=[-2.7,0.9],yr=[3500,5000])\n #pfit = fit.fit1d(allstar[param][:,0],allstar[param][:,0]-ghb,ydata=allstar[param][:,3],plot=ax[1,1],zr=[-500,200],xt='Teff',xr=[3900,5100],yr=[-2.5,0.5])\n plt.draw()\n return {'caltemin': 3000., 'caltemax': 100000., 'temin' : trange[0], 'temax': trange[1], \n 'mhmin': mhrange[0], 'mhmax' : mhrange[1],\n 'par': tefit.parameters, 'rms' :rms, 'par2d': tefit2.parameters, 'errpar' : errpar}\n\n\ndef irfm(allstar,trange=[4000,5000],mhrange=[-2.5,0.75],out='dteff') :\n '''\n Compares allstar ASPCPAP Teff with various photometric Teff from JAJ compilation (SAGA, CL, TH, SFD)\n Does fits \n\n Args:\n allstar : allStar structure\n\n '''\n\n # select stars\n gd=apselect.select(allstar,badval=['STAR_BAD'],teff=trange,mh=mhrange,raw=True)\n allstar=allstar[gd]\n\n # get IRFM data\n irfm=fits.open(os.environ['APOGEE_DIR']+'/data/calib/irfm_temp.fits')[1].data\n\n # get the subsamples and match. Note that we have to do this separately for each subsample because some\n # stars appear in more than one subsample\n saga=np.where(irfm['SOURCE'] == 'SAGA')[0]\n saga1,saga2=match.match(np.chararray.strip(allstar['APOGEE_ID']),np.chararray.strip(irfm['2MASS ID'][saga]))\n cl=np.where(irfm['SOURCE'] == 'CL')[0]\n cl1,cl2=match.match(np.chararray.strip(allstar['APOGEE_ID']),np.chararray.strip(irfm['2MASS ID'][cl]))\n th=np.where(irfm['SOURCE'] == 'TH')[0]\n th1,th2=match.match(np.chararray.strip(allstar['APOGEE_ID']),np.chararray.strip(irfm['2MASS ID'][th]))\n sfd=np.where(irfm['SOURCE'] == 'SFD')[0]\n sfd1,sfd2=match.match(np.chararray.strip(allstar['APOGEE_ID']),np.chararray.strip(irfm['2MASS ID'][sfd]))\n\n # plot diff color-coded by gravity as f([M/H])\n fig,ax=plots.multi(2,2,hspace=0.001,wspace=0.001)\n xr=[-3.0,1.0]\n yr=[-400,300]\n zr=[3500,6000]\n bins=np.arange(-2.5,0.75,0.25)\n\n # SAGA\n plots.plotc(ax[0,0],allstar['FPARAM'][saga1,3],allstar['FPARAM'][saga1,0]-irfm['IRFM TEFF'][saga[saga2]],allstar['FPARAM'][saga1,0],zr=zr,xr=xr,yr=yr,xt='[M/H]',yt='ASPCAP-photometric Teff')\n mean=bindata(allstar['FPARAM'][saga1,3],allstar['FPARAM'][saga1,0]-irfm['IRFM TEFF'][saga[saga2]],bins)\n plots.plotp(ax[0,0],bins,mean,marker='o',size=40)\n ax[0,0].text(0.1,0.9,'SAGA',transform=ax[0,0].transAxes)\n\n # CL\n plots.plotc(ax[0,1],allstar['FPARAM'][cl1,3],allstar['FPARAM'][cl1,0]-irfm['IRFM TEFF'][cl[cl2]],allstar['FPARAM'][cl1,0],zr=zr,xr=xr,yr=yr,xt='[M/H]')\n mean=bindata(allstar['FPARAM'][cl1,3],(allstar['FPARAM'][cl1,0]-irfm['IRFM TEFF'][cl[cl2]]),bins)\n plots.plotp(ax[0,1],bins,mean,marker='o',size=40)\n ax[0,1].text(0.1,0.9,'CL',transform=ax[0,1].transAxes)\n\n # TH\n plots.plotc(ax[1,0],allstar['FPARAM'][th1,3],allstar['FPARAM'][th1,0]-irfm['IRFM TEFF'][th[th2]],allstar['FPARAM'][th1,0],zr=zr,xr=xr,yr=yr,xt='[M/H]',yt='ASPCAP-photometric Teff')\n mean=bindata(allstar['FPARAM'][th1,3],(allstar['FPARAM'][th1,0]-irfm['IRFM TEFF'][th[th2]]),bins)\n plots.plotp(ax[1,0],bins,mean,marker='o',size=40)\n ax[1,0].text(0.1,0.9,'TH',transform=ax[1,0].transAxes)\n\n # SFD\n plots.plotc(ax[1,1],allstar['FPARAM'][sfd1,3],allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]],allstar['FPARAM'][sfd1,0],zr=zr,xr=xr,yr=yr,xt='[M/H]')\n mean=bindata(allstar['FPARAM'][sfd1,3],(allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]]),bins)\n plots.plotp(ax[1,1],bins,mean,marker='o',size=40)\n ax[1,1].text(0.1,0.9,'SFD',transform=ax[1,1].transAxes)\n\n fig.savefig(out+'_mh.png')\n\n # plot diff color-coded by gravity as f([M/H])\n fig,ax=plots.multi(2,2,hspace=0.001,wspace=0.001)\n zr=[-2.0,0.5]\n yr=[-400,300]\n xr=[6000,3500]\n bins=np.arange(3500,5500,250)\n\n # SAGA\n plots.plotc(ax[0,0],allstar['FPARAM'][saga1,0],allstar['FPARAM'][saga1,0]-irfm['IRFM TEFF'][saga[saga2]],allstar['FPARAM'][saga1,3],zr=zr,xr=xr,yr=yr,xt='Teff',yt='ASPCAP-photometric Teff')\n mean=bindata(allstar['FPARAM'][saga1,0],(allstar['FPARAM'][saga1,0]-irfm['IRFM TEFF'][saga[saga2]]),bins)\n plots.plotp(ax[0,0],bins,mean,marker='o',size=40)\n ax[0,0].text(0.1,0.9,'SAGA',transform=ax[0,0].transAxes)\n\n # CL\n plots.plotc(ax[0,1],allstar['FPARAM'][cl1,0],allstar['FPARAM'][cl1,0]-irfm['IRFM TEFF'][cl[cl2]],allstar['FPARAM'][cl1,3],zr=zr,xr=xr,yr=yr,xt='Teff')\n mean=bindata(allstar['FPARAM'][cl1,0],(allstar['FPARAM'][cl1,0]-irfm['IRFM TEFF'][cl[cl2]]),bins)\n plots.plotp(ax[0,1],bins,mean,marker='o',size=40)\n ax[0,1].text(0.1,0.9,'CL',transform=ax[0,1].transAxes)\n\n # TH\n plots.plotc(ax[1,0],allstar['FPARAM'][th1,0],allstar['FPARAM'][th1,0]-irfm['IRFM TEFF'][th[th2]],allstar['FPARAM'][th1,3],zr=zr,xr=xr,yr=yr,xt='Teff',yt='ASPCAP-photometric Teff')\n mean=bindata(allstar['FPARAM'][th1,0],(allstar['FPARAM'][th1,0]-irfm['IRFM TEFF'][th[th2]]),bins)\n plots.plotp(ax[1,0],bins,mean,marker='o',size=40)\n ax[1,0].text(0.1,0.9,'TH',transform=ax[1,0].transAxes)\n\n # SFD\n plots.plotc(ax[1,1],allstar['FPARAM'][sfd1,0],allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]],allstar['FPARAM'][sfd1,3],zr=zr,xr=xr,yr=yr,xt='Teff')\n mean=bindata(allstar['FPARAM'][sfd1,0],(allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]]),bins)\n plots.plotp(ax[1,1],bins,mean,marker='o',size=40)\n ax[1,1].text(0.1,0.9,'SFD',transform=ax[1,1].transAxes)\n\n fig.savefig(out+'_teff.png')\n\n # do 2D fits with Teff and [M/H], and 1D fits with each\n\n fig,ax=plots.multi(2,2,hspace=0.5,wspace=0.001)\n ax[0,1].xaxis.set_visible(False)\n ax[0,1].yaxis.set_visible(False)\n pfit = fit.fit2d(ax[0,0],allstar['FPARAM'][sfd1,3],allstar['FPARAM'][sfd1,0],allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]],plot=True,zr=[-500,200],xt='[M/H]',yt=['Teff'],zt='$\\Delta Teff$')\n pfit = fit.fit1d(ax[1,0],allstar['FPARAM'][sfd1,3],allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]],ydata=allstar['FPARAM'][sfd1,0],plot=True,zr=[-500,200],xt='[M/H]',yt='$\\Delta Teff$',xr=[-2.7,0.9],yr=[3500,5000])\n pfit = fit.fit1d(ax[1,1],allstar['FPARAM'][sfd1,0],allstar['FPARAM'][sfd1,0]-irfm['IRFM TEFF'][sfd[sfd2]],ydata=allstar['FPARAM'][sfd1,3],plot=True,zr=[-500,200],xt='Teff',xr=[3900,5100],yr=[-2.5,0.5])\n\n pdb.set_trace()\n\n return pfit\n\ndef cte_ghb(jk0,feh,dwarf=False) :\n \"\"\"\n Color-temperature relation from Gonzalez Hernandez & Bonifacio (2009): (J-K)_0 - Teff\n \"\"\"\n if dwarf :\n b0=0.6524 ; b1=0.5813 ; b2=0.1225 ; b3=-0.0646 ; b4=0.0370 ; b5=0.0016 # dwarfs\n else :\n b0=0.6517 ; b1=0.6312 ; b2=0.0168 ; b3=-0.0381 ; b4=0.0256 ; b5=0.0013 # giants\n theta=b0+b1*jk0+b2*jk0**2+b3*jk0*feh+b4*feh+b5*feh**2\n dtheta_djk = b1+2*b2*jk0+b3*feh\n dt_djk= -5040./theta**2*dtheta_djk\n\n return 5040./theta, dt_djk\n\ndef cal(a,caldir='cal/'):\n \"\"\" Apply Teff calibration\n \"\"\"\n aspcapmask=bitmask.AspcapBitMask()\n parammask=bitmask.ParamBitMask()\n starmask=bitmask.StarBitMask()\n\n #populate PARAM[0] for stars w/o STAR_BAD (change to ALL with >=0)\n gd=np.where( ((a['ASPCAPFLAG']&aspcapmask.badval()) >= 0) )[0]\n gd=np.where( ((a['ASPCAPFLAG']&aspcapmask.getval('NO_ASPCAP_RESULT')) == 0) )[0]\n\n #initial values\n a['PARAM'][:,0] = np.nan\n a['PARAMFLAG'][gd,0] |= parammask.getval('CALRANGE_BAD')\n\n if caldir == 'none' :\n a['PARAM'][gd,0] = a['FPARAM'][gd,0]\n a['PARAMFLAG'][gd,0] &= ~parammask.getval('CALRANGE_BAD')\n return\n\n calpars=fits.open(caldir+'/tecal.fits')[1].data[0]\n calteffmin=calpars['caltemin']\n calteffmax=calpars['caltemax']\n teff=np.clip(a['FPARAM'][gd,0],calpars['temin'],calpars['temax'])\n mh=np.clip(a['FPARAM'][gd,3],calpars['mhmin'],calpars['mhmax'])\n try: snr=np.clip(a['SNREV'][gd],0,200.)\n except: \n print('No SNREV, continnue with SNR?')\n pdb.set_trace()\n snr=np.clip(a['SNR'][gd],0,200.)\n\n ok =np.where((a['FPARAM'][gd,0] >= calteffmin) & (a['FPARAM'][gd,0] <= calteffmax) )[0]\n a['PARAM'][gd[ok],0] = a['FPARAM'][gd[ok],0] - (calpars['par2d'][0]+calpars['par2d'][1]*mh[ok]+calpars['par2d'][2]*teff[ok])\n # populate uncertainties with err.apply()\n #a['PARAM_COV'][gd[ok],0,0] = err.elemerr(calpars['errpar'],a['FPARAM'][gd[ok],0]-4500.,snr[ok]-100.,a['FPARAM'][gd[ok],3])**2\n a['PARAMFLAG'][gd[ok],0] &= ~parammask.getval('CALRANGE_BAD')\n\n return \n\n", "import numpy as np\nfrom astropy.table import Column\nfrom astropy.io import fits\nfrom apogee.utils import bitmask\nfrom sdss import yanny\nimport os\nimport pdb\n\nplans = None\n\ndef add_design(tab) :\n \"\"\" Add design information for objects\n \"\"\"\n global plans\n\n for col in ['MIN_H','MAX_H','MIN_JK','MAX_JK'] :\n try : tab.add_column(Column(name=col,dtype=np.float32,length=len(tab)) )\n except : pass\n if 'MIN' in col : tab[col] = -9999.99\n else : tab[col] = 9999.99\n\n if tab['TELESCOPE'][0] == 'apo1m' : return\n\n if plans is None : plans = yanny.yanny(os.environ['PLATELIST_DIR']+'/platePlans.par')['PLATEPLANS']\n apogee_design = fits.open(os.environ['APOGEE_TARGET']+'/apogeeDesign.fits')[1].data\n apogee2_design = fits.open(os.environ['APOGEE_TARGET']+'/apogee2Design.fits')[1].data\n\n plate = int(tab['PLATE'][0]) \n iplan = np.where(np.array(plans['plateid']) == plate)[0]\n if len(iplan) == 0 : \n print('no plates found in platePlans for plate',plate)\n return\n elif len(iplan) != 1 : \n print('multiple plates found in platePlans for plate, using first',plate)\n iplan=iplan[0]\n\n if 'apogee2' in tab['SURVEY'][0] :\n idesign=np.where(apogee2_design['design_id'] == plans['designid'][iplan])[0]\n if len(idesign) == 0 : \n print('no designs for APOGEE-2 plate',plate)\n return\n elif len(idesign) != 1 : \n print('multiple designs for APOGEE-2 plate, using first ',plate)\n idesign=idesign[0]\n min_h = apogee2_design['cohort_min_h'][idesign]\n max_h = apogee2_design['cohort_max_h'][idesign]\n targflag = bitmask.Apogee2Target1()\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_SHORT'))[0]\n tab['MIN_H'][j] = min_h[0]\n tab['MAX_H'][j] = max_h[0]\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_MEDIUM'))[0]\n tab['MIN_H'][j] = min_h[1]\n tab['MAX_H'][j] = max_h[1]\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_LONG'))[0]\n tab['MIN_H'][j] = min_h[2]\n tab['MAX_H'][j] = max_h[2]\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_ONEBIN_GT_0_5'))[0]\n tab['MIN_JK'][j] = 0.5\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_TWOBIN_0_5_TO_0_8'))[0]\n tab['MIN_JK'][j] = 0.5\n tab['MAX_JK'][j] = 0.8\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_TWOBIN_GT_0_8'))[0]\n tab['MIN_JK'][j] = 0.8\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE2_ONEBIN_GT_0_3'))[0]\n tab['MIN_JK'][j] = 0.3\n \n else :\n idesign=np.where(apogee_design['design_id'] == plans['designid'][iplan])[0]\n if len(idesign) == 0 : \n print('no designs for APOGEE plate',plate)\n return\n elif len(idesign) != 1 : \n print('multiple designs for APOGEE plate, using first ',plate)\n idesign=idesign[0]\n min_h = [apogee_design['short_cohort_min_h'][idesign],\n apogee_design['medium_cohort_min_h'][idesign],\n apogee_design['long_cohort_min_h'][idesign]]\n max_h = [apogee_design['short_cohort_max_h'][idesign],\n apogee_design['medium_cohort_max_h'][idesign],\n apogee_design['long_cohort_max_h'][idesign]]\n min_jk = apogee_design['DEREDDENED_MIN_J_KS_COLOR'][idesign]\n targflag = bitmask.ApogeeTarget1()\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE_SHORT'))[0]\n tab['MIN_H'][j] = min_h[0]\n tab['MAX_H'][j] = max_h[0]\n tab['MIN_JK'][j] = min_jk\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE_INTERMEDIATE'))[0]\n tab['MIN_H'][j] = min_h[1]\n tab['MAX_H'][j] = max_h[1]\n tab['MIN_JK'][j] = min_jk\n j=np.where(tab['APOGEE_TARGET1']&targflag.getval('APOGEE_LONG'))[0]\n tab['MIN_H'][j] = min_h[2]\n tab['MAX_H'][j] = max_h[2]\n tab['MIN_JK'][j] = min_jk\n", "#!/usr/bin/env python\n\n# Imports\nimport os\nimport thecannon as tc\nfrom astropy.io import fits\nfrom astropy.table import Table\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\n#tag = '3000_18000_allstars'\n#tag = '3000_18000_rgb'\n#tag = '3000_18000_cooldwarfs'\ntag = '3000_18000_hotstars'\n#tag = '3000_18000_hotdwarfs'\n#tag = '3000_18000_coolstars'\n#tag = '3000_18000_whitedwarfs'\n\n\nprint(tag)\n\n# Import the spectra and labels\nnormalized_flux = fits.getdata('cannongrid_'+tag+'_synth_data_norm.fits.gz')\nlabelled_set=Table.read('cannongrid_'+tag+'_synth_pars.fits')\n\n# Add wavelengths\nnspec, npix = normalized_flux.shape\nwave = np.arange(npix)*0.10+3000.0\n#model3.dispersion = wave\nnormalized_ivar = normalized_flux.copy()*0 + 1e4\nvec3 = tc.vectorizer.PolynomialVectorizer(labelled_set.colnames, 3)\nmodel3 = tc.CannonModel(labelled_set, normalized_flux, normalized_ivar, vec3, wave)\nmodel3.regularization = 0 # no regularization for now\n\n# Train the model\nnr_theta, nr_s2, nr_metadata = model3.train() \nif os.path.exists('cannongrid_'+tag+'_norm_cubic_model.pkl'): os.remove('cannongrid_'+tag+'_norm_cubic_model.pkl')\nmodel3.write('cannongrid_'+tag+'_norm_cubic_model.pkl')\n\n# Check if there is a continuum model to add\ncontfile = 'cannongrid_'+tag+'_cont_cubic_model_logflux.pkl'\nif os.path.exists(contfile):\n print('Continuum model found. Adding it')\n f = open(contfile,'rb')\n cont = pickle.load(f)\n f.close()\nelse:\n cont = None\n\n# This adds my custom attributes\n# model.write() doesn't same them\ninfile = open('cannongrid_'+tag+'_norm_cubic_model.pkl','rb')\ntemp = pickle.load(infile)\ninfile.close()\ntemp['fwhm'] = 0.001\ntemp['wavevac'] = False\nif cont is not None:\n temp['continuum'] = cont\nmd = temp['metadata']\nta = md['trained_attributes']\nif cont is not None:\n ta = ta+('fwhm','wavevac','continuum')\nelse:\n ta = ta+('fwhm','wavevac')\nmd['trained_attributes'] = ta\ntemp['metadata'] = md\nos.remove('cannongrid_'+tag+'_norm_cubic_model.pkl')\noutfile = open('cannongrid_'+tag+'_norm_cubic_model.pkl','wb')\npickle.dump(temp,outfile)\noutfile.close()\n\n# Test/fit the spectra to get the labels\nlabels3, cov, meta = model3.test(normalized_flux, normalized_ivar)\n\n\n# one-to-one comparisons\nnames = model3.vectorizer.label_names\nfig = plt.figure(figsize=(15,10))\nfor i in range(0, 3):\n plt.subplot(2, 2, i+1)\n plt.plot(labelled_set[names[i]],labels3[:,i],'+')\n plt.plot(labelled_set[names[i]],labelled_set[names[i]])\n plt.xlabel('Input '+names[i])\n plt.ylabel('Recovered '+names[i])\nfig.savefig('cannongrid_'+tag+'_comparison.png') \n\n\n" ]
[ [ "numpy.linspace", "numpy.clip", "numpy.isfinite", "numpy.arange", "numpy.median", "matplotlib.pyplot.rc", "matplotlib.pyplot.draw", "numpy.chararray.strip", "matplotlib.pyplot.close", "matplotlib.cm.get_cmap", "numpy.where" ], [ "numpy.array", "numpy.where" ], [ "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.plot", "matplotlib.pyplot.subplot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
calvinfeng/openvino
[ "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac", "11f591c16852637506b1b40d083b450e56d0c8ac" ]
[ "model-optimizer/extensions/middle/GatherNdNormalizer.py", "model-optimizer/mo/middle/passes/fusing/fuse_grouped_conv.py", "model-optimizer/extensions/ops/gatherelements.py", "model-optimizer/extensions/front/binary_quantize_normalization.py", "model-optimizer/extensions/front/Softplus_fusion.py", "inference-engine/ie_bridges/python/sample/object_detection_sample_ssd/object_detection_sample_ssd.py", "model-optimizer/extensions/middle/RemoveUselessPad.py", "model-optimizer/mo/utils/ir_reader/extenders/deconvolution_extender.py", "inference-engine/ie_bridges/python/sample/classification_sample_async/classification_sample_async.py", "model-optimizer/extensions/front/onnx/constant_of_shape_ext.py", "model-optimizer/extensions/front/onnx/squeeze_ext_test.py", "model-optimizer/extensions/front/split_normalizer.py", "model-optimizer/extensions/ops/LookupTableInsert.py" ]
[ "\"\"\"\n Copyright (C) 2018-2021 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\"\"\"\nimport logging as log\n\nimport numpy as np\n\nfrom extensions.ops.gather import Gather\nfrom mo.front.common.partial_infer.utils import int64_array\nfrom mo.front.tf.graph_utils import create_op_node_with_second_input, create_op_with_const_inputs\nfrom mo.graph.graph import Graph, rename_node\nfrom mo.middle.replacement import MiddleReplacementPattern\nfrom mo.ops.reshape import Reshape\n\n\nclass GatherNDNormalize(MiddleReplacementPattern):\n \"\"\"\n Hot fix for new speech-to-text model enabling while GatherND is not implemented in IE.\n We can replace GatherND to Reshape + Gather in case when GatherND indices have just one\n meaningful dimension.\n TODO: Investigate whether we must replace GatherND with Reshape + Gather always (due to performance benefits)\n for this particular case or only if the plugin does not support GatherND.\n And the best place for the transformation is nGraph so we need to move it.\n \"\"\"\n enabled = True\n force_clean_up = True\n\n def run_before(self):\n from extensions.middle.BlockLSTMtoLSTMSequence import BlockLSTMtoLSTMSequence\n return [BlockLSTMtoLSTMSequence]\n\n def run_after(self):\n from extensions.middle.pass_separator import MiddleStart\n return [MiddleStart]\n\n def pattern(self):\n return dict(\n nodes=[('GatherND', dict(kind='op', op='GatherND', batch_dims=0))],\n edges=[]\n )\n\n @staticmethod\n def indices_check(indices: np.array, input_shape: tuple):\n \"\"\"\n Check that indices have just one meaningful dimension and all other dimensions of input have size 1.\n \"\"\"\n n_dims = indices.shape[-1]\n non_zero = None\n for i in range(n_dims):\n if not all(np.take(indices, indices=[i], axis=-1) == 0):\n if non_zero is None:\n non_zero = i\n else:\n return None\n else:\n if input_shape[i] != 1:\n return None\n return non_zero\n\n def replace_pattern(self, graph: Graph, match: dict):\n gather = match['GatherND']\n gather_name = gather.soft_get('name', gather.id)\n input_shape = gather.in_node(0).shape\n indices = gather.in_node(1).value\n if indices is None:\n # We can't do such special pass without indices value\n return\n\n # 0. All needed checks that we can replace GatherND by Gather\n gather_idx = self.indices_check(indices, input_shape)\n if gather_idx is None:\n log.warning('Node {} with op=GatherND can\\'t be normalized to op=Gather.'.format(gather_name))\n return\n\n # 1. Add Reshape and connect\n new_shape = int64_array([-1] + list(input_shape[indices.shape[-1]:]))\n reshape = create_op_node_with_second_input(graph, Reshape, new_shape,\n {'name': gather_name + '/Reshape_for_GatherND/'})\n gather.in_port(0).get_connection().set_destination(reshape.in_port(0))\n\n # 2. Change indices from Nd to 1d:\n new_indices = np.reshape(np.take(indices, indices=[gather_idx], axis=-1), [-1])\n\n rename_node(gather, gather_name + '/to_delete')\n\n # 3. Create new Gather operation and reconnect all inputs/outputs\n new_gather = create_op_with_const_inputs(graph, Gather, {1: new_indices, 2: int64_array(0)},\n {'name': gather_name})\n rename_node(new_gather, gather_name)\n\n reshape.out_port(0).connect(new_gather.in_port(0))\n\n gather.out_port(0).get_connection().set_source(new_gather.out_port(0))\n\n # 4. Remove old Gather node\n graph.remove_node(gather.id)\n", "\"\"\"\n Copyright (C) 2018-2021 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 numpy as np\n\nfrom mo.graph.graph import Node, Graph\nfrom mo.middle.passes.fusing.helpers import get_next_operation\n\n\n# TODO: unit tests\ndef concat_convolutions(graph: Graph, start_node: Node, last_node: Node):\n \"\"\"\n This function converts group of convolutions into one\n \"\"\"\n\n # Check that concatenation makes in the same order\n conv_nodes = get_next_operation(start_node)\n assert len(conv_nodes) == len(last_node.in_nodes())\n gconv = conv_nodes[0]\n\n for id in range(len(conv_nodes)):\n conv = conv_nodes[id]\n if conv.out_node().id != last_node.in_node(id).id:\n return False\n # Check that all convolutions have same weights shapes\n if not np.array_equal(conv.in_node(1).shape, gconv.in_node(1).shape):\n log.debug('Grouped convolutions fusion : convolutions have different weights shape')\n return False\n\n # Check that split and concat dims are valid\n channel_dim = gconv.channel_dims[0]\n split_axis = start_node.in_port(1).data.get_value()\n if channel_dim != split_axis or channel_dim != last_node.axis:\n log.debug('Grouped convolutions fusion : split or concat has weird axis!')\n return False\n\n # Check that all convolutions has the same parameters\n conv_attrs = ['pad', 'stride']\n for attr in conv_attrs:\n for id in range(len(conv_nodes)):\n conv = conv_nodes[id]\n if not np.array_equal(gconv[attr], conv[attr]):\n log.debug('Grouped convolutions fusion : attrs {} doesn\\'t match'.format(attr))\n return False\n\n # Check that all Convolutions has biases (if exists)\n has_biases = False\n for id in range(len(conv_nodes)):\n conv = conv_nodes[id]\n if len(conv.in_nodes()) == 3:\n if not has_biases:\n has_biases = True\n elif has_biases:\n return False # All convolution mast have biases\n\n # Check that all biases have same shape\n if has_biases:\n for id in range(len(conv_nodes)):\n conv = conv_nodes[id]\n if conv.in_node(2).shape != gconv.in_node(2).shape:\n log.debug('Group convolutions fusion : convolutions have different biases shape {} and {}'.format(\n conv.in_node(2).shape, gconv.in_node(2).shape))\n return False\n\n graph.remove_edge(gconv.in_node(0).id, gconv.id)\n graph.remove_edge(gconv.id, gconv.out_node().id)\n\n input = start_node.in_node(0)\n output = last_node.out_node()\n\n # Removing edges from data nodes to Split and Concat\n graph.remove_edge(input.id, start_node.id)\n graph.remove_edge(last_node.id, output.id)\n\n # Add edges to grouped convolution\n graph.add_edges_from([\n (input.id, gconv.id, {'in': 0}),\n (gconv.id, output.id, {'out': 0})\n ])\n\n # Concatenation of convolutions\n weights_node = gconv.in_node(1)\n bias_node = gconv.in_node(2) if has_biases else None\n\n weights_value = np.array(weights_node.value)\n bias_value = np.array(bias_node.value) if has_biases else None\n\n feature_dim = 3 if graph.graph['layout'] == 'NHWC' else 0\n\n for conv in conv_nodes[1:]:\n weights_value = np.concatenate((weights_value, conv.in_node(1).value), axis=feature_dim)\n if has_biases:\n bias_value = np.concatenate((bias_value, conv.in_node(2).value), axis=-1) # Not validated\n\n weights_node.value = np.array(weights_value)\n weights_node.shape = np.array(weights_value.shape)\n\n if has_biases:\n bias_node.value = np.array(bias_value)\n bias_node.shape = np.array(bias_value.shape)\n\n log.debug('Start node : {} Last node : {} Nodes inside : {}'.format(start_node.id, last_node.id,\n len(start_node.out_nodes())))\n log.debug('Output shape : {}'.format(weights_value.shape))\n\n gconv.group = len(conv_nodes)\n gconv.output = weights_node.shape[feature_dim]\n gconv.output_shape[feature_dim] = weights_node.shape[feature_dim]\n\n return True\n\n\n# TODO: unit tests\ndef grouped_convolutions_fusing(graph: Graph):\n while True:\n is_fused = False\n graph.clean_up()\n for node in graph.pseudo_topological_sort():\n if node.kind == 'op' and len(node.out_nodes()) > 1:\n if node.soft_get('can_be_fused') == False:\n continue\n\n is_valid_convolutions = True\n last_layer = None\n\n next_nodes = get_next_operation(node)\n # Check that all operation after this one are Convolutions\n # and all convolutions has same output\n if len(next_nodes) > 1 and all(_node.soft_get('type') in ['Convolution', 'Deconvolution'] for _node in next_nodes):\n for conv in next_nodes:\n conv_outputs = get_next_operation(conv)\n if conv.soft_get('can_be_fused') == False:\n is_valid_convolutions = False\n if len(conv_outputs) != 1:\n is_valid_convolutions = False\n if last_layer is None:\n last_layer = conv_outputs[0].id\n # TODO: this check is not working for V10 where Biases appears as separate operations\n elif conv_outputs[0].id != last_layer:\n is_valid_convolutions = False\n\n if is_valid_convolutions:\n is_fused = concat_convolutions(graph, node, Node(graph, last_layer))\n if is_fused:\n break\n\n if not is_fused:\n break\n", "\"\"\"\n Copyright (C) 2017-2021 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 numpy as np\n\nfrom mo.graph.graph import Node, Graph\nfrom mo.ops.op import Op, PermuteAttrs\n\n\nclass GatherElements(Op):\n op = 'GatherElements'\n\n def __init__(self, graph: Graph, attrs: dict):\n super().__init__(graph, {\n 'op': self.op,\n 'type': self.op,\n 'version': 'opset6',\n 'infer': self.infer,\n 'in_ports_count': 2,\n 'out_ports_count': 1,\n 'axis': 0,\n }, attrs)\n\n def backend_attrs(self):\n return ['axis']\n\n @staticmethod\n def infer(node: Node):\n data_shape = node.in_port(0).data.get_shape()\n indices_shape = node.in_port(1).data.get_shape()\n axis = node.axis\n data_rank = len(data_shape)\n\n assert data_rank >= 1, 'data_rank must be >= 1'\n assert data_rank == len(indices_shape), 'data and indices inputs for node {} must be of the ' \\\n 'same rank. Instead got {} and {}'.\\\n format(node.name, data_rank, len(indices_shape))\n assert -data_rank <= axis < data_rank, 'axis for node {0} must be within interval ' \\\n '[-{1}}, {1} - 1]. Instead got: axis={2}'.\\\n format(node.name, data_rank, axis)\n if axis < 0:\n axis += data_rank\n\n for idx, (data_sz, ind_sz) in enumerate(zip(data_shape, indices_shape)):\n if idx != axis and data_sz != ind_sz:\n raise ValueError('Sizes along axis {} for node {} do not match. data and indices must have ' \n 'equal size along all axes except for axis {}'.format(idx, node.name, axis))\n\n data = node.in_port(0).data.get_value()\n indices = node.in_port(1).data.get_value()\n\n if data is not None and indices is not None:\n out_value = np.empty(indices_shape, dtype=data.dtype)\n for idx in np.ndindex(*indices_shape):\n data_idx = list(idx)\n data_idx[node.axis] = indices[idx]\n out_value[idx] = data[tuple(data_idx)]\n node.out_port(0).data.set_value(out_value)\n else:\n node.out_port(0).data.set_shape(indices_shape)\n\n PermuteAttrs.create_permute_attrs(node, attrs=[('axis', 'input:0')])\n", "\"\"\"\n Copyright (C) 2018-2021 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 numpy as np\n\nfrom extensions.ops.elementwise import Add, Mul\nfrom mo.front.common.replacement import FrontReplacementPattern\nfrom mo.graph.graph import Graph\nfrom mo.ops.const import Const\n\n\nclass BinaryFakeQuantizeNormalization(FrontReplacementPattern):\n \"\"\"\n FakeQuantize in binary form has exceptional meaning of 1 and 2 input nodes.\n This nodes values should be equal and express threshold to quantize tensors to two levels..\n \"\"\"\n enabled = True\n\n @staticmethod\n def pattern():\n return dict(\n nodes=[\n ('min_in', dict()),\n ('max_in', dict()),\n ('quantize', dict(op='FakeQuantize', levels=2))],\n edges=[\n ('min_in', 'quantize', {'in': 1}),\n ('max_in', 'quantize', {'in': 2})\n ]\n )\n\n def replace_pattern(self, graph: Graph, match: dict):\n quantize = match['quantize']\n\n sum_node = Add(graph, dict()).create_node()\n const = Const(graph, {'value': np.array(0.5)}).create_node()\n mul_node = Mul(graph, dict()).create_node()\n\n mul_node.in_port(0).connect(sum_node.out_port(0))\n mul_node.in_port(1).connect(const.out_port(0))\n\n quantize.in_port(1).get_connection().get_source().connect(sum_node.in_port(0))\n quantize.in_port(2).get_connection().get_source().connect(sum_node.in_port(1))\n\n quantize.in_port(1).disconnect()\n quantize.in_port(2).disconnect()\n\n mul_node.out_port(0).connect(quantize.in_port(1))\n mul_node.out_port(0).connect(quantize.in_port(2))\n", "\"\"\"\n Copyright (C) 2018-2021 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\"\"\"\nimport numpy as np\n\nfrom extensions.ops.activation_ops import SoftPlus\nfrom mo.front.common.replacement import FrontReplacementSubgraph\nfrom mo.front.subgraph_matcher import SubgraphMatch\nfrom mo.graph.graph import Graph, rename_nodes\nfrom mo.middle.pattern_match import check_value\n\n\nclass SoftplusFusion(FrontReplacementSubgraph):\n \"\"\"\n The transformation looks for the pattern for the Softplus function: Softplus(x) = ln(1 + e^x)\n \"\"\"\n enabled = True\n\n def pattern(self):\n return dict(\n nodes=[\n ('exp', dict(op='Exp')),\n ('add', dict(op='Add')),\n ('const_1', dict(op='Const', value=lambda v: check_value(v, lambda x: np.allclose(x, 1.0, atol=1e-6)))),\n ('ln', dict(op='Log')),\n ],\n edges=[\n ('exp', 'add', {}),\n ('const_1', 'add', {}),\n ('add', 'ln', {}),\n ])\n\n def replace_sub_graph(self, graph: Graph, match: [dict, SubgraphMatch]):\n ln = match['ln']\n exp = match['exp']\n\n ln_name = ln.soft_get('name', ln.id)\n\n softplus = SoftPlus(graph, {}).create_node()\n softplus.in_port(0).connect(exp.in_port(0).get_source())\n ln.out_port(0).get_connection().set_source(softplus.out_port(0))\n\n rename_nodes([(ln, ln_name + '/TBR'), (softplus, ln_name)])\n", "#!/usr/bin/env python\n\"\"\"\n Copyright (c) 2018-2021 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\"\"\"\nfrom __future__ import print_function\nimport sys\nimport os\nfrom argparse import ArgumentParser, SUPPRESS\nimport cv2\nimport numpy as np\nimport logging as log\nfrom openvino.inference_engine import IECore\n\nimport ngraph as ng\n\ndef build_argparser():\n parser = ArgumentParser(add_help=False)\n args = parser.add_argument_group(\"Options\")\n args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')\n args.add_argument(\"-m\", \"--model\", help=\"Required. Path to an .xml or .onnx file with a trained model.\",\n required=True, type=str)\n args.add_argument(\"-i\", \"--input\", help=\"Required. Path to an image file.\",\n required=True, type=str)\n args.add_argument(\"-l\", \"--cpu_extension\",\n help=\"Optional. Required for CPU custom layers. \"\n \"Absolute path to a shared library with the kernels implementations.\",\n type=str, default=None)\n args.add_argument(\"-d\", \"--device\",\n help=\"Optional. Specify the target device to infer on; \"\n \"CPU, GPU, FPGA or MYRIAD is acceptable. \"\n \"Sample will look for a suitable plugin for device specified (CPU by default)\",\n default=\"CPU\", type=str)\n args.add_argument(\"--labels\", help=\"Optional. Labels mapping file\", default=None, type=str)\n args.add_argument(\"-nt\", \"--number_top\", help=\"Optional. Number of top results\", default=10, type=int)\n\n return parser\n\n\ndef main():\n log.basicConfig(format=\"[ %(levelname)s ] %(message)s\", level=log.INFO, stream=sys.stdout)\n args = build_argparser().parse_args()\n log.info(\"Loading Inference Engine\")\n ie = IECore()\n\n # ---1. Read a model in OpenVINO Intermediate Representation (.xml and .bin files) or ONNX (.onnx file) format ---\n model = args.model\n log.info(f\"Loading network:\\n\\t{model}\")\n net = ie.read_network(model=model)\n # -----------------------------------------------------------------------------------------------------\n\n # ------------- 2. Load Plugin for inference engine and extensions library if specified --------------\n log.info(\"Device info:\")\n versions = ie.get_versions(args.device)\n print(f\"{' ' * 8}{args.device}\")\n print(f\"{' ' * 8}MKLDNNPlugin version ......... {versions[args.device].major}.{versions[args.device].minor}\")\n print(f\"{' ' * 8}Build ........... {versions[args.device].build_number}\")\n\n if args.cpu_extension and \"CPU\" in args.device:\n ie.add_extension(args.cpu_extension, \"CPU\")\n log.info(f\"CPU extension loaded: {args.cpu_extension}\")\n # -----------------------------------------------------------------------------------------------------\n\n # --------------------------- 3. Read and preprocess input --------------------------------------------\n for input_key in net.input_info:\n if len(net.input_info[input_key].input_data.layout) == 4:\n n, c, h, w = net.input_info[input_key].input_data.shape\n\n images = np.ndarray(shape=(n, c, h, w))\n images_hw = []\n for i in range(n):\n image = cv2.imread(args.input)\n ih, iw = image.shape[:-1]\n images_hw.append((ih, iw))\n log.info(\"File was added: \")\n log.info(f\" {args.input}\")\n if (ih, iw) != (h, w):\n log.warning(f\"Image {args.input} is resized from {image.shape[:-1]} to {(h, w)}\")\n image = cv2.resize(image, (w, h))\n image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW\n images[i] = image\n # -----------------------------------------------------------------------------------------------------\n\n # --------------------------- 4. Configure input & output ---------------------------------------------\n # --------------------------- Prepare input blobs -----------------------------------------------------\n log.info(\"Preparing input blobs\")\n assert (len(net.input_info.keys()) == 1 or len(\n net.input_info.keys()) == 2), \"Sample supports topologies only with 1 or 2 inputs\"\n out_blob = next(iter(net.outputs))\n input_name, input_info_name = \"\", \"\"\n\n for input_key in net.input_info:\n if len(net.input_info[input_key].layout) == 4:\n input_name = input_key\n net.input_info[input_key].precision = 'U8'\n elif len(net.input_info[input_key].layout) == 2:\n input_info_name = input_key\n net.input_info[input_key].precision = 'FP32'\n if net.input_info[input_key].input_data.shape[1] != 3 and net.input_info[input_key].input_data.shape[1] != 6 or \\\n net.input_info[input_key].input_data.shape[0] != 1:\n log.error('Invalid input info. Should be 3 or 6 values length.')\n\n data = {}\n data[input_name] = images\n\n if input_info_name != \"\":\n detection_size = net.input_info[input_info_name].input_data.shape[1]\n infos = np.ndarray(shape=(n, detection_size), dtype=float)\n for i in range(n):\n infos[i, 0] = h\n infos[i, 1] = w\n for j in range(2, detection_size):\n infos[i, j] = 1.0\n data[input_info_name] = infos\n\n # --------------------------- Prepare output blobs ----------------------------------------------------\n log.info('Preparing output blobs')\n\n output_name, output_info = \"\", None\n func = ng.function_from_cnn(net)\n if func:\n ops = func.get_ordered_ops()\n for op in ops:\n if op.friendly_name in net.outputs and op.get_type_name() == \"DetectionOutput\":\n output_name = op.friendly_name\n output_info = net.outputs[output_name]\n break\n else:\n output_name = list(net.outputs.keys())[0]\n output_info = net.outputs[output_name]\n\n if output_name == \"\":\n log.error(\"Can't find a DetectionOutput layer in the topology\")\n\n output_dims = output_info.shape\n if len(output_dims) != 4:\n log.error(\"Incorrect output dimensions for SSD model\")\n max_proposal_count, object_size = output_dims[2], output_dims[3]\n\n if object_size != 7:\n log.error(\"Output item should have 7 as a last dimension\")\n\n output_info.precision = \"FP32\"\n # -----------------------------------------------------------------------------------------------------\n\n # --------------------------- Performing inference ----------------------------------------------------\n log.info(\"Loading model to the device\")\n exec_net = ie.load_network(network=net, device_name=args.device)\n log.info(\"Creating infer request and starting inference\")\n res = exec_net.infer(inputs=data)\n # -----------------------------------------------------------------------------------------------------\n\n # --------------------------- Read and postprocess output ---------------------------------------------\n log.info(\"Processing output blobs\")\n res = res[out_blob]\n boxes, classes = {}, {}\n data = res[0][0]\n for number, proposal in enumerate(data):\n if proposal[2] > 0:\n imid = np.int(proposal[0])\n ih, iw = images_hw[imid]\n label = np.int(proposal[1])\n confidence = proposal[2]\n xmin = np.int(iw * proposal[3])\n ymin = np.int(ih * proposal[4])\n xmax = np.int(iw * proposal[5])\n ymax = np.int(ih * proposal[6])\n print(f\"[{number},{label}] element, prob = {confidence:.6f} ({xmin},{ymin})-({xmax},{ymax}) \"\n f\"batch id : {imid}\", end=\"\")\n if proposal[2] > 0.5:\n print(\" WILL BE PRINTED!\")\n if not imid in boxes.keys():\n boxes[imid] = []\n boxes[imid].append([xmin, ymin, xmax, ymax])\n if not imid in classes.keys():\n classes[imid] = []\n classes[imid].append(label)\n else:\n print()\n\n tmp_image = cv2.imread(args.input)\n for imid in classes:\n for box in boxes[imid]:\n cv2.rectangle(tmp_image, (box[0], box[1]), (box[2], box[3]), (232, 35, 244), 2)\n cv2.imwrite(\"out.bmp\", tmp_image)\n log.info(\"Image out.bmp created!\")\n # -----------------------------------------------------------------------------------------------------\n\n log.info(\"Execution successful\\n\")\n log.info(\n \"This sample is an API example, for any performance measurements please use the dedicated benchmark_app tool\")\n\n\nif __name__ == '__main__':\n sys.exit(main() or 0)\n", "\"\"\"\n Copyright (C) 2018-2021 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 numpy as np\n\nfrom mo.graph.graph import Graph\nfrom mo.middle.passes.eliminate import remove_op_node_with_data_node\nfrom mo.middle.replacement import MiddleReplacementPattern\n\n\nclass RemoveUselessPad(MiddleReplacementPattern):\n \"\"\"\n The Pad layer is removed if all padding values are equal to 0 (Constant values).\n \"\"\"\n enabled = True\n\n def find_and_replace_pattern(self, graph: Graph):\n for node in graph.get_op_nodes(op='Pad'):\n all_pads_zeros = True\n for in_port_ind in range(1, 3):\n input_node = node.in_port(in_port_ind).get_source().node\n value = input_node.soft_get('value', None)\n all_pads_zeros &= input_node.soft_get('type') == 'Const' and value is not None and np.all(value == 0)\n\n if all_pads_zeros:\n remove_op_node_with_data_node(graph, node)\n", "\"\"\"\n Copyright (C) 2018-2021 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 numpy as np\n\nfrom mo.front.common.partial_infer.utils import int64_array\nfrom mo.utils.graph import Node\nfrom mo.utils.ir_reader.extender import Extender\n\n\nclass ConvolutionBackpropData_extender(Extender):\n op = 'ConvolutionBackpropData'\n\n @staticmethod\n def extend(op: Node):\n common_backpropdata_extender(op)\n\n\nclass GroupConvolutionBackpropData_extender(Extender):\n op = 'GroupConvolutionBackpropData'\n\n @staticmethod\n def extend(op: Node):\n common_backpropdata_extender(op)\n\n\ndef common_backpropdata_extender(op: Node):\n if op.has_valid('output_padding'):\n op.output_padding = int64_array([0, 0] + op.output_padding)\n\n dim = len(op.strides)\n\n if op.has_valid('pads_begin') and op.has_valid('pads_end'):\n pad = [[0, 0], [0, 0]]\n pad.extend([[op.pads_begin[i], op.pads_end[i]] for i in range(dim)])\n\n op['pad'] = int64_array(pad)\n\n op['spatial_dims'] = [i + 2 for i in range(dim)]\n\n if not op.has_valid('dilations'):\n op['dilations'] = [1 for _ in range(dim)]\n if not op.has_valid('strides'):\n op['strides'] = [1 for _ in range(dim)]\n\n op['dilation'] = int64_array([1, 1] + op.dilations)\n op['stride'] = int64_array([1, 1] + op.strides)\n\n op['infer'] = backpropdata_infer\n\n\ndef backpropdata_infer(op: Node):\n op['new_input_shapes'] = list()\n for n in op.in_nodes():\n op.new_input_shapes.append(op.in_node(n).shape)\n assert len(op.new_input_shapes) == len(op.old_input_shapes)\n\n for i in range(len(op.new_input_shapes)):\n assert np.array_equal(op.new_input_shapes[i], op.old_input_shapes[i]), 'Something wrong happened while ' \\\n '{} shape infer with type {}!'.format(op.name, op.type)\n\n Extender.const_shape_infer(op)\n", "#!/usr/bin/env python\n\"\"\"\n Copyright (C) 2018-2021 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\"\"\"\nfrom __future__ import print_function\nimport sys\nimport os\nfrom argparse import ArgumentParser, SUPPRESS\nimport cv2\nimport numpy as np\nimport logging as log\nfrom openvino.inference_engine import IECore\nimport threading\n\n\nclass InferReqWrap:\n def __init__(self, request, id, num_iter):\n self.id = id\n self.request = request\n self.num_iter = num_iter\n self.cur_iter = 0\n self.cv = threading.Condition()\n self.request.set_completion_callback(self.callback, self.id)\n\n def callback(self, statusCode, userdata):\n if (userdata != self.id):\n log.error(f\"Request ID {self.id} does not correspond to user data {userdata}\")\n elif statusCode != 0:\n log.error(f\"Request {self.id} failed with status code {statusCode}\")\n self.cur_iter += 1\n log.info(f\"Completed {self.cur_iter} Async request execution\")\n if self.cur_iter < self.num_iter:\n # here a user can read output containing inference results and put new input\n # to repeat async request again\n self.request.async_infer(self.input)\n else:\n # continue sample execution after last Asynchronous inference request execution\n self.cv.acquire()\n self.cv.notify()\n self.cv.release()\n\n def execute(self, mode, input_data):\n if (mode == \"async\"):\n log.info(f\"Start inference ({self.num_iter} Asynchronous executions)\")\n self.input = input_data\n # Start async request for the first time. Wait all repetitions of the async request\n self.request.async_infer(input_data)\n self.cv.acquire()\n self.cv.wait()\n self.cv.release()\n elif (mode == \"sync\"):\n log.info(f\"Start inference ({self.num_iter} Synchronous executions)\")\n for self.cur_iter in range(self.num_iter):\n # here we start inference synchronously and wait for\n # last inference request execution\n self.request.infer(input_data)\n log.info(f\"Completed {self.cur_iter + 1} Sync request execution\")\n else:\n log.error(\"wrong inference mode is chosen. Please use \\\"sync\\\" or \\\"async\\\" mode\")\n sys.exit(1)\n\n\n\ndef build_argparser():\n parser = ArgumentParser(add_help=False)\n args = parser.add_argument_group('Options')\n args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')\n args.add_argument(\"-m\", \"--model\", help=\"Required. Path to an .xml or .onnx file with a trained model.\",\n required=True, type=str)\n args.add_argument(\"-i\", \"--input\", help=\"Required. Path to an image files\",\n required=True, type=str, nargs=\"+\")\n args.add_argument(\"-l\", \"--cpu_extension\",\n help=\"Optional. Required for CPU custom layers. Absolute path to a shared library with the\"\n \" kernels implementations.\", type=str, default=None)\n args.add_argument(\"-d\", \"--device\",\n help=\"Optional. Specify the target device to infer on; CPU, GPU, FPGA, HDDL or MYRIAD is \"\n \"acceptable. The sample will look for a suitable plugin for device specified. Default value is CPU\",\n default=\"CPU\", type=str)\n args.add_argument(\"--labels\", help=\"Optional. Labels mapping file\", default=None, type=str)\n args.add_argument(\"-nt\", \"--number_top\", help=\"Optional. Number of top results\", default=10, type=int)\n\n return parser\n\ndef main():\n log.basicConfig(format=\"[ %(levelname)s ] %(message)s\", level=log.INFO, stream=sys.stdout)\n args = build_argparser().parse_args()\n\n # Plugin initialization for specified device and load extensions library if specified\n log.info(\"Creating Inference Engine\")\n ie = IECore()\n if args.cpu_extension and 'CPU' in args.device:\n ie.add_extension(args.cpu_extension, \"CPU\")\n\n # Read a model in OpenVINO Intermediate Representation (.xml and .bin files) or ONNX (.onnx file) format\n model = args.model\n log.info(f\"Loading network:\\n\\t{model}\")\n net = ie.read_network(model=model)\n\n assert len(net.input_info.keys()) == 1, \"Sample supports only single input topologies\"\n assert len(net.outputs) == 1, \"Sample supports only single output topologies\"\n\n log.info(\"Preparing input blobs\")\n input_blob = next(iter(net.input_info))\n out_blob = next(iter(net.outputs))\n net.batch_size = len(args.input)\n\n # Read and pre-process input images\n n, c, h, w = net.input_info[input_blob].input_data.shape\n images = np.ndarray(shape=(n, c, h, w))\n for i in range(n):\n image = cv2.imread(args.input[i])\n if image.shape[:-1] != (h, w):\n log.warning(f\"Image {args.input[i]} is resized from {image.shape[:-1]} to {(h, w)}\")\n image = cv2.resize(image, (w, h))\n image = image.transpose((2, 0, 1)) # Change data layout from HWC to CHW\n images[i] = image\n log.info(f\"Batch size is {n}\")\n\n # Loading model to the plugin\n log.info(\"Loading model to the plugin\")\n exec_net = ie.load_network(network=net, device_name=args.device)\n\n # create one inference request for asynchronous execution\n request_id = 0\n infer_request = exec_net.requests[request_id]\n\n num_iter = 10\n request_wrap = InferReqWrap(infer_request, request_id, num_iter)\n # Start inference request execution. Wait for last execution being completed\n request_wrap.execute(\"async\", {input_blob: images})\n\n # Processing output blob\n log.info(\"Processing output blob\")\n res = infer_request.output_blobs[out_blob]\n log.info(f\"Top {args.number_top} results: \")\n if args.labels:\n with open(args.labels, 'r') as f:\n labels_map = [x.split(sep=' ', maxsplit=1)[-1].strip() for x in f]\n else:\n labels_map = None\n classid_str = \"classid\"\n probability_str = \"probability\"\n for i, probs in enumerate(res.buffer):\n probs = np.squeeze(probs)\n top_ind = np.argsort(probs)[-args.number_top:][::-1]\n print(f\"Image {args.input[i]}\\n\")\n print(classid_str, probability_str)\n print(f\"{'-' * len(classid_str)} {'-' * len(probability_str)}\")\n for id in top_ind:\n det_label = labels_map[id] if labels_map else f\"{id}\"\n label_length = len(det_label)\n space_num_before = (7 - label_length) // 2\n space_num_after = 7 - (space_num_before + label_length) + 2\n print(f\"{' ' * space_num_before}{det_label}\"\n f\"{' ' * space_num_after}{probs[id]:.7f}\")\n print(\"\\n\")\n log.info(\"This sample is an API example, for any performance measurements please use the dedicated benchmark_app tool\\n\")\n\n\nif __name__ == '__main__':\n sys.exit(main() or 0)\n", "\"\"\"\n Copyright (C) 2018-2021 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\"\"\"\nimport numpy as np\nfrom onnx import numpy_helper\n\nfrom mo.front.extractor import FrontExtractorOp\nfrom mo.front.onnx.extractors.utils import onnx_attr\nfrom mo.ops.constant_of_shape import ConstantOfShape\n\n\nclass ConstantOfShapeExtractor(FrontExtractorOp):\n op = 'ConstantOfShape'\n enabled = True\n\n @classmethod\n def extract(cls, node):\n fill_value = onnx_attr(node, 'value', 't', default=np.array([0.0]), dst_type=lambda x: numpy_helper.to_array(x))\n\n ConstantOfShape.update_node_stat(node, {'fill_value': fill_value})\n return cls.enabled\n", "\"\"\"\n Copyright (C) 2018-2021 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 unittest\n\nimport numpy as np\nimport onnx\nfrom generator import generator, generate\n\nfrom extensions.front.onnx.squeeze_ext import SqueezeFrontExtractor\nfrom mo.ops.op import Op\nfrom mo.ops.squeeze import Squeeze\nfrom mo.utils.unittest.extractors import PB\n\n\n@generator\nclass TestSqueezeONNXExt(unittest.TestCase):\n @staticmethod\n def _create_squeeze_node(axes):\n if axes is None:\n pb = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n )\n else:\n pb = onnx.helper.make_node(\n 'Squeeze',\n inputs=['x'],\n outputs=['y'],\n axes=axes,\n )\n\n node = PB({'pb': pb})\n return node\n\n @classmethod\n def setUpClass(cls):\n Op.registered_ops['Squeeze'] = Squeeze\n\n @generate(*[[0, 1, 2, 3], [1], None])\n def test_squeeze_ext(self, axes):\n node = self._create_squeeze_node(axes)\n SqueezeFrontExtractor.extract(node)\n\n exp_res = {\n 'type': 'Squeeze',\n 'squeeze_dims': axes,\n }\n\n for key in exp_res.keys():\n if type(node[key]) in [list, np.ndarray]:\n self.assertTrue(np.array_equal(np.array(node[key]), np.array(exp_res[key])))\n else:\n self.assertEqual(node[key], exp_res[key])\n", "\"\"\"\n Copyright (C) 2018-2021 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 numpy as np\n\nfrom extensions.ops.split import Split, VariadicSplit\nfrom mo.front.common.replacement import FrontReplacementOp\nfrom mo.front.common.replacement import FrontReplacementSubgraph\nfrom mo.front.tf.graph_utils import create_op_with_const_inputs\nfrom mo.graph.graph import Graph\nfrom mo.ops.squeeze import Squeeze\nfrom mo.utils.error import Error\n\n\nclass SqueezeAxis(FrontReplacementOp):\n \"\"\"\n Split-like operations from original frameworks split tensor by a certain `axis` dimension, removing\n dimension over which splitting is performed. The \"Split\" layer of IE doesn't do that.\n This replacer inserts Squeeze operation for each output of the Split nodes to remove the dimension.\n\n It is applicable to Unpack from TF operation and MxNet SliceChannel\n \"\"\"\n enabled = True\n\n def run_before(self):\n return [AttributedSplitToSplit, AttributedVariadicSplitToVariadicSplit]\n\n def find_and_replace_pattern(self, graph: Graph):\n for node in graph.get_op_nodes(squeeze_axis=True):\n name = node.soft_get('name', node.id)\n for out_port in node.out_ports().values():\n if node.has_valid('axis'):\n squeeze_node = create_op_with_const_inputs(graph, Squeeze, {1: np.array(node.axis)},\n {'name': name + '/Squeeze_'})\n out_port.get_connection().insert_node(squeeze_node)\n elif node.is_in_port_connected(1):\n squeeze_node = Squeeze(graph, {'name': name + '/Squeeze_'}).create_node()\n out_port.get_connection().insert_node(squeeze_node)\n node.in_port(1).get_connection().add_destination(squeeze_node.in_port(1))\n else:\n raise Error('Unknown axis to squeeze for node {}'.format(name))\n\n\nclass SplitInputsReconnect(FrontReplacementSubgraph):\n \"\"\"\n Reconnect input ports to fit IR specification\n\n The Split operation in original frameworks (e.g. TF) may have different semantics than IR specification states:\n IE: 0 - input data to Split, 1 - axis of splitting\n TF: 0 - axis of splitting, 1 - input data to Split\n \"\"\"\n enabled = True\n\n def find_and_replace_pattern(self, graph: Graph):\n for node in graph.get_op_nodes(op='Split', input_port=1):\n axis_src = node.in_port(0).get_source()\n node.in_port(0).disconnect()\n node.in_port(1).get_connection().set_destination(node.in_port(0))\n node.in_port(1).connect(axis_src)\n del node['input_port']\n\n\nclass AttributedSplitToSplit(FrontReplacementSubgraph):\n enabled = True\n\n def find_and_replace_pattern(self, graph: Graph):\n for node in graph.get_op_nodes(op='AttributedSplit'):\n name = node.soft_get('name', node.id)\n\n axis = node.soft_get('axis', None)\n assert axis is not None, \\\n 'AttributedSplit should have `axis` parameter set, but it`s not for node {}'.format(name)\n\n num_splits = node.soft_get('num_splits', None)\n assert num_splits is not None, \\\n 'AttributedSplit should have `num_splits` parameter set, but it`s not for node {}'.format(name)\n\n split = create_op_with_const_inputs(graph, Split, {1: np.int64(axis)},\n {'name': name + '/Split', 'num_splits': num_splits})\n\n for idx, port in node.out_ports().items():\n port.get_connection().set_source(split.out_port(idx))\n node.in_port(0).get_connection().set_destination(split.in_port(0))\n graph.remove_node(node.id)\n\n\nclass AttributedVariadicSplitToVariadicSplit(FrontReplacementSubgraph):\n enabled = True\n\n def find_and_replace_pattern(self, graph: Graph):\n for node in graph.get_op_nodes(op='AttributedVariadicSplit'):\n name = node.soft_get('name', node.id)\n\n axis = node.soft_get('axis', None)\n assert axis is not None, \\\n 'AttributedVariadicSplit should have `axis` parameter set, but it`s not for node {}'.format(name)\n\n size_splits = node.soft_get('size_splits', None)\n assert size_splits is not None, \\\n 'AttributedVariadicSplit should have `size_splits` parameter set, but it`s not for node {}'.format(name)\n\n split = create_op_with_const_inputs(graph, VariadicSplit, {1: np.int64(axis), 2: size_splits},\n {'name': name + '/VariadicSplit', 'out_ports_count': len(size_splits)})\n\n for idx, port in node.out_ports().items():\n port.get_connection().set_source(split.out_port(idx))\n\n node.in_port(0).get_connection().set_destination(split.in_port(0))\n graph.remove_node(node.id)\n\n\nclass VariadicSplitInputsSwap(FrontReplacementSubgraph):\n enabled = True\n\n def find_and_replace_pattern(self, graph: Graph):\n for node in graph.get_op_nodes(op='VariadicSplit', swap_axis_and_split_size_inputs=True):\n axis_src = node.in_port(2).get_source()\n node.in_port(2).disconnect()\n node.in_port(1).get_connection().set_destination(node.in_port(2))\n node.in_port(1).connect(axis_src)\n", "\"\"\"\n Copyright (C) 2018-2021 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 numpy as np\n\nfrom mo.front.common.partial_infer.utils import int64_array\nfrom mo.graph.graph import Node, Graph\nfrom mo.ops.op import Op\n\n\nclass LookupTableInsert(Op):\n '''\n This operation has only output control flow edges and no output data edges in some models.\n And for these cases implementation of the shape inference is needed since the shape inference is executed\n before control flow edges resolving. This operation has non-tensor output so the output shape is empty.\n '''\n enabled = False\n op = 'LookupTableInsert'\n\n def __init__(self, graph: Graph, attrs: dict):\n mandatory_props = {\n 'type': None,\n 'op': self.op,\n 'infer': self.infer,\n 'in_ports_count': 3,\n 'out_ports_count': 1,\n }\n super().__init__(graph, mandatory_props, attrs)\n\n @staticmethod\n def infer(node: Node):\n node_name = node.soft_get('name', node.id)\n connected_in_ports = [port for port in node.in_ports().values() if not port.disconnected()]\n assert len(connected_in_ports) == 3, \\\n \"Incorrect number of inputs for {} node\".format(node_name)\n\n # check shapes of input tensors\n keys_shape = node.in_port(1).data.get_shape()\n values_shape = node.in_port(2).data.get_shape()\n assert np.array_equal(keys_shape, values_shape), \\\n 'Shapes of tensors with keys and values must be equal for {} node'.format(node_name)\n\n # set output shape that must be empty\n # since output is not a tensor\n node.out_port(0).data.set_shape(int64_array([]))\n" ]
[ [ "numpy.take" ], [ "numpy.array", "numpy.array_equal" ], [ "numpy.ndindex", "numpy.empty" ], [ "numpy.array" ], [ "numpy.allclose" ], [ "numpy.int", "numpy.ndarray" ], [ "numpy.all" ], [ "numpy.array_equal" ], [ "numpy.argsort", "numpy.squeeze", "numpy.ndarray" ], [ "numpy.array" ], [ "numpy.array" ], [ "numpy.int64", "numpy.array" ], [ "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shaunster0/kornia
[ "71acf455ee36f2050b7be5ea993b6db773f502eb", "71acf455ee36f2050b7be5ea993b6db773f502eb", "71acf455ee36f2050b7be5ea993b6db773f502eb" ]
[ "test/geometry/test_homography.py", "tutorials/filter_edges.py", "kornia/filters/sobel.py" ]
[ "import random\n\nimport pytest\nimport torch\nfrom torch.autograd import gradcheck\n\nimport kornia\nfrom kornia.geometry.homography import find_homography_dlt, find_homography_dlt_iterated\nfrom kornia.testing import assert_close\n\n\nclass TestFindHomographyDLT:\n def test_smoke(self, device, dtype):\n points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)\n points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)\n weights = torch.ones(1, 4, device=device, dtype=dtype)\n H = find_homography_dlt(points1, points2, weights)\n assert H.shape == (1, 3, 3)\n\n @pytest.mark.parametrize(\"batch_size, num_points\", [(1, 4), (2, 5), (3, 6)])\n def test_shape(self, batch_size, num_points, device, dtype):\n B, N = batch_size, num_points\n points1 = torch.rand(B, N, 2, device=device, dtype=dtype)\n points2 = torch.rand(B, N, 2, device=device, dtype=dtype)\n weights = torch.ones(B, N, device=device, dtype=dtype)\n H = find_homography_dlt(points1, points2, weights)\n assert H.shape == (B, 3, 3)\n\n @pytest.mark.parametrize(\"batch_size, num_points\", [(1, 4), (2, 5), (3, 6)])\n def test_shape_noweights(self, batch_size, num_points, device, dtype):\n B, N = batch_size, num_points\n points1 = torch.rand(B, N, 2, device=device, dtype=dtype)\n points2 = torch.rand(B, N, 2, device=device, dtype=dtype)\n H = find_homography_dlt(points1, points2, None)\n assert H.shape == (B, 3, 3)\n\n @pytest.mark.parametrize(\"batch_size, num_points\", [(1, 4), (2, 5), (3, 6)])\n def test_points_noweights(self, batch_size, num_points, device, dtype):\n B, N = batch_size, num_points\n points1 = torch.rand(B, N, 2, device=device, dtype=dtype)\n points2 = torch.rand(B, N, 2, device=device, dtype=dtype)\n weights = torch.ones(B, N, device=device, dtype=dtype)\n H_noweights = find_homography_dlt(points1, points2, None)\n H_withweights = find_homography_dlt(points1, points2, weights)\n assert H_noweights.shape == (B, 3, 3) and H_withweights.shape == (B, 3, 3)\n assert_close(H_noweights, H_withweights, rtol=1e-3, atol=1e-4)\n\n @pytest.mark.parametrize(\"batch_size\", [1, 2, 5])\n def test_clean_points(self, batch_size, device, dtype):\n # generate input data\n points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)\n H = kornia.eye_like(3, points_src)\n H = H * 0.3 * torch.rand_like(H)\n H = H / H[:, 2:3, 2:3]\n\n points_dst = kornia.transform_points(H, points_src)\n weights = torch.ones(batch_size, 10, device=device, dtype=dtype)\n\n # compute transform from source to target\n dst_homo_src = find_homography_dlt(points_src, points_dst, weights)\n\n assert_close(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)\n\n @pytest.mark.grad\n @pytest.mark.skipif(torch.__version__ < '1.7', reason=\"pytorch bug of incopatible types: #33546 fixed in v1.7\")\n def test_gradcheck(self, device):\n # Save initial seed\n initial_seed = torch.random.initial_seed()\n max_number_of_checks = 10\n\n # Test gradients for a max_number_of_checks times\n current_seed = initial_seed\n for i in range(max_number_of_checks):\n torch.manual_seed(current_seed)\n points_src = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)\n points_dst = torch.rand_like(points_src)\n weights = torch.ones_like(points_src)[..., 0]\n try:\n gradcheck(\n find_homography_dlt, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6, raise_exception=True\n )\n\n # Gradcheck failed\n except RuntimeError:\n\n # All iterations failed\n if i == max_number_of_checks - 1:\n assert gradcheck(\n find_homography_dlt,\n (points_src, points_dst, weights),\n rtol=1e-6,\n atol=1e-6,\n raise_exception=True,\n )\n # Next iteration\n else:\n current_seed = random.randrange(0xFFFFFFFFFFFFFFFF)\n continue\n\n # Gradcheck succeed\n torch.manual_seed(initial_seed)\n return\n\n\nclass TestFindHomographyDLTIter:\n def test_smoke(self, device, dtype):\n points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)\n points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)\n weights = torch.ones(1, 4, device=device, dtype=dtype)\n H = find_homography_dlt_iterated(points1, points2, weights, 5)\n assert H.shape == (1, 3, 3)\n\n @pytest.mark.parametrize(\"batch_size, num_points\", [(1, 4), (2, 5), (3, 6)])\n def test_shape(self, batch_size, num_points, device, dtype):\n B, N = batch_size, num_points\n points1 = torch.rand(B, N, 2, device=device, dtype=dtype)\n points2 = torch.rand(B, N, 2, device=device, dtype=dtype)\n weights = torch.ones(B, N, device=device, dtype=dtype)\n H = find_homography_dlt_iterated(points1, points2, weights, 5)\n assert H.shape == (B, 3, 3)\n\n @pytest.mark.parametrize(\"batch_size\", [1, 2])\n def test_clean_points(self, batch_size, device, dtype):\n # generate input data\n points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)\n H = kornia.eye_like(3, points_src)\n H = H * 0.3 * torch.rand_like(H)\n H = H / H[:, 2:3, 2:3]\n\n points_dst = kornia.transform_points(H, points_src)\n weights = torch.ones(batch_size, 10, device=device, dtype=dtype)\n\n # compute transform from source to target\n dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 10)\n\n assert_close(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)\n\n @pytest.mark.grad\n @pytest.mark.skipif(torch.__version__ < '1.7', reason=\"pytorch bug of incopatible types: #33546 fixed in v1.7\")\n def test_gradcheck(self, device):\n\n # Save initial seed\n initial_seed = torch.random.initial_seed()\n max_number_of_checks = 10\n\n # Test gradients for a max_number_of_checks times\n current_seed = initial_seed\n for i in range(max_number_of_checks):\n torch.manual_seed(current_seed)\n points_src = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)\n points_dst = torch.rand_like(points_src)\n weights = torch.ones_like(points_src)[..., 0]\n try:\n gradcheck(\n find_homography_dlt_iterated,\n (points_src, points_dst, weights),\n rtol=1e-6,\n atol=1e-6,\n raise_exception=True,\n )\n\n # Gradcheck failed\n except RuntimeError:\n\n # All iterations failed\n if i == max_number_of_checks - 1:\n assert gradcheck(\n find_homography_dlt_iterated,\n (points_src, points_dst, weights),\n rtol=1e-6,\n atol=1e-6,\n raise_exception=True,\n )\n # Next iteration\n else:\n current_seed = random.randrange(0xFFFFFFFFFFFFFFFF)\n continue\n\n # Gradcheck succeed\n torch.manual_seed(initial_seed)\n return\n\n @pytest.mark.grad\n @pytest.mark.parametrize(\"batch_size\", [1, 2])\n def test_dirty_points_and_gradcheck(self, batch_size, device, dtype):\n # generate input data\n points_src = torch.rand(batch_size, 10, 2, device=device, dtype=dtype)\n H = kornia.eye_like(3, points_src)\n H = H * 0.3 * torch.rand_like(H)\n H = H / H[:, 2:3, 2:3]\n\n points_src = 100.0 * torch.rand(batch_size, 20, 2, device=device, dtype=dtype)\n points_dst = kornia.transform_points(H, points_src)\n\n # making last point an outlier\n points_dst[:, -1, :] += 20\n\n weights = torch.ones(batch_size, 20, device=device, dtype=dtype)\n\n # compute transform from source to target\n dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 0.5, 10)\n\n assert_close(\n kornia.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3\n )\n", "\"\"\"\nCompute filter edges\n====================\n\nIn this tutorial we are going to learn how to compute the first order and second\norder derivatives of an image using `kornia.filters`.\n\"\"\"\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision\nfrom matplotlib import pyplot as plt\n\nimport kornia\n\n#############################\n# We use OpenCV to load an image to memory represented in a numpy.ndarray\nimg_bgr: np.ndarray = cv2.imread('./data/doraemon.png', cv2.IMREAD_COLOR)\n\n#############################\n# Convert the numpy array to torch\nx_bgr: torch.Tensor = kornia.image_to_tensor(img_bgr)\nx_rgb: torch.Tensor = kornia.bgr_to_rgb(x_bgr)\n\n#############################\n# Create batch and normalize\nx_rgb = x_rgb.expand(2, -1, -1, -1) # 4xCxHxW\nx_gray = kornia.rgb_to_grayscale(x_rgb.float() / 255.0)\n\n\ndef imshow(input: torch.Tensor):\n out: torch.Tensor = torchvision.utils.make_grid(input, nrow=2, padding=1)\n out_np: np.ndarray = kornia.tensor_to_image(out)\n plt.imshow(out_np)\n plt.axis('off')\n\n\n#############################\n# Show original\nimshow(x_rgb)\n\n#################################\n# Compute the 1st order derivates\ngrads: torch.Tensor = kornia.spatial_gradient(x_gray, order=1) # BxCx2xHxW\ngrads_x = grads[:, :, 0]\ngrads_y = grads[:, :, 1]\n\n#################################\n# Show first derivatives in x\nimshow(grads_x)\n\n#################################\n# Show first derivatives in y\nimshow(grads_y)\n\n#################################\n# Sobel Edges\n# Once with the gradients in the two directions we can computet the Sobel edges.\n# However, in kornia we already have it implemented.\nx_sobel: torch.Tensor = kornia.sobel(x_gray)\nimshow(x_sobel)\n\n#################################\n# Compute the 2nd order derivates\ngrads: torch.Tensor = kornia.spatial_gradient(x_gray, order=2) # BxCx2xHxW\ngrads_x = grads[:, :, 0]\ngrads_y = grads[:, :, 1]\n\n#################################\n# Show second derivatives in x\nimshow(grads_x)\n\n#################################\n# Show second derivatives in y\nimshow(grads_y)\n\n#################################\n# Comute Laplacian Edges\nx_laplacian: torch.Tensor = kornia.laplacian(x_gray, kernel_size=5)\nimshow(x_laplacian)\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom kornia.filters.kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d\n\n\ndef spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> torch.Tensor:\n r\"\"\"Computes the first order image derivative in both x and y using a Sobel\n operator.\n\n .. image:: _static/img/spatial_gradient.png\n\n Args:\n input: input image tensor with shape :math:`(B, C, H, W)`.\n mode: derivatives modality, can be: `sobel` or `diff`.\n order: the order of the derivatives.\n normalized: whether the output is normalized.\n\n Return:\n the derivatives of the input feature map. with shape :math:`(B, C, 2, H, W)`.\n\n Examples:\n >>> input = torch.rand(1, 3, 4, 4)\n >>> output = spatial_gradient(input) # 1x3x2x4x4\n >>> output.shape\n torch.Size([1, 3, 2, 4, 4])\n \"\"\"\n if not isinstance(input, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(type(input)))\n\n if not len(input.shape) == 4:\n raise ValueError(\"Invalid input shape, we expect BxCxHxW. Got: {}\".format(input.shape))\n # allocate kernel\n kernel: torch.Tensor = get_spatial_gradient_kernel2d(mode, order)\n if normalized:\n kernel = normalize_kernel2d(kernel)\n\n # prepare kernel\n b, c, h, w = input.shape\n tmp_kernel: torch.Tensor = kernel.to(input).detach()\n tmp_kernel = tmp_kernel.unsqueeze(1).unsqueeze(1)\n\n # convolve input tensor with sobel kernel\n kernel_flip: torch.Tensor = tmp_kernel.flip(-3)\n\n # Pad with \"replicate for spatial dims, but with zeros for channel\n spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]\n out_channels: int = 3 if order == 2 else 2\n padded_inp: torch.Tensor = F.pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')[:, :, None]\n\n return F.conv3d(padded_inp, kernel_flip, padding=0).view(b, c, out_channels, h, w)\n\n\ndef spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1) -> torch.Tensor:\n r\"\"\"Computes the first and second order volume derivative in x, y and d using a diff\n operator.\n\n Args:\n input: input features tensor with shape :math:`(B, C, D, H, W)`.\n mode: derivatives modality, can be: `sobel` or `diff`.\n order: the order of the derivatives.\n\n Return:\n the spatial gradients of the input feature map.\n\n Shape:\n - Input: :math:`(B, C, D, H, W)`. D, H, W are spatial dimensions, gradient is calculated w.r.t to them.\n - Output: :math:`(B, C, 3, D, H, W)` or :math:`(B, C, 6, D, H, W)`\n\n Examples:\n >>> input = torch.rand(1, 4, 2, 4, 4)\n >>> output = spatial_gradient3d(input)\n >>> output.shape\n torch.Size([1, 4, 3, 2, 4, 4])\n \"\"\"\n if not isinstance(input, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(type(input)))\n\n if not len(input.shape) == 5:\n raise ValueError(\"Invalid input shape, we expect BxCxDxHxW. Got: {}\".format(input.shape))\n # allocate kernel\n kernel: torch.Tensor = get_spatial_gradient_kernel3d(mode, order)\n\n # prepare kernel\n b, c, d, h, w = input.shape\n tmp_kernel: torch.Tensor = kernel.to(input).detach()\n tmp_kernel = tmp_kernel.repeat(c, 1, 1, 1, 1)\n\n # convolve input tensor with grad kernel\n kernel_flip: torch.Tensor = tmp_kernel.flip(-3)\n\n # Pad with \"replicate for spatial dims, but with zeros for channel\n spatial_pad = [\n kernel.size(2) // 2,\n kernel.size(2) // 2,\n kernel.size(3) // 2,\n kernel.size(3) // 2,\n kernel.size(4) // 2,\n kernel.size(4) // 2,\n ]\n out_ch: int = 6 if order == 2 else 3\n return F.conv3d(F.pad(input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(\n b, c, out_ch, d, h, w\n )\n\n\ndef sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:\n r\"\"\"Computes the Sobel operator and returns the magnitude per channel.\n\n .. image:: _static/img/sobel.png\n\n Args:\n input: the input image with shape :math:`(B,C,H,W)`.\n normalized: if True, L1 norm of the kernel is set to 1.\n eps: regularization number to avoid NaN during backprop.\n\n Return:\n the sobel edge gradient magnitudes map with shape :math:`(B,C,H,W)`.\n\n Example:\n >>> input = torch.rand(1, 3, 4, 4)\n >>> output = sobel(input) # 1x3x4x4\n >>> output.shape\n torch.Size([1, 3, 4, 4])\n \"\"\"\n if not isinstance(input, torch.Tensor):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(type(input)))\n\n if not len(input.shape) == 4:\n raise ValueError(\"Invalid input shape, we expect BxCxHxW. Got: {}\".format(input.shape))\n\n # comput the x/y gradients\n edges: torch.Tensor = spatial_gradient(input, normalized=normalized)\n\n # unpack the edges\n gx: torch.Tensor = edges[:, :, 0]\n gy: torch.Tensor = edges[:, :, 1]\n\n # compute gradient maginitude\n magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)\n\n return magnitude\n\n\nclass SpatialGradient(nn.Module):\n r\"\"\"Computes the first order image derivative in both x and y using a Sobel\n operator.\n\n Args:\n mode: derivatives modality, can be: `sobel` or `diff`.\n order: the order of the derivatives.\n normalized: whether the output is normalized.\n\n Return:\n the sobel edges of the input feature map.\n\n Shape:\n - Input: :math:`(B, C, H, W)`\n - Output: :math:`(B, C, 2, H, W)`\n\n Examples:\n >>> input = torch.rand(1, 3, 4, 4)\n >>> output = SpatialGradient()(input) # 1x3x2x4x4\n \"\"\"\n\n def __init__(self, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> None:\n super(SpatialGradient, self).__init__()\n self.normalized: bool = normalized\n self.order: int = order\n self.mode: str = mode\n\n def __repr__(self) -> str:\n return (\n self.__class__.__name__ + '('\n 'order=' + str(self.order) + ', ' + 'normalized=' + str(self.normalized) + ', ' + 'mode=' + self.mode + ')'\n )\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n return spatial_gradient(input, self.mode, self.order, self.normalized)\n\n\nclass SpatialGradient3d(nn.Module):\n r\"\"\"Computes the first and second order volume derivative in x, y and d using a diff\n operator.\n\n Args:\n mode: derivatives modality, can be: `sobel` or `diff`.\n order: the order of the derivatives.\n\n Return:\n the spatial gradients of the input feature map.\n\n Shape:\n - Input: :math:`(B, C, D, H, W)`. D, H, W are spatial dimensions, gradient is calculated w.r.t to them.\n - Output: :math:`(B, C, 3, D, H, W)` or :math:`(B, C, 6, D, H, W)`\n\n Examples:\n >>> input = torch.rand(1, 4, 2, 4, 4)\n >>> output = SpatialGradient3d()(input)\n >>> output.shape\n torch.Size([1, 4, 3, 2, 4, 4])\n \"\"\"\n\n def __init__(self, mode: str = 'diff', order: int = 1) -> None:\n super(SpatialGradient3d, self).__init__()\n self.order: int = order\n self.mode: str = mode\n self.kernel = get_spatial_gradient_kernel3d(mode, order)\n return\n\n def __repr__(self) -> str:\n return self.__class__.__name__ + '(' 'order=' + str(self.order) + ', ' + 'mode=' + self.mode + ')'\n\n def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore\n return spatial_gradient3d(input, self.mode, self.order)\n\n\nclass Sobel(nn.Module):\n r\"\"\"Computes the Sobel operator and returns the magnitude per channel.\n\n Args:\n normalized: if True, L1 norm of the kernel is set to 1.\n eps: regularization number to avoid NaN during backprop.\n\n Return:\n the sobel edge gradient magnitudes map.\n\n Shape:\n - Input: :math:`(B, C, H, W)`\n - Output: :math:`(B, C, H, W)`\n\n Examples:\n >>> input = torch.rand(1, 3, 4, 4)\n >>> output = Sobel()(input) # 1x3x4x4\n \"\"\"\n\n def __init__(self, normalized: bool = True, eps: float = 1e-6) -> None:\n super(Sobel, self).__init__()\n self.normalized: bool = normalized\n self.eps: float = eps\n\n def __repr__(self) -> str:\n return self.__class__.__name__ + '(' 'normalized=' + str(self.normalized) + ')'\n\n def forward(self, input: torch.Tensor) -> torch.Tensor:\n return sobel(input, self.normalized, self.eps)\n" ]
[ [ "torch.ones", "torch.rand_like", "torch.manual_seed", "torch.random.initial_seed", "torch.rand", "torch.autograd.gradcheck", "torch.ones_like" ], [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.axis" ], [ "torch.sqrt", "torch.nn.functional.pad", "torch.nn.functional.conv3d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jradavenport/helloTESS
[ "1bd4680640e7b92ae3b2eeba19cc63e8b834eead" ]
[ "code/combine_sectors.py" ]
[ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport matplotlib\nimport os\nfrom glob import glob\nfrom matplotlib.colors import LogNorm\n\nfrom scipy.optimize import curve_fit\n\nfrom astropy.table import Table\nimport astropy.io.fits as fits\nfrom astropy.stats import LombScargle, BoxLeastSquares\nimport exoplanet as xo\nfrom stuff import FINDflare, EasyE\n\nmatplotlib.rcParams.update({'font.size':18})\nmatplotlib.rcParams.update({'font.family':'serif'})\n\nftype = '.pdf'\n\n\ndef RunSectors(tess_dir = '/Users/james/Desktop/tess/', run_dir = '/Users/james/Desktop/helloTESS/', clobber=True, Nsector=3):\n '''\n Do some simplier things on stars that are observed in mulitple sectors\n\n should probably be combined with run_sector.py.... but oh well for now!\n '''\n\n sectors = ['sector001', 'sector002', 'sector003', 'sector004', 'sector005', 'sector006', 'sector007', 'sector008']\n\n # just in case glob wants to re-order things, be sure grab them in Sector order\n files = []\n for k in range(len(sectors)):\n files = files + glob(tess_dir + sectors[k] + '/*.fits', recursive=True)\n\n # get the unique object IDs (NOT the simplest way, but matches the next step)\n obj = pd.Series(files).str.split('-', expand=True).groupby(by=2).count().index\n\n # get the count of unique object IDs\n Nobj = pd.Series(files).str.split('-', expand=True).groupby(by=2).count()[0]\n\n # for k in range(max(Nobj)):\n # print(k+1, sum(Nobj > k))\n # obj[0] # example Object ID (TIC #)\n\n o5 = np.where((Nobj > Nsector))[0] # was named \"o5\" because originally wanted Over 5 observations. Now pick other N\n\n print(str(len(o5)) + ' objects with Nobs > 3 Sectors')\n for k in range(0, len(o5)):\n print(k, obj[o5][k])\n files_k = pd.Series(files)[np.where((pd.Series(files).str.split('-', expand=True)[2] == obj[o5][k]))[0]].values\n\n rot_out_k = MultiSector(files_k, clobber=clobber)\n if k==0:\n rot_out = rot_out_k\n else:\n rot_out = pd.concat([rot_out, rot_out_k], ignore_index=True, sort=False)\n rot_out.to_csv(run_dir + '/outputs/longerP_rot_out.csv')\n return\n\n\ndef MultiSector(TICs, tess_dir = '/Users/james/Desktop/tess/',\n run_dir = '/Users/james/Desktop/helloTESS/',\n clobber=False):\n '''\n Run the basic set of tools on every light curve -> NOW FOR MULTI-SECTOR DATA\n\n Produce a diagnostic plot for each light curve\n\n '''\n\n if not os.path.isdir(run_dir + 'figures/longerP'):\n os.makedirs(run_dir + 'figures/longerP')\n\n tbit = False\n for k in range(len(TICs)):\n tbl = -1\n try:\n tbl = Table.read(TICs[k], format='fits')\n tbl['PDCSAP_FLUX'] = tbl['PDCSAP_FLUX'] - np.nanmedian(tbl['PDCSAP_FLUX'])\n\n if tbit == False:\n df_tbl = tbl.to_pandas()\n tbit = True\n else:\n df_tbl = pd.concat([df_tbl, tbl.to_pandas()], ignore_index=True, sort=False)\n\n except:\n tbl = -1\n print('bad file: ' + TICs[k])\n\n\n\n df_tbl['PDCSAP_FLUX'] = df_tbl['PDCSAP_FLUX'] + np.nanmedian(df_tbl['SAP_FLUX'])\n\n # make harsh quality cuts, and chop out a known bad window of time (might add more later)\n AOK = (df_tbl['QUALITY'] == 0) & ((df_tbl['TIME'] < 1347) | (df_tbl['TIME'] > 1350))\n\n # do a running median for a basic smooth\n smo = df_tbl['PDCSAP_FLUX'][AOK].rolling(128, center=True).median().values\n med = np.nanmedian(smo)\n\n\n # make an output plot for every file\n figname = run_dir + 'figures/longerP/' + TICs[0].split('-')[2] + '.jpeg'\n makefig = ((not os.path.exists(figname)) | clobber)\n\n if makefig:\n plt.figure(figsize=(14,6))\n plt.errorbar(df_tbl['TIME'][AOK], df_tbl['PDCSAP_FLUX'][AOK]/med, yerr=df_tbl['PDCSAP_FLUX_ERR'][AOK]/med,\n linestyle=None, alpha=0.25, label='PDC_FLUX')\n plt.plot(df_tbl['TIME'][AOK], smo/med, label='128pt MED', c='orange')\n\n# Smed = np.nanmedian(df_tbl['SAP_FLUX'][AOK])\n# plt.errorbar(df_tbl['TIME'][AOK], df_tbl['SAP_FLUX'][AOK]/Smed, yerr=df_tbl['SAP_FLUX_ERR'][AOK]/Smed,\n# linestyle=None, alpha=0.25, label='SAP_FLUX')\n\n\n # require at least 1000 good datapoints for analysis\n if sum(AOK) > 1000:\n # find OK points in the smoothed LC\n SOK = np.isfinite(smo)\n\n\n # Lomb Scargle\n LS = LombScargle(df_tbl['TIME'][AOK][SOK], smo[SOK]/med, dy=df_tbl['PDCSAP_FLUX_ERR'][AOK][SOK]/med)\n frequency, power = LS.autopower(minimum_frequency=1./40.,\n maximum_frequency=1./0.1,\n samples_per_peak=7)\n best_frequency = frequency[np.argmax(power)]\n\n per_out = 1./best_frequency\n per_amp = np.nanmax(power)\n per_med = np.nanmedian(power)\n per_std = np.nanstd(smo[SOK]/med)\n\n if np.nanmax(power) > 0.2:\n LSmodel = LS.model(df_tbl['TIME'][AOK][SOK], best_frequency)\n if makefig:\n plt.plot(df_tbl['TIME'][AOK][SOK], LSmodel,\n label='L-S P='+format(1./best_frequency, '6.3f')+'d, pk='+format(np.nanmax(power), '6.3f'),\n c='green')\n\n\n # ACF w/ Exoplanet package\n acf = xo.autocorr_estimator(df_tbl['TIME'][AOK][SOK].values, smo[SOK]/med,\n yerr=df_tbl['PDCSAP_FLUX_ERR'][AOK][SOK].values/med,\n min_period=0.1, max_period=40, max_peaks=2)\n ACF_1pk = -1\n ACF_1dt = -1\n if len(acf['peaks']) > 0:\n ACF_1dt = acf['peaks'][0]['period']\n ACF_1pk = acf['autocorr'][1][np.where((acf['autocorr'][0] == acf['peaks'][0]['period']))[0]][0]\n\n if makefig:\n plt.plot(df_tbl['TIME'][AOK][SOK],\n np.nanstd(smo[SOK]/med) * ACF_1pk * np.sin(df_tbl['TIME'][AOK][SOK] / ACF_1dt * 2 * np.pi) + 1,\n label = 'ACF=' + format(ACF_1dt, '6.3f') + 'd, pk=' + format(ACF_1pk, '6.3f'), lw=2,\n alpha=0.7, c='FireBrick')\n\n\n # here is where a simple Eclipse (EB) finder goes\n EE = EasyE(smo[SOK]/med, df_tbl['PDCSAP_FLUX_ERR'][AOK][SOK]/med, N1=5, N2=3, N3=2)\n EclFlg = 0\n if np.size(EE) > 0:\n EclFlg = 1\n if makefig:\n for j in range(len(EE[0])):\n plt.scatter(df_tbl['TIME'][AOK][SOK][(EE[0][j]):(EE[1][j]+1)],\n smo[SOK] [(EE[0][j]):(EE[1][j]+1)] / med,\n color='k', marker='s', s=5, alpha=0.75, label='_nolegend_')\n plt.scatter([],[], color='k', marker='s', s=5, alpha=0.75, label='Ecl?')\n\n\n\n # add BLS\n# bls = BoxLeastSquares(df_tbl['TIME'][AOK][SOK], smo[SOK]/med, dy=df_tbl['PDCSAP_FLUX_ERR'][AOK][SOK]/med)\n# blsP = bls.autopower(0.1, method='fast', objective='snr')\n# blsPer = blsP['period'][np.argmax(blsP['power'])]\n# if ((4*np.nanstd(blsP['power']) + np.nanmedian(blsP['power']) < np.nanmax(blsP['power'])) &\n# (np.nanmax(blsP['power']) > 50.) &\n# (blsPer < 0.95 * np.nanmax(blsP['period']))\n# ):\n# blsPeriod = blsPer\n# blsAmpl = np.nanmax(blsP['power'])\n# plt.plot([],[], ' ', label='BLS='+format(blsPer, '6.3f')+'d')\n\n if makefig:\n plt.title(TICs[0].split('-')[2], fontsize=12)\n plt.ylabel('Flux')\n plt.xlabel('BJD - 2457000 (days)')\n plt.legend(fontsize=10)\n\n plt.savefig(figname, bbox_inches='tight', pad_inches=0.25, dpi=100)\n plt.close()\n\n\n\n# # write per-sector output files\n# ALL_TIC = pd.Series(files_i).str.split('-', expand=True).iloc[:,-3].astype('int')\n\n# flare_out = pd.DataFrame(data={'TIC':ALL_TIC[FL_id], 'i0':FL_t0, 'i1':FL_t1, 'med':FL_f0, 'peak':FL_f1})\n# flare_out.to_csv(run_dir + sector + '_flare_out.csv')\n\n rot_out = pd.DataFrame(data={'TIC':TICs[0].split('-')[2],\n 'per':per_out, 'Pamp':per_amp, 'Pmed':per_med, 'StdLC':per_std,\n 'acf_pk':ACF_1pk, 'acf_per':ACF_1dt, 'ecl_flg':EclFlg}, index=[0])\n # 'bls_period':blsPeriod, 'bls_ampl':blsAmpl, )\n# rot_out.to_csv(run_dir + sector + '_rot_out.csv')\n\n return rot_out\n\n\nif __name__ == \"__main__\":\n '''\n let this file be called from the terminal directly. e.g.:\n $ python analysis.py\n '''\n RunSectors()\n\n\n\n\n### junk code i probably dont need\n# sect1 = glob(tess_dir + sectors[0] + '/*.fits', recursive=True)\n# sect2 = glob(tess_dir + sectors[1] + '/*.fits', recursive=True)\n# sect3 = glob(tess_dir + sectors[2] + '/*.fits', recursive=True)\n# sect4 = glob(tess_dir + sectors[3] + '/*.fits', recursive=True)\n# sect5 = glob(tess_dir + sectors[4] + '/*.fits', recursive=True)\n# sect6 = glob(tess_dir + sectors[5] + '/*.fits', recursive=True)\n#\n# files = sect1 + sect2 + sect3 + sect4 + sect5 + sect6\n# # make into an array for looping later!\n# s_lens = [len(sect1), len(sect2), len(sect3), len(sect4), len(sect5), len(sect6)]\n# print(s_lens, len(files))\n" ]
[ [ "numpy.nanmax", "matplotlib.pyplot.legend", "numpy.nanmedian", "pandas.Series", "matplotlib.pyplot.plot", "numpy.nanstd", "numpy.where", "numpy.sin", "numpy.size", "numpy.argmax", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.close", "matplotlib.pyplot.figure", "pandas.concat", "matplotlib.pyplot.savefig", "matplotlib.rcParams.update", "matplotlib.pyplot.ylabel", "numpy.isfinite", "matplotlib.pyplot.scatter", "matplotlib.pyplot.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
pavstar619/HackerRank
[ "eb6c95e16688c02921c1df6b6ea613667a251457" ]
[ "Python/Numpy/Shape and Reshape.py" ]
[ "import numpy as np\n\nclass Main:\n def __init__(self):\n self.li = list(map(int, input().split()))\n self.np_li = np.array(self.li)\n \n def output(self):\n print(np.reshape(self.np_li, (3,3)))\n \nif __name__ == '__main__':\n obj = Main()\n obj.output()\n" ]
[ [ "numpy.reshape", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kundajelab/pylearn2
[ "17ebf0c37b35637e337b3ae884806d2c99beb31c" ]
[ "pylearn2/models/dbm/layer.py" ]
[ "\"\"\"\nCommon DBM Layer classes\n\"\"\"\nfrom __future__ import print_function\n\n__authors__ = [\"Ian Goodfellow\", \"Vincent Dumoulin\"]\n__copyright__ = \"Copyright 2012-2013, Universite de Montreal\"\n__credits__ = [\"Ian Goodfellow\"]\n__license__ = \"3-clause BSD\"\n__maintainer__ = \"LISA Lab\"\n\nimport functools\nimport logging\nimport numpy as np\nimport operator\nfrom theano.compat.six.moves import input, reduce, xrange\nimport time\nimport warnings\n\nfrom theano import tensor as T, function, config\nimport theano\nfrom theano.gof.op import get_debug_values\nfrom theano.printing import Print\n\nfrom pylearn2.compat import OrderedDict\nfrom pylearn2.expr.nnet import sigmoid_numpy\nfrom pylearn2.expr.probabilistic_max_pooling import max_pool_channels, max_pool_b01c, max_pool, max_pool_c01b\nfrom pylearn2.linear.conv2d import make_random_conv2D, make_sparse_random_conv2D\nfrom pylearn2.linear.conv2d_c01b import setup_detector_layer_c01b\nfrom pylearn2.linear.matrixmul import MatrixMul\nfrom pylearn2.models import Model\nfrom pylearn2.models.dbm import init_sigmoid_bias_from_marginals\nfrom pylearn2.space import VectorSpace, CompositeSpace, Conv2DSpace, Space\nfrom pylearn2.utils import is_block_gradient\nfrom pylearn2.utils import sharedX, safe_zip, py_integer_types, block_gradient\nfrom pylearn2.utils.exc import reraise_as\nfrom pylearn2.utils.rng import make_theano_rng\nfrom pylearn2.utils import safe_union\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Layer(Model):\n \"\"\"\n Abstract class.\n A layer of a DBM.\n May only belong to one DBM.\n\n Each layer has a state (\"total state\") that can be split into\n the piece that is visible to the layer above (\"upward state\")\n and the piece that is visible to the layer below (\"downward state\").\n (Since visible layers don't have a downward state, the downward_state\n method only appears in the DBM_HiddenLayer subclass)\n\n For simple layers, all three of these are the same thing.\n \"\"\"\n\n def get_dbm(self):\n \"\"\"\n Returns the DBM that this layer belongs to, or None\n if it has not been assigned to a DBM yet.\n \"\"\"\n\n if hasattr(self, 'dbm'):\n return self.dbm\n\n return None\n\n def set_dbm(self, dbm):\n \"\"\"\n Assigns this layer to a DBM.\n\n Parameters\n ----------\n dbm : WRITEME\n \"\"\"\n assert self.get_dbm() is None\n self.dbm = dbm\n\n def get_total_state_space(self):\n \"\"\"\n Returns the Space that the layer's total state lives in.\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement \" +\\\n \"get_total_state_space()\")\n\n\n def get_monitoring_channels(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return OrderedDict()\n\n def get_monitoring_channels_from_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return OrderedDict()\n\n def upward_state(self, total_state):\n \"\"\"\n Takes total_state and turns it into the state that layer_above should\n see when computing P( layer_above | this_layer).\n\n So far this has two uses:\n\n * If this layer consists of a detector sub-layer h that is pooled\n into a pooling layer p, then total_state = (p,h) but layer_above\n should only see p.\n * If the conditional P( layer_above | this_layer) depends on\n parameters of this_layer, sometimes you can play games with\n the state to avoid needing the layers to communicate. So far\n the only instance of this usage is when the visible layer\n is N( Wh, beta). This makes the hidden layer be\n sigmoid( v beta W + b). Rather than having the hidden layer\n explicitly know about beta, we can just pass v beta as\n the upward state.\n\n Parameters\n ----------\n total_state : WRITEME\n\n Notes\n -----\n This method should work both for computing sampling updates\n and for computing mean field updates. So far I haven't encountered\n a case where it needs to do different things for those two\n contexts.\n \"\"\"\n return total_state\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n Returns a shared variable containing an actual state (not a mean field\n state) for this variable.\n\n Parameters\n ----------\n num_examples : WRITEME\n numpy_rng : WRITEME\n\n Returns\n -------\n WRITEME\n \"\"\"\n\n raise NotImplementedError(\"%s doesn't implement make_state\" %\n type(self))\n\n def make_symbolic_state(self, num_examples, theano_rng):\n \"\"\"\n Returns a theano symbolic variable containing an actual state (not a\n mean field state) for this variable.\n\n Parameters\n ----------\n num_examples : WRITEME\n numpy_rng : WRITEME\n\n Returns\n -------\n WRITEME\n \"\"\"\n\n raise NotImplementedError(\"%s doesn't implement make_symbolic_state\" %\n type(self))\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n Returns an expression for samples of this layer's state, conditioned on\n the layers above and below Should be valid as an update to the shared\n variable returned by self.make_state\n\n Parameters\n ----------\n state_below : WRITEME\n Corresponds to layer_below.upward_state(full_state_below),\n where full_state_below is the same kind of object as you get\n out of layer_below.make_state\n state_above : WRITEME\n Corresponds to layer_above.downward_state(full_state_above)\n\n theano_rng : WRITEME\n An MRG_RandomStreams instance\n\n Returns\n -------\n WRITEME\n\n Notes\n -----\n This can return multiple expressions if this layer's total state\n consists of more than one shared variable.\n \"\"\"\n\n if hasattr(self, 'get_sampling_updates'):\n raise AssertionError(\"Looks like \"+str(type(self))+\" needs to rename get_sampling_updates to sample.\")\n\n raise NotImplementedError(\"%s doesn't implement sample\" %\n type(self))\n\n def expected_energy_term(self, state,\n average,\n state_below,\n average_below):\n \"\"\"\n Returns a term of the expected energy of the entire model.\n This term should correspond to the expected value of terms\n of the energy function that:\n\n - involve this layer only\n - if there is a layer below, include terms that involve both this layer\n and the layer below\n\n Do not include terms that involve the layer below only.\n Do not include any terms that involve the layer above, if it\n exists, in any way (the interface doesn't let you see the layer\n above anyway).\n\n Parameters\n ----------\n state_below : WRITEME\n Upward state of the layer below.\n state : WRITEME\n Total state of this layer\n average_below : bool\n If True, the layer below is one of the variables to integrate\n over in the expectation, and state_below gives its variational\n parameters. If False, that layer is to be held constant and\n state_below gives a set of assignments to it average: like\n average_below, but for 'state' rather than 'state_below'\n\n Returns\n -------\n rval : tensor_like\n A 1D theano tensor giving the expected energy term for each example\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement expected_energy_term.\")\n\n def finalize_initialization(self):\n \"\"\"\n Some layers' initialization depends on layer above being initialized,\n which is why this method is called after `set_input_space` has been\n called.\n \"\"\"\n pass\n\n\nclass VisibleLayer(Layer):\n \"\"\"\n Abstract class.\n A layer of a DBM that may be used as a visible layer.\n Currently, all implemented layer classes may be either visible\n or hidden but not both. It may be worth making classes that can\n play both roles though. This would allow getting rid of the BinaryVector\n class.\n \"\"\"\n\n def get_total_state_space(self):\n \"\"\"\n Returns the total state of the layer.\n\n Returns\n -------\n total_state : member of the input space\n The total state of the layer.\n \"\"\"\n return self.get_input_space()\n\n\nclass HiddenLayer(Layer):\n \"\"\"\n Abstract class.\n A layer of a DBM that may be used as a hidden layer.\n \"\"\"\n\n def downward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return total_state\n\n def get_stdev_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement get_stdev_rewards\")\n\n def get_range_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement get_range_rewards\")\n\n def get_l1_act_cost(self, state, target, coeff, eps):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement get_l1_act_cost\")\n\n def get_l2_act_cost(self, state, target, coeff):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(str(type(self))+\" does not implement get_l2_act_cost\")\n\n\nclass BinaryVector(VisibleLayer):\n \"\"\"\n A DBM visible layer consisting of binary random variables living\n in a VectorSpace.\n\n Parameters\n ----------\n nvis : int\n Dimension of the space\n bias_from_marginals : pylearn2.datasets.dataset.Dataset\n Dataset, whose marginals are used to initialize the visible biases\n center : bool\n If True, use Gregoire Montavon's centering trick\n copies : int\n Use this number of virtual copies of the state. All the copies\n still share parameters. This can be useful for balancing the\n amount of influencing two neighboring layers have on each other\n if the layers have different numbers or different types of units.\n Without this replication, layers with more units or units with\n a greater dynamic range would dominate the interaction due to\n the symmetric nature of undirected interactions.\n \"\"\"\n def __init__(self,\n nvis,\n bias_from_marginals = None,\n center = False,\n copies = 1, learn_init_inpainting_state = False):\n\n super(BinaryVector, self).__init__()\n self.__dict__.update(locals())\n del self.self\n # Don't serialize the dataset\n del self.bias_from_marginals\n\n self.space = VectorSpace(nvis)\n self.input_space = self.space\n\n origin = self.space.get_origin()\n\n if bias_from_marginals is None:\n init_bias = np.zeros((nvis,))\n else:\n init_bias = init_sigmoid_bias_from_marginals(bias_from_marginals)\n\n self.bias = sharedX(init_bias, 'visible_bias')\n\n if center:\n self.offset = sharedX(sigmoid_numpy(init_bias))\n\n def get_biases(self):\n \"\"\"\n Returns\n -------\n biases : ndarray\n The numpy value of the biases\n \"\"\"\n return self.bias.get_value()\n\n def set_biases(self, biases, recenter=False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.bias.set_value(biases)\n if recenter:\n assert self.center\n self.offset.set_value(sigmoid_numpy(self.bias.get_value()))\n\n def upward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n rval = total_state - self.offset\n else:\n rval = total_state\n\n if not hasattr(self, 'copies'):\n self.copies = 1\n\n return rval * self.copies\n\n\n def get_params(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return [self.bias]\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n\n assert state_below is None\n if self.copies != 1:\n raise NotImplementedError()\n\n msg = layer_above.downward_message(state_above)\n\n bias = self.bias\n\n z = msg + bias\n\n phi = T.nnet.sigmoid(z)\n\n rval = theano_rng.binomial(size = phi.shape, p = phi, dtype = phi.dtype,\n n = 1 )\n\n return rval\n\n def mf_update(self, state_above, layer_above):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n msg = layer_above.downward_message(state_above)\n mu = self.bias\n\n z = msg + mu\n\n rval = T.nnet.sigmoid(z)\n\n return rval\n\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if not hasattr(self, 'copies'):\n self.copies = 1\n if self.copies != 1:\n raise NotImplementedError()\n driver = numpy_rng.uniform(0.,1., (num_examples, self.nvis))\n mean = sigmoid_numpy(self.bias.get_value())\n sample = driver < mean\n\n rval = sharedX(sample, name = 'v_sample_shared')\n\n return rval\n\n def make_symbolic_state(self, num_examples, theano_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if not hasattr(self, 'copies'):\n self.copies = 1\n if self.copies != 1:\n raise NotImplementedError()\n mean = T.nnet.sigmoid(self.bias)\n rval = theano_rng.binomial(size=(num_examples, self.nvis), p=mean,\n dtype=theano.config.floatX)\n\n return rval\n\n def expected_energy_term(self, state, average, state_below = None, average_below = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if self.center:\n state = state - self.offset\n\n assert state_below is None\n assert average_below is None\n assert average in [True, False]\n self.space.validate(state)\n\n # Energy function is linear so it doesn't matter if we're averaging or not\n rval = -T.dot(state, self.bias)\n\n assert rval.ndim == 1\n\n return rval * self.copies\n\n def init_inpainting_state(self, V, drop_mask, noise = False, return_unmasked = False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n assert drop_mask is None or drop_mask.ndim > 1\n\n unmasked = T.nnet.sigmoid(self.bias.dimshuffle('x',0))\n # this condition is needed later if unmasked is used as V_hat\n assert unmasked.ndim == 2\n # this condition is also needed later if unmasked is used as V_hat\n assert hasattr(unmasked.owner.op, 'scalar_op')\n if drop_mask is not None:\n masked_mean = unmasked * drop_mask\n else:\n masked_mean = unmasked\n if not hasattr(self, 'learn_init_inpainting_state'):\n self.learn_init_inpainting_state = 0\n if not self.learn_init_inpainting_state:\n masked_mean = block_gradient(masked_mean)\n masked_mean.name = 'masked_mean'\n\n if noise:\n theano_rng = theano.sandbox.rng_mrg.MRG_RandomStreams(42)\n # we want a set of random mean field parameters, not binary samples\n unmasked = T.nnet.sigmoid(theano_rng.normal(avg = 0.,\n std = 1., size = masked_mean.shape,\n dtype = masked_mean.dtype))\n masked_mean = unmasked * drop_mask\n masked_mean.name = 'masked_noise'\n\n if drop_mask is None:\n rval = masked_mean\n else:\n masked_V = V * (1-drop_mask)\n rval = masked_mean + masked_V\n rval.name = 'init_inpainting_state'\n\n if return_unmasked:\n assert unmasked.ndim > 1\n return rval, unmasked\n\n return rval\n\n\n def inpaint_update(self, state_above, layer_above, drop_mask = None, V = None, return_unmasked = False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n msg = layer_above.downward_message(state_above)\n mu = self.bias\n\n z = msg + mu\n z.name = 'inpainting_z_[unknown_iter]'\n\n unmasked = T.nnet.sigmoid(z)\n\n if drop_mask is not None:\n rval = drop_mask * unmasked + (1-drop_mask) * V\n else:\n rval = unmasked\n\n rval.name = 'inpainted_V[unknown_iter]'\n\n if return_unmasked:\n owner = unmasked.owner\n assert owner is not None\n op = owner.op\n assert hasattr(op, 'scalar_op')\n assert isinstance(op.scalar_op, T.nnet.sigm.ScalarSigmoid)\n return rval, unmasked\n\n return rval\n\n\n def recons_cost(self, V, V_hat_unmasked, drop_mask = None, use_sum=False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if use_sum:\n raise NotImplementedError()\n\n V_hat = V_hat_unmasked\n\n assert hasattr(V_hat, 'owner')\n owner = V_hat.owner\n assert owner is not None\n op = owner.op\n block_grad = False\n if is_block_gradient(op):\n assert isinstance(op.scalar_op, theano.scalar.Identity)\n block_grad = True\n real, = owner.inputs\n owner = real.owner\n op = owner.op\n\n if not hasattr(op, 'scalar_op'):\n raise ValueError(\"Expected V_hat_unmasked to be generated by an Elemwise op, got \"+str(op)+\" of type \"+str(type(op)))\n assert isinstance(op.scalar_op, T.nnet.sigm.ScalarSigmoid)\n z ,= owner.inputs\n if block_grad:\n z = block_gradient(z)\n\n if V.ndim != V_hat.ndim:\n raise ValueError(\"V and V_hat_unmasked should have same ndim, but are %d and %d.\" % (V.ndim, V_hat.ndim))\n unmasked_cost = V * T.nnet.softplus(-z) + (1 - V) * T.nnet.softplus(z)\n assert unmasked_cost.ndim == V_hat.ndim\n\n if drop_mask is None:\n masked_cost = unmasked_cost\n else:\n masked_cost = drop_mask * unmasked_cost\n\n return masked_cost.mean()\n\nclass BinaryVectorMaxPool(HiddenLayer):\n \"\"\"\n A hidden layer that does max-pooling on binary vectors.\n It has two sublayers, the detector layer and the pooling\n layer. The detector layer is its downward state and the pooling\n layer is its upward state.\n\n Parameters\n ----------\n detector_layer_dim : int\n Number of units in the detector layer\n pool_size : int\n Number of detector units per pooling unit\n (Pools are disjoint)\n layer_name : str\n Name of the layer\n irange : float\n If specified, initialize the weights in U(-irange, irange)\n include_prob : , optional\n Probability of including a weight element in the set of weights\n initialized to U(-irange, irange). If not included it is\n initialized to 0.\n sparse_init : int\n If specified, initialize this many weights in each column\n to be nonzero.\n sparse_stdev : float\n When using sparse_init, the non-zero weights are drawn from\n a Gaussian distribution with mean 0 and standard deviation\n `sparse_stdev`\n init_bias : float or ndarray\n Initialize the biases to this value\n W_lr_scale : float\n Multiply the learning rate on the weights by this number\n b_lr_scale : float\n Multiply the learning rate on the biases by this number\n center : bool\n If True, use Gregoire Montavon's centering trick\n mask_weights : WRITEME\n max_col_norm : float\n Constrain the columns of the weight matrix to have at most\n this norm\n copies : int\n See BinaryVector docstring for explanation\n \"\"\"\n # TODO: this layer uses (pooled, detector) as its total state,\n # which can be confusing when listing all the states in\n # the network left to right. Change this and\n # pylearn2.expr.probabilistic_max_pooling to use\n # (detector, pooled)\n\n def __init__(self,\n detector_layer_dim,\n pool_size,\n layer_name,\n irange = None,\n sparse_init = None,\n sparse_stdev = 1.,\n include_prob = 1.0,\n init_bias = 0.,\n W_lr_scale = None,\n b_lr_scale = None,\n center = False,\n mask_weights = None,\n max_col_norm = None,\n copies = 1):\n super(BinaryVectorMaxPool, self).__init__()\n self.__dict__.update(locals())\n del self.self\n\n self.b = sharedX( np.zeros((self.detector_layer_dim,)) + init_bias, name = layer_name + '_b')\n\n if self.center:\n if self.pool_size != 1:\n raise NotImplementedError()\n self.offset = sharedX(sigmoid_numpy(self.b.get_value()))\n\n def get_lr_scalers(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if not hasattr(self, 'W_lr_scale'):\n self.W_lr_scale = None\n\n if not hasattr(self, 'b_lr_scale'):\n self.b_lr_scale = None\n\n rval = OrderedDict()\n\n if self.W_lr_scale is not None:\n W, = self.transformer.get_params()\n rval[W] = self.W_lr_scale\n\n if self.b_lr_scale is not None:\n rval[self.b] = self.b_lr_scale\n\n return rval\n\n def set_input_space(self, space):\n \"\"\"\n .. todo::\n\n WRITEME\n\n Notes\n -----\n This resets parameters!\n \"\"\"\n\n self.input_space = space\n\n if isinstance(space, VectorSpace):\n self.requires_reformat = False\n self.input_dim = space.dim\n else:\n self.requires_reformat = True\n self.input_dim = space.get_total_dimension()\n self.desired_space = VectorSpace(self.input_dim)\n\n\n if not (self.detector_layer_dim % self.pool_size == 0):\n raise ValueError(\"detector_layer_dim = %d, pool_size = %d. Should be divisible but remainder is %d\" %\n (self.detector_layer_dim, self.pool_size, self.detector_layer_dim % self.pool_size))\n\n self.h_space = VectorSpace(self.detector_layer_dim)\n self.pool_layer_dim = self.detector_layer_dim / self.pool_size\n self.output_space = VectorSpace(self.pool_layer_dim)\n\n rng = self.dbm.rng\n if self.irange is not None:\n assert self.sparse_init is None\n W = rng.uniform(-self.irange,\n self.irange,\n (self.input_dim, self.detector_layer_dim)) * \\\n (rng.uniform(0.,1., (self.input_dim, self.detector_layer_dim))\n < self.include_prob)\n else:\n assert self.sparse_init is not None\n W = np.zeros((self.input_dim, self.detector_layer_dim))\n def mask_rejects(idx, i):\n if self.mask_weights is None:\n return False\n return self.mask_weights[idx, i] == 0.\n for i in xrange(self.detector_layer_dim):\n assert self.sparse_init <= self.input_dim\n for j in xrange(self.sparse_init):\n idx = rng.randint(0, self.input_dim)\n while W[idx, i] != 0 or mask_rejects(idx, i):\n idx = rng.randint(0, self.input_dim)\n W[idx, i] = rng.randn()\n W *= self.sparse_stdev\n\n W = sharedX(W)\n W.name = self.layer_name + '_W'\n\n self.transformer = MatrixMul(W)\n\n W ,= self.transformer.get_params()\n assert W.name is not None\n\n if self.mask_weights is not None:\n expected_shape = (self.input_dim, self.detector_layer_dim)\n if expected_shape != self.mask_weights.shape:\n raise ValueError(\"Expected mask with shape \"+str(expected_shape)+\" but got \"+str(self.mask_weights.shape))\n self.mask = sharedX(self.mask_weights)\n\n @functools.wraps(Model._modify_updates)\n def _modify_updates(self, updates):\n\n # Patch old pickle files\n if not hasattr(self, 'mask_weights'):\n self.mask_weights = None\n if not hasattr(self, 'max_col_norm'):\n self.max_col_norm = None\n\n if self.mask_weights is not None:\n W ,= self.transformer.get_params()\n if W in updates:\n updates[W] = updates[W] * self.mask\n\n if self.max_col_norm is not None:\n W, = self.transformer.get_params()\n if W in updates:\n updated_W = updates[W]\n col_norms = T.sqrt(T.sum(T.sqr(updated_W), axis=0))\n desired_norms = T.clip(col_norms, 0, self.max_col_norm)\n updates[W] = updated_W * (desired_norms / (1e-7 + col_norms))\n\n\n def get_total_state_space(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return CompositeSpace((self.output_space, self.h_space))\n\n def get_params(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n assert self.b.name is not None\n W ,= self.transformer.get_params()\n assert W.name is not None\n rval = self.transformer.get_params()\n assert not isinstance(rval, set)\n rval = list(rval)\n assert self.b not in rval\n rval.append(self.b)\n return rval\n\n def get_weight_decay(self, coeff):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if isinstance(coeff, str):\n coeff = float(coeff)\n assert isinstance(coeff, float) or hasattr(coeff, 'dtype')\n W ,= self.transformer.get_params()\n return coeff * T.sqr(W).sum()\n\n def get_weights(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.requires_reformat:\n # This is not really an unimplemented case.\n # We actually don't know how to format the weights\n # in design space. We got the data in topo space\n # and we don't have access to the dataset\n raise NotImplementedError()\n W ,= self.transformer.get_params()\n return W.get_value()\n\n def set_weights(self, weights):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n W, = self.transformer.get_params()\n W.set_value(weights)\n\n def set_biases(self, biases, recenter = False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.b.set_value(biases)\n if recenter:\n assert self.center\n if self.pool_size != 1:\n raise NotImplementedError()\n self.offset.set_value(sigmoid_numpy(self.b.get_value()))\n\n def get_biases(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return self.b.get_value()\n\n def get_weights_format(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return ('v', 'h')\n\n def get_weights_view_shape(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n total = self.detector_layer_dim\n cols = self.pool_size\n if cols == 1:\n # Let the PatchViewer decidew how to arrange the units\n # when they're not pooled\n raise NotImplementedError()\n # When they are pooled, make each pooling unit have one row\n rows = total / cols\n return rows, cols\n\n\n def get_weights_topo(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if not isinstance(self.input_space, Conv2DSpace):\n raise NotImplementedError()\n\n W ,= self.transformer.get_params()\n\n W = W.T\n\n W = W.reshape((self.detector_layer_dim, self.input_space.shape[0],\n self.input_space.shape[1], self.input_space.num_channels))\n\n W = Conv2DSpace.convert(W, self.input_space.axes, ('b', 0, 1, 'c'))\n\n return function([], W)()\n\n def upward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n p,h = total_state\n self.h_space.validate(h)\n self.output_space.validate(p)\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n return p - self.offset\n\n if not hasattr(self, 'copies'):\n self.copies = 1\n\n return p * self.copies\n\n def downward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n p,h = total_state\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n return h - self.offset\n\n return h * self.copies\n\n def get_monitoring_channels(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n W ,= self.transformer.get_params()\n\n assert W.ndim == 2\n\n sq_W = T.sqr(W)\n\n row_norms = T.sqrt(sq_W.sum(axis=1))\n col_norms = T.sqrt(sq_W.sum(axis=0))\n\n return OrderedDict([\n ('row_norms_min' , row_norms.min()),\n ('row_norms_mean' , row_norms.mean()),\n ('row_norms_max' , row_norms.max()),\n ('col_norms_min' , col_norms.min()),\n ('col_norms_mean' , col_norms.mean()),\n ('col_norms_max' , col_norms.max()),\n ])\n\n\n def get_monitoring_channels_from_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n P, H = state\n\n rval = OrderedDict()\n\n if self.pool_size == 1:\n vars_and_prefixes = [ (P,'') ]\n else:\n vars_and_prefixes = [ (P, 'p_'), (H, 'h_') ]\n\n for var, prefix in vars_and_prefixes:\n v_max = var.max(axis=0)\n v_min = var.min(axis=0)\n v_mean = var.mean(axis=0)\n v_range = v_max - v_min\n\n # max_x.mean_u is \"the mean over *u*nits of the max over e*x*amples\"\n # The x and u are included in the name because otherwise its hard\n # to remember which axis is which when reading the monitor\n # I use inner.outer rather than outer_of_inner or something like that\n # because I want mean_x.* to appear next to each other in the alphabetical\n # list, as these are commonly plotted together\n for key, val in [\n ('max_x.max_u', v_max.max()),\n ('max_x.mean_u', v_max.mean()),\n ('max_x.min_u', v_max.min()),\n ('min_x.max_u', v_min.max()),\n ('min_x.mean_u', v_min.mean()),\n ('min_x.min_u', v_min.min()),\n ('range_x.max_u', v_range.max()),\n ('range_x.mean_u', v_range.mean()),\n ('range_x.min_u', v_range.min()),\n ('mean_x.max_u', v_mean.max()),\n ('mean_x.mean_u', v_mean.mean()),\n ('mean_x.min_u', v_mean.min())\n ]:\n rval[prefix+key] = val\n\n return rval\n\n def get_stdev_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = 0.\n\n P, H = state\n self.output_space.validate(P)\n self.h_space.validate(H)\n\n\n if self.pool_size == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n if isinstance(coeffs, str):\n coeffs = float(coeffs)\n assert isinstance(coeffs, float)\n _, state = state\n state = [state]\n coeffs = [coeffs]\n else:\n assert all([len(elem) == 2 for elem in [state, coeffs]])\n\n for s, c in safe_zip(state, coeffs):\n assert all([isinstance(elem, float) for elem in [c]])\n if c == 0.:\n continue\n mn = s.mean(axis=0)\n dev = s - mn\n stdev = T.sqrt(T.sqr(dev).mean(axis=0))\n rval += (0.5 - stdev).mean()*c\n\n return rval\n def get_range_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = 0.\n\n P, H = state\n self.output_space.validate(P)\n self.h_space.validate(H)\n\n\n if self.pool_size == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n if isinstance(coeffs, str):\n coeffs = float(coeffs)\n assert isinstance(coeffs, float)\n _, state = state\n state = [state]\n coeffs = [coeffs]\n else:\n assert all([len(elem) == 2 for elem in [state, coeffs]])\n\n for s, c in safe_zip(state, coeffs):\n assert all([isinstance(elem, float) for elem in [c]])\n if c == 0.:\n continue\n mx = s.max(axis=0)\n assert hasattr(mx.owner.op, 'grad')\n assert mx.ndim == 1\n mn = s.min(axis=0)\n assert hasattr(mn.owner.op, 'grad')\n assert mn.ndim == 1\n r = mx - mn\n rval += (1 - r).mean()*c\n\n return rval\n\n def get_l1_act_cost(self, state, target, coeff, eps = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = 0.\n\n P, H = state\n self.output_space.validate(P)\n self.h_space.validate(H)\n\n\n if self.pool_size == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n if not isinstance(target, float):\n raise TypeError(\"BinaryVectorMaxPool.get_l1_act_cost expected target of type float \" + \\\n \" but an instance named \"+self.layer_name + \" got target \"+str(target) + \" of type \"+str(type(target)))\n assert isinstance(coeff, float) or hasattr(coeff, 'dtype')\n _, state = state\n state = [state]\n target = [target]\n coeff = [coeff]\n if eps is None:\n eps = [0.]\n else:\n eps = [eps]\n else:\n assert all([len(elem) == 2 for elem in [state, target, coeff]])\n if eps is None:\n eps = [0., 0.]\n if target[1] > target[0]:\n warnings.warn(\"Do you really want to regularize the detector units to be more active than the pooling units?\")\n\n for s, t, c, e in safe_zip(state, target, coeff, eps):\n assert all([isinstance(elem, float) or hasattr(elem, 'dtype') for elem in [t, c, e]])\n if c == 0.:\n continue\n m = s.mean(axis=0)\n assert m.ndim == 1\n rval += T.maximum(abs(m-t)-e,0.).mean()*c\n\n return rval\n\n def get_l2_act_cost(self, state, target, coeff):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = 0.\n\n P, H = state\n self.output_space.validate(P)\n self.h_space.validate(H)\n\n\n if self.pool_size == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n if not isinstance(target, float):\n raise TypeError(\"BinaryVectorMaxPool.get_l1_act_cost expected target of type float \" + \\\n \" but an instance named \"+self.layer_name + \" got target \"+str(target) + \" of type \"+str(type(target)))\n assert isinstance(coeff, float) or hasattr(coeff, 'dtype')\n _, state = state\n state = [state]\n target = [target]\n coeff = [coeff]\n else:\n assert all([len(elem) == 2 for elem in [state, target, coeff]])\n if target[1] > target[0]:\n warnings.warn(\"Do you really want to regularize the detector units to be more active than the pooling units?\")\n\n for s, t, c in safe_zip(state, target, coeff):\n assert all([isinstance(elem, float) or hasattr(elem, 'dtype') for elem in [t, c]])\n if c == 0.:\n continue\n m = s.mean(axis=0)\n assert m.ndim == 1\n rval += T.square(m-t).mean()*c\n\n return rval\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.copies != 1:\n raise NotImplementedError()\n\n if theano_rng is None:\n raise ValueError(\"theano_rng is required; it just defaults to None so that it may appear after layer_above / state_above in the list.\")\n\n if state_above is not None:\n msg = layer_above.downward_message(state_above)\n else:\n msg = None\n\n if self.requires_reformat:\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n z = self.transformer.lmul(state_below) + self.b\n p, h, p_sample, h_sample = max_pool_channels(z,\n self.pool_size, msg, theano_rng)\n\n return p_sample, h_sample\n\n def downward_message(self, downward_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.h_space.validate(downward_state)\n rval = self.transformer.lmul_T(downward_state)\n\n if self.requires_reformat:\n rval = self.desired_space.format_as(rval, self.input_space)\n\n return rval * self.copies\n\n def init_mf_state(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n # work around theano bug with broadcasted vectors\n z = T.alloc(0., self.dbm.batch_size, self.detector_layer_dim).astype(self.b.dtype) + \\\n self.b.dimshuffle('x', 0)\n rval = max_pool_channels(z = z,\n pool_size = self.pool_size)\n return rval\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\" Returns a shared variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n\n if not hasattr(self, 'copies'):\n self.copies = 1\n\n if self.copies != 1:\n raise NotImplementedError()\n\n\n empty_input = self.h_space.get_origin_batch(num_examples)\n empty_output = self.output_space.get_origin_batch(num_examples)\n\n h_state = sharedX(empty_input)\n p_state = sharedX(empty_output)\n\n theano_rng = make_theano_rng(None, numpy_rng.randint(2 ** 16), which_method=\"binomial\")\n\n default_z = T.zeros_like(h_state) + self.b\n\n p_exp, h_exp, p_sample, h_sample = max_pool_channels(\n z = default_z,\n pool_size = self.pool_size,\n theano_rng = theano_rng)\n\n assert h_sample.dtype == default_z.dtype\n\n f = function([], updates = [\n (p_state , p_sample),\n (h_state , h_sample)\n ])\n\n f()\n\n p_state.name = 'p_sample_shared'\n h_state.name = 'h_sample_shared'\n\n return p_state, h_state\n\n def make_symbolic_state(self, num_examples, theano_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\"\n Returns a theano symbolic variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n\n if not hasattr(self, 'copies'):\n self.copies = 1\n\n if self.copies != 1:\n raise NotImplementedError()\n\n default_z = T.alloc(self.b, num_examples, self.detector_layer_dim)\n\n p_exp, h_exp, p_sample, h_sample = max_pool_channels(z=default_z,\n pool_size=self.pool_size,\n theano_rng=theano_rng)\n\n assert h_sample.dtype == default_z.dtype\n\n return p_sample, h_sample\n\n def expected_energy_term(self, state, average, state_below, average_below):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n # Don't need to do anything special for centering, upward_state / downward state\n # make it all just work\n\n self.input_space.validate(state_below)\n\n if self.requires_reformat:\n if not isinstance(state_below, tuple):\n for sb in get_debug_values(state_below):\n if sb.shape[0] != self.dbm.batch_size:\n raise ValueError(\"self.dbm.batch_size is %d but got shape of %d\" % (self.dbm.batch_size, sb.shape[0]))\n assert reduce(operator.mul, sb.shape[1:]) == self.input_dim\n\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n downward_state = self.downward_state(state)\n self.h_space.validate(downward_state)\n\n # Energy function is linear so it doesn't matter if we're averaging or not\n # Specifically, our terms are -u^T W d - b^T d where u is the upward state of layer below\n # and d is the downward state of this layer\n\n bias_term = T.dot(downward_state, self.b)\n weights_term = (self.transformer.lmul(state_below) * downward_state).sum(axis=1)\n\n rval = -bias_term - weights_term\n\n assert rval.ndim == 1\n\n return rval * self.copies\n\n def linear_feed_forward_approximation(self, state_below):\n \"\"\"\n Used to implement TorontoSparsity. Unclear exactly what properties of\n it are important or how to implement it for other layers.\n\n Properties it must have: output is same kind of data structure (ie,\n tuple of theano 2-tensors) as mf_update.\n\n Properties it probably should have for other layer types: an\n infinitesimal change in state_below or the parameters should cause the\n same sign of change in the output of linear_feed_forward_approximation\n and in mf_update\n\n Should not have any non-linearities that cause the gradient to shrink\n\n Should disregard top-down feedback\n\n Parameters\n ----------\n state_below : WRITEME\n \"\"\"\n\n z = self.transformer.lmul(state_below) + self.b\n\n if self.pool_size != 1:\n # Should probably implement sum pooling for the non-pooled version,\n # but in reality it's not totally clear what the right answer is\n raise NotImplementedError()\n\n return z, z\n\n def mf_update(self, state_below, state_above, layer_above = None, double_weights = False, iter_name = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n self.input_space.validate(state_below)\n\n if self.requires_reformat:\n if not isinstance(state_below, tuple):\n for sb in get_debug_values(state_below):\n if sb.shape[0] != self.dbm.batch_size:\n raise ValueError(\"self.dbm.batch_size is %d but got shape of %d\" % (self.dbm.batch_size, sb.shape[0]))\n assert reduce(operator.mul, sb.shape[1:]) == self.input_dim\n\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n if iter_name is None:\n iter_name = 'anon'\n\n if state_above is not None:\n assert layer_above is not None\n msg = layer_above.downward_message(state_above)\n msg.name = 'msg_from_'+layer_above.layer_name+'_to_'+self.layer_name+'['+iter_name+']'\n else:\n msg = None\n\n if double_weights:\n state_below = 2. * state_below\n state_below.name = self.layer_name + '_'+iter_name + '_2state'\n z = self.transformer.lmul(state_below) + self.b\n if self.layer_name is not None and iter_name is not None:\n z.name = self.layer_name + '_' + iter_name + '_z'\n p,h = max_pool_channels(z, self.pool_size, msg)\n\n p.name = self.layer_name + '_p_' + iter_name\n h.name = self.layer_name + '_h_' + iter_name\n\n return p, h\n\n\nclass Softmax(HiddenLayer):\n \"\"\"\n A layer representing a single softmax distribution of a\n set of discrete categories.\n\n Parameters\n ----------\n n_classes : int\n The number of discrete categories.\n layer_name : str\n The name of the layer.\n irange : float\n If not None, initialze the weights in U(-irange, irange)\n sparse_init : int\n If not None, initialize `sparse_init` weights per column\n to N(0, sparse_istdev^2)\n sparse_istdev : float\n see above\n W_lr_scale : float\n Scale the learning rate on the weights by this amount\n b_lr_scale : float\n Scale the learning rate on the biases by this amount\n max_col_norm : float\n If not None, constrain the columns of the weight matrix\n to have at most this L2 norm\n copies : int\n Make this many copies of the random variables, all sharing\n the same weights. This allows the undirected model to\n behave as if it has asymmetric connections.\n center : bool\n If True, use Gregoire Montavon's centering trick.\n learn_init_inpainting_state : bool\n If True, and using inpainting-based methods (MP-DBM), learn\n a parameter controlling the initial value of the mean field\n state for this layer.\n \"\"\"\n\n presynaptic_name = \"presynaptic_Y_hat\"\n\n def __init__(self, n_classes, layer_name, irange = None,\n sparse_init = None, sparse_istdev = 1., W_lr_scale = None,\n b_lr_scale = None,\n max_col_norm = None,\n copies = 1, center = False,\n learn_init_inpainting_state = True):\n\n super(Softmax, self).__init__()\n\n if isinstance(W_lr_scale, str):\n W_lr_scale = float(W_lr_scale)\n\n self.__dict__.update(locals())\n del self.self\n\n assert isinstance(n_classes, py_integer_types)\n\n self.output_space = VectorSpace(n_classes)\n self.b = sharedX( np.zeros((n_classes,)), name = 'softmax_b')\n\n if self.center:\n b = self.b.get_value()\n self.offset = sharedX(np.exp(b) / np.exp(b).sum())\n\n @functools.wraps(Model._modify_updates)\n def _modify_updates(self, updates):\n\n if not hasattr(self, 'max_col_norm'):\n self.max_col_norm = None\n\n if self.max_col_norm is not None:\n W = self.W\n if W in updates:\n updated_W = updates[W]\n col_norms = T.sqrt(T.sum(T.sqr(updated_W), axis=0))\n desired_norms = T.clip(col_norms, 0, self.max_col_norm)\n updates[W] = updated_W * (desired_norms / (1e-7 + col_norms))\n\n @functools.wraps(Model.get_lr_scalers)\n def get_lr_scalers(self):\n\n rval = OrderedDict()\n\n # Patch old pickle files\n if not hasattr(self, 'W_lr_scale'):\n self.W_lr_scale = None\n\n if self.W_lr_scale is not None:\n assert isinstance(self.W_lr_scale, float)\n rval[self.W] = self.W_lr_scale\n\n if not hasattr(self, 'b_lr_scale'):\n self.b_lr_scale = None\n\n if self.b_lr_scale is not None:\n assert isinstance(self.b_lr_scale, float)\n rval[self.b] = self.b_lr_scale\n\n return rval\n\n def get_total_state_space(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return self.output_space\n\n def get_monitoring_channels_from_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n mx = state.max(axis=1)\n\n return OrderedDict([\n ('mean_max_class' , mx.mean()),\n ('max_max_class' , mx.max()),\n ('min_max_class' , mx.min())\n ])\n\n def set_input_space(self, space):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.input_space = space\n\n if not isinstance(space, Space):\n raise TypeError(\"Expected Space, got \"+\n str(space)+\" of type \"+str(type(space)))\n\n self.input_dim = space.get_total_dimension()\n self.needs_reformat = not isinstance(space, VectorSpace)\n\n self.desired_space = VectorSpace(self.input_dim)\n\n if not self.needs_reformat:\n assert self.desired_space == self.input_space\n\n rng = self.dbm.rng\n\n if self.irange is not None:\n assert self.sparse_init is None\n W = rng.uniform(-self.irange,self.irange, (self.input_dim,self.n_classes))\n else:\n assert self.sparse_init is not None\n W = np.zeros((self.input_dim, self.n_classes))\n for i in xrange(self.n_classes):\n for j in xrange(self.sparse_init):\n idx = rng.randint(0, self.input_dim)\n while W[idx, i] != 0.:\n idx = rng.randint(0, self.input_dim)\n W[idx, i] = rng.randn() * self.sparse_istdev\n\n self.W = sharedX(W, 'softmax_W' )\n\n self._params = [ self.b, self.W ]\n\n def get_weights_topo(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if not isinstance(self.input_space, Conv2DSpace):\n raise NotImplementedError()\n desired = self.W.get_value().T\n ipt = self.desired_space.format_as(desired, self.input_space)\n rval = Conv2DSpace.convert_numpy(ipt, self.input_space.axes, ('b', 0, 1, 'c'))\n return rval\n\n def get_weights(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if not isinstance(self.input_space, VectorSpace):\n raise NotImplementedError()\n\n return self.W.get_value()\n\n def set_weights(self, weights):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.W.set_value(weights)\n\n def set_biases(self, biases, recenter=False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.b.set_value(biases)\n if recenter:\n assert self.center\n self.offset.set_value( (np.exp(biases) / np.exp(biases).sum()).astype(self.offset.dtype))\n\n def get_biases(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return self.b.get_value()\n\n def get_weights_format(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return ('v', 'h')\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n\n if self.copies != 1:\n raise NotImplementedError(\"need to draw self.copies samples and average them together.\")\n\n if state_above is not None:\n # If you implement this case, also add a unit test for it.\n # Or at least add a warning that it is not tested.\n raise NotImplementedError()\n\n if theano_rng is None:\n raise ValueError(\"theano_rng is required; it just defaults to None so that it may appear after layer_above / state_above in the list.\")\n\n self.input_space.validate(state_below)\n\n # patch old pickle files\n if not hasattr(self, 'needs_reformat'):\n self.needs_reformat = self.needs_reshape\n del self.needs_reshape\n\n if self.needs_reformat:\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n self.desired_space.validate(state_below)\n\n\n z = T.dot(state_below, self.W) + self.b\n h_exp = T.nnet.softmax(z)\n h_sample = theano_rng.multinomial(pvals = h_exp, dtype = h_exp.dtype)\n\n return h_sample\n\n def mf_update(self, state_below, state_above = None, layer_above = None, double_weights = False, iter_name = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if state_above is not None:\n raise NotImplementedError()\n\n if double_weights:\n raise NotImplementedError()\n\n self.input_space.validate(state_below)\n\n # patch old pickle files\n if not hasattr(self, 'needs_reformat'):\n self.needs_reformat = self.needs_reshape\n del self.needs_reshape\n\n if self.needs_reformat:\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n for value in get_debug_values(state_below):\n if value.shape[0] != self.dbm.batch_size:\n raise ValueError(\"state_below should have batch size \"+str(self.dbm.batch_size)+\" but has \"+str(value.shape[0]))\n\n self.desired_space.validate(state_below)\n\n assert self.W.ndim == 2\n assert state_below.ndim == 2\n\n b = self.b\n\n Z = T.dot(state_below, self.W) + b\n\n rval = T.nnet.softmax(Z)\n\n for value in get_debug_values(rval):\n assert value.shape[0] == self.dbm.batch_size\n\n return rval\n\n def downward_message(self, downward_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if not hasattr(self, 'copies'):\n self.copies = 1\n\n rval = T.dot(downward_state, self.W.T) * self.copies\n\n rval = self.desired_space.format_as(rval, self.input_space)\n\n return rval\n\n def recons_cost(self, Y, Y_hat_unmasked, drop_mask_Y, scale):\n \"\"\"\n The cost of reconstructing `Y` as `Y_hat`. Specifically,\n the negative log probability.\n\n This cost is for use with multi-prediction training.\n\n Parameters\n ----------\n Y : target space batch\n The data labels\n Y_hat_unmasked : target space batch\n The output of this layer's `mf_update`; the predicted\n values of `Y`. Even though the model is only predicting\n the dropped values, we take predictions for all the\n values here.\n drop_mask_Y : 1-D theano tensor\n A batch of 0s/1s, with 1s indicating that variables\n have been dropped, and should be included in the\n reconstruction cost. One indicator per example in the\n batch, since each example in this layer only has one\n random variable in it.\n scale : float\n Multiply the cost by this amount.\n We need to do this because the visible layer also goes into\n the cost. We use the mean over units and examples, so that\n the scale of the cost doesn't change too much with batch\n size or example size.\n We need to multiply this cost by scale to make sure that\n it is put on the same scale as the reconstruction cost\n for the visible units. ie, scale should be 1/nvis\n \"\"\"\n\n\n Y_hat = Y_hat_unmasked\n assert hasattr(Y_hat, 'owner')\n owner = Y_hat.owner\n assert owner is not None\n op = owner.op\n if isinstance(op, Print):\n assert len(owner.inputs) == 1\n Y_hat, = owner.inputs\n owner = Y_hat.owner\n op = owner.op\n assert isinstance(op, T.nnet.Softmax)\n z ,= owner.inputs\n assert z.ndim == 2\n\n z = z - z.max(axis=1).dimshuffle(0, 'x')\n log_prob = z - T.log(T.exp(z).sum(axis=1).dimshuffle(0, 'x'))\n # we use sum and not mean because this is really one variable per row\n log_prob_of = (Y * log_prob).sum(axis=1)\n masked = log_prob_of * drop_mask_Y\n assert masked.ndim == 1\n\n rval = masked.mean() * scale * self.copies\n\n return - rval\n\n def init_mf_state(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = T.nnet.softmax(self.b.dimshuffle('x', 0)) + T.alloc(0., self.dbm.batch_size, self.n_classes).astype(config.floatX)\n return rval\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\" Returns a shared variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n\n if self.copies != 1:\n raise NotImplementedError(\"need to make self.copies samples and average them together.\")\n\n t1 = time.time()\n\n empty_input = self.output_space.get_origin_batch(num_examples)\n h_state = sharedX(empty_input)\n\n default_z = T.zeros_like(h_state) + self.b\n\n theano_rng = make_theano_rng(None, numpy_rng.randint(2 ** 16),\n which_method=\"binomial\")\n\n h_exp = T.nnet.softmax(default_z)\n\n h_sample = theano_rng.multinomial(pvals = h_exp, dtype = h_exp.dtype)\n\n h_state = sharedX( self.output_space.get_origin_batch(\n num_examples))\n\n\n t2 = time.time()\n\n f = function([], updates = [(\n h_state , h_sample\n )])\n\n t3 = time.time()\n\n f()\n\n t4 = time.time()\n\n logger.info('{0}.make_state took {1}'.format(self, t4-t1))\n logger.info('\\tcompose time: {0}'.format(t2-t1))\n logger.info('\\tcompile time: {0}'.format(t3-t2))\n logger.info('\\texecute time: {0}'.format(t4-t3))\n\n h_state.name = 'softmax_sample_shared'\n\n return h_state\n\n def make_symbolic_state(self, num_examples, theano_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\"\n Returns a symbolic variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n\n if self.copies != 1:\n raise NotImplementedError(\"need to make self.copies samples and average them together.\")\n\n default_z = T.alloc(self.b, num_examples, self.n_classes)\n\n h_exp = T.nnet.softmax(default_z)\n\n h_sample = theano_rng.multinomial(pvals=h_exp, dtype=h_exp.dtype)\n\n return h_sample\n\n def get_weight_decay(self, coeff):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if isinstance(coeff, str):\n coeff = float(coeff)\n assert isinstance(coeff, float) or hasattr(coeff, 'dtype')\n return coeff * T.sqr(self.W).sum()\n\n def upward_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.center:\n return state - self.offset\n return state\n\n def downward_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if not hasattr(self, 'center'):\n self.center = False\n if self.center:\n \"\"\"TODO: write a unit test verifying that inference or sampling\n below a centered Softmax layer works\"\"\"\n return state - self.offset\n return state\n\n def expected_energy_term(self, state, average, state_below, average_below):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if self.center:\n state = state - self.offset\n\n self.input_space.validate(state_below)\n if self.needs_reformat:\n state_below = self.input_space.format_as(state_below, self.desired_space)\n self.desired_space.validate(state_below)\n\n # Energy function is linear so it doesn't matter if we're averaging or not\n # Specifically, our terms are -u^T W d - b^T d where u is the upward state of layer below\n # and d is the downward state of this layer\n\n bias_term = T.dot(state, self.b)\n weights_term = (T.dot(state_below, self.W) * state).sum(axis=1)\n\n rval = -bias_term - weights_term\n\n rval *= self.copies\n\n assert rval.ndim == 1\n\n return rval\n\n def init_inpainting_state(self, Y, noise):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if noise:\n theano_rng = make_theano_rng(None, 2012+10+30, which_method=\"binomial\")\n return T.nnet.softmax(theano_rng.normal(avg=0., size=Y.shape, std=1., dtype='float32'))\n rval = T.nnet.softmax(self.b)\n if not hasattr(self, 'learn_init_inpainting_state'):\n self.learn_init_inpainting_state = 1\n if not self.learn_init_inpainting_state:\n rval = block_gradient(rval)\n return rval\n\n def install_presynaptic_outputs(self, outputs_dict, batch_size):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n assert self.presynaptic_name not in outputs_dict\n outputs_dict[self.presynaptic_name] = self.output_space.make_shared_batch(batch_size, self.presynaptic_name)\n\n\nclass GaussianVisLayer(VisibleLayer):\n \"\"\"\n Implements a visible layer that is conditionally gaussian with\n diagonal variance. The layer lives in a Conv2DSpace.\n\n Parameters\n ----------\n rows, cols, channels : WRITEME\n the shape of the space\n learn_init_inpainting : bool, optional\n WRITEME\n nvis : WRITEME\n init_beta : WRITEME\n the initial value of the precision parameter\n min_beta : WRITEME\n clip beta so it is at least this big (default 1)\n init_mu : WRITEME\n the initial value of the mean parameter\n tie_beta : WRITEME\n None or a string specifying how to tie beta 'locations' = tie beta\n across locations, ie beta should be a vector with one elem per channel\n tie_mu : WRITEME\n None or a string specifying how to tie mu 'locations' = tie mu across\n locations, ie mu should be a vector with one elem per channel\n bias_from_marginals : WRITEME\n beta_lr_scale : WRITEME\n axes : tuple\n WRITEME\n \"\"\"\n def __init__(self,\n rows = None,\n cols = None,\n learn_init_inpainting_state=True,\n channels = None,\n nvis = None,\n init_beta = 1.,\n min_beta = 1.,\n init_mu = None,\n tie_beta = None,\n tie_mu = None,\n bias_from_marginals = None,\n beta_lr_scale = 'by_sharing',\n axes = ('b', 0, 1, 'c')):\n\n warnings.warn(\"GaussianVisLayer math very faith based, need to finish working through gaussian.lyx\")\n\n self.__dict__.update(locals())\n del self.self\n\n if bias_from_marginals is not None:\n del self.bias_from_marginals\n if self.nvis is None:\n raise NotImplementedError()\n assert init_mu is None\n init_mu = bias_from_marginals.X.mean(axis=0)\n\n if init_mu is None:\n init_mu = 0.\n if nvis is None:\n assert rows is not None\n assert cols is not None\n assert channels is not None\n self.space = Conv2DSpace(shape=[rows,cols], num_channels=channels, axes=axes)\n # To make GaussianVisLayer compatible with any axis ordering\n self.batch_axis=list(axes).index('b')\n self.axes_to_sum = list(range(len(axes)))\n self.axes_to_sum.remove(self.batch_axis)\n else:\n assert rows is None\n assert cols is None\n assert channels is None\n self.space = VectorSpace(nvis)\n self.axes_to_sum = 1\n self.batch_axis = None\n self.input_space = self.space\n\n origin = self.space.get_origin()\n\n beta_origin = origin.copy()\n assert tie_beta in [ None, 'locations']\n if tie_beta == 'locations':\n assert nvis is None\n beta_origin = np.zeros((self.space.num_channels,))\n self.beta = sharedX(beta_origin + init_beta,name = 'beta')\n assert self.beta.ndim == beta_origin.ndim\n\n mu_origin = origin.copy()\n assert tie_mu in [None, 'locations']\n if tie_mu == 'locations':\n assert nvis is None\n mu_origin = np.zeros((self.space.num_channels,))\n self.mu = sharedX( mu_origin + init_mu, name = 'mu')\n assert self.mu.ndim == mu_origin.ndim\n\n\n\n def get_monitoring_channels(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = OrderedDict()\n\n rval['beta_min'] = self.beta.min()\n rval['beta_mean'] = self.beta.mean()\n rval['beta_max'] = self.beta.max()\n\n return rval\n\n\n def get_params(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.mu is None:\n return [self.beta]\n return [self.beta, self.mu]\n\n def get_lr_scalers(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = OrderedDict()\n\n if self.nvis is None:\n rows, cols = self.space.shape\n num_loc = float(rows * cols)\n\n assert self.tie_beta in [None, 'locations']\n if self.beta_lr_scale == 'by_sharing':\n if self.tie_beta == 'locations':\n assert self.nvis is None\n rval[self.beta] = 1. / num_loc\n elif self.beta_lr_scale == None:\n pass\n else:\n rval[self.beta] = self.beta_lr_scale\n\n assert self.tie_mu in [None, 'locations']\n if self.tie_mu == 'locations':\n warn = True\n assert self.nvis is None\n rval[self.mu] = 1./num_loc\n logger.warning(\"mu lr_scaler hardcoded to 1/sharing\")\n\n return rval\n\n @functools.wraps(Model._modify_updates)\n def _modify_updates(self, updates):\n if self.beta in updates:\n updated_beta = updates[self.beta]\n updates[self.beta] = T.clip(updated_beta,\n self.min_beta,1e6)\n\n def set_biases(self, bias):\n \"\"\"\n Set mean parameter\n\n Parameters\n ----------\n bias: WRITEME\n Vector of size nvis\n \"\"\"\n self.mu = sharedX(bias, name = 'mu')\n\n def broadcasted_mu(self):\n \"\"\"\n Returns mu, broadcasted to have the same shape as a batch of data\n \"\"\"\n\n if self.tie_mu == 'locations':\n def f(x):\n if x == 'c':\n return 0\n return 'x'\n axes = [f(ax) for ax in self.axes]\n rval = self.mu.dimshuffle(*axes)\n else:\n assert self.tie_mu is None\n if self.nvis is None:\n axes = [0, 1, 2]\n axes.insert(self.axes.index('b'), 'x')\n rval = self.mu.dimshuffle(*axes)\n else:\n rval = self.mu.dimshuffle('x', 0)\n\n self.input_space.validate(rval)\n\n return rval\n\n def broadcasted_beta(self):\n \"\"\"\n Returns beta, broadcasted to have the same shape as a batch of data\n \"\"\"\n return self.broadcast_beta(self.beta)\n\n def broadcast_beta(self, beta):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\"\n Returns beta, broadcasted to have the same shape as a batch of data\n \"\"\"\n\n if self.tie_beta == 'locations':\n def f(x):\n if x == 'c':\n return 0\n return 'x'\n axes = [f(ax) for ax in self.axes]\n rval = beta.dimshuffle(*axes)\n else:\n assert self.tie_beta is None\n if self.nvis is None:\n axes = [0, 1, 2]\n axes.insert(self.axes.index('b'), 'x')\n rval = beta.dimshuffle(*axes)\n else:\n rval = beta.dimshuffle('x', 0)\n\n self.input_space.validate(rval)\n\n return rval\n\n def init_inpainting_state(self, V, drop_mask, noise = False, return_unmasked = False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n \"\"\"for Vv, drop_mask_v in get_debug_values(V, drop_mask):\n assert Vv.ndim == 4\n assert drop_mask_v.ndim in [3,4]\n for i in xrange(drop_mask.ndim):\n if Vv.shape[i] != drop_mask_v.shape[i]:\n print(Vv.shape)\n print(drop_mask_v.shape)\n assert False\n \"\"\"\n\n unmasked = self.broadcasted_mu()\n\n if drop_mask is None:\n assert not noise\n assert not return_unmasked\n return unmasked\n masked_mu = unmasked * drop_mask\n if not hasattr(self, 'learn_init_inpainting_state'):\n self.learn_init_inpainting_state = True\n if not self.learn_init_inpainting_state:\n masked_mu = block_gradient(masked_mu)\n masked_mu.name = 'masked_mu'\n\n if noise:\n theano_rng = make_theano_rng(None, 42, which_method=\"binomial\")\n unmasked = theano_rng.normal(avg = 0.,\n std = 1., size = masked_mu.shape,\n dtype = masked_mu.dtype)\n masked_mu = unmasked * drop_mask\n masked_mu.name = 'masked_noise'\n\n\n masked_V = V * (1-drop_mask)\n rval = masked_mu + masked_V\n rval.name = 'init_inpainting_state'\n\n if return_unmasked:\n return rval, unmasked\n return rval\n\n\n def expected_energy_term(self, state, average, state_below = None, average_below = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n assert state_below is None\n assert average_below is None\n self.space.validate(state)\n if average:\n raise NotImplementedError(str(type(self))+\" doesn't support integrating out variational parameters yet.\")\n else:\n rval = 0.5 * (self.beta * T.sqr(state - self.mu)).sum(axis=self.axes_to_sum)\n assert rval.ndim == 1\n return rval\n\n\n def inpaint_update(self, state_above, layer_above, drop_mask = None, V = None,\n return_unmasked = False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n msg = layer_above.downward_message(state_above)\n mu = self.broadcasted_mu()\n\n z = msg + mu\n z.name = 'inpainting_z_[unknown_iter]'\n\n if drop_mask is not None:\n rval = drop_mask * z + (1-drop_mask) * V\n else:\n rval = z\n\n rval.name = 'inpainted_V[unknown_iter]'\n\n if return_unmasked:\n return rval, z\n\n return rval\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n assert state_below is None\n msg = layer_above.downward_message(state_above)\n mu = self.mu\n\n z = msg + mu\n rval = theano_rng.normal(size = z.shape, avg = z, dtype = z.dtype,\n std = 1. / T.sqrt(self.beta))\n return rval\n\n def recons_cost(self, V, V_hat_unmasked, drop_mask = None, use_sum=False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n return self._recons_cost(V=V, V_hat_unmasked=V_hat_unmasked, drop_mask=drop_mask, use_sum=use_sum, beta=self.beta)\n\n\n def _recons_cost(self, V, V_hat_unmasked, beta, drop_mask=None, use_sum=False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n V_hat = V_hat_unmasked\n\n assert V.ndim == V_hat.ndim\n beta = self.broadcasted_beta()\n unmasked_cost = 0.5 * beta * T.sqr(V-V_hat) - 0.5*T.log(beta / (2*np.pi))\n assert unmasked_cost.ndim == V_hat.ndim\n\n if drop_mask is None:\n masked_cost = unmasked_cost\n else:\n masked_cost = drop_mask * unmasked_cost\n\n if use_sum:\n return masked_cost.mean(axis=0).sum()\n\n return masked_cost.mean()\n\n return masked_cost.mean()\n\n def upward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.nvis is None and total_state.ndim != 4:\n raise ValueError(\"total_state should have 4 dimensions, has \"+str(total_state.ndim))\n assert total_state is not None\n V = total_state\n self.input_space.validate(V)\n upward_state = (V - self.broadcasted_mu()) * self.broadcasted_beta()\n return upward_state\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n shape = [num_examples]\n\n if self.nvis is None:\n rows, cols = self.space.shape\n channels = self.space.num_channels\n shape.append(rows)\n shape.append(cols)\n shape.append(channels)\n else:\n shape.append(self.nvis)\n\n sample = numpy_rng.randn(*shape)\n\n sample *= 1./np.sqrt(self.beta.get_value())\n sample += self.mu.get_value()\n rval = sharedX(sample, name = 'v_sample_shared')\n\n return rval\n\n def install_presynaptic_outputs(self, outputs_dict, batch_size):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n outputs_dict['output_V_weighted_pred_sum'] = self.space.make_shared_batch(batch_size)\n\n def ensemble_prediction(self, symbolic, outputs_dict, ensemble):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\"\n Output a symbolic expression for V_hat_unmasked based on taking the\n geometric mean over the ensemble and renormalizing.\n n - 1 members of the ensemble have modified outputs_dict and the nth\n gives its prediction in \"symbolic\". The parameters for the nth one\n are currently loaded in the model.\n \"\"\"\n\n weighted_pred_sum = outputs_dict['output_V_weighted_pred_sum'] \\\n + self.broadcasted_beta() * symbolic\n\n beta_sum = sum(ensemble.get_ensemble_variants(self.beta))\n\n unmasked_V_hat = weighted_pred_sum / self.broadcast_beta(beta_sum)\n\n return unmasked_V_hat\n\n def ensemble_recons_cost(self, V, V_hat_unmasked, drop_mask=None,\n use_sum=False, ensemble=None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n beta = sum(ensemble.get_ensemble_variants(self.beta)) / ensemble.num_copies\n\n return self._recons_cost(V=V, V_hat_unmasked=V_hat_unmasked, beta=beta, drop_mask=drop_mask,\n use_sum=use_sum)\n\n\nclass ConvMaxPool(HiddenLayer):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n def __init__(self,\n output_channels,\n kernel_rows,\n kernel_cols,\n pool_rows,\n pool_cols,\n layer_name,\n center = False,\n irange = None,\n sparse_init = None,\n scale_by_sharing = True,\n init_bias = 0.,\n border_mode = 'valid',\n output_axes = ('b', 'c', 0, 1)):\n self.__dict__.update(locals())\n del self.self\n\n assert (irange is None) != (sparse_init is None)\n\n self.b = sharedX( np.zeros((output_channels,)) + init_bias, name = layer_name + '_b')\n assert border_mode in ['full','valid']\n\n def broadcasted_bias(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n assert self.b.ndim == 1\n\n shuffle = [ 'x' ] * 4\n shuffle[self.output_axes.index('c')] = 0\n\n return self.b.dimshuffle(*shuffle)\n\n\n def get_total_state_space(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return CompositeSpace((self.h_space, self.output_space))\n\n def set_input_space(self, space):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\" Note: this resets parameters!\"\"\"\n if not isinstance(space, Conv2DSpace):\n raise TypeError(\"ConvMaxPool can only act on a Conv2DSpace, but received \" +\n str(type(space))+\" as input.\")\n self.input_space = space\n self.input_rows, self.input_cols = space.shape\n self.input_channels = space.num_channels\n\n if self.border_mode == 'valid':\n self.h_rows = self.input_rows - self.kernel_rows + 1\n self.h_cols = self.input_cols - self.kernel_cols + 1\n else:\n assert self.border_mode == 'full'\n self.h_rows = self.input_rows + self.kernel_rows - 1\n self.h_cols = self.input_cols + self.kernel_cols - 1\n\n\n if not( self.h_rows % self.pool_rows == 0):\n raise ValueError(\"h_rows = %d, pool_rows = %d. Should be divisible but remainder is %d\" %\n (self.h_rows, self.pool_rows, self.h_rows % self.pool_rows))\n assert self.h_cols % self.pool_cols == 0\n\n self.h_space = Conv2DSpace(shape = (self.h_rows, self.h_cols), num_channels = self.output_channels,\n axes = self.output_axes)\n self.output_space = Conv2DSpace(shape = (self.h_rows / self.pool_rows,\n self.h_cols / self.pool_cols),\n num_channels = self.output_channels,\n axes = self.output_axes)\n\n logger.info('{0}: detector shape: {1} '\n 'pool shape: {2}'.format(self.layer_name,\n self.h_space.shape,\n self.output_space.shape))\n\n if tuple(self.output_axes) == ('b', 0, 1, 'c'):\n self.max_pool = max_pool_b01c\n elif tuple(self.output_axes) == ('b', 'c', 0, 1):\n self.max_pool = max_pool\n else:\n raise NotImplementedError()\n\n if self.irange is not None:\n self.transformer = make_random_conv2D(self.irange, input_space = space,\n output_space = self.h_space, kernel_shape = (self.kernel_rows, self.kernel_cols),\n batch_size = self.dbm.batch_size, border_mode = self.border_mode, rng = self.dbm.rng)\n else:\n self.transformer = make_sparse_random_conv2D(self.sparse_init, input_space = space,\n output_space = self.h_space, kernel_shape = (self.kernel_rows, self.kernel_cols),\n batch_size = self.dbm.batch_size, border_mode = self.border_mode, rng = self.dbm.rng)\n self.transformer._filters.name = self.layer_name + '_W'\n\n\n W ,= self.transformer.get_params()\n assert W.name is not None\n\n if self.center:\n p_ofs, h_ofs = self.init_mf_state()\n self.p_offset = sharedX(self.output_space.get_origin(), 'p_offset')\n self.h_offset = sharedX(self.h_space.get_origin(), 'h_offset')\n f = function([], updates={self.p_offset: p_ofs[0,:,:,:], self.h_offset: h_ofs[0,:,:,:]})\n f()\n\n\n def get_params(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n assert self.b.name is not None\n W ,= self.transformer.get_params()\n assert W.name is not None\n\n return [ W, self.b]\n\n def state_to_b01c(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if tuple(self.output_axes) == ('b',0,1,'c'):\n return state\n return [ Conv2DSpace.convert(elem, self.output_axes, ('b', 0, 1, 'c'))\n for elem in state ]\n\n def get_range_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = 0.\n\n if self.pool_rows == 1 and self.pool_cols == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n assert isinstance(coeffs, float)\n _, state = state\n state = [state]\n coeffs = [coeffs]\n else:\n assert all([len(elem) == 2 for elem in [state, coeffs]])\n\n for s, c in safe_zip(state, coeffs):\n if c == 0.:\n continue\n # Range over everything but the channel index\n # theano can only take gradient through max if the max is over 1 axis or all axes\n # so I manually unroll the max for the case I use here\n assert self.h_space.axes == ('b', 'c', 0, 1)\n assert self.output_space.axes == ('b', 'c', 0, 1)\n mx = s.max(axis=3).max(axis=2).max(axis=0)\n assert hasattr(mx.owner.op, 'grad')\n mn = s.min(axis=3).max(axis=2).max(axis=0)\n assert hasattr(mn.owner.op, 'grad')\n assert mx.ndim == 1\n assert mn.ndim == 1\n r = mx - mn\n rval += (1. - r).mean() * c\n\n return rval\n\n def get_l1_act_cost(self, state, target, coeff, eps):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\"\n\n target: if pools contain more than one element, should be a list with\n two elements. the first element is for the pooling units and\n the second for the detector units.\n\n \"\"\"\n rval = 0.\n\n\n if self.pool_rows == 1 and self.pool_cols == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n assert isinstance(target, float)\n assert isinstance(coeff, float)\n _, state = state\n state = [state]\n target = [target]\n coeff = [coeff]\n if eps is None:\n eps = 0.\n eps = [eps]\n else:\n if eps is None:\n eps = [0., 0.]\n assert all([len(elem) == 2 for elem in [state, target, coeff]])\n p_target, h_target = target\n if h_target > p_target and (coeff[0] != 0. and coeff[1] != 0.):\n # note that, within each group, E[p] is the sum of E[h]\n warnings.warn(\"Do you really want to regularize the detector units to be more active than the pooling units?\")\n\n for s, t, c, e in safe_zip(state, target, coeff, eps):\n if c == 0.:\n continue\n # Average over everything but the channel index\n m = s.mean(axis= [ ax for ax in range(4) if self.output_axes[ax] != 'c' ])\n assert m.ndim == 1\n rval += T.maximum(abs(m-t)-e,0.).mean()*c\n\n return rval\n\n def get_lr_scalers(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.scale_by_sharing:\n # scale each learning rate by 1 / # times param is reused\n h_rows, h_cols = self.h_space.shape\n num_h = float(h_rows * h_cols)\n return OrderedDict([(self.transformer._filters, 1./num_h),\n (self.b, 1. / num_h)])\n else:\n return OrderedDict()\n\n def upward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n p,h = total_state\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n p -= self.p_offset\n h -= self.h_offset\n\n return p\n\n def downward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n p,h = total_state\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n p -= self.p_offset\n h -= self.h_offset\n\n return h\n\n def get_monitoring_channels_from_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n P, H = state\n\n if tuple(self.output_axes) == ('b',0,1,'c'):\n p_max = P.max(axis=(0,1,2))\n p_min = P.min(axis=(0,1,2))\n p_mean = P.mean(axis=(0,1,2))\n else:\n assert tuple(self.output_axes) == ('b','c',0,1)\n p_max = P.max(axis=(0,2,3))\n p_min = P.min(axis=(0,2,3))\n p_mean = P.mean(axis=(0,2,3))\n p_range = p_max - p_min\n\n rval = {\n 'p_max_max' : p_max.max(),\n 'p_max_mean' : p_max.mean(),\n 'p_max_min' : p_max.min(),\n 'p_min_max' : p_min.max(),\n 'p_min_mean' : p_min.mean(),\n 'p_min_max' : p_min.max(),\n 'p_range_max' : p_range.max(),\n 'p_range_mean' : p_range.mean(),\n 'p_range_min' : p_range.min(),\n 'p_mean_max' : p_mean.max(),\n 'p_mean_mean' : p_mean.mean(),\n 'p_mean_min' : p_mean.min()\n }\n\n return rval\n\n def get_weight_decay(self, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n W , = self.transformer.get_params()\n return coeffs * T.sqr(W).sum()\n\n\n\n def mf_update(self, state_below, state_above, layer_above = None, double_weights = False, iter_name = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n self.input_space.validate(state_below)\n\n if iter_name is None:\n iter_name = 'anon'\n\n if state_above is not None:\n assert layer_above is not None\n msg = layer_above.downward_message(state_above)\n msg.name = 'msg_from_'+layer_above.layer_name+'_to_'+self.layer_name+'['+iter_name+']'\n else:\n msg = None\n\n if not hasattr(state_below, 'ndim'):\n raise TypeError(\"state_below should be a TensorType, got \" +\n str(state_below) + \" of type \" + str(type(state_below)))\n if state_below.ndim != 4:\n raise ValueError(\"state_below should have ndim 4, has \"+str(state_below.ndim))\n\n if double_weights:\n state_below = 2. * state_below\n state_below.name = self.layer_name + '_'+iter_name + '_2state'\n z = self.transformer.lmul(state_below) + self.broadcasted_bias()\n if self.layer_name is not None and iter_name is not None:\n z.name = self.layer_name + '_' + iter_name + '_z'\n p,h = self.max_pool(z, (self.pool_rows, self.pool_cols), msg)\n\n p.name = self.layer_name + '_p_' + iter_name\n h.name = self.layer_name + '_h_' + iter_name\n\n return p, h\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if state_above is not None:\n msg = layer_above.downward_message(state_above)\n try:\n self.output_space.validate(msg)\n except TypeError as e:\n reraise_as(TypeError(str(type(layer_above))+\".downward_message gave something that was not the right type: \"+str(e)))\n else:\n msg = None\n\n z = self.transformer.lmul(state_below) + self.broadcasted_bias()\n p, h, p_sample, h_sample = self.max_pool(z,\n (self.pool_rows, self.pool_cols), msg, theano_rng)\n\n return p_sample, h_sample\n\n def downward_message(self, downward_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.h_space.validate(downward_state)\n return self.transformer.lmul_T(downward_state)\n\n def set_batch_size(self, batch_size):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.transformer.set_batch_size(batch_size)\n\n def get_weights_topo(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n outp, inp, rows, cols = range(4)\n raw = self.transformer._filters.get_value()\n\n return np.transpose(raw,(outp,rows,cols,inp))\n\n\n def init_mf_state(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n default_z = self.broadcasted_bias()\n shape = {\n 'b': self.dbm.batch_size,\n 0: self.h_space.shape[0],\n 1: self.h_space.shape[1],\n 'c': self.h_space.num_channels\n }\n # work around theano bug with broadcasted stuff\n default_z += T.alloc(*([0.]+[shape[elem] for elem in self.h_space.axes])).astype(default_z.dtype)\n assert default_z.ndim == 4\n\n p, h = self.max_pool(\n z = default_z,\n pool_shape = (self.pool_rows, self.pool_cols))\n\n return p, h\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\" Returns a shared variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n\n t1 = time.time()\n\n empty_input = self.h_space.get_origin_batch(self.dbm.batch_size)\n h_state = sharedX(empty_input)\n\n default_z = T.zeros_like(h_state) + self.broadcasted_bias()\n\n theano_rng = make_theano_rng(None, numpy_rng.randint(2 ** 16),\n which_method=\"binomial\")\n\n p_exp, h_exp, p_sample, h_sample = self.max_pool(\n z = default_z,\n pool_shape = (self.pool_rows, self.pool_cols),\n theano_rng = theano_rng)\n\n p_state = sharedX( self.output_space.get_origin_batch(\n self.dbm.batch_size))\n\n\n t2 = time.time()\n\n f = function([], updates = [\n (p_state, p_sample),\n (h_state, h_sample)\n ])\n\n t3 = time.time()\n\n f()\n\n t4 = time.time()\n\n logger.info('{0}.make_state took'.format(self, t4-t1))\n logger.info('\\tcompose time: {0}'.format(t2-t1))\n logger.info('\\tcompile time: {0}'.format(t3-t2))\n logger.info('\\texecute time: {0}'.format(t4-t3))\n\n p_state.name = 'p_sample_shared'\n h_state.name = 'h_sample_shared'\n\n return p_state, h_state\n\n def expected_energy_term(self, state, average, state_below, average_below):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n self.input_space.validate(state_below)\n\n downward_state = self.downward_state(state)\n self.h_space.validate(downward_state)\n\n # Energy function is linear so it doesn't matter if we're averaging or not\n # Specifically, our terms are -u^T W d - b^T d where u is the upward state of layer below\n # and d is the downward state of this layer\n\n bias_term = (downward_state * self.broadcasted_bias()).sum(axis=(1,2,3))\n weights_term = (self.transformer.lmul(state_below) * downward_state).sum(axis=(1,2,3))\n\n rval = -bias_term - weights_term\n\n assert rval.ndim == 1\n\n return rval\n\n\nclass ConvC01B_MaxPool(HiddenLayer):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n def __init__(self,\n output_channels,\n kernel_shape,\n pool_rows,\n pool_cols,\n layer_name,\n center = False,\n irange = None,\n sparse_init = None,\n scale_by_sharing = True,\n init_bias = 0.,\n pad = 0,\n partial_sum = 1):\n self.__dict__.update(locals())\n del self.self\n\n assert (irange is None) != (sparse_init is None)\n self.output_axes = ('c', 0, 1, 'b')\n self.detector_channels = output_channels\n self.tied_b = 1\n\n def broadcasted_bias(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if self.b.ndim != 1:\n raise NotImplementedError()\n\n shuffle = [ 'x' ] * 4\n shuffle[self.output_axes.index('c')] = 0\n\n return self.b.dimshuffle(*shuffle)\n\n\n def get_total_state_space(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return CompositeSpace((self.h_space, self.output_space))\n\n def set_input_space(self, space):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n \"\"\" Note: this resets parameters!\"\"\"\n\n setup_detector_layer_c01b(layer=self,\n input_space=space,\n rng=self.dbm.rng,)\n\n if not tuple(space.axes) == ('c', 0, 1, 'b'):\n raise AssertionError(\"You're not using c01b inputs. Ian is enforcing c01b inputs while developing his pipeline to make sure it runs at maximal speed. If you really don't want to use c01b inputs, you can remove this check and things should work. If they don't work it's only because they're not tested.\")\n if self.dummy_channels != 0:\n raise NotImplementedError(str(type(self))+\" does not support adding dummy channels for cuda-convnet compatibility yet, you must implement that feature or use inputs with <=3 channels or a multiple of 4 channels\")\n\n self.input_rows = self.input_space.shape[0]\n self.input_cols = self.input_space.shape[1]\n self.h_rows = self.detector_space.shape[0]\n self.h_cols = self.detector_space.shape[1]\n\n if not(self.h_rows % self.pool_rows == 0):\n raise ValueError(self.layer_name + \": h_rows = %d, pool_rows = %d. Should be divisible but remainder is %d\" %\n (self.h_rows, self.pool_rows, self.h_rows % self.pool_rows))\n assert self.h_cols % self.pool_cols == 0\n\n self.h_space = Conv2DSpace(shape = (self.h_rows, self.h_cols), num_channels = self.output_channels,\n axes = self.output_axes)\n self.output_space = Conv2DSpace(shape = (self.h_rows / self.pool_rows,\n self.h_cols / self.pool_cols),\n num_channels = self.output_channels,\n axes = self.output_axes)\n\n logger.info('{0} : detector shape: {1} '\n 'pool shape: {2}'.format(self.layer_name,\n self.h_space.shape,\n self.output_space.shape))\n\n assert tuple(self.output_axes) == ('c', 0, 1, 'b')\n self.max_pool = max_pool_c01b\n\n if self.center:\n p_ofs, h_ofs = self.init_mf_state()\n self.p_offset = sharedX(self.output_space.get_origin(), 'p_offset')\n self.h_offset = sharedX(self.h_space.get_origin(), 'h_offset')\n f = function([], updates={self.p_offset: p_ofs[:,:,:,0], self.h_offset: h_ofs[:,:,:,0]})\n f()\n\n\n def get_params(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n assert self.b.name is not None\n W ,= self.transformer.get_params()\n assert W.name is not None\n\n return [ W, self.b]\n\n def state_to_b01c(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n if tuple(self.output_axes) == ('b',0,1,'c'):\n return state\n return [ Conv2DSpace.convert(elem, self.output_axes, ('b', 0, 1, 'c'))\n for elem in state ]\n\n def get_range_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = 0.\n\n if self.pool_rows == 1 and self.pool_cols == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n assert isinstance(coeffs, float)\n _, state = state\n state = [state]\n coeffs = [coeffs]\n else:\n assert all([len(elem) == 2 for elem in [state, coeffs]])\n\n for s, c in safe_zip(state, coeffs):\n if c == 0.:\n continue\n # Range over everything but the channel index\n # theano can only take gradient through max if the max is over 1 axis or all axes\n # so I manually unroll the max for the case I use here\n assert self.h_space.axes == ('b', 'c', 0, 1)\n assert self.output_space.axes == ('b', 'c', 0, 1)\n mx = s.max(axis=3).max(axis=2).max(axis=0)\n assert hasattr(mx.owner.op, 'grad')\n mn = s.min(axis=3).max(axis=2).max(axis=0)\n assert hasattr(mn.owner.op, 'grad')\n assert mx.ndim == 1\n assert mn.ndim == 1\n r = mx - mn\n rval += (1. - r).mean() * c\n\n return rval\n\n def get_l1_act_cost(self, state, target, coeff, eps):\n \"\"\"\n .. todo::\n\n WRITEME properly\n\n Parameters\n ----------\n state : WRITEME\n target : WRITEME\n if pools contain more than one element, should be a list\n with two elements. the first element is for the pooling\n units and the second for the detector units.\n coeff : WRITEME\n eps : WRITEME\n \"\"\"\n rval = 0.\n\n\n if self.pool_rows == 1 and self.pool_cols == 1:\n # If the pool size is 1 then pools = detectors\n # and we should not penalize pools and detectors separately\n assert len(state) == 2\n assert isinstance(target, float)\n assert isinstance(coeff, float)\n _, state = state\n state = [state]\n target = [target]\n coeff = [coeff]\n if eps is None:\n eps = 0.\n eps = [eps]\n else:\n if eps is None:\n eps = [0., 0.]\n assert all([len(elem) == 2 for elem in [state, target, coeff]])\n p_target, h_target = target\n if h_target > p_target and (coeff[0] != 0. and coeff[1] != 0.):\n # note that, within each group, E[p] is the sum of E[h]\n warnings.warn(\"Do you really want to regularize the detector units to be more active than the pooling units?\")\n\n for s, t, c, e in safe_zip(state, target, coeff, eps):\n if c == 0.:\n continue\n # Average over everything but the channel index\n m = s.mean(axis= [ ax for ax in range(4) if self.output_axes[ax] != 'c' ])\n assert m.ndim == 1\n rval += T.maximum(abs(m-t)-e,0.).mean()*c\n\n return rval\n\n def get_lr_scalers(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n rval = OrderedDict()\n\n if self.scale_by_sharing:\n # scale each learning rate by 1 / # times param is reused\n h_rows, h_cols = self.h_space.shape\n num_h = float(h_rows * h_cols)\n rval[self.transformer._filters] = 1. /num_h\n rval[self.b] = 1. / num_h\n\n return rval\n\n def upward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n p,h = total_state\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n p -= self.p_offset\n h -= self.h_offset\n\n return p\n\n def downward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n p,h = total_state\n\n if not hasattr(self, 'center'):\n self.center = False\n\n if self.center:\n p -= self.p_offset\n h -= self.h_offset\n\n return h\n\n def get_monitoring_channels_from_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n P, H = state\n\n axes = tuple([i for i, ax in enumerate(self.output_axes) if ax != 'c'])\n p_max = P.max(axis=(0,1,2))\n p_min = P.min(axis=(0,1,2))\n p_mean = P.mean(axis=(0,1,2))\n\n p_range = p_max - p_min\n\n rval = {\n 'p_max_max' : p_max.max(),\n 'p_max_mean' : p_max.mean(),\n 'p_max_min' : p_max.min(),\n 'p_min_max' : p_min.max(),\n 'p_min_mean' : p_min.mean(),\n 'p_min_max' : p_min.max(),\n 'p_range_max' : p_range.max(),\n 'p_range_mean' : p_range.mean(),\n 'p_range_min' : p_range.min(),\n 'p_mean_max' : p_mean.max(),\n 'p_mean_mean' : p_mean.mean(),\n 'p_mean_min' : p_mean.min()\n }\n\n return rval\n\n def get_weight_decay(self, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n W , = self.transformer.get_params()\n return coeffs * T.sqr(W).sum()\n\n def mf_update(self, state_below, state_above, layer_above = None, double_weights = False, iter_name = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n self.input_space.validate(state_below)\n\n if iter_name is None:\n iter_name = 'anon'\n\n if state_above is not None:\n assert layer_above is not None\n msg = layer_above.downward_message(state_above)\n msg.name = 'msg_from_'+layer_above.layer_name+'_to_'+self.layer_name+'['+iter_name+']'\n else:\n msg = None\n\n if not hasattr(state_below, 'ndim'):\n raise TypeError(\"state_below should be a TensorType, got \" +\n str(state_below) + \" of type \" + str(type(state_below)))\n if state_below.ndim != 4:\n raise ValueError(\"state_below should have ndim 4, has \"+str(state_below.ndim))\n\n if double_weights:\n state_below = 2. * state_below\n state_below.name = self.layer_name + '_'+iter_name + '_2state'\n z = self.transformer.lmul(state_below) + self.broadcasted_bias()\n if self.layer_name is not None and iter_name is not None:\n z.name = self.layer_name + '_' + iter_name + '_z'\n p,h = self.max_pool(z, (self.pool_rows, self.pool_cols), msg)\n\n p.name = self.layer_name + '_p_' + iter_name\n h.name = self.layer_name + '_h_' + iter_name\n\n return p, h\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(\"Need to update for C01B\")\n\n if state_above is not None:\n msg = layer_above.downward_message(state_above)\n try:\n self.output_space.validate(msg)\n except TypeError as e:\n reraise_as(TypeError(str(type(layer_above))+\".downward_message gave something that was not the right type: \"+str(e)))\n else:\n msg = None\n\n z = self.transformer.lmul(state_below) + self.broadcasted_bias()\n p, h, p_sample, h_sample = self.max_pool(z,\n (self.pool_rows, self.pool_cols), msg, theano_rng)\n\n return p_sample, h_sample\n\n def downward_message(self, downward_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.h_space.validate(downward_state)\n return self.transformer.lmul_T(downward_state)\n\n def set_batch_size(self, batch_size):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.transformer.set_batch_size(batch_size)\n\n def get_weights_topo(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return self.transformer.get_weights_topo()\n\n def init_mf_state(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n default_z = self.broadcasted_bias()\n shape = {\n 'b': self.dbm.batch_size,\n 0: self.h_space.shape[0],\n 1: self.h_space.shape[1],\n 'c': self.h_space.num_channels\n }\n # work around theano bug with broadcasted stuff\n default_z += T.alloc(*([0.]+[shape[elem] for elem in self.h_space.axes])).astype(default_z.dtype)\n assert default_z.ndim == 4\n\n p, h = self.max_pool(\n z = default_z,\n pool_shape = (self.pool_rows, self.pool_cols))\n\n return p, h\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME properly\n\n Returns a shared variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n raise NotImplementedError(\"Need to update for C01B\")\n\n t1 = time.time()\n\n empty_input = self.h_space.get_origin_batch(self.dbm.batch_size)\n h_state = sharedX(empty_input)\n\n default_z = T.zeros_like(h_state) + self.broadcasted_bias()\n\n theano_rng = make_theano_rng(None, numpy_rng.randint(2 ** 16),\n which_method=\"binomial\")\n\n p_exp, h_exp, p_sample, h_sample = self.max_pool(\n z = default_z,\n pool_shape = (self.pool_rows, self.pool_cols),\n theano_rng = theano_rng)\n\n p_state = sharedX( self.output_space.get_origin_batch(\n self.dbm.batch_size))\n\n\n t2 = time.time()\n\n f = function([], updates = [\n (p_state, p_sample),\n (h_state, h_sample)\n ])\n\n t3 = time.time()\n\n f()\n\n t4 = time.time()\n\n logger.info('{0}.make_state took {1}'.format(self, t4-t1))\n logger.info('\\tcompose time: {0}'.format(t2-t1))\n logger.info('\\tcompile time: {0}'.format(t3-t2))\n logger.info('\\texecute time: {0}'.format(t4-t3))\n\n p_state.name = 'p_sample_shared'\n h_state.name = 'h_sample_shared'\n\n return p_state, h_state\n\n def expected_energy_term(self, state, average, state_below, average_below):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n raise NotImplementedError(\"Need to update for C01B\")\n self.input_space.validate(state_below)\n\n downward_state = self.downward_state(state)\n self.h_space.validate(downward_state)\n\n # Energy function is linear so it doesn't matter if we're averaging or not\n # Specifically, our terms are -u^T W d - b^T d where u is the upward state of layer below\n # and d is the downward state of this layer\n\n bias_term = (downward_state * self.broadcasted_bias()).sum(axis=(1,2,3))\n weights_term = (self.transformer.lmul(state_below) * downward_state).sum(axis=(1,2,3))\n\n rval = -bias_term - weights_term\n\n assert rval.ndim == 1\n\n return rval\n\n\nclass BVMP_Gaussian(BinaryVectorMaxPool):\n \"\"\"\n Like BinaryVectorMaxPool, but must have GaussianVisLayer\n as its input. Uses its beta to bias the hidden units appropriately.\n See gaussian.lyx\n\n beta is *not* considered a parameter of this layer, it's just an\n external factor influencing how this layer behaves.\n Gradient can still flow to beta, but it will only be included in\n the parameters list if some class other than this layer includes it.\n\n .. todo::\n\n WRITEME : parameter list\n \"\"\"\n\n def __init__(self,\n input_layer,\n detector_layer_dim,\n pool_size,\n layer_name,\n irange = None,\n sparse_init = None,\n sparse_stdev = 1.,\n include_prob = 1.0,\n init_bias = 0.,\n W_lr_scale = None,\n b_lr_scale = None,\n center = False,\n mask_weights = None,\n max_col_norm = None,\n copies = 1):\n warnings.warn(\"BVMP_Gaussian math is very faith-based, need to complete gaussian.lyx\")\n\n args = locals()\n\n del args['input_layer']\n del args['self']\n super(BVMP_Gaussian, self).__init__(**args)\n self.input_layer = input_layer\n\n def get_weights(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if self.requires_reformat:\n # This is not really an unimplemented case.\n # We actually don't know how to format the weights\n # in design space. We got the data in topo space\n # and we don't have access to the dataset\n raise NotImplementedError()\n W ,= self.transformer.get_params()\n W = W.get_value()\n\n x = input(\"multiply by beta?\")\n if x == 'y':\n beta = self.input_layer.beta.get_value()\n return (W.T * beta).T\n assert x == 'n'\n return W\n\n def set_weights(self, weights):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(\"beta would make get_weights for visualization not correspond to set_weights\")\n W, = self.transformer.get_params()\n W.set_value(weights)\n\n def set_biases(self, biases, recenter = False):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.b.set_value(biases)\n if recenter:\n assert self.center\n if self.pool_size != 1:\n raise NotImplementedError()\n self.offset.set_value(sigmoid_numpy(self.b.get_value()))\n\n def get_biases(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return self.b.get_value() - self.beta_bias().eval()\n\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(\"need to account for beta\")\n if self.copies != 1:\n raise NotImplementedError()\n\n if theano_rng is None:\n raise ValueError(\"theano_rng is required; it just defaults to None so that it may appear after layer_above / state_above in the list.\")\n\n if state_above is not None:\n msg = layer_above.downward_message(state_above)\n else:\n msg = None\n\n if self.requires_reformat:\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n z = self.transformer.lmul(state_below) + self.b\n p, h, p_sample, h_sample = max_pool_channels(z,\n self.pool_size, msg, theano_rng)\n\n return p_sample, h_sample\n\n def downward_message(self, downward_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = self.transformer.lmul_T(downward_state)\n\n if self.requires_reformat:\n rval = self.desired_space.format_as(rval, self.input_space)\n\n return rval * self.copies\n\n def init_mf_state(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n # work around theano bug with broadcasted vectors\n z = T.alloc(0., self.dbm.batch_size, self.detector_layer_dim).astype(self.b.dtype) + \\\n self.b.dimshuffle('x', 0) + self.beta_bias()\n rval = max_pool_channels(z = z,\n pool_size = self.pool_size)\n return rval\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME properly\n\n Returns a shared variable containing an actual state\n (not a mean field state) for this variable.\n \"\"\"\n raise NotImplementedError(\"need to account for beta\")\n\n if not hasattr(self, 'copies'):\n self.copies = 1\n\n if self.copies != 1:\n raise NotImplementedError()\n\n\n empty_input = self.h_space.get_origin_batch(num_examples)\n empty_output = self.output_space.get_origin_batch(num_examples)\n\n h_state = sharedX(empty_input)\n p_state = sharedX(empty_output)\n\n theano_rng = make_theano_rng(None, numpy_rng.randint(2 ** 16),\n which_method=\"binomial\")\n\n default_z = T.zeros_like(h_state) + self.b\n\n p_exp, h_exp, p_sample, h_sample = max_pool_channels(\n z = default_z,\n pool_size = self.pool_size,\n theano_rng = theano_rng)\n\n assert h_sample.dtype == default_z.dtype\n\n f = function([], updates = [\n (p_state , p_sample),\n (h_state , h_sample)\n ])\n\n f()\n\n p_state.name = 'p_sample_shared'\n h_state.name = 'h_sample_shared'\n\n return p_state, h_state\n\n def expected_energy_term(self, state, average, state_below, average_below):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n raise NotImplementedError(\"need to account for beta, and maybe some oether stuff\")\n\n # Don't need to do anything special for centering, upward_state / downward state\n # make it all just work\n\n self.input_space.validate(state_below)\n\n if self.requires_reformat:\n if not isinstance(state_below, tuple):\n for sb in get_debug_values(state_below):\n if sb.shape[0] != self.dbm.batch_size:\n raise ValueError(\"self.dbm.batch_size is %d but got shape of %d\" % (self.dbm.batch_size, sb.shape[0]))\n assert reduce(operator.mul, sb.shape[1:]) == self.input_dim\n\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n downward_state = self.downward_state(state)\n self.h_space.validate(downward_state)\n\n # Energy function is linear so it doesn't matter if we're averaging or not\n # Specifically, our terms are -u^T W d - b^T d where u is the upward state of layer below\n # and d is the downward state of this layer\n\n bias_term = T.dot(downward_state, self.b)\n weights_term = (self.transformer.lmul(state_below) * downward_state).sum(axis=1)\n\n rval = -bias_term - weights_term\n\n assert rval.ndim == 1\n\n return rval * self.copies\n\n def linear_feed_forward_approximation(self, state_below):\n \"\"\"\n .. todo::\n\n WRITEME properly\n\n Used to implement TorontoSparsity. Unclear exactly what properties of it are\n important or how to implement it for other layers.\n\n Properties it must have:\n output is same kind of data structure (ie, tuple of theano 2-tensors)\n as mf_update\n\n Properties it probably should have for other layer types:\n An infinitesimal change in state_below or the parameters should cause the same sign of change\n in the output of linear_feed_forward_approximation and in mf_update\n\n Should not have any non-linearities that cause the gradient to shrink\n\n Should disregard top-down feedback\n \"\"\"\n raise NotImplementedError(\"need to account for beta\")\n\n z = self.transformer.lmul(state_below) + self.b\n\n if self.pool_size != 1:\n # Should probably implement sum pooling for the non-pooled version,\n # but in reality it's not totally clear what the right answer is\n raise NotImplementedError()\n\n return z, z\n\n def beta_bias(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n W, = self.transformer.get_params()\n beta = self.input_layer.beta\n assert beta.ndim == 1\n return - 0.5 * T.dot(beta, T.sqr(W))\n\n def mf_update(self, state_below, state_above, layer_above = None, double_weights = False, iter_name = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n\n self.input_space.validate(state_below)\n\n if self.requires_reformat:\n if not isinstance(state_below, tuple):\n for sb in get_debug_values(state_below):\n if sb.shape[0] != self.dbm.batch_size:\n raise ValueError(\"self.dbm.batch_size is %d but got shape of %d\" % (self.dbm.batch_size, sb.shape[0]))\n assert reduce(operator.mul, sb.shape[1:]) == self.input_dim\n\n state_below = self.input_space.format_as(state_below, self.desired_space)\n\n if iter_name is None:\n iter_name = 'anon'\n\n if state_above is not None:\n assert layer_above is not None\n msg = layer_above.downward_message(state_above)\n msg.name = 'msg_from_'+layer_above.layer_name+'_to_'+self.layer_name+'['+iter_name+']'\n else:\n msg = None\n\n if double_weights:\n state_below = 2. * state_below\n state_below.name = self.layer_name + '_'+iter_name + '_2state'\n z = self.transformer.lmul(state_below) + self.b + self.beta_bias()\n if self.layer_name is not None and iter_name is not None:\n z.name = self.layer_name + '_' + iter_name + '_z'\n p,h = max_pool_channels(z, self.pool_size, msg)\n\n p.name = self.layer_name + '_p_' + iter_name\n h.name = self.layer_name + '_h_' + iter_name\n\n return p, h\n\nclass CompositeLayer(HiddenLayer):\n \"\"\"\n A Layer constructing by aligning several other Layer\n objects side by side\n\n Parameters\n ----------\n components : WRITEME\n A list of layers that are combined to form this layer\n inputs_to_components : None or dict mapping int to list of int\n Should be None unless the input space is a CompositeSpace\n If inputs_to_components[i] contains j, it means input i will\n be given as input to component j.\n If an input dodes not appear in the dictionary, it will be given\n to all components.\n\n This field allows one CompositeLayer to have another as input\n without forcing each component to connect to all members\n of the CompositeLayer below. For example, you might want to\n have both densely connected and convolutional units in all\n layers, but a convolutional unit is incapable of taking a\n non-topological input space.\n \"\"\"\n\n\n def __init__(self, layer_name, components, inputs_to_components = None):\n self.layer_name = layer_name\n\n self.components = list(components)\n assert isinstance(components, list)\n for component in components:\n assert isinstance(component, HiddenLayer)\n self.num_components = len(components)\n self.components = list(components)\n\n if inputs_to_components is None:\n self.inputs_to_components = None\n else:\n if not isinstance(inputs_to_components, dict):\n raise TypeError(\"CompositeLayer expected inputs_to_components to be a dict, got \"+str(type(inputs_to_components)))\n self.inputs_to_components = OrderedDict()\n for key in inputs_to_components:\n assert isinstance(key, int)\n assert key >= 0\n value = inputs_to_components[key]\n assert isinstance(value, list)\n assert all([isinstance(elem, int) for elem in value])\n assert min(value) >= 0\n assert max(value) < self.num_components\n self.inputs_to_components[key] = list(value)\n\n def set_input_space(self, space):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n self.input_space = space\n\n if not isinstance(space, CompositeSpace):\n assert self.inputs_to_components is None\n self.routing_needed = False\n else:\n if self.inputs_to_components is None:\n self.routing_needed = False\n else:\n self.routing_needed = True\n assert max(self.inputs_to_components) < space.num_components\n # Invert the dictionary\n self.components_to_inputs = OrderedDict()\n for i in xrange(self.num_components):\n inputs = []\n for j in xrange(space.num_components):\n if i in self.inputs_to_components[j]:\n inputs.append(i)\n if len(inputs) < space.num_components:\n self.components_to_inputs[i] = inputs\n\n for i, component in enumerate(self.components):\n if self.routing_needed and i in self.components_to_inputs:\n cur_space = space.restrict(self.components_to_inputs[i])\n else:\n cur_space = space\n\n component.set_input_space(cur_space)\n\n self.output_space = CompositeSpace([ component.get_output_space() for component in self.components ])\n\n def make_state(self, num_examples, numpy_rng):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return tuple(component.make_state(num_examples, numpy_rng) for\n component in self.components)\n\n def get_total_state_space(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return CompositeSpace([component.get_total_state_space() for component in self.components])\n\n def set_batch_size(self, batch_size):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n for component in self.components:\n component.set_batch_size(batch_size)\n\n def set_dbm(self, dbm):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n for component in self.components:\n component.set_dbm(dbm)\n\n def mf_update(self, state_below, state_above, layer_above = None, double_weights = False, iter_name = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = []\n\n for i, component in enumerate(self.components):\n if self.routing_needed and i in self.components_to_inputs:\n cur_state_below =self.input_space.restrict_batch(state_below, self.components_to_inputs[i])\n else:\n cur_state_below = state_below\n\n class RoutingLayer(object):\n def __init__(self, idx, layer):\n self.__dict__.update(locals())\n del self.self\n self.layer_name = 'route_'+str(idx)+'_'+layer.layer_name\n\n def downward_message(self, state):\n return self.layer.downward_message(state)[self.idx]\n\n if layer_above is not None:\n cur_layer_above = RoutingLayer(i, layer_above)\n else:\n cur_layer_above = None\n\n mf_update = component.mf_update(state_below = cur_state_below,\n state_above = state_above,\n layer_above = cur_layer_above,\n double_weights = double_weights,\n iter_name = iter_name)\n\n rval.append(mf_update)\n\n return tuple(rval)\n\n def init_mf_state(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return tuple([component.init_mf_state() for component in self.components])\n\n\n def get_weight_decay(self, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return sum([component.get_weight_decay(coeff) for component, coeff\n in safe_zip(self.components, coeffs)])\n\n def upward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return tuple([component.upward_state(elem)\n for component, elem in\n safe_zip(self.components, total_state)])\n\n def downward_state(self, total_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return tuple([component.downward_state(elem)\n for component, elem in\n safe_zip(self.components, total_state)])\n\n def downward_message(self, downward_state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n if isinstance(self.input_space, CompositeSpace):\n num_input_components = self.input_space.num_components\n else:\n num_input_components = 1\n\n rval = [ None ] * num_input_components\n\n def add(x, y):\n if x is None:\n return y\n if y is None:\n return x\n return x + y\n\n for i, packed in enumerate(safe_zip(self.components, downward_state)):\n component, state = packed\n if self.routing_needed and i in self.components_to_inputs:\n input_idx = self.components_to_inputs[i]\n else:\n input_idx = range(num_input_components)\n\n partial_message = component.downward_message(state)\n\n if len(input_idx) == 1:\n partial_message = [ partial_message ]\n\n assert len(input_idx) == len(partial_message)\n\n for idx, msg in safe_zip(input_idx, partial_message):\n rval[idx] = add(rval[idx], msg)\n\n if len(rval) == 1:\n rval = rval[0]\n else:\n rval = tuple(rval)\n\n self.input_space.validate(rval)\n\n return rval\n\n def get_l1_act_cost(self, state, target, coeff, eps):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return sum([ comp.get_l1_act_cost(s, t, c, e) \\\n for comp, s, t, c, e in safe_zip(self.components, state, target, coeff, eps)])\n\n def get_range_rewards(self, state, coeffs):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return sum([comp.get_range_rewards(s, c)\n for comp, s, c in safe_zip(self.components, state, coeffs)])\n\n def get_params(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n return reduce(lambda x, y: safe_union(x, y),\n [component.get_params() for component in self.components])\n\n def get_weights_topo(self):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n logger.info('Get topological weights for which layer?')\n for i, component in enumerate(self.components):\n logger.info('{0} {1}'.format(i, component.layer_name))\n x = input()\n return self.components[int(x)].get_weights_topo()\n\n def get_monitoring_channels_from_state(self, state):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = OrderedDict()\n\n for layer, s in safe_zip(self.components, state):\n d = layer.get_monitoring_channels_from_state(s)\n for key in d:\n rval[layer.layer_name+'_'+key] = d[key]\n\n return rval\n\n def sample(self, state_below = None, state_above = None,\n layer_above = None,\n theano_rng = None):\n \"\"\"\n .. todo::\n\n WRITEME\n \"\"\"\n rval = []\n\n for i, component in enumerate(self.components):\n if self.routing_needed and i in self.components_to_inputs:\n cur_state_below =self.input_space.restrict_batch(state_below, self.components_to_inputs[i])\n else:\n cur_state_below = state_below\n\n class RoutingLayer(object):\n def __init__(self, idx, layer):\n self.__dict__.update(locals())\n del self.self\n self.layer_name = 'route_'+str(idx)+'_'+layer.layer_name\n\n def downward_message(self, state):\n return self.layer.downward_message(state)[self.idx]\n\n if layer_above is not None:\n cur_layer_above = RoutingLayer(i, layer_above)\n else:\n cur_layer_above = None\n\n sample = component.sample(state_below = cur_state_below,\n state_above = state_above,\n layer_above = cur_layer_above,\n theano_rng = theano_rng)\n\n rval.append(sample)\n\n return tuple(rval)\n" ]
[ [ "numpy.exp", "numpy.zeros", "numpy.transpose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Simon-Will/neuralmonkey
[ "b686a9d302cb10eda5fca991e1d7ee6b9e84b75a", "b686a9d302cb10eda5fca991e1d7ee6b9e84b75a" ]
[ "neuralmonkey/processors/alignment.py", "neuralmonkey/tests/test_model_part.py" ]
[ "import re\nfrom typing import List\n\nimport numpy as np\n\n# pylint: disable=too-few-public-methods\n\nID_SEP = re.compile(r\"[-:]\")\n\n\nclass WordAlignmentPreprocessor(object):\n \"\"\"A preprocessor for word alignments in a text format.\n\n One of the following formats is expected:\n\n s1-t1 s2-t2 ...\n\n s1:1/w1 s2:t2/w2 ...\n\n where each `s` and `t` is the index of a word in the source and target\n sentence, respectively, and `w` is the corresponding weight. If the weight\n is not given, it is assumend to be 1. The separators `-` and `:` are\n interchangeable.\n\n The output of the preprocessor is an alignment matrix of the fixed shape\n (target_len, source_len) for each sentence.\n \"\"\"\n\n def __init__(self, source_len, target_len, dtype=np.float32,\n normalize=True, zero_based=True):\n self._source_len = source_len\n self._target_len = target_len\n self._dtype = dtype\n self._normalize = normalize\n self._zero_based = zero_based\n\n def __call__(self, sentence: List[str]):\n result = np.zeros((self._target_len, self._source_len), self._dtype)\n\n for ali in sentence:\n ids, _, str_weight = ali.partition(\"/\")\n i, j = [int(id_str) for id_str in ID_SEP.split(ids)]\n weight = float(str_weight) if str_weight else 1.\n\n if not self._zero_based:\n i -= 1\n j -= 1\n\n if i < self._source_len and j < self._target_len:\n result[j][i] = weight\n\n if self._normalize:\n with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n result /= result.sum(axis=1, keepdims=True)\n result[np.isnan(result)] = 0\n\n return result\n", "#!/usr/bin/env python3.5\n\"\"\"Test ModelPart class.\"\"\"\n\nimport os\nimport tempfile\nimport unittest\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom neuralmonkey.vocabulary import Vocabulary\nfrom neuralmonkey.encoders.recurrent import SentenceEncoder\n\n\nclass Test(unittest.TestCase):\n \"\"\"Test capabilities of model part.\"\"\"\n def test_save_and_load(self):\n \"\"\"Try to save and load encoder.\"\"\"\n vocabulary = Vocabulary()\n vocabulary.add_word(\"a\")\n vocabulary.add_word(\"b\")\n\n checkpoint_file = tempfile.NamedTemporaryFile(delete=False)\n checkpoint_file.close()\n\n encoder = SentenceEncoder(\n name=\"enc\", vocabulary=Vocabulary(), data_id=\"data_id\",\n embedding_size=10, rnn_size=20, max_input_len=30,\n save_checkpoint=checkpoint_file.name,\n load_checkpoint=checkpoint_file.name)\n\n # NOTE: This assert needs to be here otherwise the model has\n # no parameters since the sentence encoder is initialized lazily\n self.assertIsInstance(encoder.temporal_states, tf.Tensor)\n\n encoders_variables = tf.get_collection(\n tf.GraphKeys.GLOBAL_VARIABLES, scope=\"enc\")\n\n sess_1 = tf.Session()\n sess_1.run(tf.global_variables_initializer())\n encoder.save(sess_1)\n\n sess_2 = tf.Session()\n sess_2.run(tf.global_variables_initializer())\n encoder.load(sess_2)\n\n values_in_sess_1 = sess_1.run(encoders_variables)\n values_in_sess_2 = sess_2.run(encoders_variables)\n\n self.assertTrue(\n all(np.all(v1 == v2) for v1, v2 in\n zip(values_in_sess_1, values_in_sess_2)))\n\n os.remove(checkpoint_file.name)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.errstate", "numpy.isnan", "numpy.zeros" ], [ "tensorflow.get_collection", "tensorflow.global_variables_initializer", "tensorflow.Session", "numpy.all" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]