def bulkread(self, data=[], lengthR='<STR_LIT:None>', readmode=<NUM_LIT:1>):

<EOL>if (<NUM_LIT:1> > lengthR > <NUM_LIT>) | (len(data) > <NUM_LIT>):<EOL><INDENT>print(<EOL>'<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>if (lengthR == '<STR_LIT:None>') & (readmode == <NUM_LIT:1>):<EOL><INDENT>lengthR = len(data)<EOL><DEDENT>commandW = <NUM_LIT> | (self.lsbfirst << <NUM_LIT:3>) | self.write_clock_ve<EOL>lengthW = len(data) - <NUM_LIT:1><EOL>len_lowW = (lengthW) & <NUM_LIT><EOL>len_highW = ((lengthW) >> <NUM_LIT:8>) & <NUM_LIT><EOL>commandR = <NUM_LIT> | (self.lsbfirst << <NUM_LIT:3>) | (self.read_clock_ve << <NUM_LIT:2>)<EOL>length = lengthR<EOL>if lengthR % <NUM_LIT:2> == <NUM_LIT:1>:<EOL><INDENT>length += <NUM_LIT:1><EOL><DEDENT>length = length/<NUM_LIT:2><EOL>lenremain = lengthR - length<EOL>len_lowR = (length - <NUM_LIT:1>) & <NUM_LIT><EOL>len_highR = ((length - <NUM_LIT:1>) >> <NUM_LIT:8>) & <NUM_LIT><EOL>logger.debug(<EOL>'<STR_LIT>'.format(commandW))<EOL>logger.debug('<STR_LIT>'.format(commandR))<EOL>self._assert_cs()<EOL>self._ft232h._write(str(bytearray((commandW, len_lowW, len_highW))))<EOL>self._ft232h._write(str(bytearray(data)))<EOL>self._ft232h._write(str(bytearray((commandR, len_lowR, len_highR))))<EOL>payload1 = self._ft232h._poll_read(length)<EOL>self._ft232h._write(str(bytearray((commandR, len_lowR, len_highR))))<EOL>payload2 = self._ft232h._poll_read(lenremain)<EOL>self._deassert_cs()<EOL>return bytearray(payload1 + payload2)<EOL>

Half-duplex SPI write then read. Send command and payload to slave as bytearray
            then consequently read out response from the slave for length in bytes.
        Designed for use with NOR or NAND flash chips, and possibly SD cards...etc...
        Read command is cut in half and performed twice in series to prevent single byte errors.
        Hardware limits per command are enforced before doing anything.
        Read length is an optional argument, so that it can function similar to transfer
            but still half-duplex.
        For reading without writing, one can send a blank array or skip that argument.


<EOL>if (len(data) > <NUM_LIT>):<EOL><INDENT>print(<EOL>'<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>command = <NUM_LIT> | (self.lsbfirst << <NUM_LIT:3>) | (<EOL>self.read_clock_ve << <NUM_LIT:2>) | self.write_clock_ve<EOL>logger.debug('<STR_LIT>'.format(command))<EOL>data1 = data[:len(data)/<NUM_LIT:2>]<EOL>data2 = data[len(data)/<NUM_LIT:2>:]<EOL>len_low1 = (len(data1) - <NUM_LIT:1>) & <NUM_LIT><EOL>len_high1 = ((len(data1) - <NUM_LIT:1>) >> <NUM_LIT:8>) & <NUM_LIT><EOL>len_low2 = (len(data2) - <NUM_LIT:1>) & <NUM_LIT><EOL>len_high2 = ((len(data2) - <NUM_LIT:1>) >> <NUM_LIT:8>) & <NUM_LIT><EOL>payload1 = '<STR_LIT>'<EOL>payload2 = '<STR_LIT>'<EOL>self._assert_cs()<EOL>if len(data1) > <NUM_LIT:0>:<EOL><INDENT>self._ft232h._write(str(bytearray((command, len_low1, len_high1))))<EOL>self._ft232h._write(str(bytearray(data1)))<EOL>payload1 = self._ft232h._poll_read(len(data1))<EOL><DEDENT>if len(data2) > <NUM_LIT:0>:<EOL><INDENT>self._ft232h._write(str(bytearray((command, len_low2, len_high2))))<EOL>self._ft232h._write(str(bytearray(data2)))<EOL>payload2 = self._ft232h._poll_read(len(data2))<EOL><DEDENT>self._deassert_cs()<EOL>return bytearray(payload1 + payload2)<EOL>

Full-duplex SPI read and write.  The specified array of bytes will be
        clocked out the MOSI line, while simultaneously bytes will be read from
        the MISO line.  Read bytes will be returned as a bytearray object.


def __init__(self, ft232h, address, clock_hz=<NUM_LIT>):

self._address = address<EOL>self._ft232h = ft232h<EOL>self._ft232h.mpsse_set_clock(clock_hz, three_phase=True)<EOL>self._ft232h._write('<STR_LIT>')<EOL>self._idle()<EOL>

Create an instance of the I2C device at the specified address on the
        specified I2C bus number.


<EOL>self._ft232h.setup_pins({<NUM_LIT:0>: GPIO.OUT, <NUM_LIT:1>: GPIO.OUT, <NUM_LIT:2>: GPIO.IN},<EOL>{<NUM_LIT:0>: GPIO.HIGH, <NUM_LIT:1>: GPIO.HIGH})<EOL>


<EOL>self._command = []<EOL>self._expected = <NUM_LIT:0><EOL>


<EOL>self._command.append('<STR_LIT>')<EOL>self._ft232h._write('<STR_LIT>'.join(self._command))<EOL>return bytearray(self._ft232h._poll_read(self._expected))<EOL>

End I2C transaction and get response bytes, including ACKs.


<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.HIGH, <NUM_LIT:1>: GPIO.LOW}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.LOW, <NUM_LIT:1>: GPIO.LOW}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>

Send I2C start signal. Must be called within a transaction start/end.


self._ft232h.output_pins({<NUM_LIT:0>: GPIO.HIGH, <NUM_LIT:1>: GPIO.HIGH}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>

Set I2C signals to idle state with SCL and SDA at a high value. Must
        be called within a transaction start/end.


<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.LOW, <NUM_LIT:1>: GPIO.LOW}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.HIGH, <NUM_LIT:1>: GPIO.LOW}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.HIGH, <NUM_LIT:1>: GPIO.HIGH}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>

Send I2C stop signal. Must be called within a transaction start/end.


for i in range(length-<NUM_LIT:1>):<EOL><INDENT>self._command.append('<STR_LIT>')<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.LOW, <NUM_LIT:1>: GPIO.HIGH}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio())<EOL><DEDENT>self._command.append('<STR_LIT>')<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.LOW, <NUM_LIT:1>: GPIO.HIGH}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio())<EOL>self._expected += length<EOL>

Read the specified number of bytes from the I2C bus.  Length is the
        number of bytes to read (must be 1 or more).


for byte in data:<EOL><INDENT>self._command.append(str(bytearray((<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, byte))))<EOL>self._ft232h.output_pins({<NUM_LIT:0>: GPIO.LOW, <NUM_LIT:1>: GPIO.HIGH}, write=False)<EOL>self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)<EOL>self._command.append('<STR_LIT>')<EOL><DEDENT>self._expected += len(data)<EOL>

Write the specified number of bytes to the chip.


if read:<EOL><INDENT>return (self._address << <NUM_LIT:1>) | <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>return self._address << <NUM_LIT:1><EOL><DEDENT>

Return the address byte with the specified R/W bit set.  If read is
        True the R/W bit will be 1, otherwise the R/W bit will be 0.


for byte in response:<EOL><INDENT>if byte & <NUM_LIT> != <NUM_LIT>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT><DEDENT>

Check all the specified bytes have the ACK bit set.  Throws a
        RuntimeError exception if not all the ACKs are set.


self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(False)])<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>if len(response) != <NUM_LIT:1>:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>'.format(len(response)))<EOL><DEDENT>return ((response[<NUM_LIT:0>] & <NUM_LIT>) == <NUM_LIT>)<EOL>

Attempt to detect if a device at this address is present on the I2C
        bus.  Will send out the device's address for writing and verify an ACK
        is received.  Returns true if the ACK is received, and false if not.


value = value & <NUM_LIT><EOL>self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(False), value])<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>self._verify_acks(response)<EOL>

Write an 8-bit value on the bus (without register).


value = value & <NUM_LIT><EOL>self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(False), register, value])<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>self._verify_acks(response)<EOL>

Write an 8-bit value to the specified register.


def write16(self, register, value, little_endian=True):

value = value & <NUM_LIT><EOL>value_low = value & <NUM_LIT><EOL>value_high = (value >> <NUM_LIT:8>) & <NUM_LIT><EOL>if not little_endian:<EOL><INDENT>value_low, value_high = value_high, value_low<EOL><DEDENT>self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(False), register, value_low,<EOL>value_high])<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>self._verify_acks(response)<EOL>

Write a 16-bit value to the specified register.


self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(False), register] + data)<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>self._verify_acks(response)<EOL>


if length <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(True), register])<EOL>self._i2c_stop()<EOL>self._i2c_idle()<EOL>self._i2c_start()<EOL>self._i2c_read_bytes(length)<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>self._verify_acks(response[:-length])<EOL>return response[-length:]<EOL>

Read a length number of bytes from the specified register.  Results
        will be returned as a bytearray.


Read an 8-bit value on the bus (without register).


Read an unsigned byte from the specified register.


result = self.readU8(register)<EOL>if result > <NUM_LIT>:<EOL><INDENT>result -= <NUM_LIT><EOL><DEDENT>return result<EOL>

Read a signed byte from the specified register.


def readU16(self, register, little_endian=True):

self._idle()<EOL>self._transaction_start()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(False), register])<EOL>self._i2c_stop()<EOL>self._i2c_idle()<EOL>self._i2c_start()<EOL>self._i2c_write_bytes([self._address_byte(True)])<EOL>self._i2c_read_bytes(<NUM_LIT:2>)<EOL>self._i2c_stop()<EOL>response = self._transaction_end()<EOL>self._verify_acks(response[:-<NUM_LIT:2>])<EOL>if little_endian:<EOL><INDENT>return (response[-<NUM_LIT:1>] << <NUM_LIT:8>) | response[-<NUM_LIT:2>]<EOL><DEDENT>else:<EOL><INDENT>return (response[-<NUM_LIT:2>] << <NUM_LIT:8>) | response[-<NUM_LIT:1>]<EOL><DEDENT>

Read an unsigned 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first).


def readS16(self, register, little_endian=True):

result = self.readU16(register, little_endian)<EOL>if result > <NUM_LIT>:<EOL><INDENT>result -= <NUM_LIT><EOL><DEDENT>return result<EOL>

Read a signed 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first).


return self.readU16(register, little_endian=True)<EOL>

Read an unsigned 16-bit value from the specified register, in little
        endian byte order.


return self.readU16(register, little_endian=False)<EOL>

Read an unsigned 16-bit value from the specified register, in big
        endian byte order.


return self.readS16(register, little_endian=True)<EOL>

Read a signed 16-bit value from the specified register, in little
        endian byte order.


return self.readS16(register, little_endian=False)<EOL>

Read a signed 16-bit value from the specified register, in big
        endian byte order.


