def main(args):
    # read all the images in the folder
    image_list = glob.glob(args.data_dir + os.sep + '*.' + args.img_extn)

    up = None
    if args.modelType == 2:
        up = torch.nn.Upsample(scale_factor=16, mode='bilinear')
    else:
        up = torch.nn.Upsample(scale_factor=2, mode='bilinear')
    if args.gpu:
        up = up.cuda()

    p = args.p
    q = args.q
    classes = args.classes
    if args.modelType == 2:
        modelA = Net.ESPNet_Encoder(
            classes, p, q)  # Net.Mobile_SegNetDilatedIA_C_stage1(20)
        model_weight_file = args.weightsDir + os.sep + 'encoder' + os.sep + 'espnet_p_' + str(
            p) + '_q_' + str(q) + '.pth'
        if not os.path.isfile(model_weight_file):
            print(
                'Pre-trained model file does not exist. Please check ../pretrained/encoder folder'
            )
            exit(-1)
        modelA.load_state_dict(torch.load(model_weight_file))
    elif args.modelType == 1:
        modelA = Net.ESPNet(classes, p,
                            q)  # Net.Mobile_SegNetDilatedIA_C_stage1(20)
        model_weight_file = args.weightsDir + os.sep + 'decoder' + os.sep + 'espnet_p_' + str(
            p) + '_q_' + str(q) + '.pth'
        if not os.path.isfile(model_weight_file):
            print(
                'Pre-trained model file does not exist. Please check ../pretrained/decoder folder'
            )
            exit(-1)
        modelA.load_state_dict(torch.load(model_weight_file))
    else:
        print('Model not supported')
    # modelA = torch.nn.DataParallel(modelA)
    if args.gpu:
        modelA = modelA.cuda()

    # set to evaluation mode
    modelA.eval()

    if not os.path.isdir(args.savedir):
        os.mkdir(args.savedir)

    evaluateModel(args, modelA, up, image_list)
Пример #2
0
    def model2(self):
        input_dim = 4
        output_dim = 1
        model = Model2.LinearRegressionModel(input_dim, output_dim)
        criterion = nn.MSELoss()  # 损失函数为均方差

        learning_rate = 0.01
        self.optimizer21 = torch.optim.SGD(model.parameters(),
                                           lr=learning_rate)
        '''训练网络'''

        for epoch in range(self.epochs21):
            epoch += 1
            # 清空梯度参数
            self.optimizer21.zero_grad()
            # 获得输出
            outputs = model(self.x)
            # 计算损失
            loss = criterion(outputs, self.y)

            # 反向传播
            loss.backward()
            # 更新参数
            self.optimizer21.step()
        return model
Пример #3
0
 def __init__(self):
     self.train_number = 200
     self.model11 = Model1.NonLinearRegression()
     self.model21 = Model2.LinearRegressionModel(4, 1)
     learning_rate = 0.01
     self.optimizer11 = torch.optim.SGD(self.model11.parameters(),
                                        lr=learning_rate)
     self.optimizer21 = torch.optim.SGD(self.model21.parameters(),
                                        lr=learning_rate)
     self.max = 0
     self.min = 0
Пример #4
0
def SolveProblem(problem, constructive=True, aco=True, Model=False):
    nt = len([(v, i) for v in range(1, problem.numVertices)
              for i in range(problem.numTasks[problem.request[v]])])

    print('num tasks', nt)
    if constructive:
        ts = time.time()
        sol = Constructive.Constructive(problem)
        te = time.time()
        print('Constructive heuristic')
        print('  Solution:', len(sol), 'days')
        print('  Time:', te - ts)

    if aco:
        ts = time.time()
        sol = ACO.Main.Solve(problem)
        te = time.time()
        print('Ant Colony Algorithm')
        print('  Solution:', len(sol), 'days')
        print('  Time:', te - ts)

    if Model:
        print('Model')

        info, _ = Model2.Solve(problem, sol, integer=False)
        lbroot = info['lb']

        ts = time.time()
        info, sol = Model2.Solve(problem, sol, integer=True)
        te = time.time()

        print('  Upper bound:', info['ub'])
        if info['status'] == 'MIP_optimal':
            print('  Lower bound:', info['ub'])
        else:
            print('  Lower bound:', info['lb'])

        print('  Root lower bound:', lbroot)
        print('  Root lower bound (with cplex cuts):', info['lbroot'])
        print('  Number of nodes:', info['numnodes'])
        print('  Time', te - ts)
