def require_project():
     Definitions.require_package()
     DisasmTools.require_package()
     FixTools.require_package()
     IDAItems.require_package()
     MiscTools.require_package()
     SrchTools.require_package()
def main():
    #lists and dictionaries used for this instance
    states=[]
    states2 = {}
    catagory=[]
    catagoryDict={}

    #imports the csv file and appends the data to corrisponding lists
    with open('U.S._Chronic_Disease_Indicators__CDI_.csv', newline='') as f:
        reader = csv.reader(f)
        for row in reader:
            states.append(row[1])
            catagory.append(row[3])

    #sorts lists into dictionaries without duplicates
    dfi.classify(catagory, catagoryDict)
    dfi.classify(states, states2)

    #counts frequency of diseases and adds to corrisponding key in dictionary
    dfi.count(catagory, catagoryDict)

    #generates wordcloud using list of diseases
    dfi.wordcloud(catagory)
    #generates color plot using list of deiseases and dictionary of states
    dfi.colorize(catagory, states2)

    #opens html file
    webbrowser.open("htmlthing.html")
Example #3
0
def testGame(envName, verbose=True):
    env = Definitions.makeSeededEnvironment(envName)
    net = Net.Net(env.observation_space, env.action_space)
    net = net.to(Definitions.device)
    policy = PolicyLearner.PolicyLearner(net)
    dataHandler = DataHandler.DataHandler(policy, env)

    sumReward = 0.
    maxReward = -1e9
    nIters = 20
    for i in range(nIters):
        dataHandler.render(episodes=3)

        confidenceMul = i
        policy.setConfidenceMul(confidenceMul)
        for j in range(10):
            reward = dataHandler.generate(episodes=10)
            dataHandler.reset(keepSize=40000)
            dataHandler.train(batchSize=8, useFraction=0.1)
        if verbose:
            print(envName, "   iteration:",
                  str(i + 1) + "/" + str(nIters),
                  "   reward:", reward, "   trained on:",
                  len(dataHandler.inputs), "    confidence multipiler:",
                  confidenceMul)
        sumReward += reward
        maxReward = max(maxReward, reward)
        Definitions.saveModel(net, envName, i + 1, reward)

    avgReward = sumReward / nIters
    if verbose:
        print("%s   Avg: %.2f   Max: %.2f" % (envName, avgReward, maxReward))
        print()
    env.close()
    return avgReward, maxReward
def main():
    #lists and dictionaries used for this instance
    states = []
    states2 = {}
    catagory = []
    catagoryDict = {}

    #imports the csv file and appends the data to corrisponding lists
    with open('U.S._Chronic_Disease_Indicators__CDI_.csv', newline='') as f:
        reader = csv.reader(f)
        for row in reader:
            states.append(row[1])
            catagory.append(row[3])

    #sorts lists into dictionaries without duplicates
    dfi.classify(catagory, catagoryDict)
    dfi.classify(states, states2)

    #counts frequency of diseases and adds to corrisponding key in dictionary
    dfi.count(catagory, catagoryDict)

    #generates wordcloud using list of diseases
    dfi.wordcloud(catagory)
    #generates color plot using list of deiseases and dictionary of states
    dfi.colorize(catagory, states2)

    #opens html file
    webbrowser.open("htmlthing.html")
Example #5
0
def add_to_dataframe(path, date, name):
    for x in range(1, len(d.definitions(name))):
        for filename in os.listdir(path, date, ):
            if filename.endswith(+".csv") and filename.beginswith(date+d.definitions(name)[x]):
                print(os.path.join(path, filename))
            else:
                continue