def __init__(self, port, device, max_speed_hz=<NUM_LIT>):

import spidev<EOL>self._device = spidev.SpiDev()<EOL>self._device.open(port, device)<EOL>self._device.max_speed_hz=max_speed_hz<EOL>self._device.mode = <NUM_LIT:0><EOL>self._device.cshigh = False<EOL>

Initialize an SPI device using the SPIdev interface.  Port and device
        identify the device, for example the device /dev/spidev1.0 would be port
        1 and device 0.


Set the speed of the SPI clock in hertz.  Note that not all speeds
        are supported and a lower speed might be chosen by the hardware.


if mode < <NUM_LIT:0> or mode > <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._device.mode = mode<EOL>

Set SPI mode which controls clock polarity and phase.  Should be a
        numeric value 0, 1, 2, or 3.  See wikipedia page for details on meaning:
        http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus


if order == MSBFIRST:<EOL><INDENT>self._device.lsbfirst = False<EOL><DEDENT>elif order == LSBFIRST:<EOL><INDENT>self._device.lsbfirst = True<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

Set order of bits to be read/written over serial lines.  Should be
        either MSBFIRST for most-significant first, or LSBFIRST for
        least-signifcant first.


Close communication with the SPI device.


Half-duplex SPI write.  The specified array of bytes will be clocked
        out the MOSI line.


return bytearray(self._device.readbytes(length))<EOL>

Half-duplex SPI read.  The specified length of bytes will be clocked
        in the MISO line and returned as a bytearray object.


return bytearray(self._device.xfer2(data))<EOL>

Full-duplex SPI read and write.  The specified array of bytes will be
        clocked out the MOSI line, while simultaneously bytes will be read from
        the MISO line.  Read bytes will be returned as a bytearray object.


if mode < <NUM_LIT:0> or mode > <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._device.mode(mode)<EOL>


if order == MSBFIRST:<EOL><INDENT>self._device.lsbmode(False)<EOL><DEDENT>elif order == LSBFIRST:<EOL><INDENT>self._device.lsbmode(True)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>


self._device.write(bytearray(data))<EOL>


def __init__(self, gpio, sclk, mosi=None, miso=None, ss=None):

self._gpio = gpio<EOL>self._sclk = sclk<EOL>self._mosi = mosi<EOL>self._miso = miso<EOL>self._ss = ss<EOL>gpio.setup(sclk, GPIO.OUT)<EOL>if mosi is not None:<EOL><INDENT>gpio.setup(mosi, GPIO.OUT)<EOL><DEDENT>if miso is not None:<EOL><INDENT>gpio.setup(miso, GPIO.IN)<EOL><DEDENT>if ss is not None:<EOL><INDENT>gpio.setup(ss, GPIO.OUT)<EOL>gpio.set_high(ss)<EOL><DEDENT>self.set_mode(<NUM_LIT:0>)<EOL>self.set_bit_order(MSBFIRST)<EOL>

Initialize bit bang (or software) based SPI.  Must provide a BaseGPIO
        class, the SPI clock, and optionally MOSI, MISO, and SS (slave select)
        pin numbers. If MOSI is set to None then writes will be disabled and fail
        with an error, likewise for MISO reads will be disabled.  If SS is set to
        None then SS will not be asserted high/low by the library when
        transfering data.


pass<EOL>

Set the speed of the SPI clock.  This is unsupported with the bit
        bang SPI class and will be ignored.


if mode < <NUM_LIT:0> or mode > <NUM_LIT:3>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if mode & <NUM_LIT>:<EOL><INDENT>self._clock_base = GPIO.HIGH<EOL><DEDENT>else:<EOL><INDENT>self._clock_base = GPIO.LOW<EOL><DEDENT>if mode & <NUM_LIT>:<EOL><INDENT>self._read_leading = False<EOL><DEDENT>else:<EOL><INDENT>self._read_leading = True<EOL><DEDENT>self._gpio.output(self._sclk, self._clock_base)<EOL>


<EOL>if order == MSBFIRST:<EOL><INDENT>self._mask = <NUM_LIT><EOL>self._write_shift = operator.lshift<EOL>self._read_shift = operator.rshift<EOL><DEDENT>elif order == LSBFIRST:<EOL><INDENT>self._mask = <NUM_LIT><EOL>self._write_shift = operator.rshift<EOL>self._read_shift = operator.lshift<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>


pass<EOL>

Close the SPI connection.  Unused in the bit bang implementation.


def write(self, data, assert_ss=True, deassert_ss=True):

<EOL>if self._mosi is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if assert_ss and self._ss is not None:<EOL><INDENT>self._gpio.set_low(self._ss)<EOL><DEDENT>for byte in data:<EOL><INDENT>for i in range(<NUM_LIT:8>):<EOL><INDENT>if self._write_shift(byte, i) & self._mask:<EOL><INDENT>self._gpio.set_high(self._mosi)<EOL><DEDENT>else:<EOL><INDENT>self._gpio.set_low(self._mosi)<EOL><DEDENT>self._gpio.output(self._sclk, not self._clock_base)<EOL>self._gpio.output(self._sclk, self._clock_base)<EOL><DEDENT><DEDENT>if deassert_ss and self._ss is not None:<EOL><INDENT>self._gpio.set_high(self._ss)<EOL><DEDENT>

Half-duplex SPI write.  If assert_ss is True, the SS line will be
        asserted low, the specified bytes will be clocked out the MOSI line, and
        if deassert_ss is True the SS line be put back high.


def read(self, length, assert_ss=True, deassert_ss=True):

if self._miso is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if assert_ss and self._ss is not None:<EOL><INDENT>self._gpio.set_low(self._ss)<EOL><DEDENT>result = bytearray(length)<EOL>for i in range(length):<EOL><INDENT>for j in range(<NUM_LIT:8>):<EOL><INDENT>self._gpio.output(self._sclk, not self._clock_base)<EOL>if self._read_leading:<EOL><INDENT>if self._gpio.is_high(self._miso):<EOL><INDENT>result[i] |= self._read_shift(self._mask, j)<EOL><DEDENT>else:<EOL><INDENT>result[i] &= ~self._read_shift(self._mask, j)<EOL><DEDENT><DEDENT>self._gpio.output(self._sclk, self._clock_base)<EOL>if not self._read_leading:<EOL><INDENT>if self._gpio.is_high(self._miso):<EOL><INDENT>result[i] |= self._read_shift(self._mask, j)<EOL><DEDENT>else:<EOL><INDENT>result[i] &= ~self._read_shift(self._mask, j)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if deassert_ss and self._ss is not None:<EOL><INDENT>self._gpio.set_high(self._ss)<EOL><DEDENT>return result<EOL>

Half-duplex SPI read.  If assert_ss is true, the SS line will be
        asserted low, the specified length of bytes will be clocked in the MISO
        line, and if deassert_ss is true the SS line will be put back high.
        Bytes which are read will be returned as a bytearray object.


def transfer(self, data, assert_ss=True, deassert_ss=True):

if self._mosi is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self._miso is None:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if assert_ss and self._ss is not None:<EOL><INDENT>self._gpio.set_low(self._ss)<EOL><DEDENT>result = bytearray(len(data))<EOL>for i in range(len(data)):<EOL><INDENT>for j in range(<NUM_LIT:8>):<EOL><INDENT>if self._write_shift(data[i], j) & self._mask:<EOL><INDENT>self._gpio.set_high(self._mosi)<EOL><DEDENT>else:<EOL><INDENT>self._gpio.set_low(self._mosi)<EOL><DEDENT>self._gpio.output(self._sclk, not self._clock_base)<EOL>if self._read_leading:<EOL><INDENT>if self._gpio.is_high(self._miso):<EOL><INDENT>result[i] |= self._read_shift(self._mask, j)<EOL><DEDENT>else:<EOL><INDENT>result[i] &= ~self._read_shift(self._mask, j)<EOL><DEDENT><DEDENT>self._gpio.output(self._sclk, self._clock_base)<EOL>if not self._read_leading:<EOL><INDENT>if self._gpio.is_high(self._miso):<EOL><INDENT>result[i] |= self._read_shift(self._mask, j)<EOL><DEDENT>else:<EOL><INDENT>result[i] &= ~self._read_shift(self._mask, j)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if deassert_ss and self._ss is not None:<EOL><INDENT>self._gpio.set_high(self._ss)<EOL><DEDENT>return result<EOL>

Full-duplex SPI read and write.  If assert_ss is true, the SS line
        will be asserted low, the specified bytes will be clocked out the MOSI
        line while bytes will also be read from the MISO line, and if
        deassert_ss is true the SS line will be put back high.  Bytes which are
        read will be returned as a bytearray object.


<EOL>raise RuntimeError('<STR_LIT>')<EOL>


plat = Platform.platform_detect()<EOL>if plat == Platform.RASPBERRY_PI:<EOL><INDENT>if Platform.pi_revision() == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT><DEDENT>elif plat == Platform.BEAGLEBONE_BLACK:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>

Return the default bus number based on the device platform.  For a
    Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned.
    For a Beaglebone Black the first user accessible bus, 1, will be returned.


def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs):

if busnum is None:<EOL><INDENT>busnum = get_default_bus()<EOL><DEDENT>return Device(address, busnum, i2c_interface, **kwargs)<EOL>

Return an I2C device for the specified address and on the specified bus.
    If busnum isn't specified, the default I2C bus for the platform will attempt
    to be detected.


plat = Platform.platform_detect()<EOL>if plat == Platform.RASPBERRY_PI and os.path.exists('<STR_LIT>'):<EOL><INDENT>subprocess.check_call('<STR_LIT>', shell=True)<EOL>subprocess.check_call('<STR_LIT>', shell=True)<EOL><DEDENT>

Enable repeated start conditions for I2C register reads.  This is the
    normal behavior for I2C, however on some platforms like the Raspberry Pi
    there are bugs which disable repeated starts unless explicitly enabled with
    this function.  See this thread for more details:
      http://www.raspberrypi.org/forums/viewtopic.php?f=44&t=15840


def __init__(self, address, busnum, i2c_interface=None):

self._address = address<EOL>if i2c_interface is None:<EOL><INDENT>import Adafruit_PureIO.smbus<EOL>self._bus = Adafruit_PureIO.smbus.SMBus(busnum)<EOL><DEDENT>else:<EOL><INDENT>self._bus = i2c_interface(busnum)<EOL><DEDENT>self._logger = logging.getLogger('<STR_LIT>'.format(busnum, address))<EOL>

Create an instance of the I2C device at the specified address on the
        specified I2C bus number.


value = value & <NUM_LIT><EOL>self._bus.write_byte(self._address, value)<EOL>self._logger.debug("<STR_LIT>",<EOL>value)<EOL>

Write an 8-bit value on the bus (without register).


value = value & <NUM_LIT><EOL>self._bus.write_byte_data(self._address, register, value)<EOL>self._logger.debug("<STR_LIT>",<EOL>value, register)<EOL>

Write an 8-bit value to the specified register.


value = value & <NUM_LIT><EOL>self._bus.write_word_data(self._address, register, value)<EOL>self._logger.debug("<STR_LIT>",<EOL>value, register, register+<NUM_LIT:1>)<EOL>

Write a 16-bit value to the specified register.


self._bus.write_i2c_block_data(self._address, register, data)<EOL>self._logger.debug("<STR_LIT>",<EOL>register, data)<EOL>