Пример #5
0
    def inference(self):
        if self.arch == "Model1":
            model = Model1.build(self.x, n_classes=self.n_classes)
            return model
        elif self.arch == "Model2":
            #raise NotImplementedError
            model = Model2.build(self.x, n_classes=self.n_classes)
            print("model shape:", model.shape)
            return model

        elif self.arch == "Model3":
            #raise NotImplementedError
            model = Model3.build(self.x, n_classes=self.n_classes)
            print("model shape:", model.shape)
            return model

        else:
            model = Model1.build(self.x, n_classes=self.n_classes)
            print("model shape:", model.shape)
            return model
Пример #6
0
import Model1
import Model2
import Model3
import Model4

##test = Model1.ML_Model1()
test1 = Model2.ML_Model1()
test2 = Model3.ML_Model1()
test3 = Model4.ML_Model1()

print(Model1.ML_Model1().Load_Model_Predict([1, 1, 1]))
print(test1.Load_Model_Predict([1, 1, 7]))
print(test2.Load_Model_Predict([1, 3, 12]))
print(test3.Load_Model_Predict([1, 7, 10]))
Пример #7
0
def do_click():
  global prevTableTheta
  

  #init dictionary of users
  global d

  #add artificial delay
  time.sleep(0.5)

  #manually set value
  totalPicsNum = 19
  survey_duration = 10*60*60 #10 hours to prevent retaking

  #get the data that the buttonClicked posted
  requestData = json.loads(request.body.getvalue())
  sessionData = requestData["sessionData"]

  if "toSurvey" in sessionData:
    return json.dumps({"toSurvey":True})

  #init log variable
  global data

  #go to next/prev pic according to button clicked
  buttonClicked = requestData["buttonID"]
  if sessionData["picCount"]<5:
    if buttonClicked==0:
      sessionData["picCount"] -= 1
    elif buttonClicked==1:
      sessionData["picCount"] += 1

  if sessionData["picCount"]==1:
    ret = {"imageURL": "images/Slide1.JPG",
           "buttonLabels": ["null", "Next"],
           "instructionText": "Instructions 1/3",
           "sessionData": sessionData,
       "buttonClass": "btn-primary"}
    return json.dumps(ret)

  if sessionData["picCount"]==2:
    ret = {"imageURL": "images/Slide2.JPG",
           "buttonLabels": ["null", "Next"],
           "instructionText": " ",
           "sessionData": sessionData,
       "buttonClass": "btn-primary"}
    return json.dumps(ret)

  if sessionData["picCount"]==3:
    ret = {"imageURL": "images/Slide3.JPG",
           "buttonLabels": ["Prev", "Next"],
           "instructionText": " ",
           "sessionData": sessionData}
    return json.dumps(ret)
  
  if sessionData["picCount"]==4:
    ret = {"imageURL": "images/Slide4.JPG",
           "buttonLabels": ["Prev", "START"],
           "instructionText": " ",
           "sessionData": sessionData}
    return json.dumps(ret)

  if sessionData["picCount"]==5:
    #generate a cookie with user's ID
    gen_id = ''.join(random.choice(string.ascii_uppercase +
      string.digits) for _ in range(6))
    response.set_cookie('mturk_id', gen_id, max_age=survey_duration, path='/')
    data[gen_id] = []
    #get ip
    ip = request.environ.get('REMOTE_ADDR')
    data[gen_id].append(ip)
    #timestamp
    startTime = datetime.datetime.now()
    data[gen_id].append("start: "+ str(startTime))
    timestart1[gen_id] = startTime
    sessionData["playVideo"] = 0
    sessionData["playedLong"] = 0
    ret = {"imageURL": "images/T100.jpg",
           "buttonLabels": ['<i class="fa fa-2x fa-rotate-right fa-rotate-225"></i>',
                            '<i class="fa fa-2x fa-rotate-left fa-rotate-135"></i>'],
           "instructionText": "Choose how you would like to rotate the table.",
           "sessionData": sessionData,
       "buttonClass": "btn-success"}
    sessionData["picCount"]+=1       
    return json.dumps(ret)
  
  #following code may need mturk_id, so get it once now
  mturk_id = request.cookies.get('mturk_id','NOT SET')

  if sessionData["picCount"]==7:
    sessionData["playVideo"] = 0
    ret = {"imageURL": "images/Slide5.JPG",
           "buttonLabels": ["null", "START"],
           "instructionText": " ",
           "sessionData": sessionData,
       "buttonClass": "btn-primary"}
    data[mturk_id].append("round two")
    sessionData["picCount"]+=1
    #timestamp
    firstFinish = datetime.datetime.now()
    data[mturk_id].append("firstFinish: "+ str(firstFinish))
    timeDelta = firstFinish-timestart1[mturk_id]
    data[mturk_id].append("timeDelta: "+ str(timeDelta.total_seconds()))
    return json.dumps(ret)

  if sessionData["picCount"]==8:
    sessionData["playVideo"] = 0
    Model2.restartTask(d,request.cookies.get('mturk_id','NOT SET'))
    ret = {"imageURL": "images/T100.jpg",
           "buttonLabels": ['<i class="fa fa-2x fa-rotate-right fa-rotate-225"></i>',
                            '<i class="fa fa-2x fa-rotate-left fa-rotate-135"></i>'],
           "instructionText": "Choose how you would like to rotate the table.",
           "sessionData": sessionData,
       "buttonClass": "btn-success"}
    #timestamp
    secondStart = datetime.datetime.now()
    data[mturk_id].append("secondStart: "+ str(secondStart))
    timestart2[mturk_id] = secondStart
    sessionData["picCount"]+=1  
    return json.dumps(ret)  
  
  #record in log
  data[mturk_id].append(buttonClicked)

  #get next move
  currTableTheta, oldTableTheta, message = \
    Model2.getMove(d,request.cookies.get('mturk_id','NOT SET'),buttonClicked)

  #play the long video if the human-robot actions
  # are the same and it's the first time this is happening
  suffix=""
  if oldTableTheta==currTableTheta and sessionData["playedLong"]==0:
    suffix="l"
    sessionData["playedLong"]=1
  videoLink = "videos/{}to{}{}.mp4".format(oldTableTheta, currTableTheta,suffix)
  imageLink = "images/T{}.jpg".format(currTableTheta)
  if currTableTheta==0 or currTableTheta==180:
    if sessionData["picCount"]==6:
      Model2.setPrevGoalStateTheta(d,request.cookies.get('mturk_id','NOT SET'), currTableTheta)
      sessionData["picCount"]+=1
    elif sessionData["picCount"]==9:
      sessionData["toSurvey"] = True
      #timestamp
      secondFinish = datetime.datetime.now()
      data[mturk_id].append("secondFinish: "+ str(secondFinish))
      timeDelta = secondFinish-timestart2[mturk_id]
      data[mturk_id].append("timeDelta2: "+ str(timeDelta.total_seconds()))
    
    ret = {"videoURL": videoLink,
           "imageURL": imageLink,
           "buttonLabels": ["null","Next"],
           "instructionText": "The table is in a horizontal position. You finished the task!",
           "sessionData": sessionData}
    return json.dumps(ret)
  else:
    sessionData["playVideo"] = 1
    ret = {"videoURL": videoLink,
           "imageURL":imageLink,
           "buttonLabels": ['<i class="fa fa-2x fa-rotate-right fa-rotate-225"></i>',
                            '<i class="fa fa-2x fa-rotate-left fa-rotate-135"></i>'],
           "instructionText": "<br>",
           "sessionData": sessionData,
           "buttonClass": "btn-success"}
    return json.dumps(ret)
