Example #1
0
def limit_versions(language, limit, operator):
    """
    Limits given languages with the given operator:

    :param language:
        A `Language` instance.
    :param limit:
        A number to limit the versions.
    :param operator:
        The operator to use for the limiting.
    :return:
        A new `Language` instance with limited versions.
    :raises ValueError:
        If no version is left anymore.
    """
    if isinstance(limit, int):
        versions = [version for version in language.versions
                    if operator(int(version), limit)]
    else:

        versions = [version for version in language.versions
                    if operator(version, limit)]
    if not versions:
        raise ValueError('No versions left')
    return type(language)(*versions)
 def _mul_div(self, other, operator):
     if isinstance(other, self.__class__):
         result = operator(self.value, other.value)
         return result.plus_minus((self.rel ** 2.0 + other.rel ** 2.0) ** (1/2), relative=True)
     else:
         result = operator(self.value, other)
         return result.plus_minus(abs(operator(self.error, other)))
Example #3
0
 def _operator_on_other(self, other, operator):
     try:
         return Position(operator(self.x, other[0]),
                         operator(self.y, other[1]))
     except TypeError:
         return Position(operator(self.x, other),
                         operator(self.y, other))
Example #4
0
 def should_record_call(self):
     for operator in self.operators:
         left, right = Dingus.many(2)
         operator(left, right)
         operator_name_without_mangling = operator.__name__.replace('_', '')
         magic_method_name = '__%s__' % operator_name_without_mangling
         yield assert_call_was_logged, left, magic_method_name, right
Example #5
0
 def test_device_ordering(self, context, operator):
     try:
         device = Device.from_path(context, "/devices/platform")
     except DeviceNotFoundAtPathError:
         pytest.skip("device not found")
     with pytest.raises(TypeError) as exc_info:
         operator(device, device)
     assert str(exc_info.value) == "Device not orderable"