Example #6
0
def preprocessMuscle(entity):

    for i in range(0,len(entity.muscles)):
        if entity.muscles[i].mesh == None:
            entity.muscles[i].mesh = Graphics.VBO_cylinder(6,2)
            Graphics.buildVBO(entity.muscles[i])

        P1 = entity.muscles[i].Aworld
        P2 = entity.muscles[i].Bworld
        P3 = entity.muscles[i].Cworld
        if P1 == [] or P2 == [] or P3 == []:
            continue

        """ set muscle model matrix """
        Ux = Definitions.vector4D((0, 1, 0, 0))
        Vx = Definitions.vector4D((0, P1[0][0]-P2[0][0], P1[0][1]-P2[0][1], P1[0][2]-P2[0][2]))
        scale = math.sqrt(Vx.x*Vx.x + Vx.y*Vx.y + Vx.z*Vx.z)
        center = Definitions.vector4D((0, 0.5*(P1[0][0]+P2[0][0]), 0.5*(P1[0][1]+P2[0][1]), 0.5*(P1[0][2]+P2[0][2])))
        Wx = Definitions.vector4D.AngleAxisBetween2Vec(Ux,Vx)
    
        Definitions.modelMatrix.push()
        Definitions.modelMatrix.set(Definitions.I)
        Definitions.modelMatrix.translate(center.x, center.y, center.z)
        Definitions.modelMatrix.rotate(Wx.o, Wx.x, Wx.y, Wx.z)

        """ readjust facing direction """
        uy = np.dot(np.array([0, 1, 0, 0]), Definitions.modelMatrix.peek()) # Note : not same as Ux because here it's [x,y,z,o] and in vector4D it's [o,x,y,z]
        vy = np.array([0.5*(P1[0][0]+P2[0][0])-P3[0][0], 0.5*(P1[0][1]+P2[0][1])-P3[0][1], 0.5*(P1[0][2]+P2[0][2])-P3[0][2], 0])
        Uy = Definitions.vector4D((0, uy[0], uy[1], uy[2]))
        Vy = Definitions.vector4D((0, vy[0], vy[1], vy[2]))
        Wy = Definitions.vector4D.AngleAxisBetween2Vec(Uy,Vy)
        if Definitions.vector4D.VecDot(Vx,Wy) < 0:
            Wy.o = -Wy.o

        Definitions.modelMatrix.rotate(Wy.o, 1, 0, 0)
            
        Definitions.modelMatrix.scale(scale,0.03,0.03)

        entity.muscles[i].modelMatrix = Definitions.modelMatrix.peek()
        
        if entity.muscles[i].id == Definitions.lookingAtID:
            Definitions.lookingAt = np.dot(np.array([[0, 0, 0, 1]]), entity.muscles[i].modelMatrix)
        
        for sensor in Sensors.virtuSens + Sensors.zoiSens:
            if sensor.attach == entity.muscles[i].tag:
                sensor.h = 0.6
                if sensor.type == 'Eye':
                    sensor.h = 0.4
                if ID.idCategory(sensor.id) == ID.ZOI:
                    sensor.h = 0.55
                Sensors.preprocessSensor(sensor, scale, 0.03, 0.03)
        Definitions.modelMatrix.pop()
Example #7
0
def loadPosture(entity, fileName):
    if fileName == "":
        return

    file = open(pathAvatars + entity.tag + '/' + pathPostures + fileName + extension, 'r')
    line = file.readline() # read entity position
    px, py, pz, trash = line.split(";")
    line = file.readline() # read entity position
    orientation = map(float, line.split(";"))
    entity.position = [float(px), float(py), float(pz)]
    entity.orientation = orientation
    while True:
        line = file.readline() # read part name
        if line == "":
            break
        ID, a,b,c = map(str, line.split(";"))
        line = file.readline() # read part orientations
        swing = map(float, line.split(";"))
        line = file.readline() # read part orientations
        twist = map(float, line.split(";"))
        for part in entity.limbs:
            if part.tag == ID:
                part.swing = swing
                part.twist = twist
                part.mesh.twistVBO(Definitions.vector4D(part.twist).quatAngle())
                break
    file.close()
def downloadZip(mes_Min, ano_Min, mes_Max, ano_Max, nome):
    setup.setup()
    end = 1
    while 1 == 1:
        url = Definitions.definitions(nome)[0]
        if mes_Min <= 9:
            url = url + '/' + str(ano_Min) + '0' + str(mes_Min)
        else:
            url = url + '/' + str(ano_Min) + str(mes_Min)
        print(url)

        request = requests.get(url, allow_redirects=True)
        print(request.headers.get('content-type'))
        if mes_Min <= 9:
            open(
                'Data/00_Zip/' + nome + str(ano_Min) + '-' + '0' +
                str(mes_Min) + '.zip', 'wb').write(request.content)
            unzipper('Data/00_Zip/' + nome + str(ano_Min) + '-' + '0' +
                     str(mes_Min) + '.zip')
        else:
            open(
                'Data/00_Zip/' + nome + str(ano_Min) + '-' + str(mes_Min) +
                '.zip', 'wb').write(request.content)
            unzipper('Data/00_Zip/' + nome + str(ano_Min) + '-' +
                     str(mes_Min) + '.zip')
        mes_Min += 1
        if mes_Min == 12:
            ano_Min = ano_Min + 1
            mes_Min = 1
        if end == 0:
            break
        if not (mes_Min != mes_Max or ano_Min != ano_Max):
            end = 0
Example #9
0
 def test_accesssStartPoint(self):
     legalPoint = (6, 9)
     illegalPoint = 10
     carrier = Definitions.InfoCarrier()
     carrier.setStartPoint(legalPoint)
     self.assertEqual(carrier.getStartPoint(), legalPoint)
     self.assertRaises(AssertionError, carrier.setStartPoint, illegalPoint)
Example #10
0
 def test_accessDuration(self):
     legalDuration = 18
     illegalDuration = 18.0
     carrier = Definitions.InfoCarrier()
     carrier.setDuration(legalDuration)
     self.assertEqual(carrier.getDuration(), legalDuration)
     self.assertRaises(AssertionError, carrier.setDuration, illegalDuration)
Example #11
0
 def test_accessSpeed(self):
     legalSpeed = 0.0
     illegalSpeed = 16
     carrier = Definitions.InfoCarrier()
     carrier.setSpeed(legalSpeed)
     self.assertEqual(carrier.getSpeed(), legalSpeed)
     self.assertRaises(AssertionError, carrier.setSpeed, illegalSpeed)
