Esempio n. 1
0
 def fitting(self,
             data,
             link="log",
             family=1,
             n=10000,
             loss_function="MLE",
             lr=4e-08):
     prob_dict = {1: Probability.poisson, 2: Probability.binominal}
     p = Probability_select(prob_dict[family])
     prob = p.prob
     link_dict = {
         "log": Link.log,
         "logit": Link.logit
     }  # "identity": Link.identity, "logit":Link.logit}
     l = Link_select(link_dict[link])
     link = l.link
     beta1 = np.random.random()
     beta2 = np.random.random()
     #beta2=0
     beta = np.array([beta1, beta2])
     if family == 1:
         prob_func = lambda b: self.poisson_curve(
             data[1], link(np.multiply(data[0], b[1]) + b[0]))
     if family == 2:
         prob_func = lambda b: self.binom_curve(
             data[1], link(data[0] * b[1] + b[0]), N=10)
     if loss_function == "MLE":
         p = 1
         lr = lr
         predicter = lambda b: self.likelihood_function(prob_func(b))
     elif loss_function == "LSE":
         lr = 5e-04
         p = -1
         data = self.standalization(data)
         print(data)
         predicter = lambda b: np.sum(
             (data[1] - link(data[0] * b[1] + b[0]))**2)
     grad = Gradient()
     bata, betalist = grad.steepest_discent(predicter,
                                            beta,
                                            n=n,
                                            p=p,
                                            lr=lr)
     a = lambda x: link(x * beta[1] + beta[0])
     r = self._Coef_deter(a, data)
     self.link = lambda x, b: link(x * b[1] + b[0])
     print("beta1:{} beta2:{}".format(beta[0], beta[1]))
     return a, betalist, r
Esempio n. 2
0
    def __init__(self):
        #self.id = random.uniform(0, 999999999)
        Rectangle.__init__(self)
        self.handler = Handler()
        self.magnetos = Magnetos()
        self.offset = Point()
        self.pivot = Point()
        self.selected = False
        self.resizing = False
        self.direction = NONE
        self.control = AUTOMATIC
        self.z = 0

        self.hints = False
        from ui.canvas import Canvas
        self.canvas = Canvas()
        self.handler.is_testing = self.canvas.is_testing

        self.dash = []
        self.thickness = 1.0

        self.fill_style = COLOR
        self.fill_color = Color(0.25, 0.25, 0.25, 0.25)
        self.stroke_color = Color(0.25, 0.25, 0.25, 1.0)
        self.gradient = Gradient()
Esempio n. 3
0
    def notmax_suppression(self):
        print(self.gradient_var.get())
        grad = Gradient(self.gradient_var.get())

        grad_matrix, ang_matrix = grad.gradient_analysis(self.blur_image)
        self.notmax_suppr_img = Image.fromarray(
            grad.notmax_suppression(grad_matrix, ang_matrix))
        self.notmax_suppr_image = ImageTk.PhotoImage(self.notmax_suppr_img)

        tk.Label(image=self.notmax_suppr_image).grid(row=0,
                                                     column=1,
                                                     rowspan=5)
        tk.Button(
            text='Сохранить',
            command=lambda: self.save_image(self.notmax_suppr_img)).place(
                x=250, y=27)
Esempio n. 4
0
    def gradient(self, path, numberOfIterations, learningRate):
        global current_step
        data = self.loadData(path)
        print("data_loaded")
        self.current_step = 0
        nextStepList = []
        firstStepGradient = Gradient(data)
        print("firstStepGradient done")
        coefficints = firstStepGradient.train(numberOfIterations, learningRate)
        print("train0")
        for movement in data:
            if firstStepGradient.sigmoidFunction(
                    firstStepGradient.prediction(coefficints, movement)) < 0.5:
                currentValue = 0
            else:
                currentValue = 1
            #print(currentValue)
            if currentValue == 0:
                movement.setAI_direction(1)
            else:
                nextStepList.append(movement)

        current_step = 1
        nextStepGradient = Gradient(nextStepList)
        coefficints = nextStepGradient.train(numberOfIterations, learningRate)
        print("train1")
        for movement in nextStepList:
            if nextStepGradient.sigmoidFunction(
                    nextStepGradient.prediction(coefficints, movement)) < 0.5:
                currentValue = 0
            else:
                currentValue = 1
            #print(currentValue)
            movement.setAI_direction(int(currentValue))

        for movement in data:
            print(movement.getAI_direction())
