Example #1
1
File: views.py Project: mv/nagcat
def getColors(names):
    rng_state = random.getstate()

    n = len(names)
    colors = []
    offset = 0
    for i in range(n):
        random.seed(names[i])
        # Make a random color
        h = 360 * ((float(i) / n + offset) % 1)
        s = 0.6 + 0.4 * random.random()
        l = 0.375 + 0.25 * random.random()

        # convert it from HSL to RGB
        c = (1 - abs(2 * l - 1)) * s
        hp = floor(h / 60)
        x = c * (1 - abs(hp % 2 - 1))
        (rp, gp, bp) = {0: (c, x, 0), 1: (x, c, 0), 2: (0, c, x), 3: (0, x, c), 4: (x, 0, c), 5: (c, 0, x)}[hp]

        m = l - 0.5 * c
        r, g, b = [x * 256 for x in (rp + m, gp + m, bp + m)]

        # Convert it to a hex color
        colors.append("#%02x%02x%02x" % (r, g, b))

    random.setstate(rng_state)

    return colors
 def get_needle(self, center):
     needle_height, needle_width = self.needle_im.shape
     needle_top_left_x = 0
     needle_top_left_y = 0
     needle_bottom_right_x = needle_width
     needle_bottom_right_y = needle_height
     top_left_x = center[0] - self.needle_center[0]
     if top_left_x < 0:
         needle_top_left_x = abs(top_left_x)
         top_left_x = 0
     top_left_y = center[1] - self.needle_center[1]
     if top_left_y < 0:
         needle_top_left_y = abs(top_left_y)
         top_left_y = 0
     bottom_right_x = top_left_x + needle_width
     if bottom_right_x > DEF.WIDTH:
         needle_bottom_right_x = needle_bottom_right_x - (bottom_right_x - DEF.WIDTH)
         bottom_right_x = DEF.WIDTH
     bottom_right_y = top_left_y + needle_height
     if bottom_right_y > DEF.HEIGHT:
         needle_bottom_right_y = needle_bottom_right_y - (bottom_right_y - DEF.HEIGHT)
         bottom_right_y = DEF.HEIGHT
     self.needle_canvas[top_left_y:bottom_right_y, top_left_x:bottom_right_x] = self.rotated[
         needle_top_left_y:needle_bottom_right_y, needle_top_left_x:needle_bottom_right_x
     ]
    def _DistributedCashbotBossObject__watchDrift(self, task):
        v = self.physicsObject.getVelocity()
        if abs(v[0]) < 0.0001 and abs(v[1]) < 0.0001:
            self.d_requestFree()
            self.demand("Free")

        return Task.cont
Example #4
1
def shotMain(vals, bline, eline, element_size, line_size, filter_diff):
    """ the actual shot filter code - needs to be separate as clean filter calls it as well """
    for i in range(line_size)[bline:eline]:
        for j in range(element_size)[1:-2]:
            left = vals[0][i * element_size + j - 1]
            value = vals[0][i * element_size + j]
            right = vals[0][i * element_size + j + 2]

            left_diff = value - left
            right_diff = value - right
            sign = left_diff * right_diff
            if sign < 0:
                continue

            left_diff = abs(left_diff)
            if left_diff < filter_diff:
                continue

            right_diff = abs(right_diff)
            if right_diff < filter_diff:
                continue

            """ for some reason, have to do this to floor the value """
            p = (left + right) / 2
            a = field((p,))
            b = a.floor().getValues(0)
            vals[0][i * element_size + j] = b[0]

    return vals