Example #6
0
    def edit(self, activity, options):
        operator, delta = self._parse_time_delta(options.time)

        for lap in activity.laps:
            lap.start_time = operator(lap.start_time, delta)

            for trackpoint in lap.trackpoints:
                trackpoint.time = operator(trackpoint.time, delta)
    def test_rate_operator_negative_rate_full(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]

        domain = Domain(points, vertices)

        # Flat surface with 1m of water
        domain.set_quantity("elevation", 0)
        domain.set_quantity("stage", 10.0)
        domain.set_quantity("friction", 0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({"exterior": Br})

        #        print domain.quantities['elevation'].centroid_values
        #        print domain.quantities['stage'].centroid_values
        #        print domain.quantities['xmomentum'].centroid_values
        #        print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = [0, 1, 3]

        # Catchment_Rain_Polygon = read_polygon(join('CatchmentBdy.csv'))
        # rainfall = file_function(join('1y120m.tms'), quantities=['rainfall'])
        rate = -1.0
        factor = 10.0
        default_rate = 0.0

        operator = Rate_operator(domain, rate=rate, factor=factor, indices=None, default_rate=default_rate)

        # Apply Operator
        domain.timestep = 2.0
        operator()

        stage_ex = [0.0, 0.0, 0.0, 0.0]
        step_integral = -80.0

        # print domain.quantities['elevation'].centroid_values
        # print domain.quantities['stage'].centroid_values
        # print domain.quantities['xmomentum'].centroid_values
        # print domain.quantities['ymomentum'].centroid_values
        # print domain.fractional_step_volume_integral

        assert num.allclose(domain.quantities["stage"].centroid_values, stage_ex)
        assert num.allclose(domain.quantities["xmomentum"].centroid_values, 0.0)
        assert num.allclose(domain.quantities["ymomentum"].centroid_values, 0.0)
        assert num.allclose(domain.fractional_step_volume_integral, step_integral)
Example #8
0
 def combine(self, other, operator):
   result = collections.defaultdict(fractions.Fraction)
   for x, px in self._dist.iteritems():
     if isinstance(other, self.__class__):
       for y, py in other._dist.iteritems():
         result[operator(x, y)] += px * py
     else:
       result[operator(x, other)] += px
   return self.__class__(result)
Example #9
0
def mod_karma(thing, operator):
    thing = thing.strip()

    if thing in memory:
        memory[thing] = operator(memory[thing], 1)
    else:
        memory[thing] = operator(0, 1)

    log.info("%s's new karma: %s" % (thing, memory[thing]))
    with open( jsoned_memory, "wb" ) as f:
        json.dump( memory, f )
    def test_rate_operator_simple(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1,0,2], [1,2,4], [4,2,5], [3,1,4]]

        domain = Domain(points, vertices)

        #Flat surface with 1m of water
        domain.set_quantity('elevation', 0)
        domain.set_quantity('stage', 1.0)
        domain.set_quantity('friction', 0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({'exterior': Br})


#        print domain.quantities['stage'].centroid_values
#        print domain.quantities['xmomentum'].centroid_values
#        print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = [0,1,3]

        rate = 1.0
        factor = 10.0
        default_rate= 0.0

        operator = Rate_operator(domain, rate=rate, factor=factor, \
                      indices=indices, default_rate = default_rate)
        
        # Apply Operator
        domain.timestep = 2.0
        operator()

        stage_ex = [ 21.,  21.,   1.,  21.]

#        print domain.quantities['stage'].centroid_values
#        print domain.quantities['xmomentum'].centroid_values
#        print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values, stage_ex)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values, 0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values, 0.0)
        assert num.allclose(domain.fractional_step_volume_integral, factor*domain.timestep*(rate*domain.areas[indices]).sum())
Example #11
0
    def end(operator, record, arg):
        logger.debug("comparing end times %r(%r, %r)", operator, record.endTime, arg)

        # We need a special-case for NULL endTime for conferences in progress
        if record.endTime is None:
            return operator(None, arg)

        end = arrow.get(record.endTime)
        if arg is None:
            return operator(end, None)
        return operator(end, _ReplayFilters._normalize_time_val(arg))
Example #12
0
    def _operate(self, other, operator):
        K1 = self.keys()
        K2 = other.keys()
        keys = set(K1 + K2)

        default = operator(self.default, other.default)
        
        result = SparseVector(default=default)
        for key in keys:
            result[key] = operator(self.get(key, self.default), other.get(key, self.default))

        return result
Example #13
0
 def reverse_binary_operator(self, other, operator):
     try:
         self.assert_same_keys(other)
         result = self._get_empty_self()
         for key in self:
             result[key] = operator(other[key], self[key])
         return result
     except TypeError:
         result = self._get_empty_self()
         for key in self:
             result[key] = operator(other, self[key])
         return result
Example #14
0
	def do_operator(self, operator, query, value, result):
		op = operator(mock_queryable, value)
		assert isinstance(op, Op)
		assert op.operation == query[1:]
		assert op.as_query == result
		
		if __debug__:
			a = MockQueryable()
			a.__disallowed_operators__ = {query}
			
			try:
				operator(a, value)
			except NotImplementedError as e:
				assert query in str(e)
Example #15
0
 def _build_statement(self, quals, columns, sortkeys):
     statement = select([self.table])
     clauses = []
     for qual in quals:
         operator = OPERATORS.get(qual.operator, None)
         if operator:
             clauses.append(operator(self.table.c[qual.field_name],
                                     qual.value))
         else:
             log_to_postgres('Qual not pushed to foreign db: %s' % qual,
                             WARNING)
     if clauses:
         statement = statement.where(and_(*clauses))
     if columns:
         columns = [self.table.c[col] for col in columns]
     else:
         columns = self.table.c
     statement = statement.with_only_columns(columns)
     orders = []
     for sortkey in sortkeys:
         column = self.table.c[sortkey.attname]
         if sortkey.is_reversed:
             column = column.desc()
         if sortkey.collate:
             column = column.collate('"%s"' % sortkey.collate)
         if self.engine.driver != 'pymssql' && sortkey.nulls_first:
             column = column.nullsfirst()
         else self.engine.driver != 'pymssql':
             column = column.nullslast()
         statement = statement.order_by(column)
Example #16
0
def iscompatible(requirements, version):
    """Return whether or not `requirements` is compatible with `version`

    Arguments:
        requirements (str): Requirement to compare, e.g. foo==1.0.1
        version (tuple): Version to compare against, e.g. (1, 0, 1)

    Example:
        >>> iscompatible("foo", (1, 0, 0))
        True
        >>> iscompatible("foo<=1", (0, 9, 0))
        True
        >>> iscompatible("foo>=1, <1.3", (1, 2, 0))
        True
        >>> iscompatible("foo>=0.9.9", (1, 0, 0))
        True
        >>> iscompatible("foo>=1.1, <2.1", (2, 0, 0))
        True
        >>> iscompatible("foo==1.0.0", (1, 0, 0))
        True
        >>> iscompatible("foo==1.0.0", (1, 0, 1))
        False

    """

    results = list()

    for operator_string, requirement_string in parse_requirements(requirements):
        operator = operators[operator_string]
        required = string_to_tuple(requirement_string)
        result = operator(version, required)

        results.append(result)

    return all(results)
Example #17
0
 def _apply_binary_scalar_operator(self, operator, other):
     oshape = None
     r = None
     try:        
         if isinstance(other, Weights):
             if other._max_weight != self._max_weight:
                 ValueError("Operation not possible as operands have "
                            "incompatible maximum conductances.")
             oshape = other.shape
             r = numpy.array(self._weights)
         else:
             if isinstance(other, list): 
                 oshape = numpy.shape(other)
             elif not hasattr(initializer, '__getitem__'):
                 raise TypeError("Second operand could not be interpreted "
                                 "as an array of weights.")
         if oshape != None and oshape != self.shape:
             raise IndexError
         if r == None:
             r = numpy.zeros(oshape)
             for x in xrange(self._dim1):
                 for y in xrange(self._dim2):
                     r[x][y] = operator(self._weights[x][y], other[x][y])
         else:
             r -= other._weights                
     except IndexError:
         raise ValueError("Operation not possible as operands have "
                          "incompatible shapes.")
     w = Weights([0], max_weight=self._max_weight)
     w._dim1, w._dim2 = self.shape
     w._weights = r
     return w
Example #18
0
 def comparison(vm, frame, offset, bytecode):
     b, a = frame.pop(), frame.pop()
     assert isinstance(a, int) and isinstance(b, int)
     if operator(a, b):
         frame.pc = decode_signed_offset(bytecode, frame.pc)-1
         return
     frame.pc = frame.pc+2
Example #19
0
 def _build_statement(self, quals, columns, sortkeys):
     statement = select([self.table])
     clauses = []
     for qual in quals:
         operator = OPERATORS.get(qual.operator, None)
         if operator:
             clauses.append(operator(self.table.c[qual.field_name],
                                     qual.value))
         else:
             log_to_postgres('Qual not pushed to foreign db: %s' % qual,
                             WARNING)
     if clauses:
         statement = statement.where(and_(*clauses))
     if columns:
         columns = [self.table.c[col] for col in columns]
     else:
         columns = self.table.c
     statement = statement.with_only_columns(columns)
     orders = []
     for sortkey in sortkeys:
         column = self.table.c[sortkey.attname]
         if sortkey.is_reversed:
             column = column.desc()
         if sortkey.collate:
             column = column.collate('"%s"' % sortkey.collate)
         null_ordering = self._need_explicit_null_ordering(sortkey)
         if null_ordering:
             column = null_ordering(column)
         statement = statement.order_by(column)
     return statement
def majorityCnt(classList):
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys(): classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.iteritems(),key=operator(1),reverse=True)
    return sortedClassCount[0][0]