Example #12
0
def augment_state(state):
    #import pdb
    #pdb.set_trace()
    # TODO: Move into Definitions + Add propapagation
    return tf.concat(
        to_col([State.TFP(state), State.depr(state)] +
               [getattr(State, "K" + str(i))(state) for i in range(2, 7)] + [
                   Definitions.K_total(state, None),
                   Definitions.r(state, None),
                   Definitions.w(state, None),
                   Definitions.Y(state, None)
               ] + [
                   Definitions.r(state, None) *
                   getattr(State, "K" + str(i))(state) for i in range(2, 7)
               ]),
        axis=1)
Example #13
0
 def test_accessMoveDirection(self):
     legalDirection = Definitions.Rotate.NA
     illegalDirection = 7
     carrier = Definitions.InfoCarrier()
     carrier.setMoveDirection(legalDirection)
     self.assertEqual(carrier.getMoveDirection(), legalDirection)
     self.assertRaises(AssertionError, carrier.setMoveDirection,
                       illegalDirection)
Example #14
0
 def test_accessSourceImageName(self):
     legalName = "test.jpg"
     illegalName = 888
     carrier = Definitions.InfoCarrier()
     carrier.setSourceImageName(legalName)
     self.assertEqual(carrier.getSourceImageName(), legalName)
     self.assertRaises(AssertionError, carrier.setSourceImageName,
                       illegalName)
Example #15
0
 def test_accessDestinationVideoName(self):
     legalName = "test.avi"
     illegalName = 999
     carrier = Definitions.InfoCarrier()
     carrier.setDestinationVideoName(legalName)
     self.assertEqual(carrier.getDestinationVideoName(), legalName)
     self.assertRaises(AssertionError, carrier.setDestinationVideoName,
                       illegalName)
Example #16
0
 def test_accessMovePattern(self):
     legalPattern = Definitions.MovePattern.NA
     illegalPattern = 1.1
     carrier = Definitions.InfoCarrier()
     carrier.setMovePattern(legalPattern)
     self.assertEqual(carrier.getMovePattern(), legalPattern)
     self.assertRaises(AssertionError, carrier.setMovePattern,
                       illegalPattern)
Example #17
0
def equations(state, policy_state):
    E_t = State.E_t_gen(state, policy_state)

    loss_dict = {}

    betaK = Definitions.betaK(state, policy_state)

    # original eq 1
    loss_dict['eq_1'] = lambday_norm - (
        State.nux(state) /
        (Cy_norm)) + beta * b_habit * E_t(lambda s, ps: State.nux(s) /
                                          (Definitions.Cy_norm(s, ps)))

    loss_dict['eq_2'] = lambday_norm - beta * (
        1.0 + iy) * E_t(lambda s, ps: Definitions.lambday_norm(s, ps) *
                        (1.0 / (1.0 + Definitions.piy_norm(s, ps))))

    loss_dict['eq_3'] = lambday_norm - muy_norm * State.Zx(state) * (
        (1.0 - kappa / 2.0 * (Iy_norm / State.Ix(state) - 1.0)**2.0) - kappa *
        (Iy_norm / State.Ix(state) - 1.0) * Iy_norm / State.Ix(state)
    ) - beta * E_t(lambda s, ps: Definitions.muy_norm(s, ps) * State.Zx(
        s) * kappa * (Definitions.Iy_norm(s, ps) / Iy_norm - 1.0) *
                   (Definitions.Iy_norm(s, ps) / Iy_norm)**2.0)

    return loss_dict
Example #18
0
def prepare_data(df_train,
                 df_test,
                 feature_col,
                 target_col,
                 binary=True,
                 category=True,
                 target=True):
    """ Function to take prepare the input data for model prediction """
    train, test = lib.prepare_test_train_data(df_train,
                                              df_test,
                                              binary=binary,
                                              category=category,
                                              scaling=False,
                                              target=target)
    df_train_scaled = lib.scaleData(train[feature_col])
    df_test_scaled = lib.scaleData(test[feature_col])

    return df_train_scaled, train[target_col], df_test_scaled, test[target_col]
Example #19
0
def main():
    env = gym.make(envName)
    net = Definitions.loadModel(envName,
                                iteration=iteration,
                                loadBest=(iteration is None))
    policy = PolicyLearner.PolicyLearner(net)
    policy.setConfidenceMul(confidenceMul)
    dataHandler = DataHandler.DataHandler(policy, env)
    dataHandler.render(episodes=int(1e9))