Esempio n. 5
0
def main():
	#pygame init
	pygame.mixer.pre_init(SAMPLE_RATE, BIT, CHANNELS, BUFFER_SIZE)
	pygame.init()
	pygame.display.set_mode((WIDTH, HEIGHT))
	pygame.display.set_caption('PyTone')

	#make background
	background = Gradient((WIDTH, HEIGHT), GRAD_START, GRAD_END)

	#path to medias
	path = 'media/'

	pygame.display.set_icon(pygame.image.load(path + 'petrol.png'))

	#intro duration in milliseconds
	duration = 4000

	#states
	intro = Intro(background, path, duration)
	menu = Menu(background, path)
	game = Game(background, path)
	instructions = Instructions(background, path)

	intro.run()

	#storing return value from menu
	running = True
	while running:
		option = menu.run()
		if option == NEW_GAME:
			option = game.run()

		elif option == INSTRUCTIONS:
			instructions.run()
		elif option == PRACTICE:
			#intro.run()
			game.set_practise(True)
			game.run()
			game.set_practise(False)

		#no elif here to make different states be able to quit as well
		if option == pygame.locals.QUIT:
			pygame.quit()
			running = False
Esempio n. 6
0
    def draw(self, context):
        ###context.save()
        radius = float(self.get_property("radius"))

        dash = list()
        context.set_dash(dash)
        context.set_line_width(1)

        if radius > (self.height / 2) or radius > (self.width / 2):
            if (self.height / 2) < (self.width / 2):
                radius = self.height / 2
            else:
                radius = self.width / 2

        context.move_to(self.x, self.y + radius)
        context.arc(self.x + radius, self.y + radius, radius, pi, -pi / 2)
        context.line_to(self.x + self.width - radius, self.y)
        context.arc(self.x + self.width - radius, self.y + radius, radius,
                    -pi / 2, 0)
        context.line_to(self.x + self.width, self.y + self.height - radius)
        context.arc(self.x + self.width - radius,
                    self.y + self.height - radius, radius, 0, pi / 2)
        context.line_to(self.x + radius, self.y + self.height)
        context.arc(self.x + radius, self.y + self.height - radius, radius,
                    pi / 2, pi)
        context.close_path()

        self.fill_style = GRADIENT  # DEBUG

        if self.fill_style == GRADIENT:
            self.set_gradient(
                Gradient(0, self.x, self.y, self.x + self.width, self.y))
            context.set_source(self.gradient.gradient)
        elif self.fill_style == COLOR:
            context.set_source_rgba(self.fill_color.red, self.fill_color.green,
                                    self.fill_color.blue,
                                    self.fill_color.alpha)
        context.fill_preserve()

        context.set_source_rgba(self.stroke_color.red, self.stroke_color.green,
                                self.stroke_color.blue,
                                self.stroke_color.alpha)
        context.stroke()
        Object.draw(self, context)
Esempio n. 7
0
def genFeatures():

    outPath = "./XNUG2TestData_3512133158_Image1334Concat.hdf"
    data = GetLabelledObject(outPath)
    rawDataObj = data.RawData
    lowRes = rawDataObj.LowResData
    hiRes = rawDataObj.HiResData
    EventLabels = data.Labels
    # decimate the high resolution data so it isnt impossible to plot
    # itll go from about 13 million points to 100K or so
    deciStep = 130
    hiForce = hiRes.force[::deciStep]
    lowForce = lowRes.force

    # construct a function which computes the derivative of hiRes.force with respect to hiRes.time
    gradient = Gradient(hiRes.force)

    # apply the gradient function to all data points in hiRes.time and print the computed derivatives
    print list(map(gradient.function, hiRes.time))
Esempio n. 8
0
 def set_gradient(self,
                  gradient=Gradient()):  #ToDo: by name and from Canvas!
     self.fill_style = GRADIENT
     self.gradient = gradient