results = self._bus.read_i2c_block_data(self._address, register, length)<EOL>self._logger.debug("<STR_LIT>",<EOL>register, results)<EOL>return results<EOL>

Read a length number of bytes from the specified register.  Results
        will be returned as a bytearray.


result = self._bus.read_byte(self._address) & <NUM_LIT><EOL>self._logger.debug("<STR_LIT>",<EOL>result)<EOL>return result<EOL>

Read an 8-bit value on the bus (without register).


result = self._bus.read_byte_data(self._address, register) & <NUM_LIT><EOL>self._logger.debug("<STR_LIT>",<EOL>result, register)<EOL>return result<EOL>

Read an unsigned byte from the specified register.


result = self.readU8(register)<EOL>if result > <NUM_LIT>:<EOL><INDENT>result -= <NUM_LIT><EOL><DEDENT>return result<EOL>

Read a signed byte from the specified register.


result = self._bus.read_word_data(self._address,register) & <NUM_LIT><EOL>self._logger.debug("<STR_LIT>",<EOL>result, register, register+<NUM_LIT:1>)<EOL>if not little_endian:<EOL><INDENT>result = ((result << <NUM_LIT:8>) & <NUM_LIT>) + (result >> <NUM_LIT:8>)<EOL><DEDENT>return result<EOL>

Read an unsigned 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first).


result = self.readU16(register, little_endian)<EOL>if result > <NUM_LIT>:<EOL><INDENT>result -= <NUM_LIT><EOL><DEDENT>return result<EOL>

Read a signed 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first).


return self.readU16(register, little_endian=True)<EOL>

Read an unsigned 16-bit value from the specified register, in little
        endian byte order.


return self.readU16(register, little_endian=False)<EOL>

Read an unsigned 16-bit value from the specified register, in big
        endian byte order.


return self.readS16(register, little_endian=True)<EOL>

Read a signed 16-bit value from the specified register, in little
        endian byte order.


return self.readS16(register, little_endian=False)<EOL>

Read a signed 16-bit value from the specified register, in big
        endian byte order.


regex = r"<STR_LIT>"<EOL>messages = re.findall(regex, text, re.DOTALL)<EOL>parsed = []<EOL>for commit, author, message in messages:<EOL><INDENT>parsed.append((<EOL>commit[:<NUM_LIT:10>],<EOL>re.sub(r"<STR_LIT>", "<STR_LIT>", author), <EOL>message.strip()<EOL>))<EOL><DEDENT>return parsed<EOL>

Will parse git log messages in the 'short' format


pass<EOL>

Is this VCS class available for the given project directory


pass<EOL>

Get a list of changes since (and not including) the given version name

        Output should be in the format:
        [
            (commit, author, message),
            ...
        ]


pass<EOL>


pass<EOL>

Get the download url for the given version.

Return None if unsupported


def version_bump(self, version, type="<STR_LIT>"):

parsed_version = LooseVersion(version).version<EOL>total_components = max(<NUM_LIT:3>, len(parsed_version))<EOL>bits = []<EOL>for bit in parsed_version:<EOL><INDENT>try:<EOL><INDENT>bit = int(bit)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>bits.append(bit)<EOL><DEDENT>indexes = {<EOL>"<STR_LIT>": <NUM_LIT:0>,<EOL>"<STR_LIT>": <NUM_LIT:1>,<EOL>"<STR_LIT>": <NUM_LIT:2>,<EOL>}<EOL>bits += [<NUM_LIT:0>] * (<NUM_LIT:3> - len(bits)) <EOL>bits[indexes[type]] += <NUM_LIT:1><EOL>for i in range(indexes[type] + <NUM_LIT:1>, <NUM_LIT:3>):<EOL><INDENT>bits[i] = <NUM_LIT:0><EOL><DEDENT>return "<STR_LIT:.>".join(map(str, bits))<EOL>

Increment version number string 'version'.

Type can be one of: major, minor, or bug


def determine_paths(self, package_name=None, create_package_dir=False, dry_run=False):

<EOL>self.project_dir = Path(os.getenv('<STR_LIT>') or os.getcwd())<EOL>distribution = self.get_distribution()<EOL>if distribution:<EOL><INDENT>self.project_name = distribution.get_name()<EOL><DEDENT>else:<EOL><INDENT>self.project_name = self.project_dir.name<EOL><DEDENT>if os.path.isdir(self.project_dir / "<STR_LIT:src>"):<EOL><INDENT>package_search_dir = self.project_dir / "<STR_LIT:src>"<EOL><DEDENT>else:<EOL><INDENT>package_search_dir = self.project_dir<EOL><DEDENT>created_package_dir = False<EOL>if not package_name:<EOL><INDENT>package_name = self.project_name.replace("<STR_LIT:->", "<STR_LIT:_>")<EOL>def get_matches(name):<EOL><INDENT>possibles = [n for n in os.listdir(package_search_dir) if os.path.isdir(package_search_dir / n)]<EOL>return difflib.get_close_matches(name, possibles, n=<NUM_LIT:1>, cutoff=<NUM_LIT>)<EOL><DEDENT>close = get_matches(package_name)<EOL>if not close and "<STR_LIT:_>" in package_name:<EOL><INDENT>short_package_name = "<STR_LIT:_>".join(package_name.split("<STR_LIT:_>")[<NUM_LIT:1>:])<EOL>close = get_matches(short_package_name)<EOL><DEDENT>if not close:<EOL><INDENT>if create_package_dir:<EOL><INDENT>package_dir = package_search_dir / package_name<EOL>created_package_dir = True<EOL>if not dry_run:<EOL><INDENT>print("<STR_LIT>" % package_dir)<EOL>os.mkdir(package_dir)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % package_dir)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise CommandError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>package_name = close[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>self.package_name = package_name<EOL>self.package_dir = package_search_dir / package_name<EOL>if not os.path.exists(self.package_dir) and not created_package_dir:<EOL><INDENT>raise CommandError("<STR_LIT>" % self.package_dir)<EOL><DEDENT>

Determine paths automatically and a little intelligently


raise NotImplementedError<EOL>

Returns distance and gradient of distance w.r.t. to self.other


rng.seed(seed)<EOL>nprng.seed(seed)<EOL>

Sets the seeds of both random number generators used by Foolbox.

    Parameters
    ----------
    seed : int
        The seed for both random number generators.


import tensorflow as tf<EOL>bounds = (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>channel_axis = <NUM_LIT:3><EOL>channels = <NUM_LIT:10>  <EOL>def mean_brightness_net(images):<EOL><INDENT>logits = tf.reduce_mean(images, axis=(<NUM_LIT:1>, <NUM_LIT:2>))<EOL>return logits<EOL><DEDENT>images = tf.placeholder(tf.float32, (None, <NUM_LIT:5>, <NUM_LIT:5>, channels))<EOL>logits = mean_brightness_net(images)<EOL>with tf.Session():<EOL><INDENT>model = TensorFlowModel(<EOL>images,<EOL>logits,<EOL>bounds=bounds,<EOL>channel_axis=channel_axis)<EOL>yield model<EOL><DEDENT>

Creates a simple brightness model that does not require training.


cm_model = contextmanager(bn_model)<EOL>with cm_model() as model:<EOL><INDENT>model = ModelWithoutGradients(model)<EOL>yield model<EOL><DEDENT>


GradientEstimator = request.param<EOL>def eg_bn_model():<EOL><INDENT>cm_model = contextmanager(bn_model)<EOL>with cm_model() as model:<EOL><INDENT>gradient_estimator = GradientEstimator(epsilon=<NUM_LIT>)<EOL>model = ModelWithEstimatedGradients(model, gradient_estimator)<EOL>yield model<EOL><DEDENT><DEDENT>return eg_bn_model<EOL>

Same as bn_model but with estimated gradient.


import tensorflow as tf<EOL>bounds = (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>channel_axis = <NUM_LIT:3><EOL>channels = <NUM_LIT:10>  <EOL>def mean_brightness_net(images):<EOL><INDENT>logits = tf.reduce_mean(images, axis=(<NUM_LIT:1>, <NUM_LIT:2>))<EOL>return logits<EOL><DEDENT>images = tf.placeholder(tf.float32, (None, <NUM_LIT:5>, <NUM_LIT:5>, channels))<EOL>logits = mean_brightness_net(images)<EOL>def preprocessing(x):<EOL><INDENT>x = binarize(x, (<NUM_LIT:0>, <NUM_LIT:1>))<EOL>def backward(x):<EOL><INDENT>return x<EOL><DEDENT>return x, backward<EOL><DEDENT>with tf.Session():<EOL><INDENT>model = TensorFlowModel(<EOL>images,<EOL>logits,<EOL>bounds=bounds,<EOL>channel_axis=channel_axis,<EOL>preprocessing=preprocessing)<EOL>yield model<EOL><DEDENT>


import tensorflow as tf<EOL>bounds = (<NUM_LIT:0>, <NUM_LIT:1>)<EOL>channel_axis = <NUM_LIT:3><EOL>channels = <NUM_LIT:10>  <EOL>def mean_brightness_net(images):<EOL><INDENT>logits = tf.reduce_mean(images, axis=(<NUM_LIT:1>, <NUM_LIT:2>))<EOL>return logits<EOL><DEDENT>images = tf.placeholder(tf.float32, (None, <NUM_LIT:5>, <NUM_LIT:5>, channels))<EOL>logits = mean_brightness_net(images)<EOL>def preprocessing(x):<EOL><INDENT>x = binarize(x, (<NUM_LIT:0>, <NUM_LIT:1>), included_in='<STR_LIT>')<EOL>def backward(x):<EOL><INDENT>return x<EOL><DEDENT>return x, backward<EOL><DEDENT>with tf.Session():<EOL><INDENT>model = TensorFlowModel(<EOL>images,<EOL>logits,<EOL>bounds=bounds,<EOL>channel_axis=channel_axis,<EOL>preprocessing=preprocessing)<EOL>yield model<EOL><DEDENT>


return self.__class__.__name__<EOL>

Returns a human readable name that uniquely identifies
        the criterion with its hyperparameters.

        Returns
        -------
        str
            Human readable name that uniquely identifies the criterion
            with its hyperparameters.

        Notes
        -----
        Defaults to the class name but subclasses can provide more
        descriptive names and must take hyperparameters into account.


@abstractmethod<EOL><INDENT>def is_adversarial(self, predictions, label):<DEDENT>

raise NotImplementedError<EOL>

Decides if predictions for an image are adversarial given
        a reference label.

        Parameters
        ----------
        predictions : :class:`numpy.ndarray`
            A vector with the pre-softmax predictions for some image.
        label : int
            The label of the unperturbed reference image.

        Returns
        -------
        bool
            True if an image with the given predictions is an adversarial
            example when the ground-truth class is given by label, False
            otherwise.


names = (criterion.name() for criterion in self._criteria)<EOL>return '<STR_LIT>'.join(sorted(names))<EOL>

Concatenates the names of the given criteria in alphabetical order.

        If a sub-criterion is itself a combined criterion, its name is
        first split into the individual names and the names of the
        sub-sub criteria is used instead of the name of the sub-criterion.
        This is done recursively to ensure that the order and the hierarchy
        of the criteria does not influence the name.

        Returns
        -------
        str
            The alphabetically sorted names of the sub-criteria concatenated
            using double underscores between them.


def _process_gradient(self, backward, dmdp):

if backward is None:  <EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>dmdx = backward(dmdp)<EOL>assert dmdx.dtype == dmdp.dtype<EOL>return dmdx<EOL>

backward: `callable`
    callable that backpropagates the gradient of the model w.r.t to
    preprocessed input through the preprocessing to get the gradient
    of the model's output w.r.t. the input before preprocessing
dmdp: gradient of model w.r.t. preprocessed input


raise NotImplementedError<EOL>

Calculates predictions for a batch of images.

        Parameters
        ----------
        images : `numpy.ndarray`
            Batch of inputs with shape as expected by the model.

        Returns
        -------
        `numpy.ndarray`
            Predictions (logits, i.e. before the softmax) with shape
            (batch size, number of classes).

        See Also
        --------
        :meth:`predictions`


return np.squeeze(self.batch_predictions(image[np.newaxis]), axis=<NUM_LIT:0>)<EOL>

Convenience method that calculates predictions for a single image.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).

        Returns
        -------
        `numpy.ndarray`
            Vector of predictions (logits, i.e. before the softmax) with
            shape (number of classes,).

        See Also
        --------
        :meth:`batch_predictions`


raise NotImplementedError<EOL>

Determines the number of classes.

        Returns
        -------
        int
            The number of classes for which the model creates predictions.


@abstractmethod<EOL><INDENT>def predictions_and_gradient(self, image, label):<DEDENT>

raise NotImplementedError<EOL>

Calculates predictions for an image and the gradient of
        the cross-entropy loss w.r.t. the image.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).
        label : int
            Reference label used to calculate the gradient.

        Returns
        -------
        predictions : `numpy.ndarray`
            Vector of predictions (logits, i.e. before the softmax) with
            shape (number of classes,).
        gradient : `numpy.ndarray`
            The gradient of the cross-entropy loss w.r.t. the image. Will
            have the same shape as the image.

        See Also
        --------
        :meth:`gradient`


_, gradient = self.predictions_and_gradient(image, label)<EOL>return gradient<EOL>

Calculates the gradient of the cross-entropy loss w.r.t. the image.

        The default implementation calls predictions_and_gradient.
        Subclasses can provide more efficient implementations that
        only calculate the gradient.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).
        label : int
            Reference label used to calculate the gradient.

        Returns
        -------
        gradient : `numpy.ndarray`
            The gradient of the cross-entropy loss w.r.t. the image. Will
            have the same shape as the image.

        See Also
        --------
        :meth:`gradient`


