Exemple #1
0
def Os_move(game):
    # get the Os move
    decision = Decision(game)
    our_move = decision.move
    game.BOARD_STATE.update(our_move)
    time.sleep(0.25)
    decision.update()  # refresh X and Os after move
    if len(decision.Os) > 2:
        game.did_anyone_win("O")
def test_responses_can_be_added_to_choices():
    """A choice can have responses added to it."""
    decision = Decision()
    decision.add_choice('Truck')
    decision.add_choice('Van')
    decision.add_response('Truck', 'It goes offroad real nice')
    decision.add_response('Van', 'You can sleep in it')

    expected = {
        'Truck': ['It goes offroad real nice'],
        'Van': ['You can sleep in it'],
    }

    assert decision.choices == expected
Exemple #3
0
    def process_month(self, year_index, month_index):
        Logger.tail_log('第{}年'.format(year_index),
                        tag_name=LogConst.MONTHLY_LOG_NAME)
        Logger.log('第{}月'.format(month_index),
                   tag_name=LogConst.MONTHLY_LOG_NAME)
        income = self.income_manager.calc_income_month()
        gongjijin = self.income_manager.calc_income_ggj()
        gjj_debt = self.outcome_manager.calc_outcome_month_debt_gjj()
        other_outcome = self.outcome_manager.calc_outcome_month_debt_except_gjj(
        )
        gjj_tiqu = 0

        if gjj_debt > gongjijin:
            invest = income + gongjijin - gjj_debt - other_outcome
        else:
            invest = income - other_outcome
            self._gjj_account += gongjijin - gjj_debt

        if month_index % 3 == 0 and not Decision.decide_to_buy_house():
            gjj_tiqu_max = 6000 * 2
            gjj_tiqu = gjj_tiqu_max if self._gjj_account > gjj_tiqu_max else self._gjj_account
            self._gjj_account -= gjj_tiqu
            invest += gjj_tiqu

        msg = '[income]{} [gongjijin]{} [gjj_debt]{} [other_outcome]{} [gjj_tiqu]{} [invest]{}' \
              ''.format(income, gongjijin, gjj_debt, other_outcome, gjj_tiqu, invest)
        Logger.log(msg, tag_name=LogConst.MONTHLY_LOG_NAME)

        self.invest_manager.invest_process_month()
        self.invest_manager.throw_money(invest)
        self.print_account()
Exemple #4
0
def main(responses):
    pub = rospy.Publisher('tocabi/emotion', Int64, queue_size=10)
    rospy.init_node('Emotion')
    prev_speaking_flag = -1
    prev_action = 1
    cur_action = 1
    D = Decision()
    for response in responses:
        
        if not response.results:
            continue

        result = response.results[0]
        
        cur_flag = 0 if result.is_final == False else 1
        if prev_speaking_flag != cur_flag and not result.is_final:
            # TODO: Modulize Action Part 
            IS_SPEAKING = True
            cur_action = D.decide(IS_SPEAKING, "")
            print("Started Speaking!")
            if cur_action != prev_action:
                prev_action = cur_action

            prev_speaking_flag = cur_flag
            pub.publish(cur_action)
        
        if not result.alternatives:
            continue
        
        transcript = result.alternatives[0].transcript 
        
        if result.is_final:
            IS_SPEAKING = False
            # TODO: Modulize Action Part  
            cur_action = D.decide(IS_SPEAKING, transcript)
            print "Finished speaking. Recognized sentence: ", "'",transcript,"'"
            print "Classified Emotion Index: ", cur_action,"\n"

            if cur_action != prev_action:
                prev_action = cur_action

            prev_speaking_flag = -1
            pub.publish(cur_action)
            # Exit recognition if any of the transcribed phrases could be one of ["exit", "quit"]
            if re.search(r"\b(exit|quit)\b", transcript, re.I):
                print("Exiting..")
                break