Example #20
0
def equations(state, policy_state):
    E_t = State.E_t_gen(state, policy_state)
    
    loss_dict = {}

    delta_1 = Definitions.delta_1(state, policy_state)
    
    #original equation
    loss_dict['eq_1'] = E_t(lambda s, ps: PolicyState.Cy(policy_state) * PolicyState.Cy(ps) * PolicyState.lambday(policy_state) - PolicyState.Cy(ps) * State.nux(state) + PolicyState.Cy(policy_state) * beta * b_habit * State.nux (s))    
    
    # original eq 1
    #loss_dict['eq_1'] = PolicyState.lambday(policy_state) - (State.nux(state) / (PolicyState.Cy(policy_state) )) + beta * b_habit * E_t(lambda s, ps: State.nux (s) / (PolicyState.Cy(ps)))    
        
    loss_dict['eq_2'] = PolicyState.lambday(policy_state) * PolicyState.Ry(policy_state) - PolicyState.muy(policy_state) * (delta_1 + delta_2 *(PolicyState.uy(policy_state) - 1.0)) 
    
    loss_dict['eq_3'] = PolicyState.lambday(policy_state) - beta * (1.0 + PolicyState.iy(policy_state)) * E_t(lambda s, ps: (1.0/(1.0 + PolicyState.piy(ps) )))
    
    loss_dict['eq_4'] = PolicyState.lambday(policy_state) - PolicyState.muy(policy_state) * State.Zx(state) * ((1.0 - kappa/2.0 * (PolicyState.Iy(policy_state) - 1.0 )**2.0) - kappa * (PolicyState.Iy(policy_state) - 1.0) * PolicyState.Iy(policy_state)) - beta * E_t(lambda s, ps: PolicyState.muy(ps) * State.Zx(s) * kappa * (PolicyState.Iy(ps) - 1.0) * PolicyState.Iy(ps)**2.0 )
    
    loss_dict['eq_5'] = PolicyState.muy(policy_state) - beta * E_t(lambda s, ps: PolicyState.muy(ps) * PolicyState.Ry(ps) * PolicyState.uy(ps) + PolicyState.muy(ps) * (1.0 - (delta_0 + delta_1 * (PolicyState.uy(ps) - 1.0) + delta_2/2.0 * (PolicyState.uy(ps) - 1.0)**2.0 )))   
    
    loss_dict['eq_6'] = PolicyState.h1y(policy_state) * PolicyState.whashy(policy_state)**(eps_w * (1.0 + chi)) - State.nux(state) * State.psix(state) * PolicyState.wy(policy_state)**(eps_w * (1.0 + chi)) * PolicyState.Ny(policy_state)**(1.0 + chi) - phi_w * beta * (1.0 + PolicyState.piy(policy_state))**(-zeta_w * eps_w * ( 1.0 + chi )) * E_t(lambda s, ps: (1.0 + PolicyState.piy(ps))**(eps_w * (1.0 + chi)) * PolicyState.whashy(ps)**(eps_w * (1.0 + chi)) * PolicyState.h1y(ps))
 
    loss_dict['eq_7'] = PolicyState.h2y(policy_state) * PolicyState.whashy(policy_state)**eps_w - PolicyState.lambday(policy_state) * PolicyState.wy(policy_state)**eps_w * PolicyState.Ny(policy_state) - phi_w * beta * (1.0 - PolicyState.piy(policy_state))**(zeta_w * (1.0 - eps_w)) * E_t(lambda s, ps: (1.0 + PolicyState.piy(ps))**(eps_w -1.0 ) * PolicyState.whashy(ps)**eps_w * PolicyState.h2y(ps))
    
    loss_dict['eq_8'] = PolicyState.whashy(policy_state) * PolicyState.h2y(policy_state) - ( eps_w / (eps_w - 1.0)) * PolicyState.h1y(policy_state)
    
    loss_dict['eq_9'] = PolicyState.wy(policy_state) *  PolicyState.Ny(policy_state) - ((1.0 - alpha) / alpha) * PolicyState.Khaty(policy_state) *  PolicyState.Ry(policy_state)
    
    loss_dict['eq_10'] = (1.0 - alpha) * State.Ax(state) * PolicyState.mcy(policy_state) * PolicyState.Khaty(policy_state)**alpha - PolicyState.wy(policy_state) * PolicyState.Ny(policy_state)**alpha
        
    loss_dict['eq_11'] = PolicyState.x1y(policy_state) - PolicyState.lambday(policy_state) * PolicyState.mcy(policy_state) * PolicyState.Yy(policy_state) - phi_p * beta * (1.0 + PolicyState.piy(policy_state))**(-zeta_p * eps_p) * E_t(lambda s, ps: (1.0 + PolicyState.piy(ps))**eps_p * PolicyState.x1y(ps) )
    
    loss_dict['eq_12'] = PolicyState.x2y(policy_state) - PolicyState.lambday(policy_state) * PolicyState.Yy(policy_state) - phi_p * beta * ( 1.0 + PolicyState.piy(policy_state))**(zeta_p *(1.0 - eps_p)) * E_t(lambda s, ps: (1.0 + PolicyState.piy(ps))**(eps_p - 1.0) * PolicyState.x2y(ps))
    
    loss_dict['eq_13'] = ((1.0 + PolicyState.pihashy(policy_state)) * PolicyState.x2y(policy_state) - (eps_p / (eps_p - 1.0)) * (1.0 + PolicyState.piy(policy_state))* PolicyState.x1y(policy_state))

    loss_dict['eq_14'] = PolicyState.Yy(policy_state) - PolicyState.Cy(policy_state) - b_habit * State.Cx(state) - PolicyState.Iy(policy_state) * State.Ix(state) - State.Gx(state) 
    
    loss_dict['eq_15'] = PolicyState.Ky(policy_state) - State.Zx(state) * (1.0 - kappa/2.0 * (PolicyState.Iy(policy_state) - 1.0 )**2.0) * PolicyState.Iy(policy_state)*State.Ix(state) - (1.0 - (delta_0 + delta_1 * (PolicyState.uy(policy_state) - 1.0) + delta_2/2.0 * (PolicyState.uy(policy_state) - 1.0)**2.0)) * State.Kx(state)       
    
    loss_dict['eq_16'] = State.Ax(state) * PolicyState.Khaty(policy_state)**alpha * PolicyState.Ny(policy_state)**(1.0 - alpha) - F_prod - PolicyState.Yy(policy_state) * PolicyState.nupy(policy_state)
    
    loss_dict['eq_17'] = PolicyState.Khaty(policy_state) - PolicyState.uy(policy_state) * State.Kx(state)
    
    loss_dict['eq_18'] = PolicyState.nupy(policy_state) * (1.0 + PolicyState.piy(policy_state))**(- eps_p) - (1.0 - phi_p) * (1.0 + PolicyState.pihashy(policy_state))**(- eps_p) - (1.0 + State.pix(state))**(-zeta_p*eps_p) * phi_p * State.nupx(state)
    
    loss_dict['eq_19'] =  (1.0 + PolicyState.piy(policy_state))**(1.0 - eps_p) - (1.0 - phi_p) * (1.0 + PolicyState.pihashy(policy_state) )**(1.0 - eps_p) - (1.0 + State.pix(state))**(zeta_p * (1.0 - eps_p)) * phi_p
    
    loss_dict['eq_20'] = PolicyState.wy(policy_state)**(1.0 - eps_w) - (1.0 - phi_w)*PolicyState.whashy(policy_state)**(1.0 - eps_w) - (1.0 + State.pix(state))**(zeta_w * (1.0 - eps_w)) * phi_w * (1.0 + PolicyState.piy(policy_state))**(eps_w - 1.0) * State.wx(state)**(1.0 - eps_w)

    loss_dict['eq_21'] = PolicyState.iy(policy_state) - tf.math.maximum((1.0 - rho_i) * i_ss + rho_i * State.ix(state) +  (1.0 - rho_i) * (phi_pi * (PolicyState.piy(policy_state) - pi_ss) + phi_y * (tf.math.log(PolicyState.Yy(policy_state)) - tf.math.log(State.Yx(state))) + State.mx(state)), i_LB )

    return loss_dict