Example #21
0
 def execute(self, quals, columns):
     """
     The quals are turned into an and'ed where clause.
     """
     statement = select([self.table])
     clauses = []
     for qual in quals:
         operator = OPERATORS.get(qual.operator, None)
         if operator:
             clauses.append(operator(self.table.c[qual.field_name],
                                     qual.value))
         else:
             log_to_postgres('Qual not pushed to foreign db: %s' % qual,
                             WARNING)
     if clauses:
         statement = statement.where(and_(*clauses))
     if columns:
         columns = [self.table.c[col] for col in columns]
     else:
         columns = self.table.c
     statement = statement.with_only_columns(columns)
     log_to_postgres(str(statement), DEBUG)
     rs = (self.connection
           .execution_options(stream_results=True)
           .execute(statement))
     for item in rs:
         yield dict(item)
Example #22
0
    def __init__(self, inputs, cols="1", operator=None):

        self.cols = make_colspec(cols)
        self.ops = map(lambda x: operator([x]), inputs)
        self.name = "catcol(%s, %s)" % (",".join(map(str, self.cols)), str(self.ops[0]))
        # print self.cols, self.ops
        Operator.__init__(self, inputs, operators.OP_N_TO_N)
Example #23
0
    def visit_BinaryExpressionNode(self, node):
        assert len(node.children) == 3
        operator = self.visit(node.children[0])
        operand_0 = self.visit(node.children[1])
        operand_1 = self.visit(node.children[2])

        return operator(operand_0, operand_1)
