コード例 #1
0
def experiment(nSpuriousDims=0, rotation=0):
    np.random.seed(params['seed'])
    animal1 = Animal(worldModel=worldModel)

    eshape = (1, 1 + nSpuriousDims)
    #base_experience = np.random.random(eshape)*2*np.pi - np.pi
    base_experience = np.zeros(eshape)
    e = np.empty(eshape)
    for i in range(10):
        sd1 = sd
        sd2 = sd * 3
        e[0, 0] = base_experience[0, 0] + stats.norm.rvs(0, sd1)
        e[0, 1:] = base_experience[0, 1:] + stats.norm.rvs(
            0, sd2, size=(1, nSpuriousDims))
        animal1.experience(e, calculate_belief=False)
    e = base_experience
    e[0, 0] += rotation
    b, orientations = animal1.experience(e,
                                         calculate_belief=True,
                                         orient=True,
                                         normalize=False)
    print()
    print('nSpuriousDims', nSpuriousDims, 'rotation', rotation)
    print(b)
    print(orientations, orientations * 180 / np.pi)
    return b, orientations
コード例 #2
0
ファイル: server.py プロジェクト: zewlie/wildally-project
def load_click_info_from_db():
    """Loads all the information needed to generate analytics JSON files."""

    orgs = Org.list_of_org_objects()
    animals = Animal.list_of_animal_objects()
    clicks = Click.list_of_click_objects()
    click_filters = ClickFilter.list_of_click_filter_objects()

    return (orgs, animals, clicks, click_filters)
コード例 #3
0
ファイル: server.py プロジェクト: zewlie/wildally-project
def load_click_info_from_db():
    """Loads all the information needed to generate analytics JSON files."""

    orgs = Org.list_of_org_objects()
    animals = Animal.list_of_animal_objects()
    clicks = Click.list_of_click_objects()
    click_filters = ClickFilter.list_of_click_filter_objects()

    return (orgs, animals, clicks, click_filters)
コード例 #4
0
ファイル: seed.py プロジェクト: zewlie/wildally-project
def load_animals():
    """Load animal types from u.animal into database."""

    print "Animals"
    Animal.query.delete()

    for row in open(animal_path):
        name = row.rstrip()

        animal = Animal(name=name)

        db.session.add(animal)
    db.session.commit()
コード例 #5
0
def create_animal():
    response = jsonify({"result": "ok", "details": "ok"})
    data = request.get_json()

    try:
        new_animal = Animal(**data)
        db.session.add(new_animal)
        db.session.commit()
    except Exception as e:
        response = jsonify({"result": "error", "details": str(e)})

    response.headers.add("Access-Control-Allow-Origin", "*")
    return response
コード例 #6
0
def load_animals():
    """Load animals from u.animal into database."""

    print "animals"

    Animal.query.delete()

    for row in open('seed_data/u.animal'):
        row = row.rstrip()
        animal_id, species_id = row.split('|')

        animal_id = int(animal_id)

        animal = Animal(animal_id=animal_id, species_id=species_id)

        db.session.add(animal)

    db.session.commit()    
コード例 #7
0
def populate_animals():
    """Create minimum sample data for the animal table."""

    Animal.query.delete()

    for i, row in enumerate(open('seed_data/dogs.csv')):
        business_id, name, species, breed, birthday, vet, note, photo_path = row.rstrip(
        ).split(",")

        a = Animal(business_id=business_id,
                   name=name,
                   breed=breed,
                   birthday=birthday,
                   vet=vet,
                   note=note,
                   species=species,
                   photo_path=photo_path)
        db.session.add(a)
    db.session.commit()
    return None
コード例 #8
0
def load_animals(animal_filename):
    """Load colors from seed_data/generic_colors into database."""

    # Delete all rows in table, so if we need to run this a second time,
    # we won't be trying to add duplicate users
    Animal.query.delete()

    #Read generic_colors file and insert data
    for row in open(animal_filename):
        row = row.rstrip()
        animal_id, species_id, breed_id, size_id, user_id, latitude, longitude, timestamp, photo, notes, found, found_by_user_id, gender_id = row.split("|")

        if found_by_user_id == "None":
            found_by_user_id = None
            
        if found == "True":
            found = True
        else:
            found = False

        animals = Animal(species_id=species_id,
                        breed_id=breed_id,
                        size_id=size_id,
                        user_id=user_id,
                        latitude=latitude,
                        longitude=longitude,
                        timestamp=timestamp,
                        photo=photo,
                        notes=notes,
                        found=bool(found),
                        found_by_user_id = found_by_user_id,
                        gender_id = gender_id)

        # We need to add to the session or it won't ever be stored
        db.session.add(animals)

    # Once we're done, we should commit our work
    db.session.commit()

    #finished the function
    print("Animals inserted")