Example #21
0
def conf_matrix(conf_space, n):
    from Classification.Pasta import read_seq, read_preset
    '''
    m = length of sequence
    '''
    M = []
    for conf, error in conf_space:
        line = list('*'*n)
        for frag, i in conf:
            line[i:i + len(frag)] = [DEF.three2One(r.name) for r in frag.residues]
        M.append(line)
    return M
Example #22
0
def equations(state, policy_state):
    E_t = E_t_gen(state, policy_state)

    loss_dict = {}

    for i in range(1, 6):
        loss_dict['eq_' + str(i)] = -1 + (
            (beta * E_t(lambda s, ps: Definitions.r(s, ps) *
                        (getattr(Definitions, "c" + str(i + 1))
                         (s, ps))**(-gamma)))**(-1 / gamma)) / (getattr(
                             Definitions, "c" + str(i))(state, policy_state))

    return loss_dict
Example #23
0
def predict_data(Xtest, Ytest):
    """ Function to load the already dumped model and predict the result """

    # path = os.getcwd()
    with open('model.mdl', 'rb') as model_file:
        model = pickle.load(model_file)
        # st.text(model)
        predict, confusion_matrix, class_rpt = lib.predict_data(
            model, Xtest, Ytest)

        # compute model score score
        # x_train, x_test, y_train, y_test = train_test_split(Xtrain, Ytrain, test_size=0.3, random_state=123)
        # score = model.score(Xtest, Ytest)

        return predict, confusion_matrix, class_rpt
Example #24
0
def select_item(item):
    print(Definitions.item_desc(item.name, item.itemType))

    # Checks the item type of the item
    if item.itemType == "Weapon":
        print("\nDamage: +", item.damage)

    elif item.itemType == "Armor":
        print("\nArmor: +", item.armor)

    # Calls the unequip/equip function and passes it the current item
    equip_unequip_item(item)

    # Updates the players stats
    update_char_stats(item, Definitions.charStats)
