Example #1
1
def do_padding(img, padding):
    if not padding:
        return img
    try:
        padding = float(padding)*2.0
        if padding > .9:
            padding = .9
        if padding <= 0.0:
            return img
    except ValueError:
        return

    iw, ih = img.size

    img.thumbnail(
        (
            int( round( float(img.size[0]) * (1.0 - padding) ) ),
            int( round( float(img.size[1]) * (1.0 - padding) ) )
        ),
        pil.ANTIALIAS
        )

    img = do_fill(img, "ffffff00", iw, ih)

    return img
Example #2
0
def makeFoldTable(annotFile,analysisName,testName,controlName,testMMR,controlMMR,testIdxFile,controlIdxFile,outputFolder,epsilon = 1):

    '''
    makes the fold table and writes to disk
    fold table is ranked by fold change
    first column is guideID, second column is gene name, third is fold change
    '''

    guideDict,geneDict = makeAnnotDict(annotFile)

    testIdx = utils.parseTable(testIdxFile,'\t')
    controlIdx = utils.parseTable(controlIdxFile,'\t')

    #for each guide, divide the count by the MMR then add 1 then take the log2 ratio

    outTable = [['GUIDE_ID','GENE','LOG2_RATIO',testName,controlName]]
    for i in range(len(testIdx)):

        guideID = testIdx[i][0]
        gene = guideDict[guideID]
        
        testCount = float(testIdx[i][2])/testMMR + epsilon
        controlCount = float(controlIdx[i][2])/controlMMR + epsilon

        log2Ratio = numpy.log2(testCount/controlCount)

        newLine = [guideID,gene,log2Ratio,round(testCount,4),round(controlCount,4)]

        outTable.append(newLine)

    outputFile = '%s%s_log2Ratio.txt' % (outputFolder,analysisName)
    utils.unParseTable(outTable,outputFile,'\t')
    return outputFile
    def load_small_box_image(self):
        '''
        It will load the truck image, that will be used
        for displaying the current vehicles.
        '''

        box_width_meters = 32.*0.3
        box_length_meters = 32.*0.4

        box_image = pygame.image.load('resources/waterOffset.png')

        (box_image_width, box_image_height) = box_image.get_size()

        [x_pixel_1, y_pixel_1] = self.convert_position_to_image_pixel(0, 0)
        [x_pixel_2, y_pixel_2] = self.convert_position_to_image_pixel(box_length_meters, 0)

        desired_box_width_pixels = float(x_pixel_2 - x_pixel_1)

        scale_down_ratio = desired_box_width_pixels/(box_image_width/2.)

        new_size = (int(round(scale_down_ratio*box_image_width)), int(round(scale_down_ratio*box_image_height)))

        box = pygame.transform.smoothscale(box_image,new_size)

        self.small_box_image = box

        return
Example #4
0
 def test_sampling_custom_dist(self):
     my_custom_dist = [[0.2, 3.7], [0.5, 3.8], [0.3, 4.1]]
     params = {
         'Arrival_distributions': [['Custom', my_custom_dist]],
         'Service_distributions': [['Custom', my_custom_dist]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nc = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 4.1)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 4.1)
     self.assertEqual(round(
         Nc.simulation.service_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 4.1)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.8)
     self.assertEqual(round(
         Nc.simulation.inter_arrival_times[Nc.id_number][0](), 2), 3.7)
    def __testIGE_BrokerImpl(self, quantity):
        initialCash = 42.09*quantity
        # This testcase is based on an example from Ernie Chan's book:
        # 'Quantitative Trading: How to Build Your Own Algorithmic Trading Business'
        barFeed = yahoofeed.Feed()
        barFeed.addBarsFromCSV("ige", common.get_data_file_path("sharpe-ratio-test-ige.csv"))
        strat = strategy_test.TestStrategy(barFeed, initialCash)
        strat.setUseAdjustedValues(True)
        strat.setBrokerOrdersGTC(True)
        stratAnalyzer = drawdown.DrawDown()
        strat.attachAnalyzer(stratAnalyzer)

        # Disable volume checks to match book results.
        strat.getBroker().getFillStrategy().setVolumeLimit(None)

        # Manually place the order to get it filled on the first bar.
        order = strat.getBroker().createMarketOrder(broker.Order.Action.BUY, "ige", quantity, True)  # Adj. Close: 42.09
        order.setGoodTillCanceled(True)
        strat.getBroker().placeOrder(order)
        strat.addOrder(datetime.datetime(2007, 11, 13), strat.getBroker().createMarketOrder, broker.Order.Action.SELL, "ige", quantity, True)  # Adj. Close: 127.64
        strat.run()

        self.assertTrue(round(strat.getBroker().getCash(), 2) == initialCash + (127.64 - 42.09) * quantity)
        self.assertEqual(strat.orderUpdatedCalls, 4)
        self.assertTrue(round(stratAnalyzer.getMaxDrawDown(), 5) == 0.31178)
        self.assertTrue(stratAnalyzer.getLongestDrawDownDuration() == datetime.timedelta(days=623))