Example #24
0
    def process_BoolOp(self, node, children):
        operator = children.pop(0)
        for child in children:
            if not isinstance(child, Query):
                raise ValueError("Bad expression: All operands for %s must be queries." % operator.__name__)

        return operator(*children)
Example #25
0
 def process_BinOp(self, node, children):
     left, operator, right = children
     if not isinstance(left, Query):
         raise ValueError("Bad expression: left operand for %s must be a query." % operator.__name__)
     if not isinstance(right, Query):
         raise ValueError("Bad expression: right operand for %s must be a query." % operator.__name__)
     return operator(left, right)
Example #26
0
    def execute(self, quals, columns):
        """
        The quals are turned into an and'ed where clause.
        """
        statement = select([self.table])
        clauses = []
        for qual in quals:
            operator = OPERATORS.get(qual.operator, None)
            if operator:
                clauses.append(operator(self.table.c[qual.field_name],
                                        qual.value))
            else:
                log_to_postgres('Qual not pushed to foreign db: %s' % qual,
                                WARNING)
        if clauses:
            statement = statement.where(and_(*clauses))
        if columns:
            columns = [self.table.c[col] for col in columns]
        else:
            columns = self.table.c
        statement = statement.with_only_columns(columns)
        log_to_postgres(str(statement), DEBUG)
        rs = (self.connection
              .execution_options(stream_results=True)
              .execute(statement))
        # Workaround pymssql "trash old results on new query"
        # behaviour (See issue #100)
        if self.engine.driver == 'pymssql' and self.transaction is not None:
            rs = list(rs)

        for item in rs:
            yield dict(item)
Example #27
0
def overload(operators, *args):
	for operator in operators:
		try:
			ret = operator(*args)
		except:
			pass
		else:
			return ret
Example #28
0
def unary_op(type_, operator, operation, lhs):
    if hasattr(lhs, 'operations') and lhs.operations is not None:
        lhs_operations = lhs.operations
    else:
        lhs_operations = lhs

    result = operator(type_(lhs))
    return track(result, operation(lhs_operations))
Example #29
0
def combine_multiple(subsets, operator):
    if len(subsets) == 0:
        return SubsetState()
    else:
        combined = subsets[0]
        for subset in subsets[1:]:
            combined = operator(combined, subset)
        return combined
Example #30
0
 def _arithmetic_to_number(self, operator, operand, allow_nonzero_ints=False):
     if not isinstance(operand, Capacity):
         if not allow_nonzero_ints and operand != 0:
             raise TypeError(
                 "Attempt to perform %s operation between capacity and %r" %
                 (operator.__name__, operand))
         operand = Capacity(operand)
     return operator(self.bits, operand.bits)
Example #31
0
        def prediction_func(row):
            """Look up the row's features in order of their score. Exit if the threshold is met and the tree exits on True,
            or if the threshold is not met and the tree exits on False.
            Args:
                row: Dataframe row with features as columns
            Returns:
                Series with prediction for all cues used
            """
            ret_ser = pd.Series()
            for index, cue_row in cue_df.iterrows():
                operator = operator_dict[cue_row['direction']]
                outcome = operator(row[cue_row['feature']],
                                   cue_row['threshold'])

                # store prediction in series
                ret_ser.set_value(index, outcome)

                # exit tree if outcome is exit or last cue reached
                if (cue_row['exit'] == int(outcome)) or (index + 1 == nr_rows):
                    cues_used = index + 1
                    break

            # return predictions for cues used
            return ret_ser
	def _apply_filter(self, match_objs, filters):
		"""
		"""
		if type(filters) is dict:
			filters = [filters]
		else:
			if filters is None or type(filters) is not list:
				raise ValueError("filters must be of type dict or list")

		for filter_el in filters:

			operator = LightCurve._ops[
				filter_el['operator']
			]

			attr_name = filter_el['attribute']
			match_objs = tuple(
				filter(
					lambda x: x.has_parameter(attr_name) and operator(x.get_value(attr_name), filter_el['value']), 
					match_objs
				)
			)

		return match_objs
