示例#1
0
文件: structure.py 项目: RP7/migen
	def __init__(self, bits_sign=None, name=None, variable=False, reset=0, name_override=None, min=None, max=None, related=None):
		from migen.fhdl.bitcontainer import bits_for

		Value.__init__(self)
		
		# determine number of bits and signedness
		if bits_sign is None:
			if min is None:
				min = 0
			if max is None:
				max = 2
			max -= 1 # make both bounds inclusive
			assert(min < max)
			self.signed = min < 0 or max < 0
			self.nbits = builtins.max(bits_for(min, self.signed), bits_for(max, self.signed))
		else:
			assert(min is None and max is None)
			if isinstance(bits_sign, tuple):
				self.nbits, self.signed = bits_sign
			else:
				self.nbits, self.signed = bits_sign, False
		if not isinstance(self.nbits, int) or self.nbits <= 0:
			raise ValueError("Signal width must be a strictly positive integer")
		
		self.variable = variable # deprecated
		self.reset = reset
		self.name_override = name_override
		self.backtrace = tracer.trace_back(name)
		self.related = related
示例#2
0
文件: pdf.py 项目: c-PRIMED/puq
def _get_range(sfunc, min, max):
    " Truncate PDFs with long tails"

    num_tails = int(sfunc.ppf(0) == np.NINF) + int(sfunc.ppf(1) == np.PINF)

    _range = options['pdf']['range']
    if num_tails:
        if num_tails == 2:
            range = [(1.0 - _range)/2, (1.0 + _range)/2]
        else:
            range = [1.0 - _range, _range]

    mmin = sfunc.ppf(0)
    if mmin == np.NINF:
        mmin = sfunc.ppf(range[0])
    mmax = sfunc.ppf(1)
    if mmax == np.PINF:
        mmax = sfunc.ppf(range[1])

    if min is not None:
        min = builtins.max(min, mmin)
    else:
        min = mmin

    if max is not None:
        max = builtins.min(max, mmax)
    else:
        max = mmax

    return min, max
示例#3
0
文件: structure.py 项目: wnew/migen
	def __init__(self, bits_sign=None, name=None, variable=False, reset=0, name_override=None, min=None, max=None):
		Value.__init__(self)
		
		# determine number of bits and signedness
		if bits_sign is None:
			if min is None:
				min = 0
			if max is None:
				max = 2
			max -= 1 # make both bounds inclusive
			assert(min < max)
			self.signed = min < 0 or max < 0
			self.nbits = builtins.max(bits_for(min, self.signed), bits_for(max, self.signed))
		else:
			assert(min is None and max is None)
			if isinstance(bits_sign, tuple):
				self.nbits, self.signed = bits_sign
			else:
				self.nbits, self.signed = bits_sign, False
		assert(isinstance(self.nbits, int))
		
		self.variable = variable
		self.reset = reset
		self.name_override = name_override
		self.backtrace = tracer.trace_back(name)
示例#4
0
文件: pdf.py 项目: c-PRIMED/puq
def HPDF(data, min=None, max=None):
    """
    Histogram PDF - initialized with points from a histogram.

    This function creates a PDF from a histogram.  This is useful when some other software has
    generated a PDF from your data.

    :param data: A two dimensional array. The first column is the histogram interval mean,
        and the second column is the probability.  The probability values do not need to be
        normalized.
    :param min: A minimum value for the PDF range. If your histogram has values very close
        to 0, and you know values of 0 are impossible, then you should set the ***min*** parameter.
    :param max: A maximum value for the PDF range.
    :type data: 2D numpy array
    :returns: A PDF object.
    """
    x = data[:, 0]
    y = data[:, 1]
    sp = interpolate.splrep(x, y)
    dx = (x[1] - x[0]) / 2.0
    mmin = x[0] - dx
    mmax = x[-1] + dx
    if min is not None:
        mmin = builtins.max(min, mmin)
    if max is not None:
        mmax = builtins.min(max, mmax)
    x = np.linspace(mmin, mmax, options['pdf']['numpart'])
    y = interpolate.splev(x, sp)
    y[y < 0] = 0     # if the extrapolation goes negative...
    return PDF(x, y)