def telemetry(sid, data):

    global frame_counter, second_counter, fps
    frame_counter+=1
    # Do a rough calculation of frames per second (FPS)
    if (time.time() - second_counter) > 1:
        fps = frame_counter
        frame_counter = 0
        second_counter = time.time()
    print("Current FPS: {}".format(fps))

    if data:
        global Rover
        # Initialize / update Rover with current telemetry
        Rover, image = update_rover(Rover, data)

        if np.isfinite(Rover.vel):

            # Execute the perception and decision steps to update the Rover's state
            Rover = perception_step(Rover)
            Rover = Decision.decision_step(Rover)
            #Rover = decision_step(Rover)

            # Create output images to send to server
            out_image_string1, out_image_string2 = create_output_images(Rover)

            # The action step!  Send commands to the rover!

            # Don't send both of these, they both trigger the simulator
            # to send back new telemetry so we must only send one
            # back in respose to the current telemetry data.

            # If in a state where want to pickup a rock send pickup command
            if Rover.send_pickup and not Rover.picking_up:
                send_pickup()
                # Reset Rover flags
                Rover.send_pickup = False
            else:
                # Send commands to the rover!
                commands = (Rover.throttle, Rover.brake, Rover.steer)
                send_control(commands, out_image_string1, out_image_string2)

        # In case of invalid telemetry, send null commands
        else:

            # Send zeros for throttle, brake and steer and empty images
            send_control((0, 0, 0), '', '')

        # If you want to save camera images from autonomous driving specify a path
        # Example: $ python drive_rover.py image_folder_path
        # Conditional to save image frame if folder was specified
        if args.image_folder != '':
            timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3]
            image_filename = os.path.join(args.image_folder, timestamp)
            image.save('{}.jpg'.format(image_filename))

    else:
        sio.emit('manual', data={}, skip_sid=True)
def test_choices_can_be_added():
    """Choices can be added to decide upon."""
    decision = Decision()
    decision.add_choice("Truck")
    assert decision.choices == {"Truck": []}
    decision.add_choice("Van")
    assert decision.choices == {"Truck": [], "Van": []}
Exemple #7
0
def Xs_move(game):
    # get the Xs move
    # move = decode_move(getch(),"X", game)
    # temporary !
    move = decode_move(getch(), "X", game)
    if move:
        game.BOARD_STATE.update(move)
    else:
        Xs_move(game)
    # get Xs
    decision = Decision(game)
    if len(decision.Xs) > 2:
        game.did_anyone_win("X")
Exemple #8
0
    def __init__(self, playbook_path):

        with open(playbook_path, "r") as f:
            self._pb = yaml.load(f.read())

        self._step = self._pb["starttaskid"]
        self._tasks = {}

        for task_id in self._pb["tasks"]:

            task_settings = self._pb["tasks"][task_id]["task"]
            if self._pb["tasks"][task_id]["type"] == "task":
                self._tasks[task_id] = Task(settings=task_settings)

            elif self._pb["tasks"][task_id]["type"] == "condition":
                self._tasks[task_id] = Decision(settings=task_settings)
Exemple #9
0
 def __init__(self):
     self.name = "Osyczka"
     objectives = [objectiveOne, objectiveTwo]
     constraints = [
         constraintOne, constraintTwo, constraintThree, constraintFour,
         constraintFive, constraintSix
     ]
     decisions = [
         Decision(0, 10),
         Decision(0, 10),
         Decision(1, 5),
         Decision(0, 6),
         Decision(1, 5),
         Decision(0, 10)
     ]
     Model.__init__(self, objectives, constraints, decisions)
Exemple #10
0
 def __init__(self):
     self.name = "Kursawe"
     objectives = [objectiveOne, objectiveTwo]
     decisions = [Decision(-5, 5), Decision(-5, 5), Decision(-5, 5)]
     Model.__init__(self, objectives, None, decisions)