def handleInteraction(client, userdata, message):
    data = json.loads(message.payload.decode('utf-8'))
    sourceSerial = data['serial']

    # Don't make an actuation change if this node is not a device
    if not isDevice(parseConfig()['serial']):
        logging.info('node with serial %d triggered interaction, but is not device node'
                     % parseConfig()['serial'])
        return

    for i in getOwnInteractions():
        if i['trigger_serial'] == sourceSerial:
            operator = OPS[i['operator']]
            destVal = i['value']
            srcVal = data['data']

            if operator(srcVal, destVal):
                global hardwareClient

                # Cast to correct type
                newVal = i['action']
                valType = getHardwareType()
                if valType == 'float':
                    newVal = float(newVal)
                elif valType == 'boolean':
                    newVal = bool(newVal)
                elif valType == 'integer':
                    newVal = int(newVal)

                otherNode = getNode(i['target_serial'])
                print('Interaction triggered for device \'%s\'. Changing data to \'%d\''
                      % (otherNode['display_name'], newVal))
                hardwareClient.changeValue(getHardwareName(), newVal)

                logging.info('interaction with id %d triggered' %
                             i['interaction_id'])
Example #34
0
def select_bin_from_corr(r,
                         xip,
                         xip_err,
                         radius=1 * u.arcmin,
                         operator=operator.le):
    """Aggregate measurements for r less than (or greater than) radius.

    Returns aggregate measurement for all entries where operator(r, radius).
    E.g.,
     * Passing radius=5, operator=operator.le will return averages for r<=5
     * Passing radius=2, operator=operator.gt will return averages for r >2

    Written with the use of correlation functions in mind, thus the naming
    but generically just returns averages of the arrays xip and xip_err
    where the condition is satsified

    Parameters
    ----------
    r : numpy.array
        radius
    xip : numpy.array
        correlation
    xip_err : numpy.array
        correlation uncertainty
    operator : Operation in the 'operator' module: le, ge, lt, gt

    Returns
    -------
    avg_xip, avg_xip_err : (float, float)
    """
    w, = np.where(operator(r, radius))

    avg_xip = np.average(xip[w])
    avg_xip_err = np.average(xip_err[w])

    return avg_xip, avg_xip_err
Example #35
0
    def _ufunc_binary_operator(self, *, operator: tp.Callable,
                               other) -> np.ndarray:
        '''
        Binary operators applied to an index always return an NP array. This deviates from Pandas, where some operations (multipling an int index by an int) result in a new Index, while other operations result in a np.array (using == on two Index).
        '''
        if self._recache:
            self._update_array_cache()

        if issubclass(other.__class__, Index):
            other = other.values  # operate on labels to labels

        result = operator(self._labels, other)

        # see Series._ufunc_binary_operator for notes on why
        if not isinstance(result, np.ndarray):
            if isinstance(result, BOOL_TYPES):
                result = np.full(len(self._labels), result)
            else:
                raise RuntimeError(
                    'unexpected branch from non-array result of operator application to array'
                )

        result.flags.writeable = False
        return result
def test_operator(self, operator, emulated_operator=None):
    if emulated_operator is None:
        emulated_operator = operator

    value = features.Value(value=2)
    f = operator(value, 3)
    self.assertEqual(f(), operator(2, 3))
    self.assertListEqual(f().get_property("value", get_one=False), [2, 3])

    f = operator(3, value)
    self.assertEqual(f(), operator(3, 2))

    f = operator(value, lambda: 3)
    self.assertEqual(f(), operator(2, 3))
    self.assertListEqual(f().get_property("value", get_one=False), [2, 3])

    grid_test_features(
        self,
        features.Value,
        features.Value,
        [
            {"value": 1},
            {"value": 0.5},
            {"value": np.nan},
            {"value": np.inf},
            {"value": np.random.rand(10, 10)},
        ],
        [
            {"value": 1},
            {"value": 0.5},
            {"value": np.nan},
            {"value": np.inf},
            {"value": np.random.rand(10, 10)},
        ],
        lambda a, b: emulated_operator(a["value"], b["value"]),
        operator,
    )
def test_unary_operators(operator, value, result):
    v = StatefulPublisher(value)

    try:
        value_applied = operator(v).get()
    except Exception as e:
        assert isinstance(e, result)
    else:
        assert value_applied == result

    cb = mock.Mock()

    try:
        operator(v) | op.Sink(cb)
    except Exception as e:
        assert isinstance(e, result)
    else:
        assert cb.mock_called_once_with(result)

    with pytest.raises(ValueError):
        Value(1) | operator(v)

    with pytest.raises(ValueError):
        operator(v).emit_op(0, who=Publisher())