示例#5
0
文件: audioop.py 项目: Qointum/pypy
def max(cp, size):
    _check_params(len(cp), size)

    if len(cp) == 0:
        return 0

    return builtins.max(abs(sample) for sample in _get_samples(cp, size))
def leaderboard_sequence(spectrum, n, alphabet):
    spectrum = sorted(spectrum)
    parent_mass = max(spectrum)
    leader_board = [[]]
    leader_peptide = []

    while len(leader_board) > 0:
        leader_board = expand(leader_board, alphabet)
        # copy for loop
        # leader_score = score(leader_peptide, spectrum)
        leader_score = 0
        temp = leader_board[:]
        for peptide in temp:
            mass = sum(peptide)
            if mass == parent_mass:
                s = cyc_score(peptide, spectrum)
                if s > leader_score:
                    leader_peptide = peptide
                    leader_score = s

            elif mass > parent_mass:
                leader_board.remove(peptide)

        leader_board = trim(leader_board, spectrum, n)

    return leader_peptide
示例#7
0
def _get_info_gare(name):
    return builtins.max(
        _get_referentiel_gares_voyageurs(),
        key=lambda e: fuzz.ratio(
            e["fields"].get("ut", e["fields"]["intitule_gare"]).lower(),
            name.lower() + "gare"
        )
    )
示例#8
0
文件: audioop.py 项目: Qointum/pypy
def minmax(cp, size):
    _check_params(len(cp), size)

    min_sample, max_sample = 0x7fffffff, -0x80000000
    for sample in _get_samples(cp, size):
        max_sample = builtins.max(sample, max_sample)
        min_sample = builtins.min(sample, min_sample)

    return min_sample, max_sample
示例#9
0
def max(*args):
    """Override the builtin max function to expand list arguments.

    Arguments:
        *args -- lists of numbers or individual numbers
    """
    fullList = []
    for arg in args:
        if hasattr(arg, 'extend'):
            fullList.extend(arg)
        else:
            fullList.append(arg)
    if not fullList:
        return 0
    return builtins.max(fullList)
示例#10
0
文件: structure.py 项目: peteut/migen
    def __init__(self, bits_sign=None, name=None, variable=False, reset=0,
                 reset_less=False, name_override=None, min=None, max=None,
                 related=None, attr=None):
        from migen.fhdl.bitcontainer import bits_for

        super().__init__()

        for n in [name, name_override]:
            if n is not None and not self._name_re.match(n):
                raise ValueError(
                    "Signal name {} is not a valid Python identifier"
                    .format(repr(n)))

        # determine number of bits and signedness
        if bits_sign is None:
            if min is None:
                min = 0
            if max is None:
                max = 2
            max -= 1  # make both bounds inclusive
            assert(min < max)
            self.signed = min < 0 or max < 0
            self.nbits = _builtins.max(
                bits_for(min, self.signed), bits_for(max, self.signed))
        else:
            assert(min is None and max is None)
            if isinstance(bits_sign, tuple):
                self.nbits, self.signed = bits_sign
            else:
                self.nbits, self.signed = bits_sign, False
        if isinstance(reset, (bool, int)):
            reset = Constant(reset, (self.nbits, self.signed))
        if not isinstance(self.nbits, int) or self.nbits <= 0:
            raise ValueError(
                "Signal width must be a strictly positive integer")
        if attr is None:
            attr = set()

        self.variable = variable  # deprecated
        self.reset = reset
        self.reset_less = reset_less
        self.name_override = name_override
        self.backtrace = _tracer.trace_back(name)
        self.related = related
        self.attr = attr
示例#11
0
    def on_monitors_add_clicked(self, button):
        prefix = 'monitor'
        numbers = (row[Row.Name][len(prefix):]
                   for row in self._widgets.model if row[Row.Name].startswith(prefix))
        try:
            max_number = max(int(v) for v in numbers if v.isdigit())
        except ValueError:
            max_number = 0

        row = Row._make(Name='%s%d' % (prefix, max_number + 1),
                        UserBg=False,
                        UserBgDisabled=False,
                        Laptop=True,
                        LaptopDisabled=False,
                        Background='',
                        BackgroundPixbuf=None,
                        BackgroundIsColor=False,
                        ErrorVisible=False,
                        ErrorText=None)
        rowiter = self._widgets.model.append(row)
        self._widgets.treeview.set_cursor(self._widgets.model.get_path(rowiter),
                                          self._widgets.name_column, True)