def main():
    cuda = gpuInit()
    np.random.seed(1)
    num_iterations = 1000
    count = 10  # default
    nSample = 0
    layerStart = 0
    layerLimit = 8
    learning_rate = 0
    simpleNN = 0

    while (True):
        userInput = input()
        cds = Decision.userInput(userInput)
        commands = cds.commands

        # print(cds.noErr)
        # print(commands)
        if cds.noErr:
            first = commands[0]
            if first == 0:  #createDataSet
                count = 10
                second = commands[1]
                third = commands[2]
                if second == 0:  #train
                    trainSet = dataSet.createSimpleSet(1, third, count)
                    nSample = trainSet.X.shape[1]  #batch크기 또는 train set 수
                elif second == 1:  #test
                    testSet = dataSet.createSimpleSet(1, third, count)

                print("  | create datsSet complete ")
                print("  | nSample = ", third)

            elif first == 1:  #autoBuild
                if len(commands) == 1:
                    layerStart = 0
                    layerLimit = 8
                elif len(commands) == 2:
                    layerStart = commands[1]
                    layerLimit = max(8, layerStart)
                elif len(commands) == 3:
                    layerStart = commands[1]
                    layerLimit = commands[2]
                if nSample > 0:
                    package = NeuralNetwork.autoBuilder(trainSet,
                                                        nSample,
                                                        layerStart=0,
                                                        layerLimit=8,
                                                        developmentMode=True)
                    # autoBuilder가 learning rate와 hiddenLayer의 수를 알아서 정해준다. 작업이 오래 걸릴 수 있음.
                    simpleNN = package[0]
                    learning_rate = package[1]
                    print("learning_rate", learning_rate)
                else:
                    print("  error : please load trainSet first")
                    print("  or create dataSet | use command   createDataSet")

            elif first == 2:  #model
                if len(commands) > 1:
                    second = commands[1]
                    if second == 0:  #train
                        if (learning_rate != 0) and (simpleNN != 0):
                            simpleNN.training_with_regularization(
                                trainSet, num_iterations, learning_rate)
                            train_acc = simpleNN.getAccuracy(trainSet)
                            print('train set Accuracy: %f' % train_acc + '%')
                        else:
                            print("  error : please build NN first")
                            print("  | use command   autoBuild")
                    elif second == 1:  #test
                        if (simpleNN != 0):
                            try:
                                train_acc = simpleNN.getAccuracy(trainSet)
                                test_acc = simpleNN.getAccuracy(testSet)
                                print('train set Accuracy: %f' % train_acc +
                                      '%')
                                print('test set Accuracy: %f' % test_acc + '%')
                            except:
                                print("  error : please load test set")
                        else:
                            print("  error : please build NN first")
                            print("  | use command   autoBuild")

            elif first == 3:  #loadDataSet
                second = commands[1]
                third = commands[2]
                count = 100
                if second == 0:  #train
                    trainSet = dataSet.loadDataSet(count, third)
                    nSample = trainSet.X.shape[1]  #batch크기 또는 train set 수
                elif second == 1:  #test
                    testSet = dataSet.loadDataSet(count, third)

                print("  | load datsSet complete ")
                print("  | nSample = ", nSample)
Exemple #12
0
 def __init__(self):
     self.name = "schaffer"
     objectives = [objectiveOne, objectiveTwo]
     decisions = [Decision(-10**5, 10**5)]
     Model.__init__(self, objectives, None, decisions)