Example #6
0
 def test_sampling_gamma_dist(self):
     params = {
         'Arrival_distributions': [['Gamma', 0.6, 1.2]],
         'Service_distributions': [['Gamma', 0.6, 1.2]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Ng = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 0.00)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 2.59)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 1.92)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 0.47)
     self.assertEqual(round(
         Ng.simulation.service_times[Ng.id_number][0](), 2), 0.61)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 0.00)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 1.07)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 1.15)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 0.75)
     self.assertEqual(round(
         Ng.simulation.inter_arrival_times[Ng.id_number][0](), 2), 0.00)
Example #7
0
 def test_sampling_weibull_dist(self):
     params = {
         'Arrival_distributions': [['Weibull', 0.9, 0.8]],
         'Service_distributions': [['Weibull', 0.9, 0.8]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nw = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 0.87)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 1.31)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 1.60)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 3.34)
     self.assertEqual(round(
         Nw.simulation.service_times[Nw.id_number][0](), 2), 1.31)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 2.91)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 0.01)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 0.50)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 3.36)
     self.assertEqual(round(
         Nw.simulation.inter_arrival_times[Nw.id_number][0](), 2), 0.95)
Example #8
0
	def setXYScale (self, oriWidth, oriHeight,newWidth,newHeight):
		#self.oriWidth = oriWidth
		#self.oriHeight = oriHeight
		#self.newWidth = newWidth
		#self.newHeight = nnewHeight
	    self.transX = int(round(oriWidth/newWidth *1000))/1000.0
	    self.transY = int(round(oriHeight/newHeight*1000))/1000.0
    def _str(self, i, x):
        """Handles string formatting of cell data

            i - index of the cell datatype in self._dtype 
            x - cell data to format
        """
        try:
            f = float(x)
        except:
            return str(x)

        n = self._precision
        dtype = self._dtype[i]

        if dtype == 'i':
            return str(int(round(f)))
        elif dtype == 'f':
            return '%.*f' % (n, f)
        elif dtype == 'e':
            return '%.*e' % (n, f)
        elif dtype == 't':
            return str(x)
        else:
            if f - round(f) == 0:
                if abs(f) > 1e8:
                    return '%.*e' % (n, f)
                else:
                    return str(int(round(f)))
            else:
                if abs(f) > 1e8:
                    return '%.*e' % (n, f)
                else:
                    return '%.*f' % (n, f)
def findPointOnSphere(cx, cy, cz, radius, phi, theta):
    #phi - angle around the pole 0<= phi <= 360
    #theta - angle from plan 'up' -90 <= theta <= 90
    x = cx + radius * math.cos(math.radians(theta)) * math.cos(math.radians(phi))
    z = cz + radius * math.cos(math.radians(theta)) * math.sin(math.radians(phi))
    y = cy + radius * math.sin(math.radians(theta))
    return int(round(x,0)), int(round(y,0)), int(round(z,0))
    def update(self):
        #Update the Bullet, should be called once per 'tick'
        # calculate new y velocity
        self.ticks += 1
        self.yVelocity = self.yStartVelocity + self.gravity * self.ticks
        
        # find the bullets new position
        newPos = minecraft.Vec3(self.currentPos.x + self.xVelocity,
                                self.startPos.y + (self.yStartVelocity * self.ticks + 0.5 * (self.gravity * pow(self.ticks,2))),
                                self.currentPos.z + self.zVelocity)
        #Has the bullet moved from its last drawn position
        # round the new position and compare it to the last drawn
        newDrawPos = minecraft.Vec3(int(round(newPos.x, 0)),
                                    int(round(newPos.y, 0)),
                                    int(round(newPos.z, 0)))
        movedBullet = True
        if matchVec3(newDrawPos, self.drawPos) == False:
            # if the bullet is moving to a block of air, move it, otherwise explode
            if self.mc.getBlock(newDrawPos.x, newDrawPos.y, newDrawPos.z) == block.AIR:
                # clear the last drawn bullet
                self.clear()
                # move the draw position
                self.drawPos = minecraft.Vec3(newDrawPos.x, newDrawPos.y, newDrawPos.z)
                # draw the bullet
                self.draw()
            else:
                #exploded
                self.mcDrawing.drawSphere(newDrawPos, self.blastRadius, block.AIR)
                movedBullet = False
        #Update the current position
        self.currentPos = newPos

        return movedBullet
 def test_calculatePowerCoefficients(self):
     radius = 35.5
     self.pcPadded.calculatePowerCoefficients(radius)
     windSpeed = 10
     availablePower = 0.5 * pi * np.power(radius, 2) * np.power(windSpeed, 3) * 1.225
     self.assertEqual(round(self.pcPadded.data.ix[20, 'powerCoefficient'], 2),
                      round(self.pcPadded.data.ix[20, 'powerInKilowatts'] * 1000 / availablePower, 2))