@abstractmethod<EOL><INDENT>def backward(self, gradient, image):<DEDENT>

raise NotImplementedError<EOL>

Backpropagates the gradient of some loss w.r.t. the logits
        through the network and returns the gradient of that loss w.r.t
        to the input image.

        Parameters
        ----------
        gradient : `numpy.ndarray`
            Gradient of some loss w.r.t. the logits.
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).

        Returns
        -------
        gradient : `numpy.ndarray`
            The gradient w.r.t the image.

        See Also
        --------
        :meth:`gradient`


@classmethod<EOL><INDENT>def from_keras(cls, model, bounds, input_shape=None,<EOL>channel_axis=<NUM_LIT:3>, preprocessing=(<NUM_LIT:0>, <NUM_LIT:1>)):<DEDENT>

import tensorflow as tf<EOL>if input_shape is None:<EOL><INDENT>try:<EOL><INDENT>input_shape = model.input_shape[<NUM_LIT:1>:]<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>with tf.keras.backend.get_session().as_default():<EOL><INDENT>inputs = tf.placeholder(tf.float32, (None,) + input_shape)<EOL>logits = model(inputs)<EOL>return cls(inputs, logits, bounds=bounds,<EOL>channel_axis=channel_axis, preprocessing=preprocessing)<EOL><DEDENT>

Alternative constructor for a TensorFlowModel that
        accepts a `tf.keras.Model` instance.

        Parameters
        ----------
        model : `tensorflow.keras.Model`
            A `tensorflow.keras.Model` that accepts a single input tensor
            and returns a single output tensor representing logits.
        bounds : tuple
            Tuple of lower and upper bound for the pixel values, usually
            (0, 1) or (0, 255).
        input_shape : tuple
            The shape of a single input, e.g. (28, 28, 1) for MNIST.
            If None, tries to get the the shape from the model's
            input_shape attribute.
        channel_axis : int
            The index of the axis that represents color channels.
        preprocessing: 2-element tuple with floats or numpy arrays
            Elementwises preprocessing of input; we first subtract the first
            element of preprocessing from the input and then divide the input
            by the second element.


assert logits.ndim == <NUM_LIT:1><EOL>logits = logits - np.max(logits)<EOL>e = np.exp(logits)<EOL>return e / np.sum(e)<EOL>

Transforms predictions into probability values.

    Parameters
    ----------
    logits : array_like
        The logits predicted by the model.

    Returns
    -------
    `numpy.ndarray`
        Probability values corresponding to the logits.


assert logits.ndim == <NUM_LIT:1><EOL>logits = logits - np.max(logits)<EOL>e = np.exp(logits)<EOL>s = np.sum(e)<EOL>ce = np.log(s) - logits[label]<EOL>return ce<EOL>

Calculates the cross-entropy.

    Parameters
    ----------
    logits : array_like
        The logits predicted by the model.
    label : int
        The label describing the target distribution.

    Returns
    -------
    float
        The cross-entropy between softmax(logits) and onehot(label).


assert logits.ndim == <NUM_LIT:2><EOL>logits = logits - np.max(logits, axis=<NUM_LIT:1>, keepdims=True)<EOL>e = np.exp(logits)<EOL>s = np.sum(e, axis=<NUM_LIT:1>)<EOL>ces = np.log(s) - logits[:, label]<EOL>return ces<EOL>

Calculates the cross-entropy for a batch of logits.

    Parameters
    ----------
    logits : array_like
        The logits predicted by the model for a batch of inputs.
    label : int
        The label describing the target distribution.

    Returns
    -------
    np.ndarray
        The cross-entropy between softmax(logits[i]) and onehot(label)
        for all i.


def binarize(x, values, threshold=None, included_in='<STR_LIT>'):

lower, upper = values<EOL>if threshold is None:<EOL><INDENT>threshold = (lower + upper) / <NUM_LIT><EOL><DEDENT>x = x.copy()<EOL>if included_in == '<STR_LIT>':<EOL><INDENT>x[x <= threshold] = lower<EOL>x[x > threshold] = upper<EOL><DEDENT>elif included_in == '<STR_LIT>':<EOL><INDENT>x[x < threshold] = lower<EOL>x[x >= threshold] = upper<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return x<EOL>

Binarizes the values of x.

    Parameters
    ----------
    values : tuple of two floats
        The lower and upper value to which the inputs are mapped.
    threshold : float
        The threshold; defaults to (values[0] + values[1]) / 2 if None.
    included_in : str
        Whether the threshold value itself belongs to the lower or
        upper interval.


def imagenet_example(shape=(<NUM_LIT>, <NUM_LIT>), data_format='<STR_LIT>'):