Exemple #13
0
def main(responses):
    pub = rospy.Publisher('tocabi/emotion', Int64, queue_size=10)
    overlay_control_pub = rospy.Publisher('overlay_command',
                                          String,
                                          queue_size=5)
    pose_calibration_pub = rospy.Publisher(
        '/tocabi/dg/avatar/pose_calibration_flag', Int8, queue_size=5)
    retargeting_sync_pub = rospy.Publisher('/tocabi/dg/upperbodymodecommand',
                                           Float32,
                                           queue_size=5)

    rospy.init_node('Emotion')
    prev_speaking_flag = -1
    prev_action = 1
    cur_action = 1
    D = Decision()
    for response in responses:

        if not response.results:
            continue

        result = response.results[0]

        cur_flag = 0 if result.is_final == False else 1
        if prev_speaking_flag != cur_flag and not result.is_final:
            # TODO: Modulize Action Part
            IS_SPEAKING = True
            cur_action = D.decide(IS_SPEAKING, "")
            print("Started Speaking!")
            if cur_action != prev_action:
                prev_action = cur_action

            prev_speaking_flag = cur_flag
            pub.publish(cur_action)

        if not result.alternatives:
            continue

        transcript = result.alternatives[0].transcript.lower()

        if result.is_final:

            if "close" in transcript:
                overlay_control_pub.publish("close")
            if "open" in transcript:
                overlay_control_pub.publish("open")
            if "right" in transcript:
                overlay_control_pub.publish("right")
            if "left" in transcript:
                overlay_control_pub.publish("left")
            if "up" in transcript:
                overlay_control_pub.publish("up")
            if "down" in transcript:
                overlay_control_pub.publish("down")
            if "front" in transcript:
                overlay_control_pub.publish("front")
            if "back" in transcript:
                overlay_control_pub.publish("back")
            if "opacity" in transcript:
                overlay_control_pub.publish(transcript)

            if "1" in transcript:
                pose_calibration_pub.publish(1)
            elif "2" in transcript:
                pose_calibration_pub.publish(2)
            elif "3" in transcript:
                pose_calibration_pub.publish(3)
            elif "4" in transcript:
                pose_calibration_pub.publish(4)
            elif "5" in transcript:
                pose_calibration_pub.publish(5)

            if "stop" in transcript:
                retargeting_sync_pub.publish(3)

            IS_SPEAKING = False
            # TODO: Modulize Action Part
            cur_action = D.decide(IS_SPEAKING, transcript)
            print "Finished speaking. Recognized sentence: ", "'", transcript, "'"
            print "Classified Emotion Index: ", cur_action, "\n"

            if cur_action != prev_action:
                prev_action = cur_action

            prev_speaking_flag = -1
            pub.publish(cur_action)
            # Exit recognition if any of the transcribed phrases could be one of ["exit", "quit"]
            if re.search(r"\b(exit|quit)\b", transcript, re.I):
                print("Exiting..")
                break
    def solve(racingdata):
        ampl_env = amplpy.Environment()
        ampl = amplpy.AMPL(ampl_env)

        ampl.setOption('solver', 'gurobi')
        ampl.setOption(
            'gurobi_options', "mipfocus 1"
            "relax 0"
            "timelim 7200 "
            "tunetimelimit 60 ")

        model_dir = os.path.normpath('./ampl_models/Trend3D')
        ampl.read(os.path.join(model_dir, 'f1aiTyre.mod'))

        listlaps = list(range(1, racingdata.totalLaps + 1))
        listwear = list(
            range(1,
                  (min(len(racingdata.lapData[0]), len(racingdata.lapData[1]),
                       len(racingdata.lapData[2])) + 1)))
        listtyres = racingdata.compounds.values()

        dftyres = amplpy.DataFrame('tyres')
        dftyres.setColumn('tyres', listtyres)
        ampl.setData(dftyres, 'tyres')

        dfwear = amplpy.DataFrame('stints')
        dfwear.setColumn('stints', listwear)
        ampl.setData(dfwear, 'stints')

        dflaps = amplpy.DataFrame('laps')
        dflaps.setColumn('laps', listlaps)
        ampl.setData(dflaps, 'laps')

        totallaps = ampl.getParameter('totalLaps')
        totallaps.set(racingdata.totalLaps)

        tyrelifespan = ampl.getParameter('tyreLifeSpan')
        tyrelifespan.set(len(listwear))

        pittime = ampl.getParameter('pitTime')
        pittime.set(racingdata.pitTime)

        df = amplpy.DataFrame(('tyres', 'wear'), 'usage')

        df.setValues({(tyre, wear): racingdata.futureTyreUsageData[i][j]
                      for i, tyre in enumerate(listtyres)
                      for j, wear in enumerate(listwear)})
        ampl.setData(df)
        df = amplpy.DataFrame('tyres', ['avg', 'coeff'])
        df.setValues(racingdata.trendlinedata())
        ampl.setData(df)
        print(racingdata.futureTyreUsageData)
        ampl.solve()

        solution = Decision(racingdata)

        pit = ampl.getVariable('pit')
        dfpit = pit.getValues()
        chosen = {int(row[1]): row[0] for row in dfpit if row[2] == 1}

        solution.pitDecision = chosen

        compound = ampl.getVariable('compound')
        dfcompound = compound.getValues()
        chosen = {
            int(row[2]): [row[0], int(row[1])]
            for row in dfcompound if row[3] == 1
        }
        solution.compoundStrategy = chosen

        time = ampl.getVariable('time')
        dftime = time.getValues()
        for row in dftime:
            for k, v in racingdata.compounds.items():
                if v == row[0]:
                    solution.lapTimes[k].append(row[2])
        return solution