Esempio n. 9
0
        reader = csv.DictReader(f_obj, delimiter=';')
        for line in reader:
            item = TTask12(int(line['ObjectId']), line['Alfa'], line['Beta'])
            item.load(0, line['I1'], line['Tau1'], line['Phi1'])
            item.load(1, line['I2'], line['Tau2'], line['Phi2'])
            item.load(2, line['I3'], line['Tau3'], line['Phi3'])
            item.load(3, line['I4'], line['Tau4'], line['Phi4'])            
            data.append(item)
    return data

def calcTask1(data, nju, phi, WriteLog=False, Idx=None):
    for item in data:
        if (Idx == None) or (item.Idx == Idx):
            item.calcRadiation(nju, phi, WriteLog)

def calcTask2(data, nju, phi, gradient, isAnalitic=True, WriteLog=False, Idx=None):
    for item in data:
        if (Idx == None) or (item.Idx == Idx):
            item.calcReflection(nju, phi, gradient, isAnalitic, WriteLog)

if __name__ == '__main__':  
    os.chdir(os.path.dirname(__file__))     
    data = loadTask12('../data/csv/calculation.csv')

    nju = 1.4 - 4.53j
    phi = 52
    g = Gradient()

    calcTask1(data, nju, phi, True, Idx=174) 
    calcTask2(data, nju, phi, g, WriteLog=True, Idx=174)
Esempio n. 10
0
 def run(self, opts=None):
     logger.info('--- {} running ---'.format(type(self).__name__))
     # setup gradient
     gradient = Gradient()
     if opts is not None:
         gradient.parse(opts.gradient.split())
     else:
         gradient.parse(['--default'])
     gradient.com_ref = self.com_ref
     gradient.com_cal = self.com_cal
     gradient.data_ref = self.data_ref
     # setup simplex
     simplex = Simplex()
     simplex.com_ref = self.com_ref
     simplex.com_cal = self.com_cal
     simplex.data_ref = self.data_ref
     # rather than copying, could overwrite to save memory
     self.best_ff = copy.deepcopy(self.init_ff)
     if self.best_ff.x2 is None:
         # data used by gradient, so save it
         self.calc_x2_ff(self.best_ff, save_data=True)
         # no need for data here
         self.init_ff.x2 = self.best_ff.x2
     self.current_cycle = 0
     self.last_best = None
     while ((self.last_best is None
             or abs(self.last_best - self.best_ff.x2) / self.last_best >
             self.convergence) and
            (self.loop_max is None or self.current_cycle < self.loop_max)):
         self.last_best = self.best_ff.x2
         self.current_cycle += 1
         logger.info('loop - start of cycle {} - {} ({})'.format(
             self.current_cycle, self.best_ff.x2, self.best_ff.method))
         gradient.init_ff = self.best_ff
         self.best_ff = gradient.run()
         self.best_ff.export_ff(path=self.best_ff.path +
                                '.{}.grad'.format(self.current_cycle))
         simplex.init_ff = self.best_ff
         # self.best_ff = simplex.run()
         try:
             self.best_ff = simplex.run()
         except Exception:
             logger.warning(traceback.format_exc())
             logger.warning(
                 "in case you didn't notice, simplex raised an exception")
             if simplex.trial_ffs:
                 # make a function for this...
                 self.best_ff = MM3()
                 self.best_ff.method = simplex.trial_ffs[0].method
                 self.best_ff.copy_attributes(self.init_ff)
                 if simplex.max_params is not None and len(
                         simplex.init_ff.params) > simplex.max_params:
                     self.best_ff.params = copy.deepcopy(
                         self.init_ff.params)
                     for param_i in self.best_ff.params:
                         for param_b in simplex.trial_ffs[0].params:
                             if param_i.mm3_row == param_b.mm3_row and param_i.mm3_col == param_b.mm3_col:
                                 param_i = copy.deepcopy(param_b)
                 else:
                     self.best_ff.params = copy.deepcopy(
                         simplex.trial_ffs[0].params)
                 self.best_ff.x2 = simplex.trial_ffs[0].x2
                 if simplex.trial_ffs[0].data is not None:
                     self.best_ff.data = simplex.trial_ffs[0].data
                 # ... block of code
             else:
                 logger.warning(
                     'simplex never generated trial force fields')
             self.best_ff.export_ff()
         self.best_ff.export_ff(path=self.best_ff.path +
                                '.{}.simp'.format(self.current_cycle))
         change = abs(self.last_best - self.best_ff.x2) / self.last_best
         logger.info(
             'loop - end of cycle {} - {} ({}) - % change {}'.format(
                 self.current_cycle, self.best_ff.x2, self.best_ff.method,
                 change))
     logger.info('--- {} complete ---'.format(type(self).__name__))
     logger.info('initial: {} ({})'.format(self.init_ff.x2,
                                           self.init_ff.method))
     logger.info('final: {} ({})'.format(self.best_ff.x2,
                                         self.best_ff.method))
     return self.best_ff