def gradient_check_em():
    init_theta = initialize_theta(None)
    f_approx = {}
    for f in feature_index:
        theta_plus = copy.deepcopy(init_theta)
        theta_minus = copy.deepcopy(init_theta)
        theta_plus[feature_index[f]] = init_theta[feature_index[f]] + EPS
        get_likelihood(theta_plus)  # updates fractional counts
        val_plus = get_likelihood_with_expected_counts(theta_plus)
        theta_minus[feature_index[f]] = init_theta[feature_index[f]] - EPS
        get_likelihood(theta_minus)  # updates fractional counts
        val_minus = get_likelihood_with_expected_counts(theta_minus)
        f_approx[f] = (val_plus - val_minus) / (2 * EPS)

    my_grad = get_gradient(init_theta)
    diff = []
    for k in sorted(f_approx):
        diff.append(abs(my_grad[feature_index[k]] - f_approx[k]))
        print str(round(my_grad[feature_index[k]] - f_approx[k], 3)).center(10), str(
            round(my_grad[feature_index[k]], 5)).center(10), \
            str(round(f_approx[k], 5)).center(10), k
    f_approx = sorted([(feature_index[k], v) for k, v in f_approx.items()])
    f_approx = np.array([v for k, v in f_approx])

    print 'component difference:', round(sum(diff), 3), \
        'cosine similarity:', utils.cosine_sim(f_approx, my_grad), \
        ' sign difference', utils.sign_difference(f_approx, my_grad)
Example #14
0
def Discretdata(data):
    '''
    :param data: DATA FRAME style
    :return: new discreted data
    '''
    import pandas as pd
    from pandas import DataFrame
    import numpy as np

    thres_matrix=data.describe()
    xlen=thres_matrix.shape[1]
    ylen=thres_matrix.shape[0]
    for i in xrange(data.shape[1]):
        x=data.ix[:,i].values
        for j,value in enumerate(x):
            if value > round(thres_matrix.ix[6,i]):
                x[j]=4
            elif value >round(thres_matrix.ix[5,i]):
                x[j]=3
            elif value >round(thres_matrix.ix[4,i]):
                x[j]=2
            elif value >round(thres_matrix.ix[3,i]):
                x[j]=1
            else:
                x[j]=0
    return x
Example #15
0
 def test_sampling_uniform_dist(self):
     params = {
         'Arrival_distributions': [['Uniform', 2.2, 3.3]],
         'Service_distributions': [['Uniform', 2.2, 3.3]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nu = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 2.89)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.02)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.07)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.24)
     self.assertEqual(round(
         Nu.simulation.service_times[Nu.id_number][0](), 2), 3.01)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 3.21)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 2.23)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 2.71)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 3.24)
     self.assertEqual(round(
         Nu.simulation.inter_arrival_times[Nu.id_number][0](), 2), 2.91)
Example #16
0
    def draw_cb(self, canvas, tag):
        obj = canvas.getObjectByTag(tag)
        if obj.kind != 'point':
            return True
        canvas.deleteObjectByTag(tag, redraw=False)

        if self.pxdqtag:
            try:
                canvas.deleteObjectByTag(self.pxdqtag, redraw=False)
            except:
                pass

        # Round to nearest pixel
        x, y = round(obj.x), round(obj.y)
        obj.move_to(x, y)

        # Change bad pix region appearance
        obj.radius = self._point_radius

        # Text label
        yt = y + self._text_label_offset
        obj_lbl = self.dc.Text(
            x, yt, self._text_label, color=self.pxdqcolor)

        # Update displayed values
        self.xcen = x
        self.ycen = y

        self.pxdqtag = canvas.add(self.dc.CompoundObject(obj, obj_lbl))
        return self.redo()