示例#12
0
    def __init__(self, shape=None, name=None, reset=0, reset_less=False, min=None, max=None,
                 attrs=None, decoder=None, src_loc_at=0):
        super().__init__(src_loc_at=src_loc_at)

        if name is None:
            try:
                name = tracer.get_var_name(depth=2 + src_loc_at)
            except tracer.NameNotFound:
                name = "$signal"
        self.name = name

        if shape is None:
            if min is None:
                min = 0
            if max is None:
                max = 2
            max -= 1  # make both bounds inclusive
            if not min < max:
                raise ValueError("Lower bound {} should be less than higher bound {}"
                                 .format(min, max))
            self.signed = min < 0 or max < 0
            self.nbits  = builtins.max(bits_for(min, self.signed), bits_for(max, self.signed))

        else:
            if not (min is None and max is None):
                raise ValueError("Only one of bits/signedness or bounds may be specified")
            if isinstance(shape, int):
                self.nbits, self.signed = shape, False
            else:
                self.nbits, self.signed = shape

        if not isinstance(self.nbits, int) or self.nbits < 0:
            raise TypeError("Width must be a non-negative integer, not '{!r}'".format(self.nbits))
        self.reset = int(reset)
        self.reset_less = bool(reset_less)

        self.attrs = OrderedDict(() if attrs is None else attrs)
        self.decoder = decoder
示例#13
0
def _nanmax(values, axis=None, skipna=True):
    values, mask, dtype = _get_values(values, skipna, fill_value_typ ='-inf')

    # numpy 1.6.1 workaround in Python 3.x
    if (values.dtype == np.object_
            and sys.version_info[0] >= 3):  # pragma: no cover
        import builtins

        if values.ndim > 1:
            apply_ax = axis if axis is not None else 0
            result = np.apply_along_axis(builtins.max, apply_ax, values)
        else:
            result = builtins.max(values)
    else:
        if ((axis is not None and values.shape[axis] == 0)
                or values.size == 0):
            result = com.ensure_float(values.sum(axis))
            result.fill(np.nan)
        else:
            result = values.max(axis)

    result = _wrap_results(result,dtype)
    return _maybe_null_out(result, axis, mask)
示例#14
0
def max(*args):
    '''Replacement for the built-in :func:`max() <python:max>` function.'''
    return builtins.max(*args)
示例#15
0
def max(a, b):
    """Returns the maximum of a and b."""
    return builtins.max(a, b)
示例#16
0
def max2(*args):
    return builtins.max(filter(lambda x: x is not None, args),
                        default=None)
示例#17
0
文件: handlers.py 项目: sirex/databot
def max(expr, pos, value, **kwargs):
    return builtins.max(value, **kwargs)
示例#18
0
文件: audioop.py 项目: Qointum/pypy
def _get_clipfn(size, signed=True):
    maxval = _get_maxval(size, signed)
    minval = _get_minval(size, signed)
    return lambda val: builtins.max(min(val, maxval), minval)
示例#19
0
 def __len__(self):
     if len(self.value_list) == 0:
         return 0
     return builtins.max([len(v) for v in self.value_list])
示例#20
0
def max(x):
    return builtins.max(x)
示例#21
0
文件: agal.py 项目: snjdck/Aladdin
	def nextValueRegisterIndex(self):
		index = builtins.max(-1 if v is None else i for i, v in enumerate(self.const)) + 1
		index = builtins.max(index, self.offset)
		assert index < self.count
		return index
def my_max(*args):
    print("hey, I am here...")
    # now call the builtin 'max' function
    return builtins.max(args)
# Query Jupyter server for the rows of a data frame
import json as _VSCODE_json
import pandas as _VSCODE_pd
import pandas.io.json as _VSCODE_pd_json
import builtins as _VSCODE_builtins

