<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Moving through a physical experience
Some examples of IoT application that ping a digital twin
This doc does not really teach anything new, but it will give us some exercise with the previous examples. We will need a more complicated model in future steps. 
* Adding more connections.
* Making connections using ids. 
This is the SDK repo on Github
Here is the doc on the query language
Step1:  Note the query object loves to drop values. To keep from making multiple queries, save the data somewhere.
Step3:  and a df of the tickets
Step4:  Let's sell a couple more of those tickets.
Step5:  The purpose is to create a simulation. So I'm just hacking something out real quick to make our model look a little fuller.
Step6:  You should be able to load the storage explorer at this point and look at the relationships. 
I'm going to add some areas. 
* People go into areas when the concert begins.
* areas have capacity
Also adding lines
Step7:  Ok now that we know what tickets we want to sell, let's push them to the digital twin ecosystem. This is exactly the same as what we did with Customers in step one.
Step8:  Now establishing a realtionship between the lines and the areas. If a person leaves one area they have to get into the line of the next area in order to get there.
Step9:  Now I'm going to add some people into different parts of the experience. This will change from user to user, but you can use this as an example of how this would work on your twin. Use the queries above to get the specific ids of your twins.
Step10:  Sell a couple more tickets
<ASSISTANT_TASK:>
Python Code:
from azure.identity import AzureCliCredential
from azure.digitaltwins.core import DigitalTwinsClient
# using yaml instead of 
import yaml
import uuid
# using altair instead of matplotlib for vizuals
import numpy as np
import pandas as pd
# you will get this from the ADT resource at portal.azure.com
your_digital_twin_url = "home-test-twin.api.wcus.digitaltwins.azure.net"
azure_cli = AzureCliCredential()
service_client = DigitalTwinsClient(
    your_digital_twin_url, azure_cli)
service_client
query_expression = "SELECT * FROM digitaltwins t where IS_OF_MODEL('dtmi:billmanh:patron;1')"
query_result = service_client.query_twins(query_expression)
Explanation: Moving through a physical experience
Some examples of IoT application that ping a digital twin
This doc does not really teach anything new, but it will give us some exercise with the previous examples. We will need a more complicated model in future steps. 
* Adding more connections.
* Making connections using ids. 
This is the SDK repo on Github
Here is the doc on the query language
End of explanation
values = []
for i in query_result:
    values.append(i)
df_customers = pd.DataFrame([[i['$dtId'],i['satisfaction']] for i in values],
                           columns=['id','satisfaction'])
df_customers
Explanation: Note the query object loves to drop values. To keep from making multiple queries, save the data somewhere.
End of explanation
query_expression = f
SELECT * FROM digitaltwins t where IS_OF_MODEL('dtmi:mymodels:ticket;1') and t.state='open'
query_result = service_client.query_twins(query_expression)
available_tickets_df = pd.DataFrame([[i['$dtId'],i['event_title'],i['state']] for i in query_result],
                                   columns = ['$dtId','event_title','state'])
available_tickets_df
Explanation: and a df of the tickets
End of explanation
tickets_sold = available_tickets_df.drop_duplicates(subset='event_title')['$dtId'].tolist()
tickets_sold
customers_sold = df_customers['id'].tolist()[5:7]
customers_sold
Explanation: Let's sell a couple more of those tickets.
End of explanation
for c,t in enumerate(tickets_sold):
    print(t)
    tickethoder_relationship = {
            "$relationshipId": f"{t}ownedBy{customers_sold[c]}",
            "$sourceId": t,
            "$relationshipName": "ownedBy",
            "$targetId": customers_sold[c],
            "bought_online": False
        }
    service_client.upsert_relationship(
            tickethoder_relationship["$sourceId"],
            tickethoder_relationship["$relationshipId"],
            tickethoder_relationship
        )
    patch = [
        {
            "op": "replace",
            "path": "",
            "value": "sold"
        }
    ]
    service_client.update_component(t,"state", patch)