Example #5
1
 def getPlayersInRange(self, max_range=200):
     playersInRange = []
     for player in self.server.get_players():
         x, y, z = player.x, player.y, player.z
         if abs(x - self.x) < max_range and abs(z - self.z) < max_range:
             playersInRange.append(player)
     return playersInRange
    def doubleJetAve(self, jets, probeCentral=False, etaProbeLimit=2.7):
        maxThr = 0.0
        ptmin = 10.0
        for i in xrange(jets.size()):
            ptI = jets.at(i).pt()
            if ptI < ptmin:
                continue

            etaI = abs(jets.at(i).eta())
            if etaI > 1.4:
                continue
            for j in xrange(0, jets.size()):
                if i == j:
                    continue

                ptJ = jets.at(j).pt()
                if ptJ < ptmin:
                    continue

                etaJ = abs(jets.at(j).eta())
                if not probeCentral:
                    if etaJ < etaProbeLimit:
                        continue
                else:
                    if etaJ > etaProbeLimit:
                        continue
                dphi = abs(ROOT.Math.VectorUtil.DeltaPhi(jets.at(j), jets.at(i)))
                if dphi < 2.5:
                    continue

                ptAve = (ptI + ptJ) / 2.0
                if ptAve > maxThr:
                    maxThr = ptAve

        return maxThr
Example #7
1
def lm_to_radec(ra0, dec0, l, m):
    # This function should be the inverse of radec_to_lmn, but it is
    # not. There is likely an error here.

    sind0 = math.sin(dec0)
    cosd0 = math.cos(dec0)
    dl = l
    dm = m
    d0 = dm * dm * sind0 * sind0 + dl * dl - 2 * dm * cosd0 * sind0
    sind = math.sqrt(abs(sind0 * sind0 - d0))
    cosd = math.sqrt(abs(cosd0 * cosd0 + d0))
    if sind0 > 0:
        sind = abs(sind)
    else:
        sind = -abs(sind)

    dec = math.atan2(sind, cosd)

    if l != 0:
        ra = math.atan2(-dl, (cosd0 - dm * sind0)) + ra0
    else:
        ra = math.atan2((1e-10), (cosd0 - dm * sind0)) + ra0

    # Calculate RA,Dec from l,m and phase center.  Note: As done in
    # Meqtrees, which seems to differ from l, m functions above.  Meqtrees
    # equation may have problems, judging from my difficulty fitting a
    # fringe to L4086 data.  Pandey's equation is now used in radec_to_lmn

    return (ra, dec)
Example #8
0
    def brentStep(self, ax, bx, cx, fitness, gen, dif):
        C = (3 - sqrt(5)) / 2
        R = 1 - C

        x0 = ax
        x3 = cx
        if abs(cx - bx) > abs(bx - ax):
            x1 = bx
            x2 = bx + C * (cx - bx)
        else:
            x2 = bx
            x1 = bx - C * (bx - ax)

        f1 = fitness(addGenotypes(gen, multiplyGenotype(dif, x1)))
        f2 = fitness(addGenotypes(gen, multiplyGenotype(dif, x2)))

        if f2 < f1:
            x0 = x1
            x1 = x2
            x2 = R * x1 + C * x3  # ;   % x2 = x1+c*(x3-x1)
            f1 = f2
            f2 = fitness(addGenotypes(gen, multiplyGenotype(dif, x2)))
        else:
            x3 = x2
            x2 = x1
            x1 = R * x2 + C * x0  # ;   % x1 = x2+c*(x0-x2)
            f2 = f1
            f1 = fitness(addGenotypes(gen, multiplyGenotype(dif, x1)))

        if f1 < f2:
            return [x0, x1, x2]
        else:
            return [x3, x2, x1]
def polint(xa, ya, x):
    n = len(xa)
    if not (len(xa) == len(ya)):
        print "Input x and y arrays must be same length"
        return "Error"
    # Set up auxiliary arrays
    c = Numeric.zeros(n, Numeric.Float)
    d = Numeric.zeros(n, Numeric.Float)
    c[:] = ya[:]
    d[:] = ya[:]
    # Find closest table entry
    ns = 0
    diff = abs(xa[0] - x)
    for i in range(n):
        difft = abs(xa[i] - x)
        if difft < diff:
            diff = difft
            ns = i
    y = ya[ns]
    for m in range(1, n):
        for i in range(n - m):
            ho = xa[i] - x
            hp = xa[i + m] - x
            w = c[i + 1] - d[i]
            c[i] = ho * w / (ho - hp)
            d[i] = hp * w / (ho - hp)
        if 2 * ns < (n - m):
            dy = c[ns]
        else:
            ns -= 1
            dy = d[ns]
        y += dy
        # You can also return dy as an error estimate. Here
        # to keep things simple, we just return y.
    return y