# In IJupyterVariables.getValue this '_VSCode_JupyterTestValue' will be replaced with the json stringified value of the target variable
# Indexes off of _VSCODE_targetVariable need to index types that are part of IJupyterVariable
_VSCODE_targetVariable = _VSCODE_json.loads("""_VSCode_JupyterTestValue""")
_VSCODE_evalResult = _VSCODE_builtins.eval(_VSCODE_targetVariable["name"])

# _VSCode_JupyterStartRow and _VSCode_JupyterEndRow should be replaced dynamically with the literals
# for our start and end rows
_VSCODE_startRow = _VSCODE_builtins.max(_VSCode_JupyterStartRow, 0)
_VSCODE_endRow = _VSCODE_builtins.min(_VSCode_JupyterEndRow,
                                      _VSCODE_targetVariable["rowCount"])

# Assume we have a dataframe. If not, turn our eval result into a dataframe
_VSCODE_df = _VSCODE_evalResult
if isinstance(_VSCODE_evalResult, list):
    _VSCODE_df = _VSCODE_pd.DataFrame(_VSCODE_evalResult)
elif isinstance(_VSCODE_evalResult, _VSCODE_pd.Series):
    _VSCODE_df = _VSCODE_pd.Series.to_frame(_VSCODE_evalResult)
elif isinstance(_VSCODE_evalResult, dict):
    _VSCODE_evalResult = _VSCODE_pd.Series(_VSCODE_evalResult)
    _VSCODE_df = _VSCODE_pd.Series.to_frame(_VSCODE_evalResult)
elif _VSCODE_targetVariable["type"] == "ndarray":
    _VSCODE_df = _VSCODE_pd.DataFrame(_VSCODE_evalResult)
elif hasattr(_VSCODE_df, "toPandas"):
    _VSCODE_df = _VSCODE_df.toPandas()
# If not a known type, then just let pandas handle it.
示例#24
0
def tail(qte, iterable):
    bidx = builtins.max(len(iterable) - qte, 0)
    return iterable[bidx:]
示例#25
0
文件: pipe.py 项目: lamborryan/Pipe
def max(iterable, **kwargs):
    return builtins.max(iterable, **kwargs)
示例#26
0
def drop(n, xs):
    return xs[builtins.max(0, n):]
示例#27
0
文件: bpipe.py 项目: mavnt/bpipe
def max(*args):
    if len(args) == 0:
        return bpipe(max)
    else:
        return builtins.max(*args)
示例#28
0
文件: engine.py 项目: pffijt/SimPyLC
def max(object0, object1):
    return builtins.max(evaluate(object0), evaluate(object1))
示例#29
0
文件: pipe.py 项目: nykh/PipeTwo
def argmax(items, key=_identity):
    return builtins.max(_swap(items), key=lambda p: key(p[0]))[1]
def max(arr):
    return builtins.max(arr)
示例#31
0
    #   ir: Object temperatures (IR array)
    #   to_min: Minimum object temperature
    #   to_max: Maximum object temperature
    ta, ir, to_min, to_max = fir.read_ir()
    #aver = sum(ir)/len(ir)

    ir_img = []
    face = []
    for i in ir:
        if i - to_min > 7:
            ir_img.append(i)
            face.append(i)
        else:
            ir_img.append(to_min)
    if len(face) > 1:
        face_max = builtins.max(face)
        face_min = builtins.min(face)
        face_aver = sum(face) / len(face)
        print('mean:', face_aver, 'max:', face_max, 'min:', face_min)

    if not ALT_OVERLAY:
        # Scale the image and belnd it with the framebuffer
        #fir.draw_ir(img, ir)
        fir.draw_ir(img, ir_img)
    else:
        # Create a secondary image and then blend into the frame buffer.
        extra_fb.clear()
        fir.draw_ir(extra_fb, ir, alpha=256)
        img.blend(extra_fb, alpha=128)

    # Draw ambient, min and max temperatures.
示例#32
0
文件: colors.py 项目: viridia/lux
def max(*args):
    return tuple(builtins.max(*elements) for elements in zip(*args))
示例#33
0
 def _max_by(source: Iterable[TSource]) -> TSupportsLessThan:
     return builtins.max(projection(x) for x in source)