Example #25
0
    def new_spectra(key, lipid, adducts):
        def new_list():  # .mgf format
            lst = {
                "Name:":
                f"{key} {'_'.join(str(nam) for nam in name)} {adduct}",
                "Spectrum_type:": "MS2",
                "Ion_mode:": Masses[adduct][1],
                "PrecursorMZ:": f"{mass + Masses[adduct][0]:.6f}",
                "Precursor_type:": adduct,
                "Num Peaks:": len(peaks),
                "peaks": peaks
            }
            return lst

        Mass = {  # If statements results into tuples, whereas dictionary gives floats.
            'Glycerol':
            92.047344 + sum((tail[0] - Masses['H2O'])
                            for tail in lipid),  # Sums tails for glycerolipids
            'SB':
            Masses['H2O'] + sum(tail[0] - Masses['H2O'] for tail in lipid)
        }  # Sums tails for sphingolipids
        mass = Mass[classes[key][1][1]]  # classes[key][1][1] is backbone
        if classes[key][1][2]:
            mass += (classes[key][1][2] - Masses['H2O'])  # Adds headgroup mass

        name = [tail[1] for tail in lipid
                ]  # Put together the name from tail composition and class
        if len(name) < 2:
            name.append(
                '0:0')  # Adds 0:0 to the name for Lyso GPLs / Sphingosines
        if key in ('MAG', 'DAG'):
            name.append(
                '0:0'
            )  # Adds another 0:0 to the name for MAGs and DAGs to complement TAGs

        lst = []
        for adduct in adducts:
            if (D.Masses[adduct][1] == 'P'
                    and D.Charge_Opts['POS']) or (D.Masses[adduct][1] == 'N'
                                                  and D.Charge_Opts['NEG']):
                peaks = D.generate_peaks(key, mass, lipid, adduct)
                lst.append(new_list())
            else:
                pass
        return lst
Example #26
0
 def policy_step(prev_state, policy_state):
     # coming from the lagged policy / definition
     policy_step = tf.zeros_like(prev_state)
     #policy_step = State.update(policy_step, "Kx",PolicyState.Ky(policy_state))
     policy_step = State.update(policy_step, "Kx",
                                Definitions.Ky(prev_state, policy_state))
     policy_step = State.update(
         policy_step, "Cx", (Definitions.Cy_norm(prev_state, policy_state) +
                             Parameters.b_habit * State.Cx(prev_state)))
     policy_step = State.update(
         policy_step, "Ix", (Definitions.Iy_norm(prev_state, policy_state)))
     policy_step = State.update(
         policy_step, "Yx", Definitions.Yy_norm(prev_state, policy_state))
     policy_step = State.update(
         policy_step, "wx", Definitions.wy_norm(prev_state, policy_state))
     policy_step = State.update(
         policy_step, "nupx", Definitions.nupy_norm(prev_state,
                                                    policy_state))
     policy_step = State.update(
         policy_step, "pix", Definitions.piy_norm(prev_state, policy_state))
     return State.update(policy_step, "ix",
                         Definitions.iy(prev_state, policy_state))
Example #27
0
    def fromString(cls, val: str) -> Union["Parameter", None]:
        if val in Definitions.registers:
            return Parameter.fromRegister(Definitions.registers[val])

        if re.match("^\\[([A-D]X)\\+IX\\]$", val):
            val = val[1:-4]
            return Parameter.fromIndexed(Definitions.registers[val])

        if re.match("^\\[([A-D]X|SP|IP|IX)\\]$", val):
            val = val[1:-1]
            return Parameter.fromRef(Definitions.registers[val])

        n = Definitions.parseNumber(val)
        if n != None:
            return Parameter.fromDirect(n)

        if re.match("^([0-9a-zA-Z_]{1,32})$", val):
            return Parameter.fromLabel(val[:Definitions.MAXLABELNAMELENGTH])

        return None
Example #28
0
 def powerLogic(stream):
     byindex = stream.map(lambda x: ((Definitions.getMaxPowerMeridian(x['prescription']),x['index'], x['lab_id']), 1)) \
         .reduceByKey(lambda a, b: a + b) \
         .transform(lambda x: x.sortBy(lambda (k, v): -v))
     return byindex
Example #29
0
as well as the 5 blog subsections:
    Rxeform, ShatterZones, Supreme Court Spotlight, UCPU, Cartoons