Пример #8
0
           "instructionText": "<br>",
           "sessionData": sessionData,
           "buttonClass": "btn-success"}
    return json.dumps(ret)


#when the survey is approved by surveyhandler.js, the button requests this url
#handle_survey records the responses and gives a one line html page in response
#web browsers automatically add head/body syntax for this case
@app.post('/submit_survey')
def handle_survey():
  mturk_id = request.cookies.get('mturk_id', 'EXPIRED')
  for i in xrange(1,17):
    data[mturk_id].append(request.forms.get(str(i)))
  with open('output/log.json', 'w') as outfile:
    json.dump(data, outfile)
  print("User {} submitted the survey".format(mturk_id))
  return "<p> Your answers have been submitted. ID for mturk: {}".format(mturk_id)

#the server only writes to log.json, so if there's some data there already,
#we'll copy it to another file 
def backupLog():
  i=1
  while (os.path.isfile("output/log-backup-{}.json".format(i))):
    i+=1
  shutil.copy("output/log.json","output/log-backup-{}.json".format(i))
 
Model2.globalsInit()
backupLog()
run(app, host='0.0.0.0', port=2223)
Пример #9
0
def do_click():
    global prevTableTheta

    #init dictionary of users
    global d

    #add artificial delay
    time.sleep(0.5)

    #manually set value
    totalPicsNum = 19
    survey_duration = 10 * 60 * 60  #10 hours to prevent retaking

    #get the data that the buttonClicked posted
    requestData = json.loads(request.body.getvalue())
    sessionData = requestData["sessionData"]

    if "toSurvey" in sessionData:
        return json.dumps({"toSurvey": True})

    #init log variable
    global data

    #go to next/prev pic according to button clicked
    buttonClicked = requestData["buttonID"]
    if sessionData["picCount"] < 8:
        if buttonClicked == 0:
            sessionData["picCount"] -= 1
        elif buttonClicked == 1:
            sessionData["picCount"] += 1

    if sessionData["picCount"] == 1:
        ret = {
            "imageURL": "images/Slide1.JPG",
            "buttonLabels": ["null", "Next"],
            "instructionText": "Instructions 1/3",
            "sessionData": sessionData,
            "buttonClass": "btn-primary"
        }
        return json.dumps(ret)

    if sessionData["picCount"] == 2:
        #generate a cookie with user's ID
        gen_id = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(6))
        response.set_cookie('mturk_id',
                            gen_id,
                            max_age=survey_duration,
                            path='/')
        data[gen_id] = []
        #get ip
        ip = request.environ.get('REMOTE_ADDR')
        data[gen_id].append(ip)
        ret = {
            "imageURL": "images/Slide2.JPG",
            "buttonLabels": ["Prev", "Next"],
            "instructionText": " ",
            "sessionData": sessionData,
            "buttonClass": "btn-primary"
        }
        return json.dumps(ret)

    #following code may need mturk_id, so get it once now
    mturk_id = request.cookies.get('mturk_id', 'NOT SET')

    if sessionData["picCount"] == 3:
        trialIndx[mturk_id] = 1

        ret = {
            "imageURL": "images/Slide3.JPG",
            "buttonLabels": ["Prev", "Next"],
            "instructionText": " ",
            "sessionData": sessionData,
            "buttonClass": "btn-primary"
        }
        return json.dumps(ret)

    if sessionData["picCount"] == 4:
        ret = {
            "imageURL": "images/Slide4.JPG",
            "buttonLabels": ["Prev", "Next"],
            "instructionText": " ",
            "sessionData": sessionData
        }
        return json.dumps(ret)

    if sessionData["picCount"] == 5:
        if "radioChoice" in requestData.keys():
            data[mturk_id].append("radioChoice: " + requestData["radioChoice"])
        ret = {
            "imageURL": "images/HERBspeaks.JPG",
            "buttonLabels": ["Prev", "Next"],
            "instructionText": " ",
            "sessionData": sessionData
        }
        return json.dumps(ret)

    if sessionData["picCount"] == 6:
        # we got the results from slide4 radio
        ret = {
            "imageURL": "",
            "buttonLabels": ["Prev", "Next"],
            "instructionText": " ",
            "sessionData": sessionData
        }
        return json.dumps(ret)

    if sessionData["picCount"] == 7:
        data[mturk_id].append("trustRate1: " + requestData["trustRate1"])
        ret = {
            "imageURL": "images/Slide5.JPG",
            "buttonLabels": ["Prev", "START"],
            "instructionText": " ",
            "sessionData": sessionData
        }
        return json.dumps(ret)

    if sessionData["picCount"] == 8:
        #timestamp
        startTime = datetime.datetime.now()
        data[mturk_id].append("start: " + str(startTime))
        timestart1[mturk_id] = startTime
        sessionData["playVideo"] = 0
        sessionData["playedLong"] = 0
        ret = {
            "imageURL":
            "images/T100.jpg",
            "buttonLabels": [
                '<i class="fa fa-2x fa-rotate-right fa-rotate-225"></i>',
                '<i class="fa fa-2x fa-rotate-left fa-rotate-135"></i>'
            ],
            "instructionText":
            "Choose how you would like to rotate the table.",
            "sessionData":
            sessionData,
            "buttonClass":
            "btn-success"
        }
        sessionData["picCount"] += 1
        return json.dumps(ret)

    if sessionData["picCount"] == 10:
        sessionData["playVideo"] = 0
        ret = {
            "imageURL": "",
            "buttonLabels": ["null", "Next"],
            "instructionText": " ",
            "sessionData": sessionData,
            "buttonClass": "btn-primary"
        }
        sessionData["picCount"] += 1
        #timestamp
        firstFinish = datetime.datetime.now()
        data[mturk_id].append("firstFinish: " + str(firstFinish))
        timeDelta = firstFinish - timestart1[mturk_id]
        data[mturk_id].append("timeDelta: " + str(timeDelta.total_seconds()))
        return json.dumps(ret)

    if sessionData["picCount"] == 11:
        data[mturk_id].append("trustRate2: " + requestData["trustRate2"])

        sessionData["playVideo"] = 0
        ret = {
            "imageURL": "images/Slide6.JPG",
            "buttonLabels": ["null", "START"],
            "instructionText": " ",
            "sessionData": sessionData,
            "buttonClass": "btn-primary"
        }
        data[mturk_id].append("round two")
        sessionData["picCount"] += 1
        #timestamp
        return json.dumps(ret)

    if sessionData["picCount"] == 12:
        sessionData["playVideo"] = 0
        Model2.restartTask(d, request.cookies.get('mturk_id', 'NOT SET'))
        ret = {
            "imageURL":
            "images/T100.jpg",
            "buttonLabels": [
                '<i class="fa fa-2x fa-rotate-right fa-rotate-225"></i>',
                '<i class="fa fa-2x fa-rotate-left fa-rotate-135"></i>'
            ],
            "instructionText":
            "Choose how you would like to rotate the table.",
            "sessionData":
            sessionData,
            "buttonClass":
            "btn-success"
        }
        #timestamp
        secondStart = datetime.datetime.now()
        data[mturk_id].append("secondStart: " + str(secondStart))
        timestart2[mturk_id] = secondStart
        sessionData["picCount"] += 1
        return json.dumps(ret)

    #record in log
    data[mturk_id].append(buttonClicked)

    #get next move
    currTableTheta, oldTableTheta, resultBelief, resultHAction, message = \
      Model2.getMove(d,request.cookies.get('mturk_id','NOT SET'),buttonClicked, prior)

    #debugging
    #print "Belief is: {}".format(resultBelief)
    #play the long video if the human-robot actions
    # are the same and it's the first time this is happening
    suffix = ""
    if oldTableTheta == currTableTheta and sessionData["playedLong"] == 0:
        suffix = "l"
        sessionData["playedLong"] = 1

    if (resultHAction == 'ROTATE_COUNTER_CLOCKWISE'):
        suffix = "l"
        videoLink = "videos/{}to{}{}.mp4".format(oldTableTheta, currTableTheta,
                                                 suffix)
    else:
        videoLink = "videos/{}to{}.mp4".format(oldTableTheta, currTableTheta)
    #print "VIDEOLINK:   " + videoLink
    imageLink = "images/T{}.jpg".format(currTableTheta)

    if currTableTheta == 0 or currTableTheta == 180:
        if sessionData["picCount"] == 9:
            Model2.setPrevGoalStateTheta(
                d, request.cookies.get('mturk_id', 'NOT SET'), currTableTheta)
            sessionData["picCount"] += 1
        elif sessionData["picCount"] == 13:
            sessionData["toSurvey"] = True
            #timestamp
            secondFinish = datetime.datetime.now()
            data[mturk_id].append("secondfinish: " + str(secondFinish))
            timeDelta = secondFinish - timestart2[mturk_id]
            data[mturk_id].append("timeDelta2: " +
                                  str(timeDelta.total_seconds()))

        data[mturk_id].append("trial" + str(trialIndx[mturk_id]) + "belief0:" +
                              str(resultBelief[0][0]))
        data[mturk_id].append("trial" + str(trialIndx[mturk_id]) + "belief1:" +
                              str(resultBelief[1][0]))
        data[mturk_id].append("trial" + str(trialIndx[mturk_id]) + "belief2:" +
                              str(resultBelief[2][0]))
        data[mturk_id].append("trial" + str(trialIndx[mturk_id]) + "belief3:" +
                              str(resultBelief[3][0]))
        data[mturk_id].append("trial" + str(trialIndx[mturk_id]) + "belief4:" +
                              str(resultBelief[4][0]))
        trialIndx[mturk_id] = trialIndx[mturk_id] + 1

        ret = {
            "videoURL": videoLink,
            "imageURL": imageLink,
            "buttonLabels": ["null", "Next"],
            "instructionText":
            "The table is in a horizontal position. You finished the task!",
            "sessionData": sessionData
        }
        return json.dumps(ret)
    else:
        sessionData["playVideo"] = 1
        ret = {
            "videoURL":
            videoLink,
            "imageURL":
            imageLink,
            "buttonLabels": [
                '<i class="fa fa-2x fa-rotate-right fa-rotate-225"></i>',
                '<i class="fa fa-2x fa-rotate-left fa-rotate-135"></i>'
            ],
            "instructionText":
            "<br>",
            "sessionData":
            sessionData,
            "buttonClass":
            "btn-success"
        }
        return json.dumps(ret)