示例#34
0
文件: core.py 项目: erwanp/smop
def length(a):
    try:
        return builtins.max(np.asarray(a).shape)
    except ValueError:
        return 1
 def max(*args):
     return builtins.max(*args)
示例#36
0
文件: pipe.py 项目: safwank/Pipe
def max(iterable, **kwargs):
    return builtins.max(iterable, **kwargs)
示例#37
0
文件: max.py 项目: jackfirth/pyramda
def max(xs):
    return builtins.max(xs)
示例#38
0
def max_default(values, default):
  if (values.size() == 0): return default
  return max(values)
def efficient_block(expand_ratio=1,
                    filters_in=32,
                    filters_out=16,
                    kernel_size=3,
                    strides=1,
                    zero_pad=0,
                    se_ratio=0,
                    drop_rate=0.2,
                    is_shortcut=True,
                    name='',
                    **kwargs):
    expand_ratio = kwargs.get('expand_ratio', expand_ratio)
    is_shortcut = kwargs.get('id_skip', is_shortcut)
    filters_in = kwargs.get('filters_in', filters_in)
    filters_out = kwargs.get('filters_out', filters_out)
    kernel_size = kwargs.get('kernel_size', kernel_size)
    is_shortcut = filters_in == filters_out and strides == 1 and kwargs.get(
        'id_skip', is_shortcut)
    filters = filters_in * expand_ratio
    if expand_ratio == 1 and strides == 1:

        bottleneck = Sequential(
            DepthwiseConv2d_Block((kernel_size, kernel_size),
                                  depth_multiplier=1,
                                  strides=strides,
                                  auto_pad=True,
                                  padding_mode='zero',
                                  normalization='batch',
                                  activation='swish',
                                  name=name + 'dwconv'),
            SqueezeExcite(se_filters=builtins.max(1, int(filters_in *
                                                         se_ratio)),
                          num_filters=filters_in,
                          use_bias=True) if 0 < se_ratio <= 1 else Identity(),
            Conv2d_Block((1, 1),
                         num_filters=filters_out,
                         strides=1,
                         auto_pad=True,
                         normalization='batch',
                         activation=None,
                         name=name + 'se'),
            Dropout(dropout_rate=drop_rate)
            if is_shortcut and drop_rate > 0 else Identity())

        if is_shortcut:
            return ShortCut2d(Identity(), bottleneck)
        else:
            return bottleneck

    else:
        bottleneck = Sequential(
            Conv2d_Block((1, 1),
                         num_filters=filters,
                         strides=1,
                         auto_pad=True,
                         normalization='batch',
                         activation='swish',
                         name=name + 'expand_bn'),
            DepthwiseConv2d_Block((kernel_size, kernel_size),
                                  depth_multiplier=1,
                                  strides=strides,
                                  auto_pad=True,
                                  padding_mode='zero',
                                  normalization='batch',
                                  activation='swish',
                                  name=name + 'dwconv'),
            SqueezeExcite(se_filters=builtins.max(1, int(filters_in *
                                                         se_ratio)),
                          num_filters=filters,
                          use_bias=True) if 0 < se_ratio <= 1 else Identity(),
            Conv2d_Block((1, 1),
                         num_filters=filters_out,
                         strides=1,
                         auto_pad=True,
                         normalization='batch',
                         activation=None,
                         name=name + 'se'),
            Dropout(dropout_rate=drop_rate)
            if is_shortcut and drop_rate > 0 else Identity())
        if is_shortcut:
            return ShortCut2d(Identity(), bottleneck)
        else:
            return bottleneck
def length(a):
    try:
        return __builtin__.max(np.asarray(a).shape)
    except ValueError:
        return 1