assert len(shape) == <NUM_LIT:2><EOL>assert data_format in ['<STR_LIT>', '<STR_LIT>']<EOL>from PIL import Image<EOL>path = os.path.join(os.path.dirname(__file__), '<STR_LIT>')<EOL>image = Image.open(path)<EOL>image = image.resize(shape)<EOL>image = np.asarray(image, dtype=np.float32)<EOL>image = image[:, :, :<NUM_LIT:3>]<EOL>assert image.shape == shape + (<NUM_LIT:3>,)<EOL>if data_format == '<STR_LIT>':<EOL><INDENT>image = np.transpose(image, (<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>return image, <NUM_LIT><EOL>

Returns an example image and its imagenet class label.

    Parameters
    ----------
    shape : list of integers
        The shape of the returned image.
    data_format : str
        "channels_first" or "channels_last"

    Returns
    -------
    image : array_like
        The example image.

    label : int
        The imagenet label associated with the image.

    NOTE: This function is deprecated and will be removed in the future.


def samples(dataset='<STR_LIT>', index=<NUM_LIT:0>, batchsize=<NUM_LIT:1>, shape=(<NUM_LIT>, <NUM_LIT>),<EOL>data_format='<STR_LIT>'):

from PIL import Image<EOL>images, labels = [], []<EOL>basepath = os.path.dirname(__file__)<EOL>samplepath = os.path.join(basepath, '<STR_LIT:data>')<EOL>files = os.listdir(samplepath)<EOL>for idx in range(index, index + batchsize):<EOL><INDENT>i = idx % <NUM_LIT:20><EOL>file = [n for n in files if '<STR_LIT>'.format(dataset, i) in n][<NUM_LIT:0>]<EOL>label = int(file.split('<STR_LIT:.>')[<NUM_LIT:0>].split('<STR_LIT:_>')[-<NUM_LIT:1>])<EOL>path = os.path.join(samplepath, file)<EOL>image = Image.open(path)<EOL>if dataset == '<STR_LIT>':<EOL><INDENT>image = image.resize(shape)<EOL><DEDENT>image = np.asarray(image, dtype=np.float32)<EOL>if dataset != '<STR_LIT>' and data_format == '<STR_LIT>':<EOL><INDENT>image = np.transpose(image, (<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>images.append(image)<EOL>labels.append(label)<EOL><DEDENT>labels = np.array(labels)<EOL>images = np.stack(images)<EOL>return images, labels<EOL>

Returns a batch of example images and the corresponding labels

    Parameters
    ----------
    dataset : string
        The data set to load (options: imagenet, mnist, cifar10,
        cifar100, fashionMNIST)
    index : int
        For each data set 20 example images exist. The returned batch
        contains the images with index [index, index + 1, index + 2, ...]
    batchsize : int
        Size of batch.
    shape : list of integers
        The shape of the returned image (only relevant for Imagenet).
    data_format : str
        "channels_first" or "channels_last"

    Returns
    -------
    images : array_like
        The batch of example images

    labels : array of int
        The labels associated with the images.


def onehot_like(a, index, value=<NUM_LIT:1>):

x = np.zeros_like(a)<EOL>x[index] = value<EOL>return x<EOL>

Creates an array like a, with all values
    set to 0 except one.

    Parameters
    ----------
    a : array_like
        The returned one-hot array will have the same shape
        and dtype as this array
    index : int
        The index that should be set to `value`
    value : single value compatible with a.dtype
        The value to set at the given index

    Returns
    -------
    `numpy.ndarray`
        One-hot array with the given value at the given
        location and zeros everywhere else.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>starting_point=None,<EOL>threshold=None, included_in='<STR_LIT>'):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>self._starting_point = starting_point<EOL>self.initialize_starting_point(a)<EOL>if a.image is None:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>assert a.image.dtype == a.original_image.dtype<EOL>dtype = a.original_image.dtype<EOL>assert np.issubdtype(dtype, np.floating)<EOL>min_, max_ = a.bounds()<EOL>if threshold is None:<EOL><INDENT>threshold = (min_ + max_) / <NUM_LIT><EOL><DEDENT>threshold = dtype.type(threshold)<EOL>offset = dtype.type(<NUM_LIT:1.>)<EOL>if included_in == '<STR_LIT>':<EOL><INDENT>lower = threshold<EOL>upper = np.nextafter(threshold, threshold + offset)<EOL><DEDENT>elif included_in == '<STR_LIT>':<EOL><INDENT>lower = np.nextafter(threshold, threshold - offset)<EOL>upper = threshold<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>logging.info('<STR_LIT>'.format(<EOL>min_, lower, upper, max_))<EOL>assert type(lower) == dtype.type<EOL>assert type(upper) == dtype.type<EOL>assert lower < upper<EOL>o = a.original_image<EOL>x = a.image<EOL>p = np.full_like(o, np.nan)<EOL>indices = np.logical_and(o <= lower, x <= lower)<EOL>p[indices] = o[indices]<EOL>indices = np.logical_and(o <= lower, x >= upper)<EOL>p[indices] = upper<EOL>indices = np.logical_and(o >= upper, x <= lower)<EOL>p[indices] = lower<EOL>indices = np.logical_and(o >= upper, x >= upper)<EOL>p[indices] = o[indices]<EOL>assert not np.any(np.isnan(p))<EOL>logging.info('<STR_LIT>'.format(<EOL>self.__class__.__name__, a.distance))<EOL>_, is_adversarial = a.predictions(p)<EOL>assert is_adversarial, ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>logging.info('<STR_LIT>'.format(<EOL>self.__class__.__name__, a.distance))<EOL>

For models that preprocess their inputs by binarizing the
        inputs, this attack can improve adversarials found by other
        attacks. It does os by utilizing information about the
        binarization and mapping values to the corresponding value in
        the clean input or to the right side of the threshold.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        starting_point : `numpy.ndarray`
            Adversarial input to use as a starting point.
        threshold : float
            The treshold used by the models binarization. If none,
            defaults to (model.bounds()[1] - model.bounds()[0]) / 2.
        included_in : str
            Whether the threshold value itself belongs to the lower or
            upper interval.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True, epsilons=<NUM_LIT:1000>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>image = a.original_image<EOL>bounds = a.bounds()<EOL>min_, max_ = bounds<EOL>if not isinstance(epsilons, Iterable):<EOL><INDENT>epsilons = np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, num=epsilons + <NUM_LIT:1>)[<NUM_LIT:1>:]<EOL><DEDENT>for epsilon in epsilons:<EOL><INDENT>noise = self._sample_noise(epsilon, image, bounds)<EOL>perturbed = image + epsilon * noise<EOL>perturbed = np.clip(perturbed, min_, max_)<EOL>_, is_adversarial = a.predictions(perturbed)<EOL>if is_adversarial:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Adds uniform or Gaussian noise to the image, gradually increasing
        the standard deviation until the image is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of noise levels or number of noise levels
            between 0 and 1 that should be tried.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>epsilons=<NUM_LIT:1000>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>image = a.original_image<EOL>min_, max_ = a.bounds()<EOL>axis = a.channel_axis(batch=False)<EOL>hw = [image.shape[i] for i in range(image.ndim) if i != axis]<EOL>h, w = hw<EOL>size = max(h, w)<EOL>if not isinstance(epsilons, Iterable):<EOL><INDENT>epsilons = np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, num=epsilons + <NUM_LIT:1>)[<NUM_LIT:1>:]<EOL><DEDENT>for epsilon in epsilons:<EOL><INDENT>sigmas = [epsilon * size] * <NUM_LIT:3><EOL>sigmas[axis] = <NUM_LIT:0><EOL>blurred = gaussian_filter(image, sigmas)<EOL>blurred = np.clip(blurred, min_, max_)<EOL>_, is_adversarial = a.predictions(blurred)<EOL>if is_adversarial:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Blurs the image until it is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of standard deviations of the Gaussian blur
            or number of standard deviations between 0 and 1 that should
            be tried.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>starting_point=None, initialization_attack=None):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>self._starting_point = starting_point<EOL>self._initialization_attack = initialization_attack<EOL>self.initialize_starting_point(a)<EOL>if a.image is None:<EOL><INDENT>warnings.warn(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>shape = a.original_image.shape<EOL>N = a.original_image.size<EOL>original = a.original_image.reshape(-<NUM_LIT:1>)<EOL>x = a.image.copy().reshape(-<NUM_LIT:1>)<EOL>assert original.dtype == x.dtype<EOL>while True:<EOL><INDENT>indices = list(range(N))<EOL>rng.shuffle(indices)<EOL>for index in indices:<EOL><INDENT>old_value = x[index]<EOL>new_value = original[index]<EOL>if old_value == new_value:<EOL><INDENT>continue<EOL><DEDENT>x[index] = new_value<EOL>_, is_adversarial = a.predictions(x.reshape(shape))<EOL>if is_adversarial:<EOL><INDENT>logging.info('<STR_LIT>'<EOL>'<STR_LIT>'.format(a.distance))<EOL>break<EOL><DEDENT>x[index] = old_value<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>logging.info('<STR_LIT>')<EOL>while True:<EOL><INDENT>indices = list(range(N))<EOL>rng.shuffle(indices)<EOL>improved = False<EOL>logging.info('<STR_LIT>')<EOL>for index in indices:<EOL><INDENT>old_value = x[index]<EOL>original_value = original[index]<EOL>if old_value == original_value:<EOL><INDENT>continue<EOL><DEDENT>x[index] = original_value<EOL>_, is_adversarial = a.predictions(x.reshape(shape))<EOL>if is_adversarial:  <EOL><INDENT>logging.info('<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>index, a.distance))<EOL>improved = True<EOL><DEDENT>else:<EOL><INDENT>adv_value = old_value<EOL>non_adv_value = original_value<EOL>best_adv_value = self.binary_search(<EOL>a, x, index, adv_value, non_adv_value, shape)<EOL>if old_value != best_adv_value:<EOL><INDENT>x[index] = best_adv_value<EOL>improved = True<EOL>logging.info('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>index, old_value, best_adv_value,<EOL>original_value, a.distance))<EOL><DEDENT><DEDENT><DEDENT>if not improved:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Starts with an adversarial and performs a binary search between
        the adversarial and the original for each dimension of the input
        individually.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        starting_point : `numpy.ndarray`
            Adversarial input to use as a starting point, in particular
            for targeted attacks.
        initialization_attack : :class:`Attack`
            Attack to use to find a starting point. Defaults to
            SaltAndPepperNoiseAttack.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>binary_search_steps=<NUM_LIT:5>, max_iterations=<NUM_LIT:1000>,<EOL>confidence=<NUM_LIT:0>, learning_rate=<NUM_LIT>,<EOL>initial_const=<NUM_LIT>, abort_early=True):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>if not a.has_gradient():<EOL><INDENT>logging.fatal('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>return<EOL><DEDENT>min_, max_ = a.bounds()<EOL>def to_attack_space(x):<EOL><INDENT>a = (min_ + max_) / <NUM_LIT:2><EOL>b = (max_ - min_) / <NUM_LIT:2><EOL>x = (x - a) / b<EOL>x = x * <NUM_LIT><EOL>return np.arctanh(x)<EOL><DEDENT>def to_model_space(x):<EOL><INDENT>"""<STR_LIT>"""<EOL>x = np.tanh(x)<EOL>grad = <NUM_LIT:1> - np.square(x)<EOL>a = (min_ + max_) / <NUM_LIT:2><EOL>b = (max_ - min_) / <NUM_LIT:2><EOL>x = x * b + a<EOL>grad = grad * b<EOL>return x, grad<EOL><DEDENT>att_original = to_attack_space(a.original_image)<EOL>reconstructed_original, _ = to_model_space(att_original)<EOL>const = initial_const<EOL>lower_bound = <NUM_LIT:0><EOL>upper_bound = np.inf<EOL>for binary_search_step in range(binary_search_steps):<EOL><INDENT>if binary_search_step == binary_search_steps - <NUM_LIT:1> andbinary_search_steps >= <NUM_LIT:10>:<EOL><INDENT>const = upper_bound<EOL><DEDENT>logging.info('<STR_LIT>'.format(const))<EOL>att_perturbation = np.zeros_like(att_original)<EOL>optimizer = AdamOptimizer(att_perturbation.shape)<EOL>found_adv = False  <EOL>loss_at_previous_check = np.inf<EOL>for iteration in range(max_iterations):<EOL><INDENT>x, dxdp = to_model_space(att_original + att_perturbation)<EOL>logits, is_adv = a.predictions(x)<EOL>loss, dldx = self.loss_function(<EOL>const, a, x, logits, reconstructed_original,<EOL>confidence, min_, max_)<EOL>logging.info('<STR_LIT>'.format(<EOL>loss, a.distance))<EOL>assert dldx.shape == x.shape<EOL>assert dxdp.shape == x.shape<EOL>gradient = dldx * dxdp<EOL>att_perturbation += optimizer(gradient, learning_rate)<EOL>if is_adv:<EOL><INDENT>found_adv = True<EOL><DEDENT>if abort_early anditeration % (np.ceil(max_iterations / <NUM_LIT:10>)) == <NUM_LIT:0>:<EOL><INDENT>if not (loss <= <NUM_LIT> * loss_at_previous_check):<EOL><INDENT>break  <EOL><DEDENT>loss_at_previous_check = loss<EOL><DEDENT><DEDENT>if found_adv:<EOL><INDENT>logging.info('<STR_LIT>'.format(const))<EOL>upper_bound = const<EOL><DEDENT>else:<EOL><INDENT>logging.info('<STR_LIT>'<EOL>'<STR_LIT>'.format(const))<EOL>lower_bound = const<EOL><DEDENT>if upper_bound == np.inf:<EOL><INDENT>const *= <NUM_LIT:10><EOL><DEDENT>else:<EOL><INDENT>const = (lower_bound + upper_bound) / <NUM_LIT:2><EOL><DEDENT><DEDENT>

The L2 version of the Carlini & Wagner attack.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        binary_search_steps : int
            The number of steps for the binary search used to
            find the optimal tradeoff-constant between distance and confidence.
        max_iterations : int
            The maximum number of iterations. Larger values are more
            accurate; setting it too small will require a large learning rate
            and will produce poor results.
        confidence : int or float
            Confidence of adversarial examples: a higher value produces
            adversarials that are further away, but more strongly classified
            as adversarial.
        learning_rate : float
            The learning rate for the attack algorithm. Smaller values
            produce better results but take longer to converge.
        initial_const : float
            The initial tradeoff-constant to use to tune the relative
            importance of distance and confidence. If `binary_search_steps`
            is large, the initial constant is not important.
        abort_early : bool
            If True, Adam will be aborted if the loss hasn't decreased
            for some time (a tenth of max_iterations).


@classmethod<EOL><INDENT>def loss_function(cls, const, a, x, logits, reconstructed_original,<EOL>confidence, min_, max_):<DEDENT>

targeted = a.target_class() is not None<EOL>if targeted:<EOL><INDENT>c_minimize = cls.best_other_class(logits, a.target_class())<EOL>c_maximize = a.target_class()<EOL><DEDENT>else:<EOL><INDENT>c_minimize = a.original_class<EOL>c_maximize = cls.best_other_class(logits, a.original_class)<EOL><DEDENT>is_adv_loss = logits[c_minimize] - logits[c_maximize]<EOL>is_adv_loss += confidence<EOL>is_adv_loss = max(<NUM_LIT:0>, is_adv_loss)<EOL>s = max_ - min_<EOL>squared_l2_distance = np.sum((x - reconstructed_original)**<NUM_LIT:2>) / s**<NUM_LIT:2><EOL>total_loss = squared_l2_distance + const * is_adv_loss<EOL>logits_diff_grad = np.zeros_like(logits)<EOL>logits_diff_grad[c_minimize] = <NUM_LIT:1><EOL>logits_diff_grad[c_maximize] = -<NUM_LIT:1><EOL>is_adv_loss_grad = a.backward(logits_diff_grad, x)<EOL>assert is_adv_loss >= <NUM_LIT:0><EOL>if is_adv_loss == <NUM_LIT:0>:<EOL><INDENT>is_adv_loss_grad = <NUM_LIT:0><EOL><DEDENT>squared_l2_distance_grad = (<NUM_LIT:2> / s**<NUM_LIT:2>) * (x - reconstructed_original)<EOL>total_loss_grad = squared_l2_distance_grad + const * is_adv_loss_grad<EOL>return total_loss, total_loss_grad<EOL>

Returns the loss and the gradient of the loss w.r.t. x,
        assuming that logits = model(x).


other_logits = logits - onehot_like(logits, exclude, value=np.inf)<EOL>return np.argmax(other_logits)<EOL>

Returns the index of the largest logit, ignoring the class that
        is passed as `exclude`.


def __call__(self, gradient, learning_rate,<EOL>beta1=<NUM_LIT>, beta2=<NUM_LIT>, epsilon=<NUM_LIT>):

self.t += <NUM_LIT:1><EOL>self.m = beta1 * self.m + (<NUM_LIT:1> - beta1) * gradient<EOL>self.v = beta2 * self.v + (<NUM_LIT:1> - beta2) * gradient**<NUM_LIT:2><EOL>bias_correction_1 = <NUM_LIT:1> - beta1**self.t<EOL>bias_correction_2 = <NUM_LIT:1> - beta2**self.t<EOL>m_hat = self.m / bias_correction_1<EOL>v_hat = self.v / bias_correction_2<EOL>return -learning_rate * m_hat / (np.sqrt(v_hat) + epsilon)<EOL>

Updates internal parameters of the optimizer and returns
        the change that should be applied to the variable.

        Parameters
        ----------
        gradient : `np.ndarray`
            the gradient of the loss w.r.t. to the variable
        learning_rate: float
            the learning rate in the current iteration
        beta1: float
            decay rate for calculating the exponentially
            decaying average of past gradients
        beta2: float
            decay rate for calculating the exponentially
            decaying average of past squared gradients
        epsilon: float
            small value to avoid division by zero


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>epsilons=<NUM_LIT:1000>, max_directions=<NUM_LIT:1000>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>image = a.original_image<EOL>min_, max_ = a.bounds()<EOL>if a.image is not None:  <EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>for j in range(max_directions):<EOL><INDENT>random_image = nprng.uniform(<EOL>min_, max_, size=image.shape).astype(image.dtype)<EOL>_, is_adversarial = a.predictions(random_image)<EOL>if is_adversarial:<EOL><INDENT>logging.info('<STR_LIT>'<EOL>'<STR_LIT>'.format(j + <NUM_LIT:1>))<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if not isinstance(epsilons, Iterable):<EOL><INDENT>epsilons = np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, num=epsilons + <NUM_LIT:1>)[<NUM_LIT:1>:]<EOL><DEDENT>for epsilon in epsilons:<EOL><INDENT>perturbed = (<NUM_LIT:1> - epsilon) * image + epsilon * random_image<EOL>if not a.in_bounds(perturbed):  <EOL><INDENT>np.clip(perturbed, min_, max_, out=perturbed)<EOL><DEDENT>_, is_adversarial = a.predictions(perturbed)<EOL>if is_adversarial:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Blends the image with a uniform noise image until it
        is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of blending steps or number of blending steps
            between 0 and 1 that should be tried.
        max_directions : int
            Maximum number of random images to try.