Example #10
0
    def test002_generator_one_scalar_output(self):
        # The test fails, because the `work-in-progress` ScanOp always runs in
        # place (even when told not to by DebugMode). As this op will change
        # soon, and it is in the sandbox and not for user consumption, the
        # error is marked as KnownFailure
        raise KnownFailureTest("Work-in-progress sandbox ScanOp is not fully " "functional yet")

        def f_pow2(x_tm1):
            return 2 * x_tm1

        for n_steps in [-1, 1, 5, -5]:
            state = theano.tensor.scalar("state")
            output, updates = scan_module.scan(
                f_pow2, [], state, [], n_steps=n_steps, truncate_gradient=-1, go_backwards=False
            )
            my_f = theano.function([state], output, updates=updates, allow_input_downcast=True)
            if abs(n_steps) == 1:
                assert (
                    len([x for x in my_f.maker.fgraph.toposort() if isinstance(x.op, scan_module.scan_op.ScanOp)]) == 0
                )

            rng = numpy.random.RandomState(utt.fetch_seed())
            state = rng.uniform()
            numpy_values = numpy.array([state * (2 ** (k + 1)) for k in xrange(abs(n_steps))])
            theano_values = my_f(state)
            assert numpy.allclose(numpy_values, theano_values)
Example #11
0
def si_weights_update(walking_weights, init_weights, alternatives, criteria, funcPrefCrit):
    EPS = 1e-5
    si_weights = [[[], []] for i in range(len(criteria))]
    si_rankings = [[[], []] for i in range(len(criteria))]
    si_firsts = [[[], []] for i in range(len(criteria))]
    si_diffs = [[[], []] for i in range(len(criteria))]
    for k in range(len(criteria)):
        if walking_weights[k][0] != 0:
            si_weights[k][0] = weights_update(init_weights, walking_weights[k][0] - EPS, k)
            si_ranking = rankingP2(alternatives, criteria, si_weights[k][0], funcPrefCrit)
            ind = sorted(range(len(si_ranking)), key=lambda k: si_ranking[k], reverse=True)
            si_rankings[k][0] = ind
            si_firsts[k][0] = ind[0]
            si_diffs[k][0] = 2 * abs(init_weights[k] - walking_weights[k][0])
            # print('--')
            # for i in ind:
            #     print(names[i])
        if walking_weights[k][1] != 1:
            si_weights[k][1] = weights_update(init_weights, walking_weights[k][1] + EPS, k)
            si_ranking = rankingP2(alternatives, criteria, si_weights[k][1], funcPrefCrit)
            ind = sorted(range(len(si_ranking)), key=lambda k: si_ranking[k], reverse=True)
            si_rankings[k][1] = ind
            si_firsts[k][1] = ind[0]
            si_diffs[k][1] = 2 * abs(init_weights[k] - walking_weights[k][1])
            # print('--')
            # for i in ind:
            #     print(names[i])

    return si_weights, si_rankings, si_firsts, si_diffs