Exemple #15
0
import cv2
from preprocessing import Preprocess
from thresholding import Threshold
from smoothing import Smooth
from contour import Contour
from decision import Decision
import os

SAMPLE_IMAGE = 'thresh1.jpg'
frame = cv2.imread(SAMPLE_IMAGE, cv2.IMREAD_UNCHANGED)
thresholded_image = frame
smooth_image = Smooth().smoothing(thresholded_image)
contour = Contour().find_contours(smooth_image)
center, radius, probability = Decision().decision(contour, smooth_image)
if radius is not 0:
    # cv2.putText(frame, str(probability * 100) + '%', center, cv2.FONT_HERSHEY_PLAIN, 1, (255, 0, 0), 2)
    print("Probability: " + str(probability * 100) + '%')
    cv2.circle(frame, center, radius, (255, 0, 0), 2)

cv2.imshow('Main video', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
def test_it_can_return_the_choice_with_the_most_responses():
    """The winner is the choices with the most responses."""
    decision = Decision()
    decision.add_choice('Truck')
    decision.add_choice('Van')
    decision.add_response('Truck', 'It goes offroad real nice')
    decision.add_response('Van', 'You can sleep in it')
    decision.add_response('Van', 'Its got a swivel chair')
    decision.add_response('Van', 'It can hold more dogs')

    assert decision.winner() == 'Van'
def test_it_exists():
    """Create a decision object."""
    decision = Decision()
    assert type(decision) == Decision
def test_it_has_nothing_to_decide_about_when_new():
    """New decisions have nothing to decide about when new."""
    decision = Decision()
    assert decision.choices == {}
    def run(self, candlesticks):

        # Samples a random price within the range [candlestick.open, candlestick.close]
        sample_price = lambda op, close: random.uniform(
            min(op, close), max(op, close))

        # The zero's are to take up space since our indicators require a full dataframe of OHLC datas
        self.prices = [[
            0, 0, 0, 0, sample_price(candle.open, candle.close), 0
        ] for candle in candlesticks]

        # Hacky way to ensure indices match up :(
        rsi = [None] * 14
        nine_period = [None] * 9
        fifteen_period = [None] * 15
        nine_period_ema = [None] * 9

        rsi.extend(
            self.indicators.analyze_rsi(self.prices,
                                        period_count=14,
                                        all_data=True))
        nine_period.extend(
            self.indicators.analyze_sma(self.prices,
                                        period_count=9,
                                        all_data=True))
        fifteen_period.extend(
            self.indicators.analyze_sma(self.prices,
                                        period_count=15,
                                        all_data=True))
        nine_period_ema.extend(
            self.indicators.analyze_ema(self.prices,
                                        period_count=9,
                                        all_data=True))

        for i in range(len(self.prices)):

            # Get the (sampled) closing price
            current_price = self.prices[i][4]
            current_rsi = rsi[i]["values"] if rsi[i] else None
            current_nine_period = nine_period[i]["values"] if nine_period[
                i] else None
            current_fifteen_period = fifteen_period[i][
                "values"] if fifteen_period[i] else None
            current_nine_period_ema = nine_period_ema[i][
                "values"] if nine_period_ema[i] else None

            decision = Decision({
                'currentprice': current_price,
                'rsi': current_rsi,
                'sma9': current_nine_period,
                'sma15': current_fifteen_period,
                'ema9': current_nine_period_ema
            })

            open_trades = [
                trade for trade in self.trades if trade.status == 'OPEN'
            ]

            ### CHECK TO SEE IF WE CAN OPEN A BUY POSITION
            if len(open_trades) < self.max_trades_at_once:
                if decision.should_buy(self.buy_strategy):
                    assert self.reserve > 0

                    self.buys.append((i, current_price))
                    new_trade = Trade(self.pair,
                                      current_price,
                                      self.reserve * (1 - self.trading_fee),
                                      stop_loss=self.stop_loss)
                    self.reserve = 0
                    self.trades.append(new_trade)

            ### CHECK TO SEE IF WE NEED TO SELL ANY OPEN POSITIONS
            for trade in open_trades:
                if decision.should_sell(self.sell_stategy):

                    self.sells.append((i, current_price))
                    profit, total = trade.close(current_price)
                    self.profit += profit * (1 - self.trading_fee)
                    self.reserve = total * (1 - self.trading_fee)

            ### CHECK TO SEE IF WE HAVE ACTIVATED A STOP LOSS
            for trade in self.trades:

                # Check our stop losses
                if trade.status == "OPEN" and trade.stop_loss and current_price < trade.stop_loss:
                    profit, total = trade.close(current_price)
                    self.sells.append((i, current_price))
                    self.profit += profit * (1 - self.trading_fee)
                    self.reserve = total * (1 - self.trading_fee)
Exemple #20
0
    def make_analysis(self,image):
        raw_result=[]
        for i,r in enumerate([self.roi_vertical_list,self.roi_reduce_list,self.roi_expand_list]):
            raw_result.append(self.run_compare(image.copy(),r))
            
        mean_result = [list(map(np.mean,i)) for i in raw_result]
        
        minimum_mean=[]


        for row in range(3):
            data_x=mean_result[row]
            mean=np.mean(data_x)
            minimum_mean.append(mean)

        median=np.argsort(minimum_mean)[len(minimum_mean)//2]
        data_x = mean_result[median]
        data_y=list(range(346,346-len(data_x)*20,-20))


        roi = [self.roi_vertical_list,self.roi_reduce_list,self.roi_expand_list][median]
        mean=minimum_mean[median]
        std=np.std(data_x)
        hline = self.interpolation([data_x,data_y],mean)
        ########################################################
        # find new mean if hline > 3
        ########################################################
        interval=(mean-min(data_x))//100
        counter = interval
        if len(hline)>3:
            while len(hline)>3:
                hline = self.interpolation([data_x,data_y],mean-counter)
                counter+=interval

            mean = mean-counter-interval
        ########################################################
        # combine line that is close to each other
        ########################################################
        if len(hline)==3:
            if abs(hline[0]-hline[1])<20:
                if abs(hline[1]-hline[2])<20:
                    hline = hline[0]
                else:
                    hline = [hline[0],hline[2]]
            elif abs(hline[1]-hline[2])<20:
                hline = [hline[0],hline[1]]
        elif len(hline)==2:
            if abs(hline[0]-hline[1])<20:
                hline=hline[0]


        ########################################################
        # Plot data
        ########################################################
        travel_dist = self.max_travel_dist(hline,data_y)
        print(travel_dist)
        decision = Decision()
        direction,decision_line = decision.make_decision(hline)
        print(decision_line)
        info_image = self.draw(image,roi,hline,mean,std,data_x,data_y,"median",travel_dist,decision_line,direction)
        # cv2.imshow("test",self.draw(image,hline,mean,std,data_x,data_y,"median",travel_dist))
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        return hline,info_image,direction