pass<EOL>

Additional initializer that can be overwritten by
        subclasses without redefining the full __init__ method
        including all arguments and documentation.


return self.__class__.__name__<EOL>

Returns a human readable name that uniquely identifies
        the attack with its hyperparameters.

        Returns
        -------
        str
            Human readable name that uniquely identifies the attack
            with its hyperparameters.

        Notes
        -----
        Defaults to the class name but subclasses can provide more
        descriptive names and must take hyperparameters into account.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>max_pixels=<NUM_LIT:1000>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>channel_axis = a.channel_axis(batch=False)<EOL>image = a.original_image<EOL>axes = [i for i in range(image.ndim) if i != channel_axis]<EOL>assert len(axes) == <NUM_LIT:2><EOL>h = image.shape[axes[<NUM_LIT:0>]]<EOL>w = image.shape[axes[<NUM_LIT:1>]]<EOL>min_, max_ = a.bounds()<EOL>pixels = nprng.permutation(h * w)<EOL>pixels = pixels[:max_pixels]<EOL>for i, pixel in enumerate(pixels):<EOL><INDENT>x = pixel % w<EOL>y = pixel // w<EOL>location = [x, y]<EOL>location.insert(channel_axis, slice(None))<EOL>location = tuple(location)<EOL>for value in [min_, max_]:<EOL><INDENT>perturbed = image.copy()<EOL>perturbed[location] = value<EOL>_, is_adv = a.predictions(perturbed)<EOL>if is_adv:<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT>

Perturbs just a single pixel and sets it to the min or max.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, correctly classified image. If image is a
            numpy array, label must be passed as well. If image is
            an :class:`Adversarial` instance, label must not be passed.
        label : int
            The reference label of the original image. Must be passed
            if image is a numpy array, must not be passed if image is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial image, otherwise returns
            the Adversarial object.
        max_pixels : int
            Maximum number of pixels to try.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>r=<NUM_LIT>, p=<NUM_LIT>, d=<NUM_LIT:5>, t=<NUM_LIT:5>, R=<NUM_LIT>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>assert <NUM_LIT:0> <= r <= <NUM_LIT:2><EOL>if a.target_class() is not None:<EOL><INDENT>return<EOL><DEDENT>def normalize(im):<EOL><INDENT>min_, max_ = a.bounds()<EOL>im = im - (min_ + max_) / <NUM_LIT:2><EOL>im = im / (max_ - min_)<EOL>LB = -<NUM_LIT:1> / <NUM_LIT:2><EOL>UB = <NUM_LIT:1> / <NUM_LIT:2><EOL>return im, LB, UB<EOL><DEDENT>def unnormalize(im):<EOL><INDENT>min_, max_ = a.bounds()<EOL>im = im * (max_ - min_)<EOL>im = im + (min_ + max_) / <NUM_LIT:2><EOL>return im<EOL><DEDENT>Im = a.original_image<EOL>Im, LB, UB = normalize(Im)<EOL>cI = a.original_class<EOL>channel_axis = a.channel_axis(batch=False)<EOL>axes = [i for i in range(Im.ndim) if i != channel_axis]<EOL>assert len(axes) == <NUM_LIT:2><EOL>h = Im.shape[axes[<NUM_LIT:0>]]<EOL>w = Im.shape[axes[<NUM_LIT:1>]]<EOL>channels = Im.shape[channel_axis]<EOL>def random_locations():<EOL><INDENT>n = int(<NUM_LIT:0.1> * h * w)<EOL>n = min(n, <NUM_LIT>)<EOL>locations = nprng.permutation(h * w)[:n]<EOL>p_x = locations % w<EOL>p_y = locations // w<EOL>pxy = list(zip(p_x, p_y))<EOL>pxy = np.array(pxy)<EOL>return pxy<EOL><DEDENT>def pert(Ii, p, x, y):<EOL><INDENT>Im = Ii.copy()<EOL>location = [x, y]<EOL>location.insert(channel_axis, slice(None))<EOL>location = tuple(location)<EOL>Im[location] = p * np.sign(Im[location])<EOL>return Im<EOL><DEDENT>def cyclic(r, Ibxy):<EOL><INDENT>result = r * Ibxy<EOL>if result < LB:<EOL><INDENT>result = result + (UB - LB)<EOL><DEDENT>elif result > UB:<EOL><INDENT>result = result - (UB - LB)<EOL><DEDENT>assert LB <= result <= UB<EOL>return result<EOL><DEDENT>Ii = Im<EOL>PxPy = random_locations()<EOL>for _ in range(R):<EOL><INDENT>PxPy = PxPy[nprng.permutation(len(PxPy))[:<NUM_LIT>]]<EOL>L = [pert(Ii, p, x, y) for x, y in PxPy]<EOL>def score(Its):<EOL><INDENT>Its = np.stack(Its)<EOL>Its = unnormalize(Its)<EOL>batch_logits, _ = a.batch_predictions(Its, strict=False)<EOL>scores = [softmax(logits)[cI] for logits in batch_logits]<EOL>return scores<EOL><DEDENT>scores = score(L)<EOL>indices = np.argsort(scores)[:t]<EOL>PxPy_star = PxPy[indices]<EOL>for x, y in PxPy_star:<EOL><INDENT>for b in range(channels):<EOL><INDENT>location = [x, y]<EOL>location.insert(channel_axis, b)<EOL>location = tuple(location)<EOL>Ii[location] = cyclic(r, Ii[location])<EOL><DEDENT><DEDENT>_, is_adv = a.predictions(unnormalize(Ii))<EOL>if is_adv:  <EOL><INDENT>return<EOL><DEDENT>PxPy = [<EOL>(x, y)<EOL>for _a, _b in PxPy_star<EOL>for x in range(_a - d, _a + d + <NUM_LIT:1>)<EOL>for y in range(_b - d, _b + d + <NUM_LIT:1>)]<EOL>PxPy = [(x, y) for x, y in PxPy if <NUM_LIT:0> <= x < w and <NUM_LIT:0> <= y < h]<EOL>PxPy = list(set(PxPy))<EOL>PxPy = np.array(PxPy)<EOL><DEDENT>