Example #12
0
def offset_gamma():
    # Connect to a pre-existing cluster

    insurance = h2o.import_file(pyunit_utils.locate("smalldata/glm_test/insurance.csv"))

    insurance["offset"] = insurance["Holders"].log()

    from h2o.estimators.gbm import H2OGradientBoostingEstimator

    gbm = H2OGradientBoostingEstimator(distribution="gamma", ntrees=600, max_depth=1, min_rows=1, learn_rate=0.1)
    gbm.train(x=range(3), y="Claims", training_frame=insurance, offset_column="offset")

    predictions = gbm.predict(insurance)

    # Comparison result generated from harrysouthworth's gbm:
    # 	fit2 = gbm(Claims ~ District + Group + Age+ offset(log(Holders)) , interaction.depth = 1,n.minobsinnode = 1,shrinkage = .1,bag.fraction = 1,train.fraction = 1,
    #           data = Insurance, distribution ="gamma", n.trees = 600)
    # 	pr = predict(fit2, Insurance)
    # 	pr = exp(pr+log(Insurance$Holders))
    assert abs(-1.714958 - gbm._model_json["output"]["init_f"]) < 1e-5, "expected init_f to be {0}, but got {1}".format(
        -1.714958, gbm._model_json["output"]["init_f"]
    )
    assert abs(50.1087 - predictions.mean()) < 1e-2, "expected prediction mean to be {0}, but got {1}".format(
        50.1087, predictions.mean()
    )
    assert abs(0.9133843 - predictions.min()) < 1e-4, "expected prediction min to be {0}, but got {1}".format(
        0.9133843, predictions.min()
    )
    assert abs(392.6667 - predictions.max()) < 0.1, "expected prediction max to be {0}, but got {1}".format(
        392.6667, predictions.max()
    )
Example #13
0
def raytrace(start, end):
    g = gridsize
    dx = abs(end[0] - start[0])
    dy = abs(end[1] - start[1])
    x = start[0]
    y = start[1]
    n = 1 + int(dx) + int(dy)
    if end[0] > start[0]:
        x_inc = 1
    else:
        x_inc = -1
    if end[1] > start[1]:
        y_inc = 1
    else:
        y_inc = -1
    error = dx - dy
    dx *= 2
    dy *= 2

    toRet = []
    while n > 0:
        n -= 1
        toRet += [[x, y]]

        if error > 0:
            x += x_inc
            error -= dy
        else:
            y += y_inc
            error += dx
    return toRet
Example #14
0
    def test_default_diverging_vlims(self):

        p = mat._HeatMapper(self.df_norm, **self.default_kws)
        vlim = max(abs(self.x_norm.min()), abs(self.x_norm.max()))
        nt.assert_equal(p.vmin, -vlim)
        nt.assert_equal(p.vmax, vlim)
        nt.assert_true(p.divergent)
Example #15
0
def parse_side_effects(side_effect_file, label_file):
    label_to_cids, label_to_specific_cids, label_to_names = parse_labels(label_file)
    label_to_siderids, siderid_to_descriptions = parse_raw_side_effects(side_effect_file)
    pubchem_to_siderids = {}
    pubchem_to_names = {}
    for label, cids in label_to_cids.iteritems():
        for cid in cids:
            if cid == "":
                continue
            cid = "%s" % (abs(int(cid)) - 100000000)
            siderids = pubchem_to_siderids.setdefault(cid, set())
            if label in label_to_siderids:
                siderids |= label_to_siderids[label]
            if label in label_to_names:
                for name in label_to_names[label]:
                    pubchem_to_names.setdefault(cid, set()).add(name)
                # pubchem_specific_to_siderids = {}
    for label, cids in label_to_specific_cids.iteritems():
        for cid in cids:
            if cid == "":
                continue
            cid = "%s" % abs(int(cid))
            siderids = pubchem_to_siderids.setdefault(cid, set())
            # siderids = pubchem_specific_to_siderids.setdefault(cid, set())
            if label in label_to_siderids:
                siderids |= label_to_siderids[label]
            if label in label_to_names:
                for name in label_to_names[label]:
                    pubchem_to_names.setdefault(cid, set()).add(name)
    return pubchem_to_siderids, siderid_to_descriptions, pubchem_to_names
Example #16
0
 def tail(cls, fname, window):
     """Read last N lines from file fname."""
     if window <= 0:
         raise ValueError("invalid window value %r" % window)
     with cls.open(fname) as f:
         BUFSIZ = 1024
         # True if open() was overridden and file was opened in text
         # mode. In that case readlines() will return unicode strings
         # instead of bytes.
         encoded = getattr(f, "encoding", False)
         CR = "\n" if encoded else b"\n"
         data = "" if encoded else b""
         f.seek(0, os.SEEK_END)
         fsize = f.tell()
         block = -1
         exit = False
         while not exit:
             step = block * BUFSIZ
             if abs(step) >= fsize:
                 f.seek(0)
                 newdata = f.read(BUFSIZ - (abs(step) - fsize))
                 exit = True
             else:
                 f.seek(step, os.SEEK_END)
                 newdata = f.read(BUFSIZ)
             data = newdata + data
             if data.count(CR) >= window:
                 break
             else:
                 block -= 1
         return data.splitlines()[-window:]