Esempio n. 11
0
    def enter(self, enter_params=None):
        # Get needed settings
        self.window_width = Settings.instance().settings['window_width']
        self.window_height = Settings.instance().settings['window_height']
        self.paddle_width = Settings.instance().settings['paddle_width']
        self.paddle_height = Settings.instance().settings['paddle_height']
        self.paddle_tolerance_beginner = Settings.instance(
        ).settings['paddle_tolerance_beginner']
        self.paddle_tolerance_Intermediate = Settings.instance(
        ).settings['paddle_tolerance_Intermediate']
        self.paddle_tolerance_expert = Settings.instance(
        ).settings['paddle_tolerance_expert']
        self.ball_speed_increase_beginner = Settings.instance(
        ).settings['ball_speed_increase_beginner']
        self.ball_speed_increase_intermediate = Settings.instance(
        ).settings['ball_speed_increase_intermediate']
        self.ball_speed_increase_expert = Settings.instance(
        ).settings['ball_speed_increase_expert']
        self.paddle_special_hit_threshold = Settings.instance(
        ).settings['paddle_special_hit_threshold']
        self.paddle_special_hit_increase = Settings.instance(
        ).settings['paddle_special_hit_increase']
        self.net_segments = Settings.instance().settings['net_segments']
        self.net_segments_gap = Settings.instance(
        ).settings['net_segments_gap']
        self.net_segments_height = Settings.instance(
        ).settings['net_segments_height']
        self.net_segment_width = Settings.instance(
        ).settings['net_segment_width']
        self.win_score = Settings.instance().settings['win_score']

        # Save enter parameters
        self.num_players = enter_params.get('num_players')
        self.input_device = enter_params.get('input_device')
        self.difficulty = enter_params.get('difficulty')
        self.is_demo = enter_params.get('is_demo')
        if self.is_demo is None:
            self.is_demo = False

        # Load Fonts
        load_font('fonts\\font.ttf', 'small_medium', self.cached_fonts, 32)
        load_font('fonts\\font.ttf', 'huge', self.cached_fonts, 128)

        # Load Sounds
        load_sound('sounds\\paddle_hit.wav', 'paddle_hit', self.cached_sounds)
        load_sound('sounds\\score.wav', 'score', self.cached_sounds)
        load_sound('sounds\\wall_hit.wav', 'wall_hit', self.cached_sounds)
        load_sound('sounds\\paddle_special_hit.wav', 'paddle_special_hit',
                   self.cached_sounds)

        # Play music
        play_music(1, self.music)

        # Create Entites
        self.ball = Ball(self.window_width // 2, self.window_height // 2,
                         Settings.instance().settings['ball_radius'])
        self.player1 = Paddle(self.paddle_width // 2,
                              self.paddle_height // 2 + 100, self.paddle_width,
                              self.paddle_height)
        self.player2 = Paddle(
            self.window_width - self.paddle_width // 2,
            self.window_height - self.paddle_height // 2 - 100,
            self.paddle_width, self.paddle_height)

        self.ball.set_initial_speed(self.serving_player == 2)

        # Set tolerance according to difficulty
        tolerance = random.randint(self.paddle_tolerance_beginner[0],
                                   self.paddle_tolerance_beginner[1]) / 100
        self.speed_increase = self.ball_speed_increase_beginner
        if self.difficulty == 'intermediate':
            tolerance = random.randint(
                self.paddle_tolerance_Intermediate[0],
                self.paddle_tolerance_Intermediate[1]) / 100
            self.speed_increase = self.ball_speed_increase_intermediate
        if self.difficulty == 'expert':
            tolerance = random.randint(self.paddle_tolerance_expert[0],
                                       self.paddle_tolerance_expert[1]) / 100
            self.speed_increase = self.ball_speed_increase_expert
        self.player2.set_tolerance(tolerance)

        # Load particle system
        self.particle_system = ParticleSystem(
            self.ball.get_position()[0],
            self.ball.get_position()[1], ParticleShape.SQUARE,
            Settings.instance().settings['particle_size'],
            Settings.instance().settings['particle_birth_rate'],
            Settings.instance().settings['particle_speed'],
            Settings.instance().settings['particle_death_age'])
        gradient = Gradient(
            Settings.instance().settings['particle_gradient_color_01'],
            Settings.instance().settings['particle_gradient_last_color'])
        gradient.add_color(
            Settings.instance().settings['particle_gradient_color_02'],
            Settings.instance().settings['particle_gradient_color_02_pos'])
        gradient.add_color(
            Settings.instance().settings['particle_gradient_color_03'],
            Settings.instance().settings['particle_gradient_color_03_pos'])
        gradient.add_color(
            Settings.instance().settings['particle_gradient_color_04'],
            Settings.instance().settings['particle_gradient_color_04_pos'])
        self.particle_system.set_gradient(gradient)
        self.particle_system.set_death_variance(
            Settings.instance().settings['particle_death_variant'])
        self.particle_system.set_speed_variance(
            Settings.instance().settings['particle_speed_variant'])