A black-box attack based on the idea of greedy local search.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, correctly classified image. If image is a
            numpy array, label must be passed as well. If image is
            an :class:`Adversarial` instance, label must not be passed.
        label : int
            The reference label of the original image. Must be passed
            if image is a numpy array, must not be passed if image is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial image, otherwise returns
            the Adversarial object.
        r : float
            Perturbation parameter that controls the cyclic perturbation;
            must be in [0, 2]
        p : float
            Perturbation parameter that controls the pixel sensitivity
            estimation
        d : int
            The half side length of the neighborhood square
        t : int
            The number of pixels perturbed at each round
        R : int
            An upper bound on the number of iterations


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>steps=<NUM_LIT:100>, subsample=<NUM_LIT:10>, p=None):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>if not a.has_gradient():<EOL><INDENT>return<EOL><DEDENT>if a.target_class() is not None:<EOL><INDENT>logging.fatal('<STR_LIT>')<EOL>return<EOL><DEDENT>if p is None:<EOL><INDENT>if a._distance == MeanSquaredDistance:<EOL><INDENT>p = <NUM_LIT:2><EOL><DEDENT>elif a._distance == Linfinity:<EOL><INDENT>p = np.inf<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if not (<NUM_LIT:1> <= p <= np.inf):<EOL><INDENT>raise ValueError<EOL><DEDENT>if p not in [<NUM_LIT:2>, np.inf]:<EOL><INDENT>raise NotImplementedError<EOL><DEDENT>_label = a.original_class<EOL>logits, _ = a.predictions(a.original_image)<EOL>labels = np.argsort(logits)[::-<NUM_LIT:1>]<EOL>if subsample:<EOL><INDENT>logging.info('<STR_LIT>'.format(subsample))<EOL>assert isinstance(subsample, int)<EOL>labels = labels[:subsample]<EOL><DEDENT>def get_residual_labels(logits):<EOL><INDENT>"""<STR_LIT>"""<EOL>return [<EOL>k for k in labels<EOL>if logits[k] < logits[_label]]<EOL><DEDENT>perturbed = a.original_image<EOL>min_, max_ = a.bounds()<EOL>for step in range(steps):<EOL><INDENT>logits, grad, is_adv = a.predictions_and_gradient(perturbed)<EOL>if is_adv:<EOL><INDENT>return<EOL><DEDENT>loss = -crossentropy(logits=logits, label=_label)<EOL>residual_labels = get_residual_labels(logits)<EOL>losses = [<EOL>-crossentropy(logits=logits, label=k)<EOL>for k in residual_labels]<EOL>grads = [a.gradient(perturbed, label=k) for k in residual_labels]<EOL>diffs = [(l - loss, g - grad) for l, g in zip(losses, grads)]<EOL>if p == <NUM_LIT:2>:<EOL><INDENT>distances = [abs(dl) / (np.linalg.norm(dg) + <NUM_LIT>)<EOL>for dl, dg in diffs]<EOL><DEDENT>elif p == np.inf:<EOL><INDENT>distances = [abs(dl) / (np.sum(np.abs(dg)) + <NUM_LIT>)<EOL>for dl, dg in diffs]<EOL><DEDENT>else:  <EOL><INDENT>assert False<EOL><DEDENT>optimal = np.argmin(distances)<EOL>df, dg = diffs[optimal]<EOL>if p == <NUM_LIT:2>:<EOL><INDENT>perturbation = abs(df) / (np.linalg.norm(dg) + <NUM_LIT>)**<NUM_LIT:2> * (-dg)<EOL><DEDENT>elif p == np.inf:<EOL><INDENT>perturbation = abs(df) / (np.sum(np.abs(dg)) + <NUM_LIT>)* np.sign(-dg)<EOL><DEDENT>else:  <EOL><INDENT>assert False<EOL><DEDENT>perturbed = perturbed + <NUM_LIT> * perturbation<EOL>perturbed = np.clip(perturbed, min_, max_)<EOL><DEDENT>a.predictions(perturbed)<EOL>

Simple and close to optimal gradient-based
        adversarial attack.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        steps : int
            Maximum number of steps to perform.
        subsample : int
            Limit on the number of the most likely classes that should
            be considered. A small value is usually sufficient and much
            faster.
        p : int or float
            Lp-norm that should be minimzed, must be 2 or np.inf.


a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>image = a.original_image<EOL>min_, max_ = a.bounds()<EOL>target = (max_ + min_) / <NUM_LIT:2><EOL>if not isinstance(epsilons, Iterable):<EOL><INDENT>epsilons = np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, num=epsilons + <NUM_LIT:1>)[<NUM_LIT:1>:]<EOL><DEDENT>for epsilon in epsilons:<EOL><INDENT>perturbed = (<NUM_LIT:1> - epsilon) * image + epsilon * target<EOL>_, is_adversarial = a.predictions(perturbed)<EOL>if is_adversarial:<EOL><INDENT>return<EOL><DEDENT><DEDENT>

Reduces the contrast of the image until it is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of contrast levels or number of contrast
            levels between 1 and 0 that should be tried. Epsilons are
            one minus the contrast level.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>epsilons=<NUM_LIT:100>, max_epsilon=<NUM_LIT:1>, steps=<NUM_LIT:10>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>self._run(a, epsilons=epsilons, max_epsilon=max_epsilon, steps=steps)<EOL>

Like GradientAttack but with several steps for each epsilon.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of step sizes in the gradient direction
            or number of step sizes between 0 and max_epsilon that should
            be tried.
        max_epsilon : float
            Largest step size if epsilons is not an iterable.
        steps : int
            Number of iterations to run.


Like GradientSignAttack but with several steps for each epsilon.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of step sizes in the direction of the sign of
            the gradient or number of step sizes between 0 and max_epsilon
            that should be tried.
        max_epsilon : float
            Largest step size if epsilons is not an iterable.
        steps : int
            Number of iterations to run.


a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>original_class = a.original_class<EOL>target_class = a.target_class()<EOL>if target_class is None:<EOL><INDENT>if num_random_targets == <NUM_LIT:0>:<EOL><INDENT>gradient_attack = GradientAttack()<EOL>gradient_attack(a)<EOL>adv_img = a.image<EOL>if adv_img is None:  <EOL><INDENT>num_random_targets = <NUM_LIT:1><EOL>logging.info('<STR_LIT>')  <EOL><DEDENT>else:<EOL><INDENT>logits, _ = a.predictions(adv_img)<EOL>target_class = np.argmax(logits)<EOL>target_classes = [target_class]<EOL>logging.info('<STR_LIT>'.format(target_class))  <EOL><DEDENT><DEDENT>else:  <EOL><INDENT>num_random_targets = <NUM_LIT:1><EOL><DEDENT>if num_random_targets > <NUM_LIT:0>:<EOL><INDENT>num_classes = a.num_classes()<EOL>assert num_random_targets <= num_classes - <NUM_LIT:1><EOL>target_classes = rng.sample(<EOL>range(num_classes), num_random_targets + <NUM_LIT:1>)<EOL>target_classes = [t for t in target_classes if t != original_class]  <EOL>target_classes = target_classes[:num_random_targets]<EOL>str_target_classes = [str(t) for t in target_classes]<EOL>logging.info('<STR_LIT>'.format('<STR_LIT:U+002CU+0020>'.join(str_target_classes)))  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>target_classes = [target_class]<EOL><DEDENT>a._reset()<EOL>for target in target_classes:<EOL><INDENT>image = a.original_image<EOL>mask = np.ones_like(image)<EOL>counts = np.zeros_like(image)<EOL>labels = range(a.num_classes())<EOL>perturbed = image.copy()<EOL>min_, max_ = a.bounds()<EOL>for step in range(max_iter):<EOL><INDENT>_, is_adversarial = a.predictions(perturbed)<EOL>if is_adversarial:<EOL><INDENT>return<EOL><DEDENT>idx, p_sign = self._saliency_map(<EOL>a, perturbed, target, labels, mask, fast=fast)<EOL>perturbed[idx] += -p_sign * theta * (max_ - min_)<EOL>counts[idx] += <NUM_LIT:1><EOL>if perturbed[idx] <= min_ or perturbed[idx] >= max_:<EOL><INDENT>mask[idx] = <NUM_LIT:0><EOL><DEDENT>if counts[idx] >= max_perturbations_per_pixel:<EOL><INDENT>mask[idx] = <NUM_LIT:0><EOL><DEDENT>perturbed = np.clip(perturbed, min_, max_)<EOL><DEDENT><DEDENT>

Implements the Saliency Map Attack.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        max_iter : int
            The maximum number of iterations to run.
        num_random_targets : int
            Number of random target classes if no target class is given
            by the criterion.
        fast : bool
            Whether to use the fast saliency map calculation.
        theta : float
            perturbation per pixel relative to [min, max] range.
        max_perturbations_per_pixel : int
            Maximum number of times a pixel can be modified.


def _saliency_map(self, a, image, target, labels, mask, fast=False):