Example #17
0
    def _turnLeft(self, radians, speed=0.2):
        speed = abs(speed)
        if radians < 0.0:
            speed = -1.0 * speed
            radians = -1.0 * radians
        radians = radians % math.pi
        velocity = geometry_msgs.msg.Twist()
        velocity.angular.z = speed
        # get current pose
        now = rospy.Time.now()
        self.listener.waitForTransform("base_footprint", "odom_combined", now, rospy.Duration(5.0))
        self.lock.acquire()
        (trans_start, rot_start) = (trans_end, rot_end) = self.listener.lookupTransform(
            "base_footprint", "odom_combined", rospy.Time(0)
        )
        # keep moving until rotation reached - since robot only rotates around z axis one can compare the w component of the quaternions to half the angle
        angle_turned = 0.0
        rot_start_inv = tf.transformations.quaternion_inverse(rot_start)
        while angle_turned < radians:

            self.base_vel_cmd_pub.publish(velocity)
            rospy.sleep(0.05)
            (trans_end, rot_end) = self.listener.lookupTransform("base_footprint", "odom_combined", rospy.Time(0))
            euler_angles = tf.transformations.euler_from_quaternion(
                tf.transformations.quaternion_multiply(rot_start_inv, rot_end)
            )
            angle_turned = abs(euler_angles[2])
        #            print "angle_turned", angle_turned
        self.lock.release()
Example #18
0
def scatter(x, y, equal=False, xlabel=None, ylabel=None, xinvert=False, yinvert=False):
    """
    Plot a scatter with simple formatting options
    """
    plt.scatter(x, y, 200, color=[0.3, 0.3, 0.3], edgecolors="white", linewidth=1, zorder=2)
    sns.despine()
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    if equal:
        plt.axes().set_aspect("equal")
        plt.plot([0, max([x.max(), y.max()])], [0, max([x.max(), y.max()])], color=[0.6, 0.6, 0.6], zorder=1)
        bmin = min([x.min(), y.min()])
        bmax = max([x.max(), y.max()])
        rng = abs(bmax - bmin)
        plt.xlim([bmin - rng * 0.05, bmax + rng * 0.05])
        plt.ylim([bmin - rng * 0.05, bmax + rng * 0.05])
    else:
        xrng = abs(x.max() - x.min())
        yrng = abs(y.max() - y.min())
        plt.xlim([x.min() - xrng * 0.05, x.max() + xrng * 0.05])
        plt.ylim([y.min() - yrng * 0.05, y.max() + yrng * 0.05])
    if xinvert:
        plt.gca().invert_xaxis()
    if yinvert:
        plt.gca().invert_yaxis()
Example #19
0
def compute_scale(min_, max_, logarithmic=False, order_min=None, min_scale=4, max_scale=20):
    """Compute an optimal scale between min and max"""
    if min_ == 0 and max_ == 0:
        return [0]
    if max_ - min_ == 0:
        return [min_]
    if logarithmic:
        log_scale = compute_logarithmic_scale(min_, max_, min_scale, max_scale)
        if log_scale:
            return log_scale
            # else we fallback to normal scalling
    order = round(log10(max(abs(min_), abs(max_)))) - 1
    if order_min is not None and order < order_min:
        order = order_min
    else:
        while (max_ - min_) / (10 ** order) < min_scale and (order_min is None or order > order_min):
            order -= 1
    step = float(10 ** order)
    while (max_ - min_) / step > max_scale:
        step *= 2.0
    positions = []
    position = round_to_scale(min_, step)
    while position < (max_ + step):
        rounded = round_to_scale(position, step)
        if min_ <= rounded <= max_:
            if rounded not in positions:
                positions.append(rounded)
        position += step
    if len(positions) < 2:
        return [min_, max_]
    return positions