Esempio n. 12
0
import numpy as np
from pyproj import Geod, Proj
from PIL import Image
from aggdraw import Draw, Pen
import operator
from math import pi

from gradient import Gradient

HALF_ROTATION = 180

DEFAULT_COLS = Gradient(((0, 0, 0, 0), (0.5, 0, 0, 255), (1, 255, 255, 255)))
DEFAULT_BG = (0, 0, 0)

class GCMapper:
    def __init__(self, width=800,
            height=None, bgcol=DEFAULT_BG, proj='eqc',
            cols=DEFAULT_COLS, line_width=1, gc_resolution=100):
        '''
        Create an object for turning coordinate pairs into an image.

        Parameters
            height          the height of the resultant image
            width           the width of the resultant image
            bgcol           the background color of the image,
                            as an (r,g,b) triple
            proj            the projection name as a string (passed to
                            pyproj)
            cols            a function which takes one fractional
                            argument and returns a color (r,g,b) triple
Esempio n. 13
0
from evaluate import Evaluate
from metrics import Metrics
from gradient import Gradient
import numpy as np

# Load data
u = Utils()
train_facile = u.load_matrix('data/data_train_facile.mat')

#generate pairs
pairs_idx, pairs_label = u.generate_pairs(train_facile['label'], 1000, 0.1)
newX,newY = u.select_pairs_data(pairs_idx,train_facile['X'],train_facile['label'],c=700)
feat_idx = u._feat_idx

#test gradient
g = Gradient()
M_ini = g.generate_I(newX.shape[1])
M = g.sgd_metric_learning(newX, newY, 0.002, 50000, 0, M_ini)

# Calculate distance
m = Metrics()
X = u.select_features(train_facile['X'],feat_idx)
X -= X.mean(axis=0)
X /= X.std(axis=0)
X[np.isnan(X)] = 0.
dist = m.mahalanobis_dist(X, pairs_idx,M)
#dist[np.isnan(dist)] = 50.
## Evaluate model
e = Evaluate()
e.evaluation(pairs_label,dist)
## display results
Esempio n. 14
0
    def __init__(self):
        super().__init__()

        gradient = Gradient()
        gradient.setGradient([(0, 'black'), (1, 'green'), (0.5, 'red')])
        self.setCentralWidget(gradient)