Пример #10
0

#when the survey is approved by surveyhandler.js, the button requests this url
#handle_survey records the responses and gives a one line html page in response
#web browsers automatically add head/body syntax for this case
@app.post('/submit_survey')
def handle_survey():
    mturk_id = request.cookies.get('mturk_id', 'EXPIRED')
    for i in xrange(1, 17):
        data[mturk_id].append(request.forms.get(str(i)))
    #data[mturk_id].append(request.forms.get("t3"))
    with open('output/log.json', 'w') as outfile:
        json.dump(data, outfile)
    print("User {} submitted the survey".format(mturk_id))
    return "<p> Your answers have been submitted. ID for mturk: {}".format(
        mturk_id)


#the server only writes to log.json, so if there's some data there already,
#we'll copy it to another file
def backupLog():
    i = 1
    while (os.path.isfile("output/log-backup-{}.json".format(i))):
        i += 1
    shutil.copy("output/log.json", "output/log-backup-{}.json".format(i))


Model2.globalsInit()
backupLog()
run(app, host='0.0.0.0', port=8085)
Пример #11
0
with open('xtrain_gray.npy', mode="rb") as f:
    xtrain = np.load(f)
with open('ytrain_gray.npy', mode="rb") as f:
    ytrain = np.load(f)

idxs = np.arange(len(xtrain))  # -> array([0, 1, ..., 9999])
np.random.shuffle(idxs)
x_train = []
y_train = []
for i in idxs:
    x_train.append(xtrain[i])
    y_train.append(ytrain[i])