def offset_gaussian():
    # Connect to a pre-existing cluster

    insurance = h2o.import_file(pyunit_utils.locate("smalldata/glm_test/insurance.csv"))

    insurance["offset"] = insurance["Holders"].log()

    from h2o.estimators.gbm import H2OGradientBoostingEstimator

    gbm = H2OGradientBoostingEstimator(ntrees=600, max_depth=1, min_rows=1, learn_rate=0.1, distribution="gaussian")
    gbm.train(x=range(3), y="Claims", training_frame=insurance, offset_column="offset")

    predictions = gbm.predict(insurance)

    # Comparison result generated from R's gbm:
    # 	fit2 <- gbm(Claims ~ District + Group + Age+ offset(log(Holders)) , interaction.depth = 1,n.minobsinnode = 1,
    #               shrinkage = .1,bag.fraction = 1,train.fraction = 1,
    #   data = Insurance, distribution ="gaussian", n.trees = 600)
    #   pg = predict(fit2, newdata = Insurance, type = "response", n.trees=600)
    #   pr = pg - - log(Insurance$Holders)
    assert abs(44.33016 - gbm._model_json["output"]["init_f"]) < 1e-5, "expected init_f to be {0}, but got {1}".format(
        44.33016, gbm._model_json["output"]["init_f"]
    )
    assert abs(1491.135 - gbm.mse()) < 1e-2, "expected mse to be {0}, but got {1}".format(1491.135, gbm.mse())
    assert abs(49.23438 - predictions.mean()[0]) < 1e-2, "expected prediction mean to be {0}, but got {1}".format(
        49.23438, predictions.mean()[0]
    )
    assert abs(-45.5720659304 - predictions.min()) < 1e-2, "expected prediction min to be {0}, but got {1}".format(
        -45.5720659304, predictions.min()
    )
    assert abs(207.387 - predictions.max()) < 1e-2, "expected prediction max to be {0}, but got {1}".format(
        207.387, predictions.max()
    )
Example #21
0
    def drag_pan(self, button, key, x, y):
        p = self._pan_start

        if p.mode == "drag_r_labels":
            startt, startr = p.trans_inverse.transform_point((p.x, p.y))
            t, r = p.trans_inverse.transform_point((x, y))

            # Deal with theta
            dt0 = t - startt
            dt1 = startt - t
            if abs(dt1) < abs(dt0):
                dt = abs(dt1) * sign(dt0) * -1.0
            else:
                dt = dt0 * -1.0
            dt = (dt / npy.pi) * 180.0

            rpad = self._r_label1_position.to_values()[5]
            self._r_label1_position.clear().translate(p.r_label_angle - dt, rpad)
            self._r_label2_position.clear().translate(p.r_label_angle - dt, -rpad)

        elif p.mode == "zoom":
            startt, startr = p.trans_inverse.transform_point((p.x, p.y))
            t, r = p.trans_inverse.transform_point((x, y))

            dr = r - startr

            # Deal with r
            scale = r / startr
            self.set_rmax(p.rmax / scale)
Example #22
0
    def emit_regex_code(self):
        for regex, matcher in self.matchers.iteritems():
            with self.block("def _regex%s(self):" % (abs(hash(regex)),)):
                c = self.choice_point()
                self.emit("_runner = self._Runner(self._inputstream, self._pos)")
                self.emit("_i = _runner.recognize_%s(self._pos)" % (abs(hash(regex)),))
                self.start_block("if _runner.last_matched_state == -1:")
                self.revert(c)
                self.emit("raise BacktrackException")
                self.end_block("if")
                self.emit("_upto = _runner.last_matched_index + 1")
                self.emit("_pos = self._pos")
                self.emit("assert _pos >= 0")
                self.emit("assert _upto >= 0")
                self.emit("_result = self._inputstream[_pos: _upto]")
                self.emit("self._pos = _upto")
                self.emit("return _result")

        with self.block("class _Runner(object):"):
            with self.block("def __init__(self, text, pos):"):
                self.emit("self.text = text")
                self.emit("self.pos = pos")
                self.emit("self.last_matched_state = -1")
                self.emit("self.last_matched_index = -1")
                self.emit("self.state = -1")
            for regex, matcher in self.matchers.iteritems():
                matcher = str(matcher).replace(
                    "def recognize(runner, i)", "def recognize_%s(runner, i)" % (abs(hash(regex)),)
                )
                self.emit(str(matcher))