コード例 #9
0
ファイル: server-h.py プロジェクト: glitton/petfinder_project
def like_pets():
    """Save liked pets from search results."""

    #get credentials from clicking the like button
    shelter_id = request.form.get("shelterId")
    animal = request.form.get("animal")
    name = request.form.get("name")
    breed = request.form.get("breeds")
    age = request.form.get("age")
    gender = request.form.get("gender")
    pet_id = request.form.get("petID")
    size = request.form.get("size")
    description = request.form.get("description")
    last_update = request.form.get("lastupdate")

    liked_pet = Animal(shelter_id=shelter_id,
                       animal=animal,
                       name=name,
                       breed=breed,
                       age=age,
                       gender=gender,
                       pet_id=pet_id,
                       size=size,
                       description=description,
                       last_update=last_update)


    db.session.add(liked_pet)
    db.session.commit()

    # instantiate useranimal object so users can find liked animals through usersanimals table
    new_user_animal = UserAnimal(user_id=session.get("user_id"), animal=liked_pet)
    db.session.add(new_user_animal)
    db.session.commit()

    results = {"success": True,
               "message": "Liked!", "pet_id":pet_id}

    return jsonify(results)
コード例 #10
0
 def retornar_consultas():
     return [
         Consulta(data=registro['data'], 
         servico = registro['servico'], 
         horario = registro['horario'], 
         cliente = Cliente(
             nome = registro['nome'],
             email = registro['email'],
             telefone = registro['telefone'],
             nome_login = registro['nome_login'],
             senha = registro['senha'],
             id = registro['id_cliente']), 
         animal = Animal(
             nome_dono = registro['nome_dono'],
             tipo_animal = registro['tipo_animal'],
             raca = registro['raca'],
             id = registro['id_animal']), 
         confirma = registro['confirma'], 
         mID = registro['mID']) \
         for registro in Dao.db.query("SELECT * FROM consulta \
     INNER JOIN animal ON animal.id = consulta.id_animal \
     INNER JOIN cliente ON cliente.id = consulta.id_cliente")]
    return thetas[ind]


#%% simulation
nSpuriousDims = 0
c1 = Directional(nSpuriousDims=nSpuriousDims)
c2 = NonDirectional(nSpuriousDims=nSpuriousDims)

nExperiences = 10
alpha = params['alpha']

distList = [VonMises()]
for obj in range(nSpuriousDims):
    distList.append(Gauss())
worldModel = WorldModel(CRP(alpha), GenericMixed(distList))
animal1 = Animal(worldModel=worldModel)
animal2 = Animal(worldModel=worldModel)

for i in range(nExperiences):
    e = c1.rvs()
    animal1.experience(e, calculate_belief=False)

    e = c2.rvs()
    animal2.experience(e, calculate_belief=False)

#%% plot experiences
figInd = 0
figInd += 1
f = plt.figure(figInd)
f.clear()
ax = plt.subplot(111, projection='polar')
コード例 #12
0
day5partitions = np.array([
    [0, 0, 0],
    [2, 1, 0],
    [0, 0, 0],
    [2, 1, 0],
    [0, 0, 0],
    [2, 1, 0],
])
partitions = np.vstack((day1partitions, day1partitions, day1partitions,
                        day4partitions, day5partitions, day5partitions))

#%%
alphas = np.power(10., np.arange(1, -50, -1))
posts = np.empty((len(alphas), 3)) * np.nan
for idx, alpha in enumerate(alphas):
    animal = Animal(alpha, observationModelClass=Gauss)
    for i in range(observations.shape[0]):
        animal.experience(observations[i, :])

    for i in range(3):  # for each partition
        posts[idx, i] = animal.partition_prob(partitions[:, i])

posts
#%%
figInd += 1
#%%
fig = plt.figure(figInd)
fig.clear()
bar_width = 0.2
idxs = np.array([0, 15, 30]) + 1  #+5
idxs = np.array([0, 20, 40]) + 1  #+5
def experiment(alpha=alpha_default,
               sd0=sd0_default,
               sd=sd_default,
               N=N_default,
               distance=distance_default):
    np.random.seed(1)
    _model = WorldModel(CRP(alpha), Gauss(sigma_0=sd0))
    _animal = Animal(worldModel=_model)

    experiences = np.nan * np.ones((N * nPresentations * 2))
    partition1 = np.array([])
    partition2 = np.array([])
    partitionN = np.array([])
    lps = np.nan * np.empty((N, 3))
    posts = np.nan * np.empty((N * nPresentations * 2, 3))
    similarity = np.nan * np.empty((N, 1))
    for i in range(N):
        c1 = stats.norm(loc=np.array([-distance / 2]),
                        scale=sd * np.ones((1, K)))
        c2 = stats.norm(loc=np.array([+distance / 2]),
                        scale=sd * np.ones((1, K)))

        for _i in range(nPresentations):
            experience1 = c1.rvs()
            experiences[i * nPresentations * 2 + _i * 2] = experience1
            post1 = _animal.experience(experience1)
            if i + _i == 0:
                partition1 = np.array([[0]])
                partition2 = np.array([[0]])
                partitionN = np.array([[0]])
            else:
                partition1 = np.vstack((partition1, 0))
                partition2 = np.vstack((partition2, 0))
                partitionN = np.vstack(
                    (partitionN, 2 * i * nPresentations + _i))
            if i > 0:
                posts[i * nPresentations * 2 + _i, :] = post1.squeeze()
                _animal.clusterAssignments = partition2
        for _i in range(nPresentations):
            experience2 = c2.rvs()
            experiences[i * nPresentations * 2 + _i * 2 + 1] = experience2
            post2 = _animal.experience(experience2)
            partition1 = np.vstack((partition1, 0))
            partition2 = np.vstack((partition2, 1))
            partitionN = np.vstack(
                (partitionN, (2 * i + 1) * nPresentations + _i))
            if i > 0:
                posts[i * nPresentations * 2 + nPresentations +
                      _i, :] = post2.squeeze()
            _animal.clusterAssignments = partition2

        #TODO: look over this for what to do about partitions2activity
        ret = partitions2activity(_animal, experience1,
                                  [partition1, partition2],
                                  [zeta0, zeta1A, zeta1B])
        activity1 = ret[0]
        tmp_lps = ret[1]
        ret = partitions2activity(_animal, experience2,
                                  [partition1, partition2],
                                  [zeta0, zeta1A, zeta1B])
        activity2 = ret[0]
        tmp_lps_2 = ret[1]
        np.testing.assert_array_equal(tmp_lps, tmp_lps_2)
        lps[i, 0:2] = tmp_lps
        lps[i, 0] = _animal.partition_prob(partition1)
        lps[i, 1] = _animal.partition_prob(partition2)
        lps[i, 2] = _animal.partition_prob(partitionN)
        similarity[i] = np.corrcoef(activity1, activity2)[0, 1]
    return similarity, lps, _animal, partition1, partition2, c1, c2, experiences, posts
