Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pull request for team I'm thinqing #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions team_solutions/Im_ThinQing/Check_flights.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import json
import pandas as pd
import http.client

# parser = argparse.ArgumentParser()
# parser.add_argument('-o','--origion',type=str)
# parser.add_argument('-d','--destination',type=str)
# args = parser.parse_args()


def check_flights(origin,destination,departure_date,return_date):
conn = http.client.HTTPSConnection("skyscanner50.p.rapidapi.com")

headers = {
'X-RapidAPI-Key': "20f4b82842msh0a60cfb5f9bf13ep1dfe41jsnaa9a78013956",
'X-RapidAPI-Host': "skyscanner50.p.rapidapi.com"
}

#conn.request("GET", "/api/v1/searchFlights?origin=ORD&destination=BOS&date=2023-01-29&returnDate=2023-01-30&adults=1&cabinClass=economy&filter=price&currency=USD&countryCode=US&market=en-US", headers=headers)

#conn.request("GET", f"/api/v1/searchFlights?origin={args.origion}&destination={args.destination}&date=2023-01-29&returnDate=2023-01-30&adults=1&cabinClass=economy&filter=price&currency=USD&countryCode=US&market=en-US", headers=headers)

conn.request("GET", f"/api/v1/searchFlights?origin={origin}&destination={destination}&date={departure_date}&returnDate={return_date}&adults=1&cabinClass=economy&filter=price&currency=USD&countryCode=US&market=en-US", headers=headers)

res = conn.getresponse()
data = res.read()
json_obj = json.loads(data)

flights = json_obj['data']

flight_price_total = []

id_departing = []
id_returning = []

departure_time_departing = []
departure_time_returning = []

arrival_time_departing = []
arrival_time_returning = []

duration_departing = []
duration_returning = []

carrier_departing = []
carrier_returning = []

for f in flights:
flight_price_total.append(f['price']['amount'])
id_departing.append(f['legs'][0]['id'])
id_returning.append(f['legs'][1]['id'])
departure_time_departing.append(f['legs'][0]['departure'])
departure_time_returning.append(f['legs'][1]['departure'])
arrival_time_departing.append(f['legs'][0]['arrival'])
arrival_time_returning.append(f['legs'][1]['arrival'])
duration_departing.append(f['legs'][0]['duration'])
duration_returning.append(f['legs'][1]['duration'])
carrier_departing.append(f['legs'][0]['carriers'][0]['name'])
carrier_returning.append(f['legs'][1]['carriers'][0]['name'])

df = pd.DataFrame({'flight_price_total':flight_price_total,'departure_time_departing':departure_time_departing,'departure_time_returning':departure_time_returning,'duration_departing':duration_departing,'duration_returning':duration_returning,'id_departing':id_departing,'id_returning':id_returning})

# convert time to morning / afternoon / night
df['departing_timeperiod'] = ['Morning' if 5<int(t.split('T')[1].split(':')[0])<12 else 'Afternoon' if 12<int(t.split('T')[1].split(':')[0])<18 else 'Evening' for t in departure_time_departing]
df['returning_timeperiod'] = ['Morning' if 5<int(t.split('T')[1].split(':')[0])<12 else 'Afternoon' if 12<int(t.split('T')[1].split(':')[0])<18 else 'Evening' for t in departure_time_returning]
df['time_code'] = ['00' if i == 'Morning' else '01' if i == 'Afternoon' else '10' for i in df['departing_timeperiod']]
df['airline_code'] = ['00' if i == 'American' else '01' if i == 'Delta' else '10' if i == 'United' else '11' for i in df['departing_timeperiod']]

return df

#df.to_csv('flights_info.csv',index=False)
41 changes: 41 additions & 0 deletions team_solutions/Im_ThinQing/Check_hotel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import json
import pandas as pd
import http.client

def check_hotel(region_id,Departure_date,Return_date):
conn = http.client.HTTPSConnection("hotels-com-provider.p.rapidapi.com")

headers = {
'X-RapidAPI-Key': "20f4b82842msh0a60cfb5f9bf13ep1dfe41jsnaa9a78013956",
'X-RapidAPI-Host': "hotels-com-provider.p.rapidapi.com"
}

conn.request("GET", f"/v2/hotels/search?domain=US&sort_order=PRICE_LOW_TO_HIGH&locale=en_US&checkout_date={Return_date}&region_id={region_id}&adults_number=1&checkin_date={Departure_date}&available_filter=SHOW_AVAILABLE_ONLY&meal_plan=FREE_BREAKFAST&guest_rating_min=8&price_min=10&page_number=1&amenities=WIFI%2CPARKING&price_max=500&lodging_type=HOTEL%2CHOSTEL%2CAPART_HOTEL&star_rating_ids=3%2C4%2C5", headers=headers)