'''

import Definitions
import csv
import urllib2
from bs4 import BeautifulSoup
from Definitions import getDate
from Definitions import getAge

with open('data/gate_articles.csv', 'wb') as csvfile:
    gatewrite = csv.writer(csvfile, dialect='excel')
    gatewrite.writerow(["Article Title", "Article Link", "Date", "Age (days)", "Category", "Page Number"])
    
    hashMaxPages = Definitions.makeHash()
    #for each element of the hash map
    for topic in hashMaxPages:
        #page_max is maximum number of pages to look through given the topic
        page_max = hashMaxPages[topic].max_pages
        #looks through each page from 1 to page_max - 1
        for page in range(1, page_max):
            #url_extend is specific to the topic
            url_extend = "page/" + str(page)
        
            html_doc = urllib2.urlopen("http://uchicagogate.com/category/" + hashMaxPages[topic].url + url_extend)
            
            #parses html for web page
            soup = BeautifulSoup(html_doc)
            
            #finds the h2tags with attribute class of value "entry-title"
Example #30
0
num_list = []
for course in courses:
    if course.find(",") != -1:
        full_name = course.split(",", 1)[0]
        name = full_name.encode('utf-8')
        type = course.split(",", 1)[1]
        if "rsitetinÄ—" in type:
            type = "BUS"
        x = full_name + " " + type
        num += 1
        id = uuid.uuid5(uuid.NAMESPACE_X500, x)
        if cId == id:
            num_list.append(num)
            continue
        cId = id
        course_instance = Definitions.course(id, name[:-1], type)
        course_list.append(course_instance)

teacher_list = Scrapery.teacher_list

counter = 0
count = 0
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)
funky_list = []
for link in tags:
    print("parsing: " + link)
    if counter in num_list:
        count += 1
        counter += 1
Example #31
0
def preprocessSensor(sensor, x, y, z):
    """ update sensor coordinates """
    if sensor.id == selectedSens:
        sensor.x += Events.incSens[0]
        if sensor.x < -0.5:
            sensor.x = -0.5
        elif sensor.x > 0.5:
            sensor.x = 0.5
        sensor.t += Events.incSens[1]
        sensor.s += Events.incSens[2]
        if Events.resetSens == True:
            sensor.x = 0
            sensor.t = 90
            sensor.s = 90
        UI.uiSensor.updateTable()

    Definitions.modelMatrix.push()
    """ sensor orientation """
    u = Definitions.vector4D.Eul2Quat(Definitions.vector4D((0, 0, 90, 0)))
    v = Definitions.vector4D.Eul2Quat(Definitions.vector4D(
        (0, 0, 0, sensor.t)))
    s = Definitions.vector4D.Eul2Quat(
        Definitions.vector4D((0, 0, sensor.s - 90, 0)))
    w = Definitions.vector4D.Eul2Quat(
        Definitions.vector4D((0, time.clock() * 100, 0, 0)))
    t = Definitions.vector4D.Quat2Vec(
        Definitions.vector4D.QuatProd(
            u,
            Definitions.vector4D.QuatProd(v,
                                          Definitions.vector4D.QuatProd(s,
                                                                        w))))
    """ model matrix update """
    Definitions.modelMatrix.push()
    Definitions.modelMatrix.translate(sensor.x, 0, 0)

    if math.sqrt(t.x * t.x + t.y * t.y + t.z * t.z) >= 0.0001:
        Definitions.modelMatrix.rotate(t.o, t.x, t.y, t.z)

        Definitions.modelMatrix.push()
        Definitions.modelMatrix.scale(sensor.h, 1, 1)
        Definitions.modelMatrix.translate(0.5, 0, 0)
        """ store linkModelMatrix in sensor """
        sensor.linkModelMatrix = Definitions.modelMatrix.peek()

        Definitions.modelMatrix.pop()

    Definitions.modelMatrix.translate(sensor.h, 0, 0)
    Definitions.modelMatrix.rotate(-t.o, t.x, t.y, t.z)
    Definitions.modelMatrix.scale(1 / x, 1 / y, 1 / z)
    Definitions.modelMatrix.rotate(t.o, t.x, t.y, t.z)

    for sensorData in sensorGraphics:
        if sensor.type == sensorData.type:
            scale = sensorData.scale
            break
    Definitions.modelMatrix.scale(scale, scale, scale)

    Definitions.modelMatrix.translate(0.5, 0, 0)
    """ store modelMatrix in sensor """
    sensor.modelMatrix = Definitions.modelMatrix.peek()

    Definitions.modelMatrix.pop()
    Definitions.modelMatrix.pop()
maxX = window_width
maxY = window_height

defs_.pygame.init()
clock = pygame.time.Clock()
win = pygame.display.set_mode((window_width, window_height))
defs_.pygame.display.set_caption("BumbleBeeN'TheHood")
FPS = 30

#file_json = 'Generations_data.json'
file_json = 'Generations_data_double_trapezoid_1.json'


hidden_neurons = 24
NN = defs_.RecurrentNeuralNetwork(12, 2, 12)
start_point = defs_.Point(100, 100)
robot = defs_.Robot(start_point, 25, 1, 12, 50, 10, 1, hidden_neurons)
robot.create_adjust_sensors()

#Reading the data from json, 90th generation Best fitness
chromosome = defs_.read_weights_from_json(file_json, 23, 1)
robot.NN.update_weights(chromosome)


layout = 'double box'

walls = defs_.Layout(layout)
dust = defs_.Dust(150, maxX, maxY, 8, win)

run = True
def stick(entity=characteristics(), offset=(0, 0, 0), rotation=(0, 0, 0, 0)):
    global part
    global selectedPart
    if part + 1 >= len(entity.parts):
        return

    part += 1
    current_part = part
    """ Check if part is selected """
    partIsSelected = False
    for selectedPart in selectedParts:
        if selectedPart == entity.parts[current_part][Data_id]:
            partIsSelected = True
            break
        if selectedPart == 'Wrist' and entity.parts[current_part][
                Data_id] == "Origin":
            partIsSelected = True
            break
    """ default orientation of part """
    l = Definitions.vector4D.Eul2Quat(
        Definitions.vector4D(
            (0, entity.parts[current_part][Data_angleRepos][0],
             entity.parts[current_part][Data_angleRepos][1],
             entity.parts[current_part][Data_angleRepos][2])))
    """ current rotation of part """
    q = Definitions.vector4D((entity.parts[current_part][Data_angle]))
    """ new rotation to implement """
    #if partIsSelected == True:
    #    """ swing command with saturations """
    #    sw = Definitions.vector4D.Swing(Definitions.vector4D((entity.parts[current_part][Data_swing])), (entity.parts[current_part][Data_saturation]))
    #    entity.parts[current_part][Data_swing] = [sw.o,sw.x,sw.y,sw.z]
    #
    #    """ twist command with saturations """
    #    tw = Definitions.vector4D.Twist(Definitions.vector4D((entity.parts[current_part][Data_twist])), (entity.parts[current_part][Data_saturation]))
    #    entity.parts[current_part][Data_twist] = [tw.o,tw.x,tw.y,tw.z]
    #
    #    """ resulting orientation of part ... """
    #    q = Definitions.vector4D.QuatProd(sw, tw)
    #    entity.parts[current_part][Data_angle] = [q.o,q.x,q.y,q.z]
    """ Transformations """
    #glPushMatrix()
    Definitions.modelMatrix.push()
    """ offset to apply """
    glTranslatef(
        offset[0] + entity.size * entity.parts[current_part][Data_offset][0],
        offset[1] + entity.size * entity.parts[current_part][Data_offset][1],
        offset[2] + entity.size * entity.parts[current_part][Data_offset][2])
    Definitions.modelMatrix.translate(
        offset[0] + entity.size * entity.parts[current_part][Data_offset][0],
        offset[1] + entity.size * entity.parts[current_part][Data_offset][1],
        offset[2] + entity.size * entity.parts[current_part][Data_offset][2])

    if partIsSelected == True:
        Definitions.modelMatrix.push()

        Cy = 0.5 * (entity.parts[current_part][Data_saturation][2] +
                    entity.parts[current_part][Data_saturation][3])
        Cz = 0.5 * (entity.parts[current_part][Data_saturation][4] +
                    entity.parts[current_part][Data_saturation][5])
        Qoffset = Definitions.vector4D.Eul2Quat(
            Definitions.vector4D((0, 0, Cy, Cz)))
        p = Definitions.vector4D.Quat2Vec(
            Definitions.vector4D.QuatProd(l, Qoffset))
        if math.sqrt(p.x * p.x + p.y * p.y + p.z * p.z) >= 0.0001:
            Definitions.modelMatrix.rotate(p.o, p.x, p.y, p.z)
        scale = 2 * entity.size * entity.parts[current_part][Data_dimensions][0]
        Definitions.modelMatrix.scale(scale, scale, scale)

        Graphics.SaturationModelMatrix = Graphics.SaturationModelMatrix + [[
            Definitions.modelMatrix.peek(), current_part
        ]]
        #Graphics.VBO_hypar((entity.parts[current_part][Data_saturation]))

        Definitions.modelMatrix.pop()
    """ total rotation to apply """
    p = Definitions.vector4D.Quat2Vec(Definitions.vector4D.QuatProd(l, q))
    if math.sqrt(p.x * p.x + p.y * p.y + p.z * p.z) >= 0.0001:
        #glRotatef(p.o, p.x, p.y, p.z)
        Definitions.modelMatrix.rotate(p.o, p.x, p.y, p.z)
    """ preprocess part """
    x = entity.size * entity.parts[current_part][Data_dimensions][0]
    y = entity.size * entity.parts[current_part][Data_dimensions][1]
    z = entity.size * entity.parts[current_part][Data_dimensions][2]
    dx = 0.5 * entity.size * entity.parts[current_part][Data_dimensions][0]
    dy = 0
    dz = 0
    preprocessPart(x, y, z, dx, dy, dz, partIsSelected, part)
    """ preprocess sensors """
    for sensor in Sensors.virtuSens + Sensors.zoiSens:
        if sensor.attach == entity.parts[current_part][Data_id]:
            sensor.h = 0.6
            if sensor.type == 'Eye':
                sensor.h = 0.4
            if sensor.tag == 'Zoi':
                sensor.h = 0.55
            Sensors.preprocessSensor(sensor, x, y, z)
    Definitions.modelMatrix.pop()
    """ recursive call for all parts attached to the current one """
    while part + 1 < len(entity.parts) and entity.parts[
            part + 1][Data_layer] > entity.parts[current_part][Data_layer]:
        stick(entity, (x, 0, 0), (0, 0, 0, 0))

    #glPopMatrix()
    Definitions.modelMatrix.pop()