Example #38
0
 def _test(self, a, b, operator):
     return operator(a, b)
Example #39
0
    def test_rate_operator_functions_empty_indices(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]

        domain = Domain(points, vertices)

        #Flat surface with 1m of water
        domain.set_quantity('elevation', 0.0)
        domain.set_quantity('stage', 1.0)
        domain.set_quantity('friction', 0.0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({'exterior': Br})

        verbose = False

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = []
        factor = 10.0

        def main_spatial_rate(x, y, t):
            # x and y should be an n by 1 array
            return x + y

        default_rate = 0.0

        domain.tri_full_flag[0] = 0
        operator = Rate_operator(domain, rate=main_spatial_rate, factor=factor, \
                      indices=indices, default_rate = default_rate)

        # Apply Operator
        domain.timestep = 2.0
        operator()

        t = operator.get_time()
        Q = operator.get_Q()
        x = operator.coord_c[indices, 0]
        y = operator.coord_c[indices, 1]
        rate = main_spatial_rate(x, y, t) * factor
        Q_ex = num.sum(domain.areas[indices] * rate)
        d = operator.get_timestep() * rate + 1

        #print Q_ex, Q
        #print indices
        #print "d"
        #print d
        stage_ex = num.array([1.0, 1.0, 1.0, 1.0])
        stage_ex[indices] = d

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)
        assert num.allclose(Q_ex, Q)
        assert num.allclose(domain.fractional_step_volume_integral,
                            ((d - 1.) * domain.areas[indices]).sum())
Example #40
0
# _*_coding: UTF-8_*_
__author__ = 'bwh'
import operator

bart = operator("zhangsan", 100)
print bart.get_name()
Example #41
0
def infer_dtype(left_dtype, right_dtype, operator):
    left = build_empty_series(left_dtype)
    right = build_empty_series(right_dtype)
    return operator(left, right).dtype
Example #42
0
 def wrapped(*args):
     d = {p.name: arg for arg, p in zip(args, parameters)}
     fval = f(*[d[name] for name in names1.keys()])
     gval = g(*[d[name] for name in names2.keys()])
     return operator(fval, gval)
Example #43
0
def operation(data, operator):
    result = data[0]
    for i in data[1:]:
        result = operator(result, i)
    return result
Example #44
0
 def compare(self, item, operator=operator.eq):
     getter = self._getter
     self._getter = lambda obj: operator(getter(obj),
                                         self.__get_value(item, obj))
     return self
Example #45
0
 def filter_by_price(queryset, value, operator):
     return [
         obj for obj in queryset if operator(
             get_availability(obj, context.discounts).price_range.
             min_price.gross, value)
     ]
Example #46
0
def _combine(subsets, operator):
    state = operator(*[s.subset_state for s in subsets])
    result = Subset(None)
    result.subset_state = state
    return result
Example #47
0
    def test_rate_operator_rate_quantity(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]

        domain = Domain(points, vertices)

        #Flat surface with 1m of water
        domain.set_quantity('elevation', 0.0)
        domain.set_quantity('stage', 1.0)
        domain.set_quantity('friction', 0.0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({'exterior': Br})

        verbose = False

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = [0, 1, 3]
        factor = 10.0

        from anuga import Quantity
        rate_Q = Quantity(domain)
        rate_Q.set_values(1.0)

        operator = Rate_operator(domain, rate=rate_Q, factor=factor, \
                                 indices=indices)

        # Apply Operator
        domain.timestep = 2.0
        operator()
        rate = rate_Q.centroid_values[indices]
        t = operator.get_time()
        Q = operator.get_Q()

        rate = rate * factor
        Q_ex = num.sum(domain.areas[indices] * rate)
        d = operator.get_timestep() * rate + 1

        #print "d"
        #print d
        #print Q_ex
        #print Q
        stage_ex = num.array([1.0, 1.0, 1.0, 1.0])
        stage_ex[indices] = d

        verbose = False

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)
        assert num.allclose(Q_ex, Q)
        assert num.allclose(domain.fractional_step_volume_integral,
                            ((d - 1.) * domain.areas[indices]).sum())
Example #48
0
def infer_dtypes(left_dtypes, right_dtypes, operator):
    left = build_empty_df(left_dtypes)
    right = build_empty_df(right_dtypes)
    return operator(left, right).dtypes