res = conn.getresponse()
data = res.read()

# parse

json_obj = json.loads(data)

with open('hotel_info.json', 'w') as outfile:
json.dump(json_obj, outfile,indent=4)

hotels = json_obj['properties']

names = []
prices = []
review_score = []
review_count = []
star = []

for h in hotels:
names.append(h['name'])
prices.append(h['price']['lead']['formatted'])
review_score.append(h['reviews']['score'])
review_count.append(h['reviews']['total'])
star.append(h['star'])

df = pd.DataFrame({'name':names,'price':prices,'review_score':review_score,'review_count':review_count,'star':star})
return df
27 changes: 27 additions & 0 deletions team_solutions/Im_ThinQing/Check_region_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import json
import airportsdata
import http.client

airports = airportsdata.load('IATA')

def check_region_id(Destination):

city_name = airports[Destination]['city']

conn = http.client.HTTPSConnection("hotels-com-provider.p.rapidapi.com")

headers = {
'X-RapidAPI-Key': "20f4b82842msh0a60cfb5f9bf13ep1dfe41jsnaa9a78013956",
'X-RapidAPI-Host': "hotels-com-provider.p.rapidapi.com"
}

conn.request("GET", f"/v2/regions?locale=en_US&query={city_name}&domain=US", headers=headers)

res = conn.getresponse()
data = res.read()

region_id = json.loads(data.decode("utf-8"))['data'][0]['gaiaId']

return region_id


39 changes: 39 additions & 0 deletions team_solutions/Im_ThinQing/Check_restaurant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import json
import http.client
import pandas as pd
import airportsdata

airports = airportsdata.load('IATA')

def check_restaurant(Destination):

city_name = airports[Destination]['city']

conn = http.client.HTTPSConnection("yelp-reviews.p.rapidapi.com")

headers = {
'X-RapidAPI-Key': "20f4b82842msh0a60cfb5f9bf13ep1dfe41jsnaa9a78013956",
'X-RapidAPI-Host': "yelp-reviews.p.rapidapi.com"
}

conn.request("GET", f"/business-search?query=American&location={city_name}%2C%20MA%2C%20USA&yelp_domain=yelp.com", headers=headers)

res = conn.getresponse()
data = res.read()

json_obj = json.loads(data)
restaurant = json_obj['data']

name = []
rating = []
review_count = []
price_range = []

for r in restaurant:
name.append(r['name'])
rating.append(r['rating'])
review_count.append(r['review_count'])
price_range.append(r['price_range'])

df = pd.DataFrame({'name':name,'rating':rating,'review_count':review_count,'price_range':price_range})
return df
12 changes: 12 additions & 0 deletions team_solutions/Im_ThinQing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# I'm ThinkQing

Members: Arjun Bhamra, Amanda Sutrisno, Maggpie Yao, Kusuma, Ruijie Zhu


Background:
Flight, hotel, and restaurant consistitue the majority of travel expanses. Optimizing the total cost of these three components is tricky, especially if the total number of combinations is large.

Highlight:
We applied grover's algorithm to optimize flight+hotel+resturant combinations with a given travel budget.

Documentation: ./documentation/
Empty file.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
77 changes: 77 additions & 0 deletions team_solutions/Im_ThinQing/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import random

import sys,os
sys.path.append(os.getcwd())

from Check_flights import check_flights
from Check_region_id import check_region_id
from Check_hotel import check_hotel
from Check_restaurant import check_restaurant
from covalent_grover_sampler import grover_function
from flask import Flask, render_template, request

app = Flask(__name__) # Creating our Flask Instance

@app.route('/', methods=['GET'])
def index():
""" Displays the home page accessible at '/' """

return render_template('homepage.html')

@app.route('/taskbar/', methods=['GET'])
def taskbar():
return render_template('taskbar.html')

@app.route('/result/', methods=['POST'])
def result():
Origin = request.form['Origin']
Destination = request.form['Destination']
Departure_date = request.form['Departure_date']
Return_date = request.form['Return_date']
Travel_time = request.form['Travel_time']
Airlines = request.form['Airlines']
Food_type = request.form['Food_type']
Price_range = request.form['Price_range']

df_flights = check_flights(Origin,Destination,Departure_date,Return_date)
lowest_flight_price = list(df_flights.flight_price_total)[0]
cheapest_flight_id_departing = list(df_flights.id_departing)[0]
cheapest_flight_id_returning = list(df_flights.id_returning)[0]