Example #17
0
 def test_sampling_exponential_dist(self):
     params = {
         'Arrival_distributions': [['Exponential', 4.4]],
         'Service_distributions': [['Exponential', 4.4]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Ne = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.22)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.31)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.36)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.65)
     self.assertEqual(round(
         Ne.simulation.service_times[Ne.id_number][0](), 2), 0.31)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.58)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.01)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.14)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.65)
     self.assertEqual(round(
         Ne.simulation.inter_arrival_times[Ne.id_number][0](), 2), 0.24)
Example #18
0
    def translate_selection(self, x, y, x0, y0):
        x, y = 10*round(x/10), 10*round(y/10)
        
        # survey conditions
        for frame in self:
            for point in chain(frame[0], frame[1]):
                if point[2]:
                    # do any of the points fall on another point?
                    if not frame.can_fall(point[0] + x - x0, point[1] + y - y0):
                        return

        for frame in self:
            for point in chain(frame[0], frame[1]):
                if point[2]:
                    point[:2] = [point[0] + x - x0, point[1] + y - y0]

            # check y alignment
            if frame[0][0][1] != frame[1][0][1]:
                # determine which should move
                if frame[0][0][2]:
                    flip = 1
                else:
                    flip = 0
                frame[flip][0][1] = frame[not flip][0][1]

            if frame[0][-1][1] != frame[1][-1][1]:
                # determine which should move
                if frame[0][-1][2]:
                    flip = 1
                else:
                    flip = 0
                frame[flip][-1][1] = frame[not flip][-1][1]
Example #19
0
 def test_sampling_lognormal_dist(self):
     params = {
         'Arrival_distributions': [['Lognormal', 0.8, 0.2]],
         'Service_distributions': [['Lognormal', 0.8, 0.2]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nl = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.62)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 1.64)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.19)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.31)
     self.assertEqual(round(
         Nl.simulation.service_times[Nl.id_number][0](), 2), 2.48)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.51)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.33)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 1.96)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.32)
     self.assertEqual(round(
         Nl.simulation.inter_arrival_times[Nl.id_number][0](), 2), 2.70)
Example #20
0
    def _label_iterations(self, lod):
        stroke_gradient = self.get_stroke_gradient()
        if lod == LOD.FULL and \
           self.get_style() != "flat" and stroke_gradient:
            root = self.get_layout_root()
            d = 0.4  # fake-emboss distance
            #d = max(src_size[1] * 0.02, 0.0)
            max_offset = 2

            alpha = self.get_gradient_angle()
            xo = root.context.scale_log_to_canvas_x(d * cos(alpha))
            yo = root.context.scale_log_to_canvas_y(d * sin(alpha))
            xo = min(int(round(xo)), max_offset)
            yo = min(int(round(yo)), max_offset)

            luminosity_factor = stroke_gradient * 0.25

            # shadow
            yield xo, yo, -luminosity_factor, False

            # highlight
            yield -xo, -yo, luminosity_factor, False

        # normal
        yield 0, 0, 0, True
Example #21
0
 def test_sampling_empirical_dist(self):
     my_empirical_dist = [8.0, 8.0, 8.0, 8.8, 8.8, 12.3]
     params = {
         'Arrival_distributions': [['Empirical',
             'ciw/tests/testing_parameters/sample_empirical_dist.csv']],
         'Service_distributions': [['Empirical', my_empirical_dist]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nem = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.8)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 12.3)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.0)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.0)
     self.assertEqual(round(
         Nem.simulation.service_times[Nem.id_number][0](), 2), 8.0)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.7)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.7)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.1)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.1)
     self.assertEqual(round(
         Nem.simulation.inter_arrival_times[Nem.id_number][0](), 2), 7.7)