<EOL>alphas = a.gradient(image, target) * mask<EOL>if fast:<EOL><INDENT>betas = -np.ones_like(alphas)<EOL><DEDENT>else:<EOL><INDENT>betas = np.sum([<EOL>a.gradient(image, label) * mask - alphas<EOL>for label in labels], <NUM_LIT:0>)<EOL><DEDENT>salmap = np.abs(alphas) * np.abs(betas) * np.sign(alphas * betas)<EOL>idx = np.argmin(salmap)<EOL>idx = np.unravel_index(idx, mask.shape)<EOL>pix_sign = np.sign(alphas)[idx]<EOL>return idx, pix_sign<EOL>


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>do_rotations=True, do_translations=True,<EOL>x_shift_limits=(-<NUM_LIT:5>, <NUM_LIT:5>), y_shift_limits=(-<NUM_LIT:5>, <NUM_LIT:5>),<EOL>angular_limits=(-<NUM_LIT:5>, <NUM_LIT:5>), granularity=<NUM_LIT:10>,<EOL>random_sampling=False, abort_early=True):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>min_, max_ = a.bounds()<EOL>channel_axis = a.channel_axis(batch=False)<EOL>def get_samples(limits, num, do_flag):<EOL><INDENT>lb, up = (-limits, limits) if isinstance(limits, int) else limits<EOL>if not do_flag:<EOL><INDENT>return [<NUM_LIT:0>]<EOL><DEDENT>elif random_sampling:<EOL><INDENT>return nprng.uniform(lb, up, num)<EOL><DEDENT>else:<EOL><INDENT>return np.linspace(lb, up, num)<EOL><DEDENT><DEDENT>def crop_center(img):<EOL><INDENT>start = tuple(map(lambda a, da: (a - da) // <NUM_LIT:2>, img.shape,<EOL>a.original_image.shape))<EOL>end = tuple(map(operator.add, start, a.original_image.shape))<EOL>slices = tuple(map(slice, start, end))<EOL>return img[slices]<EOL><DEDENT>x_shifts = get_samples(x_shift_limits, granularity, do_translations)<EOL>y_shifts = get_samples(y_shift_limits, granularity, do_translations)<EOL>rotations = get_samples(angular_limits, granularity, do_rotations)<EOL>transformations = product(x_shifts, y_shifts, rotations)<EOL>for x_shift, y_shift, angle in transformations:<EOL><INDENT>if channel_axis == <NUM_LIT:0>:<EOL><INDENT>xy_shift = (<NUM_LIT:0>, x_shift, y_shift)<EOL>axes = (<NUM_LIT:1>, <NUM_LIT:2>)<EOL><DEDENT>elif channel_axis == <NUM_LIT:2>:<EOL><INDENT>xy_shift = (x_shift, y_shift, <NUM_LIT:0>)<EOL>axes = (<NUM_LIT:0>, <NUM_LIT:1>)<EOL><DEDENT>else:  <EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>x = a.original_image<EOL>x = rotate(x, angle=angle, axes=axes, reshape=True, order=<NUM_LIT:1>)<EOL>x = shift(x, shift=xy_shift, mode='<STR_LIT>')<EOL>x = crop_center(x)<EOL>x = np.clip(x, min_, max_)<EOL>_, is_adv = a.predictions(x)<EOL>if abort_early and is_adv:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Adversarially chosen rotations and translations.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        do_rotations : bool
            If False no rotations will be applied to the image.
        do_translations : bool
            If False no translations will be applied to the image.
        x_shift_limits : int or (int, int)
            Limits for horizontal translations in pixels. If one integer is
            provided the limits will be (-x_shift_limits, x_shift_limits).
        y_shift_limits : int or (int, int)
            Limits for vertical translations in pixels. If one integer is
            provided the limits will be (-y_shift_limits, y_shift_limits).
        angular_limits : int or (int, int)
            Limits for rotations in degrees. If one integer is
            provided the limits will be [-angular_limits, angular_limits].
        granularity : int
            Density of sampling within limits for each dimension.
        random_sampling : bool
            If True we sample translations/rotations randomly within limits,
            otherwise we use a regular grid.
        abort_early : bool
            If True, the attack stops as soon as it finds an adversarial.


sd = np.square(self._input_images - image)<EOL>mses = np.mean(sd, axis=tuple(range(<NUM_LIT:1>, sd.ndim)))<EOL>index = np.argmin(mses)<EOL>if mses[index] > <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self._output_images[index]<EOL>

Looks up the precomputed adversarial image for a given image.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>image = a.original_image<EOL>adversarial = self._get_output(a, image)<EOL>a.predictions(adversarial)<EOL>

Attacks a model using precomputed adversarial candidates.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.


a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>if not self._approximate_gradient and not a.has_gradient():<EOL><INDENT>return<EOL><DEDENT>original_class = a.original_class<EOL>target_class = a.target_class()<EOL>if target_class is None:<EOL><INDENT>if num_random_targets == <NUM_LIT:0> and self._approximate_gradient:<EOL><INDENT>num_random_targets = <NUM_LIT:1><EOL><DEDENT>if num_random_targets == <NUM_LIT:0>:<EOL><INDENT>gradient_attack = GradientAttack()<EOL>gradient_attack(a)<EOL>adv_img = a.image<EOL>if adv_img is None:  <EOL><INDENT>num_random_targets = <NUM_LIT:1><EOL>logging.warning('<STR_LIT>')  <EOL><DEDENT>else:<EOL><INDENT>logits, _ = a.predictions(adv_img)<EOL>target_class = np.argmax(logits)<EOL>target_classes = [target_class]<EOL>logging.info('<STR_LIT>'.format(target_class))  <EOL><DEDENT><DEDENT>if num_random_targets > <NUM_LIT:0>:<EOL><INDENT>num_classes = a.num_classes()<EOL>assert num_random_targets <= num_classes - <NUM_LIT:1><EOL>target_classes = rng.sample(<EOL>range(num_classes), num_random_targets + <NUM_LIT:1>)<EOL>target_classes = [t for t in target_classes if t != original_class]  <EOL>target_classes = target_classes[:num_random_targets]<EOL>str_target_classes = [str(t) for t in target_classes]<EOL>logging.info('<STR_LIT>'.format('<STR_LIT:U+002CU+0020>'.join(str_target_classes)))  <EOL><DEDENT><DEDENT>else:<EOL><INDENT>target_classes = [target_class]<EOL><DEDENT>a._reset()<EOL>for i, target_class in enumerate(target_classes):<EOL><INDENT>self._optimize(<EOL>a, target_class,<EOL>epsilon=epsilon, maxiter=maxiter)<EOL>if len(target_classes) > <NUM_LIT:1>:  <EOL><INDENT>logging.info('<STR_LIT>'.format(i + <NUM_LIT:1>, a.distance))<EOL><DEDENT><DEDENT>

Uses L-BFGS-B to minimize the distance between the image and the
        adversarial as well as the cross-entropy between the predictions for
        the adversarial and the the one-hot encoded target class.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilon : float
            Epsilon of the binary search.
        num_random_targets : int
            Number of random target classes if no target class is given
            by the criterion.
        maxiter : int
            Maximum number of iterations for L-BFGS-B.


a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>assert epsilon > <NUM_LIT:0><EOL>self._run(a, binary_search,<EOL>epsilon, stepsize, iterations,<EOL>random_start, return_early)<EOL>

Simple iterative gradient-based attack known as
        Basic Iterative Method, Projected Gradient Descent or FGSM^k.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        binary_search : bool or int
            Whether to perform a binary search over epsilon and stepsize,
            keeping their ratio constant and using their values to start
            the search. If False, hyperparameters are not optimized.
            Can also be an integer, specifying the number of binary
            search steps (default 20).
        epsilon : float
            Limit on the perturbation size; if binary_search is True,
            this value is only for initialization and automatically
            adapted.
        stepsize : float
            Step size for gradient descent; if binary_search is True,
            this value is only for initialization and automatically
            adapted.
        iterations : int
            Number of iterations for each gradient descent run.
        random_start : bool
            Start the attack from a random point rather than from the
            original input.
        return_early : bool
            Whether an individual gradient descent run should stop as
            soon as an adversarial is found.


a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>assert epsilon > <NUM_LIT:0><EOL>self._decay_factor = decay_factor<EOL>self._run(a, binary_search,<EOL>epsilon, stepsize, iterations,<EOL>random_start, return_early)<EOL>

Momentum-based iterative gradient attack known as
        Momentum Iterative Method.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        binary_search : bool
            Whether to perform a binary search over epsilon and stepsize,
            keeping their ratio constant and using their values to start
            the search. If False, hyperparameters are not optimized.
            Can also be an integer, specifying the number of binary
            search steps (default 20).
        epsilon : float
            Limit on the perturbation size; if binary_search is True,
            this value is only for initialization and automatically
            adapted.
        stepsize : float
            Step size for gradient descent; if binary_search is True,
            this value is only for initialization and automatically
            adapted.
        iterations : int
            Number of iterations for each gradient descent run.
        decay_factor : float
            Decay factor used by the momentum term.
        random_start : bool
            Start the attack from a random point rather than from the
            original input.
        return_early : bool
            Whether an individual gradient descent run should stop as
            soon as an adversarial is found.


<EOL>self.log_every_n_steps = log_every_n_steps<EOL>self._starting_point = starting_point<EOL>self._initialization_attack = initialization_attack<EOL>self.batch_size = batch_size<EOL>self.max_directions = max_directions<EOL>self.step_adaptation = step_adaptation<EOL>self.spherical_step = spherical_step<EOL>self.source_step = source_step<EOL>self.internal_dtype = internal_dtype<EOL>self.verbose = verbose<EOL>if not verbose:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if alternative_generator:<EOL><INDENT>self.generate_candidate = self.generate_candidate_alternative<EOL><DEDENT>else:<EOL><INDENT>self.generate_candidate = self.generate_candidate_default<EOL><DEDENT>return self._apply_outer(<EOL>input_or_adv,<EOL>iterations=iterations,<EOL>tune_batch_size=tune_batch_size,<EOL>threaded_rnd=threaded_rnd,<EOL>threaded_gen=threaded_gen)<EOL>

Applies the Boundary Attack.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, correctly classified image. If image is a
            numpy array, label must be passed as well. If image is
            an :class:`Adversarial` instance, label must not be passed.
        label : int
            The reference label of the original image. Must be passed
            if image is a numpy array, must not be passed if image is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial image, otherwise returns
            the Adversarial object.
        iterations : int
            Maximum number of iterations to run. Might converge and stop
            before that.
        max_directions : int
            Maximum number of trials per ieration.
        starting_point : `numpy.ndarray`
            Adversarial input to use as a starting point, in particular
            for targeted attacks.
        initialization_attack : :class:`Attack`
            Attack to use to find a starting point. Defaults to
            BlendedUniformNoiseAttack.
        log_every_n_steps : int
            Determines verbositity of the logging.
        spherical_step : float
            Initial step size for the orthogonal (spherical) step.
        source_step : float
            Initial step size for the step towards the target.
        step_adaptation : float
            Factor by which the step sizes are multiplied or divided.
        batch_size : int
            Batch size or initial batch size if tune_batch_size is True
        tune_batch_size : bool
            Whether or not the batch size should be automatically chosen
            between 1 and max_directions.
        threaded_rnd : bool
            Whether the random number generation should be multithreaded.
        threaded_gen : bool
            Whether the candidate point generation should be multithreaded.
        alternative_generator: bool
            Whether an alternative implemenation of the candidate generator
            should be used.
        internal_dtype : np.float32 or np.float64
            Higher precision might be slower but is numerically more stable.
        verbose : bool
            Controls verbosity of the attack.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>epsilons=<NUM_LIT:1000>, max_epsilon=<NUM_LIT:1>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>return self._run(a, epsilons=epsilons, max_epsilon=max_epsilon)<EOL>

Perturbs the image with the gradient of the loss w.r.t. the image,
        gradually increasing the magnitude until the image is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of step sizes in the gradient direction
            or number of step sizes between 0 and max_epsilon that should
            be tried.
        max_epsilon : float
            Largest step size if epsilons is not an iterable.


Adds the sign of the gradient to the image, gradually increasing
        the magnitude until the image is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int or Iterable[float]
            Either Iterable of step sizes in the direction of the sign of
            the gradient or number of step sizes between 0 and max_epsilon
            that should be tried.
        max_epsilon : float
            Largest step size if epsilons is not an iterable.


@call_decorator<EOL><INDENT>def __call__(self, input_or_adv, label=None, unpack=True,<EOL>epsilons=<NUM_LIT:100>, repetitions=<NUM_LIT:10>):<DEDENT>

a = input_or_adv<EOL>del input_or_adv<EOL>del label<EOL>del unpack<EOL>image = a.original_image<EOL>min_, max_ = a.bounds()<EOL>axis = a.channel_axis(batch=False)<EOL>channels = image.shape[axis]<EOL>shape = list(image.shape)<EOL>shape[axis] = <NUM_LIT:1><EOL>r = max_ - min_<EOL>pixels = np.prod(shape)<EOL>epsilons = min(epsilons, pixels)<EOL>max_epsilon = <NUM_LIT:1><EOL>for _ in range(repetitions):<EOL><INDENT>for epsilon in np.linspace(<NUM_LIT:0>, max_epsilon, num=epsilons + <NUM_LIT:1>)[<NUM_LIT:1>:]:<EOL><INDENT>p = epsilon<EOL>u = nprng.uniform(size=shape)<EOL>u = u.repeat(channels, axis=axis)<EOL>salt = (u >= <NUM_LIT:1> - p / <NUM_LIT:2>).astype(image.dtype) * r<EOL>pepper = -(u < p / <NUM_LIT:2>).astype(image.dtype) * r<EOL>perturbed = image + salt + pepper<EOL>perturbed = np.clip(perturbed, min_, max_)<EOL>if a.normalized_distance(perturbed) >= a.distance:<EOL><INDENT>continue<EOL><DEDENT>_, is_adversarial = a.predictions(perturbed)<EOL>if is_adversarial:<EOL><INDENT>max_epsilon = min(<NUM_LIT:1>, epsilon * <NUM_LIT>)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>

Increases the amount of salt and pepper noise until the
        image is misclassified.

        Parameters
        ----------
        input_or_adv : `numpy.ndarray` or :class:`Adversarial`
            The original, unperturbed input as a `numpy.ndarray` or
            an :class:`Adversarial` instance.
        label : int
            The reference label of the original input. Must be passed
            if `a` is a `numpy.ndarray`, must not be passed if `a` is
            an :class:`Adversarial` instance.
        unpack : bool
            If true, returns the adversarial input, otherwise returns
            the Adversarial object.
        epsilons : int
            Number of steps to try between probability 0 and 1.
        repetitions : int
            Specifies how often the attack will be repeated.