region_id = check_region_id(Destination)
df_hotel = check_hotel(region_id,Departure_date,Return_date)
flight_time_code_dict = {list(df_flights.time_code)[i]: list(df_flights.flight_price_total)[i] for i in range(len(df_flights))}
flight_airline_code_dict = {list(df_flights.airline_code)[i]: list(df_flights.flight_price_total)[i] for i in range(len(df_flights))}
lowest_hotel_price = list(df_hotel.price)[0]
cheapest_hotel_name = list(df_hotel.name)[0]

df_restaurant = check_restaurant(Destination)
lowest_restaurant_price = list(df_restaurant.price_range)[0]
cheapest_restaurant_name = list(df_restaurant.name)[0]

return render_template(
'taskbar.html',
Origin=Origin,
Destination=Destination,
Departure_date=Departure_date,
Return_date=Return_date,
Travel_time=Travel_time,
Airlines=Airlines,
Food_type=Food_type,
Price_range=Price_range,
lowest_flight_price=lowest_flight_price,
cheapest_flight_id_departing=cheapest_flight_id_departing,
cheapest_flight_id_returning=cheapest_flight_id_returning,
lowest_hotel_price=lowest_hotel_price,
cheapest_hotel_name=cheapest_hotel_name,
lowest_restaurant_price=lowest_restaurant_price,
cheapest_restaurant_name=cheapest_restaurant_name,
grover_result=grover_function("1100")
)


if __name__ == '__main__':
port = 5000 + random.randint(0, 999)
url = f"http://127.0.0.1:{port}"
app.run(use_reloader=False, debug=True, port=port)
96 changes: 96 additions & 0 deletions team_solutions/Im_ThinQing/covalent_grover_sampler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import os

import covalent as ct
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import Estimator, QiskitRuntimeService, Session, Sampler

from qiskit import IBMQ
token = "09428f6730538a20ee6382d16ca3461c758d0346cdd54071ff0ae8651f1f91c0fcac8bfdb998a7688ff6f751877cab2f038d33cbfd1b6e7dc1ec8cbcdfc72b95"
#IBMQ.save_account(token)
IBMQ.load_account() # Load account from disk
IBMQ.providers() # List all available providers

def grover_function(s:str):

import random
from qiskit.quantum_info import Statevector

#secret = random.randint(0,15) # the owner is randomly picked
#secret_string = format(secret, '04b') # format the owner in 7-bit string
secret_string = s
oracle = Statevector.from_label(secret_string) # let the oracle know the owner

from qiskit.algorithms import AmplificationProblem

problem = AmplificationProblem(oracle, is_good_state=secret_string)

from qiskit.algorithms import Grover
import math

def grover(problem):
n = int(math.sqrt((len(s))))
grover = Grover(n)
circuit = grover.construct_circuit(problem)
circuit.measure_all() #NOTE THIS, REMOVED MEASUREALL BC OF OBSERVABLES, WILL SEE IF IT WORKS
#grover_circuits.append(circuit)
return circuit

@ct.electron(deps_pip=ct.DepsPip(["qiskit==0.40.0"]))
def evaluate_circuit(token: str, shots=100):
#QiskitRuntimeService.save_account(channel="ibm_quantum",
# token=token,
# instance="ibm-q-community/mit-hackathon/main",
# overwrite=True)

#with Session(service=QiskitRuntimeService(channel="ibm_quantum"), backend="ibmq_qasm_simulator"):#ibm_nairobi
#estimator = Estimator()
#sampler = Sampler()
#job = sampler.run(grover(problem))
#return job
#observables = (
#SparsePauliOp("ZZZ"),
#)
#job = estimator.run(circuits=grover(problem),
# observables=observables,
# shots=shots).result()
#return job

with Session(service=QiskitRuntimeService(channel="ibm_quantum"), backend="ibmq_qasm_simulator"):
sampler = Sampler()
job = sampler.run(circuits=grover(problem), shots=shots)
result = job.result()
result_dict = result.quasi_dists[0].binary_probabilities()
answer = max(result_dict, key=result_dict.get)
return answer
#return result
#print(result)

@ct.lattice
def test(token):
return evaluate_circuit(token)
#job = evaluate_circuit(token)
#return job
#result = job.get_result()
#return result
#result_dict = result.quasi_dists[0].binary_probabilities()
#answer = max(result_dict, key=result_dict.get)
#return answer

dispatch_id = ct.dispatch(test)(token)
print(f"\n{dispatch_id}" + " - Running")

workflow_result = ct.get_result(dispatch_id, wait=True)
print("Result")
print(workflow_result.result)

#result_dict = workflow_result.quasi_dists[0].binary_probabilities()
#answer = max(result_dict, key=result_dict.get)
#print(answer)

print("Secret String: " + secret_string)

return workflow_result.result

#grover_function("1100")
Loading