Example #22
0
    def testMetaDataHandleForSavingModel(self):
        """Test the handling of SaveModel for Data with Meta Atributes
        """

        #Test the save of a model created from a train data with meta attributes
        self.assert_(len(self.WMetaTest.domain.getmetas())>=1,"The dataset WMetaTest should have Meta Attributes")
        plsM = AZorngPLS.PLSLearner(self.WMetaTest)
        AccNoMetaBefore = evalUtilities.getClassificationAccuracy(self.NoMetaTrain,plsM) 
        AccWMetaBefore = evalUtilities.getClassificationAccuracy(self.WMetaTest,plsM)


        # Save the model 
        scratchdir = os.path.join(AZOC.SCRATCHDIR, "scratchdir"+str(time.time()))
        os.mkdir(scratchdir)
        modelPath = os.path.join(scratchdir,"PLSModel")
        plsM.write(modelPath)

        # Read in the model
        plsR = AZorngPLS.PLSread(modelPath)
        self.assert_(len(plsR.imputer.defaults.domain.getmetas())==0,"There shouldn't be any Meta data now!")

        # Calculate classification accuracy 
        AccNoMetaAfter = evalUtilities.getClassificationAccuracy(self.NoMetaTrain, plsR)
        AccWMetaAfter = evalUtilities.getClassificationAccuracy(self.WMetaTest, plsR)

        # Test that the accuracy of the model before and after saved
        self.assertEqual(AccNoMetaBefore, AccNoMetaAfter,"NoMeta: Predictions after loading saved model were different")
        self.assertEqual(AccWMetaBefore, AccWMetaAfter, "WMeta: Predictions after loading saved model were different")
        self.assertEqual(round(AccWMetaAfter,9), round(0.888888888889,9),"Accuracy was not the expected value!")
        self.assertEqual(round(AccNoMetaAfter,9), round(0.605769230769,9),"Accuracy was not the expected value!")
 
        # Remove the scratch directory
        os.system("/bin/rm -rf "+scratchdir)
Example #23
0
  def onInputVolumeChanged( self ):
    '''
    '''
    if not self.__updating:

        self.__updating = 1

        SlicerVmtkCommonLib.Helper.Debug( "onInputVolumeChanged" )

        # reset the thresholdSlider
        self.__thresholdSlider.minimum = 0
        self.__thresholdSlider.maximum = 100
        self.__thresholdSlider.minimumValue = 0
        self.__thresholdSlider.maximumValue = 100

        currentNode = self.__inputVolumeNodeSelector.currentNode()

        if currentNode:

            v = self.selectVesselnessVolume()

            # if we have a vesselnessNode, we will configure the threshold slider for it instead of the original image
            # if not, the currentNode is the input volume
            if v:
                SlicerVmtkCommonLib.Helper.Debug( "Using Vesselness volume to configure thresholdSlider.." )
                currentNode = v

            currentImageData = currentNode.GetImageData()
            currentDisplayNode = currentNode.GetDisplayNode()

            if currentImageData:
                currentScalarRange = currentImageData.GetScalarRange()
                minimumScalarValue = round( currentScalarRange[0], 0 )
                maximumScalarValue = round( currentScalarRange[1], 0 )
                self.__thresholdSlider.minimum = minimumScalarValue
                self.__thresholdSlider.maximum = maximumScalarValue

                # if the image has a small scalarRange, we have to adjust the singleStep
                if maximumScalarValue <= 10:
                    self.__thresholdSlider.singleStep = 0.1

                if currentDisplayNode:

                    if currentDisplayNode.GetApplyThreshold():

                        # if a threshold is already applied, use it!
                        self.__thresholdSlider.minimumValue = currentDisplayNode.GetLowerThreshold()
                        self.__thresholdSlider.maximumValue = currentDisplayNode.GetUpperThreshold()

                    else:

                        # don't use a threshold, use the scalar range
                        SlicerVmtkCommonLib.Helper.Debug( "Reset thresholdSlider's values." )
                        self.__thresholdSlider.minimumValue = minimumScalarValue
                        self.__thresholdSlider.maximumValue = maximumScalarValue




        self.__updating = 0
Example #24
0
def main():
    print("Code to look at runtime for insertion sort vs. Python's list sort.")
    
    numDig = 5 #number of digits to output
    
    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    print("\nSorting list with " + str(len(data)) + " elements.\n")
    
    start = time.time()
    insertionSort(data)
    end = time.time()
    print("Insertion sort -> " + str(round(end - start, numDig)) + " seconds.")

    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    start = time.time()
    data.sort()
    end = time.time()
    print("Python's sort -> " + str(round(end - start, numDig)) + " seconds.")