Explanation: The purpose is to create a simulation. So I'm just hacking something out real quick to make our model look a little fuller.
End of explanation
# # # Delete the model that you don't want. 
# # service_client.delete_model(patron_model_id)
# # Create it if you just deleted it.
# # area_model_json = yaml.safe_load(open("models/area.json"))
# line_model_json = yaml.safe_load(open("models/Patron.json"))
# service_client.create_models([line_model_json])
Explanation: You should be able to load the storage explorer at this point and look at the relationships. 
I'm going to add some areas. 
* People go into areas when the concert begins.
* areas have capacity
Also adding lines:
* Lines lead to other places, but one line can lead to many places (like the entrance).
* Lines have a capacity
End of explanation
for r in range(4):
    digital_twin_id = f'area-{r}'
    print(digital_twin_id)
    dt_json = {
        "$metadata": {
            "$model": "dtmi:mymodels:area;1"
        },
        "capacity": 3,
        "status": "open"
    }
    created_twin = service_client.upsert_digital_twin(digital_twin_id, dt_json)
    print(created_twin)
for r in range(4):
    digital_twin_id = f'line-{r}'
    print(digital_twin_id)
    dt_json = {
        "$metadata": {
            "$model": "dtmi:mymodels:line;1"
        }
    }
    created_twin = service_client.upsert_digital_twin(digital_twin_id, dt_json)
    print(created_twin)
Explanation: Ok now that we know what tickets we want to sell, let's push them to the digital twin ecosystem. This is exactly the same as what we did with Customers in step one.
End of explanation
def line_to_room(line,area,walking):
    tickethoder_relationship = {
                "$relationshipId": f"{line}leadsTo{area}",
                "$sourceId": line,
                "$relationshipName": "leadsTo",
                "$targetId": area,
                "walk_distance": walking
            }
    service_client.upsert_relationship(
            tickethoder_relationship["$sourceId"],
            tickethoder_relationship["$relationshipId"],
            tickethoder_relationship
        )
        
line_to_room("line-0","area-0",5)
line_to_room("line-1","area-1",5)
line_to_room("line-2","area-2",5)
line_to_room("line-3","area-3",5)
Explanation: Now establishing a realtionship between the lines and the areas. If a person leaves one area they have to get into the line of the next area in order to get there.
End of explanation
def cust_to_area(cust,area):
    tickethoder_relationship = {
                "$relationshipId": f"{cust}locatedIn{area}",
                "$sourceId": cust,
                "$relationshipName": "locatedIn",
                "$targetId": area,
            }
    service_client.upsert_relationship(
            tickethoder_relationship["$sourceId"],
            tickethoder_relationship["$relationshipId"],
            tickethoder_relationship
        )
        
cust_to_area("customer-e6f49d8a-711b-41c3-9db8-c7ece3dbc32c","line-1")
cust_to_area("customer-21e17d28-76c3-4c04-8df9-396703692a68","line-1")
# cust_to_area("customer-25e19268-3433-4f09-afe3-94f466313368","line-0")
# cust_to_area("customer-c87adbfa-1c6e-4ea9-9f03-83e3877ef5fc","line-2")
Explanation: Now I'm going to add some people into different parts of the experience. This will change from user to user, but you can use this as an example of how this would work on your twin. Use the queries above to get the specific ids of your twins.
End of explanation
def ticket_to_cust(ticket,cust):
    tickethoder_relationship = {
                "$relationshipId": f"{ticket}ownedBy{cust}",
                "$sourceId": ticket,
                "$relationshipName": "ownedBy",
                "$targetId": cust,
            }
    service_client.upsert_relationship(
            tickethoder_relationship["$sourceId"],
            tickethoder_relationship["$relationshipId"],
            tickethoder_relationship
        )
        
ticket_to_cust("ticket-58bf00bf-d5b8-4d06-9002-f8bf1693cc56","customer-418cbc74-b101-4f50-8cf0-6075a2a8053c")
ticket_to_cust("ticket-67f3cbfb-4b35-4e10-bf6d-3fd216093c3c","customer-9c9b5c36-69f6-4f48-9362-4aaac4cb1be4")
Explanation: Sell a couple more tickets
End of explanation
<END_TASK>