示例#41
0
    def __init__(self,
                 shape=None,
                 name=None,
                 reset=0,
                 reset_less=False,
                 min=None,
                 max=None,
                 attrs=None,
                 decoder=None,
                 src_loc_at=0):
        super().__init__(src_loc_at=src_loc_at)

        if name is not None and not isinstance(name, str):
            raise TypeError("Name must be a string, not '{!r}'".format(name))
        self.name = name or tracer.get_var_name(depth=2 + src_loc_at,
                                                default="$signal")

        if shape is None:
            if min is None:
                min = 0
            if max is None:
                max = 2
            max -= 1  # make both bounds inclusive
            if min > max:
                raise ValueError(
                    "Lower bound {} should be less or equal to higher bound {}"
                    .format(min, max + 1))
            self.signed = min < 0 or max < 0
            if min == max:
                self.nbits = 0
            else:
                self.nbits = builtins.max(bits_for(min, self.signed),
                                          bits_for(max, self.signed))

        else:
            if not (min is None and max is None):
                raise ValueError(
                    "Only one of bits/signedness or bounds may be specified")
            if isinstance(shape, int):
                self.nbits, self.signed = shape, False
            else:
                self.nbits, self.signed = shape

        if not isinstance(self.nbits, int) or self.nbits < 0:
            raise TypeError(
                "Width must be a non-negative integer, not '{!r}'".format(
                    self.nbits))
        self.reset = int(reset)
        self.reset_less = bool(reset_less)

        self.attrs = OrderedDict(() if attrs is None else attrs)
        if isinstance(decoder, type) and issubclass(decoder, Enum):

            def enum_decoder(value):
                try:
                    return "{0.name:}/{0.value:}".format(decoder(value))
                except ValueError:
                    return str(value)

            self.decoder = enum_decoder
        else:
            self.decoder = decoder
示例#42
0
    def numpy_max_pool_2d_stride_pad(x,
                                     ws,
                                     ignore_border=True,
                                     stride=None,
                                     pad=(0, 0),
                                     mode="max"):
        assert ignore_border
        pad_h = pad[0]
        pad_w = pad[1]
        h = x.shape[-2]
        w = x.shape[-1]
        assert ws[0] > pad_h
        assert ws[1] > pad_w

        def pad_img(x):
            y = np.zeros(
                (
                    x.shape[0],
                    x.shape[1],
                    x.shape[2] + pad_h * 2,
                    x.shape[3] + pad_w * 2,
                ),
                dtype=x.dtype,
            )
            y[:, :, pad_h:(x.shape[2] + pad_h), pad_w:(x.shape[3] + pad_w)] = x

            return y

        img_rows = h + 2 * pad_h
        img_cols = w + 2 * pad_w
        out_r = (img_rows - ws[0]) // stride[0] + 1
        out_c = (img_cols - ws[1]) // stride[1] + 1
        out_shp = list(x.shape[:-2])
        out_shp.append(out_r)
        out_shp.append(out_c)
        ws0, ws1 = ws
        stride0, stride1 = stride
        output_val = np.zeros(out_shp)
        y = pad_img(x)
        func = np.max
        if mode == "sum":
            func = np.sum
        elif mode != "max":
            func = np.average
        inc_pad = mode == "average_inc_pad"

        for k in np.ndindex(*x.shape[:-2]):
            for i in range(output_val.shape[-2]):
                ii_stride = i * stride[0]
                ii_end = builtins.min(ii_stride + ws[0], img_rows)
                if not inc_pad:
                    ii_stride = builtins.max(ii_stride, pad_h)
                    ii_end = builtins.min(ii_end, h + pad_h)
                for j in range(output_val.shape[-1]):
                    jj_stride = j * stride[1]
                    jj_end = builtins.min(jj_stride + ws[1], img_cols)
                    if not inc_pad:
                        jj_stride = builtins.max(jj_stride, pad_w)
                        jj_end = builtins.min(jj_end, w + pad_w)
                    patch = y[k][ii_stride:ii_end, jj_stride:jj_end]
                    output_val[k][i, j] = func(patch)
        return output_val
示例#43
0
def divide(a, b, dtype=None):
    key = lambda x: getattr(x, "__array_priority__", float("-inf"))
    f = divide_lookup.dispatch(type(builtins.max(a, b, key=key)))
    return f(a, b, dtype=dtype)
示例#44
0
def my_max(*args):
    print("hey, I am here...")
    # now call the builtin 'max' function
    return builtins.max(args)
示例#45
0
def max(source: Iterable[TSupportsLessThan]) -> TSupportsLessThan:
    """Returns the greatest of all elements of the sequence,
    compared via `max()`."""

    value: TSupportsLessThan = builtins.max(source)
    return value