Example #49
0
 def evaluate(obj):
     left_val = eval_left(obj)
     right_val = eval_right(obj)
     if left_val is None or right_val is None:
         return None
     return operator(eval_left(obj), eval_right(obj))
Example #50
0
def compare_pvector(v, other, operator):
    return operator(v.tolist(),
                    other.tolist() if isinstance(other, PVector) else other)
Example #51
0
 def make(cls, operands: Sequence[int], operator: Operator) -> 'Equation':
     return Equation(tuple(operands), operator, operator(*operands))
Example #52
0
def bad_samples(act, samples_to_drop, operator, threshold):
    df = deviation[(deviation['Activity'] == act)]
    temp = (deviation.Activity == act) & operator(deviation.attr_y_acc,
                                                  threshold)
    return samples_to_drop.extend(list(df.Sample_Num[temp]))
Example #53
0
def quantity_binary_operator(db_obj, other, operator):
    return db.and_(
        db_obj['_type'].astext == 'quantity',
        db_obj['dimensionality'].astext == str(other.dimensionality),
        operator(db_obj['magnitude_in_base_units'].astext.cast(db.Float),
                 other.magnitude_in_base_units))
Example #54
0
    def test_rate_operator_negative_rate_full(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]

        domain = Domain(points, vertices)

        #Flat surface with 1m of water
        domain.set_quantity('elevation', 0)
        domain.set_quantity('stage', 10.0)
        domain.set_quantity('friction', 0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({'exterior': Br})

        #        print domain.quantities['elevation'].centroid_values
        #        print domain.quantities['stage'].centroid_values
        #        print domain.quantities['xmomentum'].centroid_values
        #        print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = [0, 1, 3]

        #Catchment_Rain_Polygon = read_polygon(join('CatchmentBdy.csv'))
        #rainfall = file_function(join('1y120m.tms'), quantities=['rainfall'])
        rate = -1.0
        factor = 10.0
        default_rate = 0.0

        operator = Rate_operator(domain, rate=rate, factor=factor, \
                      indices=None, default_rate = default_rate)

        # Apply Operator
        domain.timestep = 2.0
        operator()

        stage_ex = [0., 0., 0., 0.]
        step_integral = -80.0

        #print domain.quantities['elevation'].centroid_values
        #print domain.quantities['stage'].centroid_values
        #print domain.quantities['xmomentum'].centroid_values
        #print domain.quantities['ymomentum'].centroid_values
        #print domain.fractional_step_volume_integral

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.fractional_step_volume_integral,
                            step_integral)
Example #55
0
    def visit_UnaryExpressionNode(self, node):
        assert len(node.children) == 2
        operator = self.visit(node.children[0])
        operand = self.visit(node.children[1])

        return lambda x: operator(operand(x))
Example #56
0
 def _(row, ctx):
     return operator(val(row, ctx))