Example #23
0
def simulateGenerations(n, participants, seats, populationSize):
    """
  Returns best reached solution. Simulates n generations, with given participants and available seats.
  Each generation has populationSize amount of solutions
  """
    gen = genRandomGeneration(participants, populationSize)
    c = 0
    best = (0, [])
    scores = []
    generationsWithoutImprovement = 0
    while c < n:
        gen = getFitnessForGeneration(gen, participants, seats)
        g = reverseList(sorted(gen))

        if (abs(best[0] - g[0][0])) < 0.00000001:
            generationsWithoutImprovement += 1
        if g[0][0] > best[0]:
            best = g[0]
            generationsWithoutImprovement = 0
        if random.random() > 0.99:
            print "gen: " + str(c)
        gen = breedAnotherGeneration(gen, participants)
        c += 1
        scores.append(
            {
                "participant_count": len(participants),
                "population_size": populationSize,
                "current_generation": c,
                "best_score": best[0],
            }
        )
        if (abs(best[0] - 1.0)) < 0.000000001:
            break
    print c
    return best, scores
Example #24
0
def test_example_03():
    set_verbose(False)

    mesh = Mesh()
    mesh.load(domain_mesh)
    mesh.refine_element(0)
    shapeset = H1Shapeset()
    pss = PrecalcShapeset(shapeset)

    # create an H1 space
    space = H1Space(mesh, shapeset)
    space.set_uniform_order(5)
    from hermes2d.examples.c03 import set_bc

    set_bc(space)
    space.assign_dofs()

    # initialize the discrete problem
    wf = WeakForm(1)
    set_forms(wf)

    solver = DummySolver()
    sys = LinSystem(wf, solver)
    sys.set_spaces(space)
    sys.set_pss(pss)

    # assemble the stiffness matrix and solve the system
    sln = Solution()
    sys.assemble()
    sys.solve_system(sln)
    assert abs(sln.l2_norm() - 0.25493) < 1e-4
    assert abs(sln.h1_norm() - 0.89534) < 1e-4
Example #25
0
    def _determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust):
        """Use some heuristics to set good defaults for colorbar and range."""
        calc_data = plot_data.data[~np.isnan(plot_data.data)]
        if vmin is None:
            vmin = np.percentile(calc_data, 2) if robust else calc_data.min()
        if vmax is None:
            vmax = np.percentile(calc_data, 98) if robust else calc_data.max()

        # Simple heuristics for whether these data should  have a divergent map
        divergent = ((vmin < 0) and (vmax > 0)) or center is not None

        # Now set center to 0 so math below makes sense
        if center is None:
            center = 0

        # A divergent map should be symmetric around the center value
        if divergent:
            vlim = max(abs(vmin - center), abs(vmax - center))
            vmin, vmax = -vlim, vlim
        self.divergent = divergent

        # Now add in the centering value and set the limits
        vmin += center
        vmax += center
        self.vmin = vmin
        self.vmax = vmax

        # Choose default colormaps if not provided
        if cmap is None:
            if divergent:
                self.cmap = "RdBu_r"
            else:
                self.cmap = cubehelix_palette(light=0.95, as_cmap=True)
        else:
            self.cmap = cmap
Example #26
0
    def factorize(self):
        """ factorize the filter into a minimal phase and maximal phase

        Returns
        -------

        (Fmin,Fmax) : tuple of filter
            Fmin : minimal phase filter
            Fmax : maximal phase filter
        """

        if self.fir:
            # selectionne les zeros interne et externe
            internal = np.where(abs(self.z) < 1)[0]
            external = np.where(abs(self.z) >= 1)[0]
            zi = self.z[internal]
            ze = self.z[external]

            Fmin = DF()
            Fmin.z = zi

            Fmax = DF()
            Fmax.z = ze

            return (Fmin, Fmax)