コード例 #14
0
plt.style.use('ggplot')
try:
    filename = stripFilename(__file__)
except NameError:
    filename = 'script'
figInd = 0

#%%
np.random.seed(params['seed'])

sd = 0.2
c1 = stats.norm(loc=np.zeros((1, 4)), scale=sd * np.ones((1, 4)))

alpha = params['alpha']
worldModel = WorldModel(CRP(alpha), Gauss())
animal1 = Animal(worldModel=worldModel)

nExperiences = 20
for i in range(nExperiences):
    animal1.experience(c1.rvs())

animal1.clusterAssignments = np.zeros((nExperiences, 1))
distance_default = 1  # distance between different features
a = 0
b = distance_default
post = np.vstack((animal1.belief(np.array([a, a, a, a])).transpose(),
                  animal1.belief(np.array([b, a, a, a])).transpose(),
                  animal1.belief(np.array([b, a, a, b])).transpose(),
                  animal1.belief(np.array([b, b, b, b])).transpose()))

#%%
コード例 #15
0
def lost_pet_form(): 
    """Adds a lost pet."""
    colors = []
    queried_colors = []
    queried_breed = []

    f = request.files['animal_photo']
    f.save('static/seed_photos/' + f.filename)

    submitted_species = request.form.get('species_quest')
    submitted_breed = request.form.get('breed_question')
    if submitted_breed:
        submitted_breed = submitted_breed
    else:
        submitted_breed = 'Unknown'
    submitted_size = request.form.get('size_quest')
    submitted_color1 = request.form.get('color1_question')
    if submitted_color1:
        colors.append(submitted_color1)
    submitted_color2 = request.form.get('color2_question')
    if submitted_color2:    
        colors.append(submitted_color2)
    submitted_color3 = request.form.get('color3_question')
    if submitted_color3:
        colors.append(submitted_color3)
    submitted_gender = request.form.get('gender_question')
    if submitted_gender:
        submitted_gender = submitted_gender
    else:
        submitted_gender = 'Unknown'
    submitted_notes = request.form.get('notes')
    submitted_latitude = request.form.get('lat')
    submitted_longitude = request.form.get('lng')
    timestamp = datetime.now()
    user_email = session.get('logged_in_user_email')


    species = Species.query.filter(Species.species == submitted_species).one()
    size = Size.query.filter(Size.size == submitted_size).one()
    for color in colors:
        queried_colors.append(Color.query.filter(Color.color == color).one())

    breed = Breed.query.filter(Breed.breed == submitted_breed,
                                 Breed.species_id == species.species_id).one()

    user = User.query.filter(User.email == user_email).one()

    gender = Gender.query.filter(Gender.gender == submitted_gender).one()


    animal = Animal(species = species,
                    breed = breed,
                    size = size, 
                    notes = submitted_notes, 
                    photo = str(f.filename),
                    latitude = submitted_latitude, 
                    longitude = submitted_longitude, 
                    user_id = user.user_id, 
                    timestamp = timestamp,
                    colors = queried_colors,
                    gender = gender
                    )

    db.session.add(animal)
    db.session.commit()
    print("submitted lost animal to database!")
    flash("Lost animal has been added to map!")
    return("it worked. yay")
コード例 #16
0
 def retornar_animais():
     # cria objeto animal com base no registro da tabela
     return [Animal(nome_dono = registro['nome_dono'], tipo_animal = registro['tipo_animal'], raca = registro['raca'], id = registro['id']) for registro in Dao.db['animal'].all()]