Example #57
0
    def test_rate_operator_rate_from_file(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]

        #---------------------------------
        #Typical ASCII file
        #---------------------------------
        finaltime = 1200
        filename = 'test_file_function'
        fid = open(filename + '.txt', 'w')
        start = time.mktime(time.strptime('2000', '%Y'))
        dt = 60  #One minute intervals
        t = 0.0
        while t <= finaltime:
            t_string = time.strftime(time_format, time.gmtime(t + start))
            fid.write('%s, %f %f %f\n' %
                      (t_string, 2 * t, t**2, sin(t * pi / 600)))
            t += dt

        fid.close()

        #Convert ASCII file to NetCDF (Which is what we really like!)
        timefile2netcdf(filename + '.txt')

        #Create file function from time series
        F = file_function(
            filename + '.tms',
            quantities=['Attribute0', 'Attribute1', 'Attribute2'])

        #Now try interpolation
        for i in range(20):
            t = i * 10
            q = F(t)

            #Exact linear intpolation
            assert num.allclose(q[0], 2 * t)
            if i % 6 == 0:
                assert num.allclose(q[1], t**2)
                assert num.allclose(q[2], sin(t * pi / 600))

        #Check non-exact

        t = 90  #Halfway between 60 and 120
        q = F(t)
        assert num.allclose((120**2 + 60**2) / 2, q[1])
        assert num.allclose((sin(120 * pi / 600) + sin(60 * pi / 600)) / 2,
                            q[2])

        t = 100  #Two thirds of the way between between 60 and 120
        q = F(t)
        assert num.allclose(2 * 120**2 / 3 + 60**2 / 3, q[1])
        assert num.allclose(
            2 * sin(120 * pi / 600) / 3 + sin(60 * pi / 600) / 3, q[2])

        #os.remove(filename + '.txt')
        #os.remove(filename + '.tms')

        domain = Domain(points, vertices)

        #Flat surface with 1m of water
        domain.set_quantity('elevation', 0)
        domain.set_quantity('stage', 1.0)
        domain.set_quantity('friction', 0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({'exterior': Br})

        #        print domain.quantities['elevation'].centroid_values
        #        print domain.quantities['stage'].centroid_values
        #        print domain.quantities['xmomentum'].centroid_values
        #        print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = [0, 1, 3]

        rate = file_function('test_file_function.tms',
                             quantities=['Attribute1'])

        factor = 1000.0
        default_rate = 17.7

        operator = Rate_operator(domain, rate=rate, factor=factor, \
                      indices=indices, default_rate = default_rate)

        # Apply Operator
        domain.set_starttime(360.0)
        domain.timestep = 1.0

        operator()

        d = domain.get_time()**2 * factor + 1.0
        stage_ex0 = [d, d, 1., d]

        #        print d, domain.get_time(), F(360.0)

        #        print domain.quantities['elevation'].centroid_values
        #        print domain.quantities['stage'].centroid_values
        #        print domain.quantities['xmomentum'].centroid_values
        #        print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex0)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.fractional_step_volume_integral,
                            ((d - 1.) * domain.areas[indices]).sum())

        domain.set_starttime(-10.0)
        domain.timestep = 1.0

        try:
            operator()
        except:
            pass
        else:
            raise Exception('Should have raised an exception, time too early')

        domain.set_starttime(1300.0)
        domain.timestep = 1.0

        operator()

        d = default_rate * factor + d
        stage_ex1 = [d, d, 1., d]

        #        print domain.quantities['elevation'].centroid_values
        #        print domain.quantities['stage'].centroid_values
        #        print domain.quantities['xmomentum'].centroid_values
        #        print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex1)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.fractional_step_volume_integral,
                            ((d - 1.) * domain.areas[indices]).sum())
Example #58
0
 def _(row, ctx):
     return operator(lhs(row, ctx), rhs(row, ctx))
def operators(Alert_price,operator,Stock_price):
    return operator(Alert_price,Stock_price)
Example #60
0
    def test_rate_operator_functions_rate_default_rate(self):
        from anuga.config import rho_a, rho_w, eta_w
        from math import pi, cos, sin

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #             bac,     bce,     ecf,     dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]

        domain = Domain(points, vertices)

        #Flat surface with 1m of water
        domain.set_quantity('elevation', 0)
        domain.set_quantity('stage', 1.0)
        domain.set_quantity('friction', 0)

        Br = Reflective_boundary(domain)
        domain.set_boundary({'exterior': Br})

        verbose = False

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        # Apply operator to these triangles
        indices = [0, 1, 3]
        factor = 10.0

        def main_rate(t):
            if t > 20:
                msg = 'Model time exceeded.'
                raise Modeltime_too_late, msg
            else:
                return 3.0 * t + 7.0

        default_rate = lambda t: 3 * t + 7


        operator = Rate_operator(domain, rate=main_rate, factor=factor, \
                      indices=indices, default_rate = default_rate)

        # Apply Operator
        domain.timestep = 2.0
        operator()

        t = operator.get_time()
        d = operator.get_timestep() * main_rate(t) * factor + 1
        stage_ex = [d, d, 1., d]

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.fractional_step_volume_integral,
                            ((d - 1.) * domain.areas[indices]).sum())

        domain.set_starttime(30.0)
        domain.timestep = 1.0
        operator()

        t = operator.get_time()
        d = operator.get_timestep() * default_rate(t) * factor + d
        stage_ex = [d, d, 1., d]

        if verbose:
            print domain.quantities['elevation'].centroid_values
            print domain.quantities['stage'].centroid_values
            print domain.quantities['xmomentum'].centroid_values
            print domain.quantities['ymomentum'].centroid_values

        assert num.allclose(domain.quantities['stage'].centroid_values,
                            stage_ex)
        assert num.allclose(domain.quantities['xmomentum'].centroid_values,
                            0.0)
        assert num.allclose(domain.quantities['ymomentum'].centroid_values,
                            0.0)