Example #27
0
 def simulate(self, ptcs):
     self.reset()
     self.ptcs = []
     smeared = []
     for gen_ptc in ptcs:
         ptc = pfsimparticle(gen_ptc)
         if ptc.pdgid() == 22:
             self.simulate_photon(ptc)
         elif abs(ptc.pdgid()) == 11:
             smeared_ptc = self.smear_electron(ptc)
             smeared.append(smeared_ptc)
             # self.simulate_electron(ptc)
         elif abs(ptc.pdgid()) == 13:
             smeared_ptc = self.smear_muon(ptc)
             smeared.append(smeared_ptc)
             # self.simulate_muon(ptc)
         elif abs(ptc.pdgid()) in [12, 14, 16]:
             self.simulate_neutrino(ptc)
         elif abs(ptc.pdgid()) > 100:  # TODO make sure this is ok
             if ptc.q() and ptc.pt() < 0.2:
                 # to avoid numerical problems in propagation
                 continue
             self.simulate_hadron(ptc)
         self.ptcs.append(ptc)
     self.pfsequence = PFSequence(self.ptcs, self.detector, self.logger)
     self.particles = copy.copy(self.pfsequence.pfreco.particles)
     self.particles.extend(smeared)
Example #28
0
 def didBulletHit(self, rect):
     if self.type == "cannon":
         if self.rect.colliderect(rect):
             return True
         else:
             return False
     elif self.type == "laser":
         if self.rect.centerx >= rect.left and self.rect.centerx <= rect.right:
             if self.direction == "up":
                 self.rect = pygame.Rect(
                     self.weaponSource.hullRect.centerx,
                     self.positionY,
                     self.size,
                     -(abs(self.weaponSource.hullRect.top) - (rect.bottom)),
                 )
             elif self.direction == "down":
                 self.rect = pygame.Rect(
                     self.weaponSource.hullRect.centerx,
                     self.positionY,
                     self.size,
                     -(abs(self.weaponSource.hullRect.bottom) - (rect.top)),
                 )
             return True
         else:
             return False
def dec(a, b):
    if 0 <= abs(a) / abs(b) <= 1:
        return a / b
    elif 0 <= abs(b) / abs(a) <= 1:
        return b / a
    else:
        return 0
Example #30
0
def psi_opt(det, to_min):
    vars = [theta, psi1, psi2, psi3, psi4]
    sympy_2_numpy = sympy_to_numpy(tuple(vars))
    deriv_sympy_func = diff_sympy_func(vars)
    n_det = sympy_2_numpy(-re(det))
    deriv_sympy = deriv_sympy_func(-re(det))
    deriv_numpy = lambda_out_array(map(lambda x: function_wrapper(sympy_2_numpy(x), 1), deriv_sympy), 1)

    def func_to_min(args):
        return function_wrapper(sympy_2_numpy(to_min), 1)(args).real

    def deriv_func_to_min(args):
        min_func = to_min
        res = lambda_out_array(map(lambda x: function_wrapper(sympy_2_numpy(x), 1), deriv_sympy_func(min_func)), 1)
        return res(args).real

    s = 0.5
    x0 = [np.pi / 3.0, s, s, s, s, s, s, s, s]
    psi_cons = complex_wrapper(lambda p: np.vdot(p[1:], p[1:]).real - 1, 1)
    psi_cons_deriv = array_stretcher(
        complex_wrapper(lambda x: [0, 2 * abs(x[1]), 2 * abs(x[2]), 2 * abs(x[3]), 2 * abs(x[4])], 1), 1
    )
    cons = {"type": "eq", "fun": psi_cons, "jac": psi_cons_deriv}
    res = minimize(func_to_min, x0, jac=False, constraints=cons, method="SLSQP", options={"disp": True})
    print res.x
    return res.x