def updateProgress(percent, barLength = 20):
	"""Update progress bar in command line"""
	hashes = '#' * int(round(percent * barLength / 100 ))
	spaces = ' ' * (barLength - len(hashes))
	
	sys.stdout.write("\rGenerating ... [{0}] {1}%".format(hashes + spaces, int(round(percent))))
	sys.stdout.flush()
Example #26
0
 def test_sampling_deterministic_dist(self):
     params = {
         'Arrival_distributions': [['Deterministic', 4.4]],
         'Service_distributions': [['Deterministic', 4.4]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nd = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.service_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
     self.assertEqual(round(
         Nd.simulation.inter_arrival_times[Nd.id_number][0](), 2), 4.40)
Example #27
0
def create_cube_request(modelname, px, py, pz, rr, rp, ry, sx, sy, sz):
    """Create a SpawnModelRequest with the parameters of the cube given.
    modelname: name of the model for gazebo
    px py pz: position of the cube (and it's collision cube)
    rr rp ry: rotation (roll, pitch, yaw) of the model
    sx sy sz: size of the cube"""
    cube = deepcopy(sdf_cube)
    # Replace size of model
    size_str = str(round(sx, 3)) + " " + \
        str(round(sy, 3)) + " " + str(round(sz, 3))
    cube = cube.replace('SIZEXYZ', size_str)
    # Replace modelname
    cube = cube.replace('MODELNAME', str(modelname))

    req = SpawnModelRequest()
    req.model_name = modelname
    req.model_xml = cube
    req.initial_pose.position.x = px
    req.initial_pose.position.y = py
    req.initial_pose.position.z = pz

    q = quaternion_from_euler(rr, rp, ry)
    req.initial_pose.orientation.x = q[0]
    req.initial_pose.orientation.y = q[1]
    req.initial_pose.orientation.z = q[2]
    req.initial_pose.orientation.w = q[3]

    return req
Example #28
0
 def test_sampling_triangular_dist(self):
     params = {
         'Arrival_distributions': [['Triangular', 1.1, 6.6, 1.5]],
         'Service_distributions': [['Triangular', 1.1, 6.6, 1.5]],
         'Number_of_servers': [1],
         'Transition_matrices': [[0.1]]
     }
     Q = ciw.Simulation(ciw.create_network(params))
     Nt = Q.transitive_nodes[0]
     ciw.seed(5)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 3.35)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 3.91)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 4.20)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 5.33)
     self.assertEqual(round(
         Nt.simulation.service_times[Nt.id_number][0](), 2), 3.90)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 5.12)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 1.35)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 2.73)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 5.34)
     self.assertEqual(round(
         Nt.simulation.inter_arrival_times[Nt.id_number][0](), 2), 3.46)
    def load_goal_image(self):
        '''
        It will load the truck image, that will be used
        for displaying the current vehicles.
        '''

        box_width_meters = 32.*0.2
        box_length_meters = 32.*0.2

        flag_image = pygame.image.load('resources/finishFlag.png')

        (flag_image_width, flag_image_height) = flag_image.get_size()

        [x_pixel_1, y_pixel_1] = self.convert_position_to_image_pixel(0, 0)
        [x_pixel_2, y_pixel_2] = self.convert_position_to_image_pixel(box_length_meters, 0)

        desired_box_width_pixels = float(x_pixel_2 - x_pixel_1)

        scale_down_ratio = desired_box_width_pixels/(flag_image_width/2.)

        new_size = (int(round(scale_down_ratio*flag_image_width)), int(round(scale_down_ratio*flag_image_height)))

        flag = pygame.transform.smoothscale(flag_image,new_size)

        self.goal_image = flag

        return
Example #30
0
def McDonalds():
    
    url = request.urlopen("http://apps.mcdonalds.se/sweden/restSite.nsf/markers?readForm")
    data = url.read().decode('utf-8')
    markers = json.loads(data)['markers']
    
    for m in markers:
        if m['vanityname'].startswith('mcdonalds'):
            
            hours = []
            
            for h in m['openhours']:
                if h == "always,1":
                    hours.append(("00:00", "24:00"))
                else:
                    hours.append(h.split(","))
            
            name = cleanupName(m['vanityname'])
            
            yield {
                'name': name,
                'title': nameToTitle(name),
                'type': 'restaurant',
                'lat': round(float(m['lat']) * 1E6),
                'lon': round(float(m['lng']) * 1E6),
                'hours': hours
            }