x_train = np.array(x_train)
y_train = np.array(y_train)

model = Model2.Model()
lr = 0.01
mn = 0.9
wd = 5e-04

optimization = Adam(model.parameters, learning_rate=lr)

batch_size = 1000
idxs = np.arange(len(xtrain))  # -> array([0, 1, ..., 9999])
np.random.shuffle(idxs)

for batch_cnt in range(0, len(xtrain) // batch_size):
    batch_indices = idxs[batch_cnt * batch_size: (batch_cnt + 1) * batch_size]
    batch = xtrain[batch_indices]  # random batch of our training data

    # compute the predictions for this batch by calling on model
Пример #12
0
def main():
    try:
        global args
        global canvas
        global settings

        controller = None
        filemerge = None
        view = None
        model = None

        settings.initialize_prefs(canvas.max_colors())

        # Only POSIX systems are supported at this point
        fileops = FileOpsPOSIX.FileOpsPOSIX()

        if len(args) == 2:
            left = args[0]
            right = args[1]

            left = os.path.realpath(left)
            right = os.path.realpath(right)

            # Instantiate the classes and link them together.
            model = Model2.Model(fileops, left, right)
            view = View2.View(canvas, model, settings)
        else:
            # len(args) == 3
            left = args[0]
            middle = args[1]
            right = args[2]

            left = os.path.realpath(left)
            middle = os.path.realpath(middle)
            right = os.path.realpath(right)

            # Instantiate the classes and link them together.
            model = Model3.Model(fileops, left, middle, right)
            view = View3.View(canvas, model, settings)

        requested_filemerge = settings.get_value('file_merge_program')
        # print('file_merge_program:', requested_filemerge)
        if requested_filemerge == 'vim':
            filemerge = FileMergeVim.FileMergeVim()
        else:
            filemerge = FileMergeEmacs.FileMergeEmacs()
        controller = Controller.Controller(model, view, canvas, filemerge)

        # Start the model. It will enumerate and then start comparing.
        model.start_enumerate()

        # Main event loop
        while not controller.need_to_quit:
            if canvas.need_to_resize:
                view.resize()
            model.render_again = False
            view.render()
            if ((model.state() == Model2.STATE_NORMAL
                 or model.state() == Model3.STATE_NORMAL)
                    and not model.render_again and not canvas.need_to_resize):
                input = canvas.get_input(0)  # wait indefinitely
            else:
                input = canvas.get_input(1)  # timeout in 1/10 second
            controller.process_input(input)

    finally:
        # print("quitting")
        if controller is not None:
            controller.destroy()
        if filemerge is not None:
            filemerge.destroy()
        if view is not None:
            view.destroy()
        if model is not None:
            model.destroy()
Пример #13
0
#coding=gbk
from matplotlib import pyplot as plt
import Model2
import Cal_para

args_model = [0, 0.6, -0.21]
args_time = [-1.55, 0, 17, 10000]
args_steps = [-1.80, 5]
args_grid = [[20, 20], [10, 2, 10, 2], 200]
time = 10000
route = []
newModel = Model2.Normal_Model(args_model=args_model,
                               args_grid=args_grid,
                               args_step=args_steps,
                               args_t=args_time,
                               simulate_time=time)
route = newModel.get_route()
draw = Cal_para.draw(route, newModel)
#draw.draw_visit_location_number_disput()
#draw.draw_location_disput()
draw.draw_location_disput_raster()
Пример #14
0
def main(args):
    classes = args.classes
    p = args.p
    q = args.q
    if args.modelType == 2:
        model = Net.ESPNet_Encoder(
            classes, p, q)  # Net.Mobile_SegNetDilatedIA_C_stage1(20)
        model_weight_file = args.weightsDir + os.sep + 'encoder' + os.sep + 'espnet_p_' + str(
            p) + '_q_' + str(q) + '.pth'
        if not os.path.isfile(model_weight_file):
            print(
                'Pre-trained model file does not exist. Please check ../pretrained/encoder folder'
            )
            exit(-1)
        model.load_state_dict(torch.load(model_weight_file))
    elif args.modelType == 1:
        model = Net.ESPNet(classes, p,
                           q)  # Net.Mobile_SegNetDilatedIA_C_stage1(20)
        model_weight_file = args.weightsDir + os.sep + 'decoder' + os.sep + 'espnet_p_' + str(
            p) + '_q_' + str(q) + '.pth'
        if not os.path.isfile(model_weight_file):
            print(
                'Pre-trained model file does not exist. Please check ../pretrained/decoder folder'
            )
            exit(-1)
        model.load_state_dict(torch.load(model_weight_file))
    else:
        print('Model not supported')

    if (not args.cpu):
        model = model.cuda(
        )  #.half()    #HALF seems to be doing slower for some reason
    #model = torch.nn.DataParallel(model).cuda()

    model.eval()

    images = torch.randn(args.batch_size, args.num_channels, args.height,
                         args.width)

    if (not args.cpu):
        images = images.cuda()  #.half()

    time_train = []

    i = 0

    while (True):
        #for step, (images, labels, filename, filenameGt) in enumerate(loader):

        start_time = time.time()

        inputs = Variable(images, volatile=True)
        outputs = model(inputs)

        #preds = outputs.cpu()
        if (not args.cpu):
            torch.cuda.synchronize(
            )  #wait for cuda to finish (cuda is asynchronous!)

        if i != 0:  #first run always takes some time for setup
            fwt = time.time() - start_time
            time_train.append(fwt)
            print("Forward time per img (b=%d): %.3f (Mean: %.3f)" %
                  (args.batch_size, fwt / args.batch_size,
                   sum(time_train) / len(time_train) / args.batch_size))

        time.sleep(1)  #to avoid overheating the GPU too much
        i += 1
Пример #15
0
def model2():
    return Model2.Model2()