EmmaScharfmannBerkeley commited on
Commit
9794d8f
·
1 Parent(s): 2b3075f

Delete Climate_site

Browse files
Files changed (34) hide show
  1. Climate_site/.DS_Store +0 -0
  2. Climate_site/pages/2_Scientific_publications_and_Authors.py +0 -211
  3. Climate_site/pages/3_Related_Companies.py +0 -88
  4. Climate_site/pages/4_University_contests.py +0 -69
  5. Climate_site/pages/5_Your_own_research:_Patents.py +0 -109
  6. Climate_site/pages/6_Your_own_research:_Scientific_Publications.py +0 -105
  7. Climate_site/pages/7_Your_own_research:_Related_Scientist.py +0 -107
  8. Climate_site/python_scripts/__init__.py +0 -1
  9. Climate_site/python_scripts/__pycache__/__init__.cpython-311.pyc +0 -0
  10. Climate_site/python_scripts/__pycache__/__init__.cpython-38.pyc +0 -0
  11. Climate_site/python_scripts/__pycache__/functions.cpython-311.pyc +0 -0
  12. Climate_site/python_scripts/__pycache__/functions.cpython-38.pyc +0 -0
  13. Climate_site/python_scripts/__pycache__/multi_input_functions.cpython-38.pyc +0 -0
  14. Climate_site/python_scripts/__pycache__/others.cpython-311.pyc +0 -0
  15. Climate_site/python_scripts/__pycache__/others.cpython-38.pyc +0 -0
  16. Climate_site/python_scripts/__pycache__/paper_functions.cpython-38.pyc +0 -0
  17. Climate_site/python_scripts/__pycache__/patent_functions.cpython-38.pyc +0 -0
  18. Climate_site/python_scripts/__pycache__/test_script.cpython-311.pyc +0 -0
  19. Climate_site/python_scripts/__pycache__/test_script.cpython-38.pyc +0 -0
  20. Climate_site/python_scripts/big_ideas_contest.tsv +0 -0
  21. Climate_site/python_scripts/functions.py +0 -125
  22. Climate_site/python_scripts/functions_companies.py +0 -447
  23. Climate_site/python_scripts/functions_contest.py +0 -478
  24. Climate_site/python_scripts/iea.txt +0 -0
  25. Climate_site/python_scripts/institutions.tsv +0 -0
  26. Climate_site/python_scripts/others.py +0 -7
  27. Climate_site/python_scripts/paper_functions.py +0 -1220
  28. Climate_site/python_scripts/paper_functions_own_details.py +0 -542
  29. Climate_site/python_scripts/patent_functions.py +0 -892
  30. Climate_site/python_scripts/patent_functions_own_details.py +0 -475
  31. Climate_site/python_scripts/preqin_companies_IEA.tsv +0 -0
  32. Climate_site/python_scripts/read_me.txt +0 -13
  33. Climate_site/python_scripts/related_companies.json +0 -0
  34. Climate_site/python_scripts/related_scientist.py +0 -366
Climate_site/.DS_Store DELETED
Binary file (6.15 kB)
 
Climate_site/pages/2_Scientific_publications_and_Authors.py DELETED
@@ -1,211 +0,0 @@
1
-
2
- import streamlit as st
3
-
4
- st.set_page_config(page_title="Scientific publications and authors", page_icon="📖")
5
-
6
-
7
- from streamlit_folium import folium_static
8
- import folium
9
- import pandas as pd
10
- #from python_scripts import functions
11
- from python_scripts import paper_functions
12
- from python_scripts import others
13
-
14
- @st.cache
15
- def convert_df(df):
16
- # IMPORTANT: Cache the conversion to prevent computation on every rerun
17
- return df.to_csv().encode('utf-8')
18
-
19
-
20
- header = st.container()
21
-
22
- paper_finder = st.container()
23
-
24
-
25
- with paper_finder:
26
-
27
-
28
- st.markdown("# Scientific publications and authors related to IEA technologies")
29
- st.sidebar.header("Scientific publications and authors")
30
- st.write(
31
- """You can find the most related scientific publications and authors for each climate related IEA technology. Enjoy!"""
32
- )
33
-
34
- st.header('Which papers are related to the technology?')
35
-
36
-
37
- st.subheader("Select the technology you want to look at")
38
- dic_technologies, dic_categories, list_categories_tech, list_technologies = paper_functions.finder()
39
-
40
- list_technologies = [ ( list_categories_tech[i] , i ) for i in range(len(list_categories_tech)) ]
41
- key0 = lambda t: t[0]
42
-
43
-
44
- # Choose the category
45
- tech_category = st.selectbox('Select a category',list_technologies, format_func = key0)
46
-
47
-
48
- # After a selection is made the choices will update
49
- # Choose the technology and number
50
- technologies = dic_technologies[tech_category[0]]
51
-
52
- technology = st.selectbox('Select a technology',technologies,format_func = key0)
53
-
54
-
55
- # Select whether or not to use keywords
56
- list_keyword_option = [ ("No pre-select them for me" , False) , ("Yes" , True )]
57
- list_keyword_bool = st.selectbox('Would you like to enter your own keywords?',list_keyword_option,format_func = key0)
58
-
59
- if list_keyword_bool[1] == True:
60
- tech_category_keyword = st.text_input("Keywords", 'Input your text here')
61
- else:
62
- tech_categories = dic_categories[technology[1]]
63
- tech_category_keyword = st.radio(
64
- "Select a keyword to search on: ",
65
- tech_categories)
66
-
67
-
68
- # Select type of papers (related to climate or not)
69
- list_climate = [ ("Any related papers" , False ) , ("Climate related papers" , True)]
70
- patent_type_bool = st.selectbox('What type of papers do you want?',list_climate,format_func = key0)
71
-
72
- size = st.slider('How many papers do you want?', 0, 100, 5)
73
-
74
- st.subheader("Look at the related scientific publications and authors")
75
- #try:
76
- #if st.button('Get more information about the technology'):
77
- reference_text, text1 , text2 = paper_functions.extract_quantitative_data_technology(
78
- technologies = technology[0],
79
- number_technology = technology[1],
80
- )
81
-
82
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Technology details:</strong> {reference_text}' , unsafe_allow_html = True)
83
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Deployment target and Announced development target:</strong> {text1}' , unsafe_allow_html = True)
84
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Announced cost reduction targets:</strong> {text2}' , unsafe_allow_html = True)
85
-
86
- #except:
87
- # st.write("No information about the technology")
88
-
89
-
90
-
91
- #try:
92
- if st.button('Get related papers'):
93
- paper_rank_df = paper_functions.get_ranking_related_papers(
94
- technologies = tech_category[1],
95
- number_technology = technology[1],
96
- research_words = tech_category_keyword,
97
- carbon_related = patent_type_bool[1],
98
- size = size
99
- )
100
- st.dataframe(paper_rank_df)
101
- #print(paper_rank_df)
102
- #except:
103
- # st.write("No paper found, try with other key words")
104
-
105
- #try:
106
- if st.button('Get the main authors'):
107
- authors = paper_functions.main_authors(
108
- technologies = tech_category[1],
109
- number_technology = technology[1],
110
- research_words = tech_category_keyword,
111
- carbon_related = patent_type_bool[1],
112
- size = size
113
- )
114
- st.dataframe(authors)
115
-
116
-
117
- csv = convert_df(authors)
118
-
119
- st.download_button(
120
- label="Download table as CSV",
121
- data=csv,
122
- file_name='authors.csv',
123
- )
124
- #print(patent_rank_df)
125
- #
126
- # except:
127
- # st.write("No author found, try with other key words")
128
-
129
- #
130
- #try:
131
-
132
- if st.button('Get the map of the main authors'):
133
- map_author = paper_functions.map_authors(
134
- technologies = tech_category[1],
135
- number_technology = technology[1],
136
- research_words = tech_category_keyword,
137
- carbon_related = patent_type_bool[1],
138
- size = size)
139
- #st.map(map_author)
140
- m = folium.Map(zoom_start = 1)
141
- dic_geo = {}
142
- for elem in map_author.index:
143
-
144
- if map_author["institution"][elem] != "Max Planck Institute for Plasma Physics - Greifswald":
145
- longitude = map_author["longitude"][elem]
146
- latitude = map_author["latitude"][elem]
147
- if str(longitude) + " " + str(latitude) not in dic_geo:
148
- dic_geo[str(longitude) + " " + str(latitude)] = {}
149
- dic_geo[str(longitude) + " " + str(latitude)]["authors"] = set()
150
- dic_geo[str(longitude) + " " + str(latitude)]["institutions"] = set()
151
- dic_geo[str(longitude) + " " + str(latitude)]["dates"] = set()
152
- dic_geo[str(longitude) + " " + str(latitude)]["authors"].add(map_author["author"][elem])
153
- dic_geo[str(longitude) + " " + str(latitude)]["institutions"].add(map_author["institution"][elem])
154
- dic_geo[str(longitude) + " " + str(latitude)]["dates"].add(map_author["date"][elem])
155
-
156
- for elem in dic_geo:
157
- folium.Marker([float(elem.split()[1]), float(elem.split()[0])], popup="Author: " + ", ".join(list(dic_geo[elem]["authors"])) + ", Institution: " + ", ".join(list(dic_geo[elem]["institutions"])) + ", Date: " + ", ".join(list(dic_geo[elem]["dates"])), tooltip=", ".join(list(dic_geo[elem]["authors"]))).add_to(m)
158
- folium_static(m)
159
-
160
- #except:
161
- # st.write("No author found, try with other key words")
162
- #
163
- #
164
- #
165
-
166
-
167
- #
168
- #
169
- #
170
- if st.button('Get more information about the related_projects'):
171
- try:
172
- reference_text,key_initiative,location_entities,papers = paper_functions.related_projects(
173
- technologies = technology[0],
174
- number_technology = technology[1],
175
- carbon_related= patent_type_bool[1],
176
- size = size)
177
-
178
- st.write(f'<p style="color:Blue"> From IEA Website:' , unsafe_allow_html = True)
179
- st.write(f'<strong>Technology details:</strong> {reference_text}' , unsafe_allow_html = True)
180
- st.write(f'<strong>Technology key initiative:</strong> {key_initiative}' , unsafe_allow_html = True)
181
- st.write(f'<strong>Extracted projects and organization name:</strong> {location_entities}' , unsafe_allow_html = True)
182
- st.write(f'<p style="color:Red"> From OpenAlex Website:' , unsafe_allow_html = True)
183
- st.dataframe(papers)
184
- except:
185
- try:
186
- st.write(f'<p style="color:Blue"> From IEA Website:' , unsafe_allow_html = True)
187
- st.write(f'<strong>Technology details:</strong> {reference_text}' , unsafe_allow_html = True)
188
- st.write(f'<strong>Technology key initiatives:</strong> {key_initiative}' , unsafe_allow_html = True)
189
- st.write(f'<strong>Extracted projects and organization name:</strong> {location_entities}' , unsafe_allow_html = True)
190
- st.write(f'<p style="color:Red"> From OpenAlex Website:' , unsafe_allow_html = True)
191
- st.write(f'No related paper found')
192
- except:
193
- st.write("No key initatives found")
194
-
195
-
196
- try:
197
- paper_id = st.text_input("More data on a paper?", 'Enter an OpenAlex paper id (ex: W100000)')
198
- url , title , abstract , date , authors , institutions = paper_functions.extract_quantitative_data_paper(
199
- work_id = paper_id)
200
-
201
- st.write(f'<p style="color:Red"> From OpenAlex Website:' , unsafe_allow_html = True)
202
- st.write(f'<p style="color:Black"> <strong> Paper link:</strong> <a href="url">{url}' , unsafe_allow_html = True)
203
- st.write(f'<strong> Paper title:</strong> {title}' , unsafe_allow_html = True)
204
- st.write(f'<strong> Paper abstract:</strong> {abstract}' , unsafe_allow_html = True)
205
- st.write(f'<strong> Paper date:</strong> {date}' , unsafe_allow_html = True)
206
- st.write(f'<strong> Paper co-inventors:</strong> {authors}' , unsafe_allow_html = True)
207
- st.write(f'<strong> Paper assignees:</strong> {institutions}' , unsafe_allow_html = True)
208
- #
209
- except:
210
- st.write("Enter a valid work id")
211
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/pages/3_Related_Companies.py DELETED
@@ -1,88 +0,0 @@
1
- import streamlit as st
2
-
3
- st.set_page_config(page_title="Related Companies", page_icon="🏛")
4
-
5
-
6
- import pandas as pd
7
- from python_scripts import functions
8
- from python_scripts import functions_companies
9
-
10
- @st.cache
11
- def convert_df(df):
12
- # IMPORTANT: Cache the conversion to prevent computation on every rerun
13
- return df.to_csv()
14
-
15
-
16
- header = st.container()
17
-
18
- company_finder = st.container()
19
-
20
-
21
- with company_finder:
22
-
23
-
24
- st.markdown("# Related companies")
25
- st.sidebar.header("Related companies")
26
- st.write(
27
- """You can find the most related companies for each climate related IEA technology. Enjoy!"""
28
- )
29
-
30
-
31
- st.subheader("Select the technology you want to look at")
32
- dic_technologies, dic_categories, list_categories_tech, list_technologies = functions_companies.finder()
33
-
34
- list_technologies = [ ( list_categories_tech[i] , i ) for i in range(len(list_categories_tech)) ]
35
- key0 = lambda t: t[0]
36
-
37
-
38
- # Choose the category
39
- tech_category = st.selectbox('Select a category',list_technologies, format_func = key0)
40
-
41
-
42
- # After a selection is made the choices will update
43
- # Choose the technology and number
44
- technologies = dic_technologies[tech_category[0]]
45
-
46
- technology = st.selectbox('Select a technology',technologies,format_func = key0)
47
-
48
- size = st.slider('How many companies do you want?', 0, 50, 10)
49
-
50
-
51
- st.subheader("Look at the related companies")
52
-
53
-
54
- try:
55
- reference_text, text1 , text2 = functions_companies.extract_quantitative_data_technology(
56
- technologies = technology[0],
57
- number_technology = technology[1],
58
- )
59
-
60
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Technology details:</strong> {reference_text}' , unsafe_allow_html = True)
61
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Deployment target and Announced development target:</strong> {text1}' , unsafe_allow_html = True)
62
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Announced cost reduction targets:</strong> {text2}' , unsafe_allow_html = True)
63
-
64
- except:
65
- st.write("No information about the technology")
66
-
67
-
68
-
69
- #try:
70
- if st.button('Get related companies'):
71
- companies_ranked = functions_companies.related_VC_deals(
72
- category = tech_category[1],
73
- number_technology = technology[1],
74
- size = size
75
- )
76
- st.dataframe(companies_ranked.style.format({"year_established": '{:.0f}'}))
77
- csv = convert_df(companies_ranked)
78
-
79
- st.download_button(
80
- label="Download table as CSV",
81
- data=csv,
82
- file_name='companies.csv',
83
-
84
- )
85
- #except:
86
- # st.write("No company found, try with other key words")
87
-
88
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/pages/4_University_contests.py DELETED
@@ -1,69 +0,0 @@
1
- import streamlit as st
2
-
3
- st.set_page_config(page_title="Related university projects", page_icon="🏛")
4
-
5
-
6
- import pandas as pd
7
- from python_scripts import functions
8
- from python_scripts import functions_contest
9
-
10
-
11
-
12
- header = st.container()
13
-
14
- company_finder = st.container()
15
-
16
-
17
- with company_finder:
18
-
19
-
20
- st.markdown("# Related university projects")
21
- st.sidebar.header("Related university projects")
22
- st.write(
23
- """You can find the most related projects which participated to the Big Ideas contest: [Big Ideas website](https://bigideascontest.org). Enjoy!"""
24
- )
25
-
26
-
27
- st.subheader("Select the technology you want to look at")
28
- dic_technologies, dic_categories, list_categories_tech, list_technologies = functions_contest.finder()
29
-
30
- list_technologies = [ ( list_categories_tech[i] , i ) for i in range(len(list_categories_tech)) ]
31
- key0 = lambda t: t[0]
32
-
33
-
34
- # Choose the category
35
- tech_category = st.selectbox('Select a category',list_technologies, format_func = key0)
36
-
37
-
38
- # After a selection is made the choices will update
39
- # Choose the technology and number
40
- technologies = dic_technologies[tech_category[0]]
41
-
42
- technology = st.selectbox('Select a technology',technologies,format_func = key0)
43
-
44
-
45
- st.subheader("Look at the related projects")
46
-
47
-
48
- try:
49
- reference_text, text1 , text2 = functions_contest.extract_quantitative_data_technology(
50
- technologies = technology[0],
51
- number_technology = technology[1],
52
- )
53
-
54
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Technology details:</strong> {reference_text}' , unsafe_allow_html = True)
55
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Deployment target and Announced development target:</strong> {text1}' , unsafe_allow_html = True)
56
- st.write(f'<p style="color:Blue"> From IEA Website: <p style="color:Black"> <strong>Announced cost reduction targets:</strong> {text2}' , unsafe_allow_html = True)
57
-
58
- except:
59
- st.write("No information about the technology")
60
-
61
-
62
-
63
- try:
64
- if st.button('Get related projects'):
65
- companies_ranked = functions_contest.big_ideas_encoding(
66
- number_technology = technology[1])
67
- st.dataframe(companies_ranked)
68
- except:
69
- st.write("No project found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/pages/5_Your_own_research:_Patents.py DELETED
@@ -1,109 +0,0 @@
1
- import streamlit as st
2
-
3
- st.set_page_config(page_title="Search patents related to your own technology", page_icon="🙋‍♀️")
4
-
5
- import pandas as pd
6
- from python_scripts import patent_functions_own_details
7
- from streamlit_folium import folium_static
8
- import folium
9
-
10
-
11
-
12
- header = st.container()
13
-
14
- own_paper_finder = st.container()
15
-
16
-
17
- with own_paper_finder:
18
-
19
-
20
- st.markdown("# Your own research: Patents and Inventors ")
21
- st.sidebar.header("Patents and Inventors")
22
- st.write(
23
- """You can find the most related patents and inventors to your technology. Enjoy!"""
24
- )
25
-
26
-
27
- st.subheader("We are searching for the patents which contain (in the title or abstract) the key words you can provide below:")
28
-
29
- key_words = st.text_input("Keywords", 'Input your text here')
30
-
31
- st.subheader("The patents are ranked according to the similary between their abstract and the description you can provide below:")
32
-
33
- details = st.text_input("Details", 'Input your text here')
34
-
35
- size = st.slider('How many patents do you want?', 0, 200, 20)
36
-
37
-
38
-
39
-
40
-
41
- try:
42
- if st.button('Get related patents'):
43
- patent_rank_df = patent_functions_own_details.get_ranking_own_research(research_key_words = key_words, details = details , size=size)
44
-
45
- st.dataframe(patent_rank_df)
46
-
47
-
48
- except:
49
- st.write("No patent found, try with other key words")
50
-
51
-
52
-
53
-
54
- try:
55
- if st.button('Get the main inventors'):
56
- inventors = patent_functions_own_details.main_inventors(research_key_words = key_words, details = details , size=size)
57
- st.dataframe(inventors)
58
-
59
- except:
60
- st.write("No inventor found, try with other key words")
61
-
62
-
63
-
64
-
65
- try:
66
-
67
- if st.button('Get the map of the main inventors patents'):
68
- map_inventor = patent_functions_own_details.map_inventors(
69
- research_key_words = key_words, details = details , size=size)
70
-
71
- m = folium.Map(zoom_start = 1)
72
- dic_geo = {}
73
- for elem in map_inventor.index:
74
-
75
- longitude = map_inventor["longitude"][elem]
76
- latitude = map_inventor["latitude"][elem]
77
- if str(longitude) + " " + str(latitude) not in dic_geo:
78
- dic_geo[str(longitude) + " " + str(latitude)] = {}
79
- dic_geo[str(longitude) + " " + str(latitude)]["inventors"] = set()
80
- dic_geo[str(longitude) + " " + str(latitude)]["dates"] = set()
81
-
82
- dic_geo[str(longitude) + " " + str(latitude)]["inventors"].add(map_inventor["inventor_name"][elem])
83
- dic_geo[str(longitude) + " " + str(latitude)]["dates"].add(map_inventor["patent_date"][elem])
84
-
85
- for elem in dic_geo:
86
- folium.Marker([float(elem.split()[1]), float(elem.split()[0])], popup="Inventors: " + ", ".join(list(dic_geo[elem]["inventors"])) + ", Date: " + ", ".join(list(dic_geo[elem]["dates"])), tooltip=", ".join(list(dic_geo[elem]["inventors"]))).add_to(m)
87
- folium_static(m)
88
-
89
- except:
90
- st.write("No inventor found, try with other key words")
91
-
92
-
93
- try:
94
- patent_id = st.text_input("More data on a patent?", 'Enter a US patent (ex: US-100000)')
95
- url , title , abstract , date , co_inventors , assignees = patent_functions_own_details.extract_quantitative_data_patent(
96
- patent_id = patent_id)
97
-
98
- st.write(f'<p style="color:Black"> <strong> Patent link:</strong> <a href="url">{url}' , unsafe_allow_html = True)
99
- st.write(f'<p style="color:Blue"> From PatentsView Website:' , unsafe_allow_html = True)
100
- st.write(f'<strong> Patent title:</strong> {title}' , unsafe_allow_html = True)
101
- st.write(f'<strong> Patent abstract:</strong> {abstract}' , unsafe_allow_html = True)
102
- st.write(f'<strong> Patent date:</strong> {date}' , unsafe_allow_html = True)
103
- st.write(f'<strong> Patent co-inventors:</strong> {co_inventors}' , unsafe_allow_html = True)
104
- st.write(f'<strong> Patent assignees:</strong> {assignees}' , unsafe_allow_html = True)
105
-
106
- except:
107
- st.write("Enter a valid patent id")
108
-
109
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/pages/6_Your_own_research:_Scientific_Publications.py DELETED
@@ -1,105 +0,0 @@
1
- import streamlit as st
2
-
3
- st.set_page_config(page_title="Search papers with your own technology", page_icon="🙋‍♀️")
4
-
5
- import pandas as pd
6
- from python_scripts import paper_functions_own_details
7
- from streamlit_folium import folium_static
8
- import folium
9
-
10
-
11
-
12
- header = st.container()
13
-
14
- own_paper_finder = st.container()
15
-
16
-
17
- with own_paper_finder:
18
-
19
-
20
- st.markdown("# Your own research: Scientific publications and authors ")
21
- st.sidebar.header("Scientific publications and authors")
22
- st.write(
23
- """You can find the most related scientific publications and authors to your technology. Enjoy!"""
24
- )
25
-
26
-
27
- st.subheader("We are searching for the scientific publications which contain (in the title, abstract or text) the key words you can provide below:")
28
-
29
- key_words = st.text_input("Keywords", 'Input your text here')
30
-
31
- st.subheader("The scientific publications are ranked according to the similary between their abstract and the description you can provide below:")
32
-
33
- details = st.text_input("Details", 'Input your text here')
34
-
35
- size = st.slider('How many papers do you want?', 0, 200, 20)
36
-
37
-
38
- try:
39
- if st.button('Get related papers'):
40
- paper_rank_df = paper_functions_own_details.get_ranking_own_research(research_key_words = key_words, details = details , display= False , size=size)
41
-
42
- st.dataframe(paper_rank_df)
43
- #print(paper_rank_df)
44
- except:
45
- st.write("No paper found, try with other key words")
46
-
47
-
48
-
49
-
50
- #try:
51
- if st.button('Get the main authors'):
52
- authors = paper_functions_own_details.main_authors(research_key_words = key_words, details = details , size=size)
53
- st.dataframe(authors)
54
-
55
- #except:
56
- # st.write("No author found, try with other key words")
57
-
58
-
59
-
60
-
61
- try:
62
-
63
- if st.button('Get the map of the main authors'):
64
- map_author = paper_functions_own_details.map_authors(research_key_words = key_words, details = details , size=size)
65
- m = folium.Map(zoom_start = 1)
66
- dic_geo = {}
67
- for elem in map_author.index:
68
-
69
- longitude = map_author["longitude"][elem]
70
- latitude = map_author["latitude"][elem]
71
- if str(longitude) + " " + str(latitude) not in dic_geo:
72
- dic_geo[str(longitude) + " " + str(latitude)] = {}
73
- dic_geo[str(longitude) + " " + str(latitude)]["authors"] = set()
74
- dic_geo[str(longitude) + " " + str(latitude)]["institutions"] = set()
75
- dic_geo[str(longitude) + " " + str(latitude)]["dates"] = set()
76
- dic_geo[str(longitude) + " " + str(latitude)]["authors"].add(map_author["author"][elem])
77
- dic_geo[str(longitude) + " " + str(latitude)]["institutions"].add(map_author["institution"][elem])
78
- dic_geo[str(longitude) + " " + str(latitude)]["dates"].add(map_author["date"][elem])
79
-
80
- for elem in dic_geo:
81
- folium.Marker([float(elem.split()[1]), float(elem.split()[0])], popup="Author: " + ", ".join(list(dic_geo[elem]["authors"])) + ", Institution: " + ", ".join(list(dic_geo[elem]["institutions"])) + ", Date: " + ", ".join(list(dic_geo[elem]["dates"])), tooltip=", ".join(list(dic_geo[elem]["authors"]))).add_to(m)
82
- folium_static(m)
83
-
84
- except:
85
- st.write("No author found, try with other key words")
86
-
87
-
88
-
89
-
90
-
91
- try:
92
- paper_id = st.text_input("More data on a paper?", 'Enter an OpenAlex paper id (ex: W100000)')
93
- url , title , abstract , date , authors , institutions = paper_functions_own_details.extract_quantitative_data_paper(
94
- work_id = paper_id)
95
-
96
- st.write(f'<p style="color:Red"> From OpenAlex Website:' , unsafe_allow_html = True)
97
- st.write(f'<p style="color:Black"> <strong> Paper link:</strong> <a href="url">{url}' , unsafe_allow_html = True)
98
- st.write(f'<strong> Paper title:</strong> {title}' , unsafe_allow_html = True)
99
- st.write(f'<strong> Paper abstract:</strong> {abstract}' , unsafe_allow_html = True)
100
- st.write(f'<strong> Paper date:</strong> {date}' , unsafe_allow_html = True)
101
- st.write(f'<strong> Paper co-inventors:</strong> {authors}' , unsafe_allow_html = True)
102
- st.write(f'<strong> Paper assignees:</strong> {institutions}' , unsafe_allow_html = True)
103
- #
104
- except:
105
- st.write("Enter a valid work id")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/pages/7_Your_own_research:_Related_Scientist.py DELETED
@@ -1,107 +0,0 @@
1
- import streamlit as st
2
-
3
- st.set_page_config(page_title="Search related scientist", page_icon="🙋‍♀️")
4
-
5
- import pandas as pd
6
- from python_scripts import related_scientist
7
- from streamlit_folium import folium_static
8
- import folium
9
-
10
-
11
-
12
- header = st.container()
13
-
14
- own_paper_finder = st.container()
15
-
16
-
17
- with own_paper_finder:
18
-
19
-
20
- st.markdown("# Searching the scientists related to somebody")
21
- st.sidebar.header("Related scientists")
22
-
23
-
24
-
25
- st.subheader("We are looking for the scientists who cite the scientist of your choice.")
26
-
27
- key_name = st.text_input("Enter the name of a scientist", 'Scientist name')
28
-
29
- key0 = lambda t: t[0]
30
- key1 = lambda t: t[1]
31
-
32
-
33
- #try:
34
- if key_name == 'Scientist name':
35
- st.write("Enter a scientist name")
36
-
37
- else:
38
-
39
- pandas_scientific_ids , scientist_ids = related_scientist.author_id_from_name(name = key_name)
40
-
41
- st.dataframe(pandas_scientific_ids)
42
-
43
-
44
-
45
- #st.write('Select the identifier(s) which correspond to the scientist you are looking for:')
46
-
47
-
48
- author_ids = st.multiselect("Select the identifier(s) which correspond to the scientist you are looking for: ", scientist_ids, format_func = key1 )
49
-
50
- size = st.slider('How many scientists do you want?', 0, 100, 10)
51
-
52
- year = st.selectbox("I want to look at the citations since: ", [ k for k in range(1980, 2023) ] , index = 38)
53
-
54
-
55
- list_option = [ ("No, I want to look at all scientist you can find." , 0) , ("Yes. I want to search by continent." , 1 ), ("Yes. I want to search by country." , 2 )]
56
- list_keyword_bool = st.selectbox('Would you like to look at the scientist from a specific country?',list_option,format_func = key0)
57
-
58
- if list_keyword_bool[1] == 2:
59
- country_code = st.text_input("Enter a country code", 'US')
60
- elif list_keyword_bool[1] == 1:
61
- country_code = st.selectbox("Select a continent", [ "Europe" , "North America" , "Asia" , "South America", "Oceania" , "Africa" ] , index = 0)
62
- else:
63
- country_code = False
64
-
65
- if len(author_ids) == 0:
66
- st.write("Select the identifier(s) which correspond to the scientist you are looking for")
67
-
68
- else:
69
-
70
-
71
-
72
- if st.button('Get the related scientist (it can take a few minutes, please, be patient 😊)'):
73
-
74
- scientists = related_scientist.from_author_id(
75
- main_author_ids = [ author_id[0] for author_id in author_ids] ,
76
- year = year,
77
- country_code = country_code,
78
- size = size)
79
-
80
- st.dataframe(scientists[0])
81
-
82
- map_author = scientists[1]
83
- m = folium.Map(zoom_start = 1)
84
- dic_geo = {}
85
- for elem in map_author.index:
86
- if map_author["institution"][elem] != "Max Planck Institute for Plasma Physics - Greifswald":
87
-
88
- longitude = map_author["longitude"][elem]
89
- latitude = map_author["latitude"][elem]
90
- if str(longitude) + " " + str(latitude) not in dic_geo:
91
- dic_geo[str(longitude) + " " + str(latitude)] = {}
92
- dic_geo[str(longitude) + " " + str(latitude)]["authors"] = set()
93
- dic_geo[str(longitude) + " " + str(latitude)]["institutions"] = set()
94
- dic_geo[str(longitude) + " " + str(latitude)]["authors"].add(map_author["author_name"][elem])
95
- dic_geo[str(longitude) + " " + str(latitude)]["institutions"].add(map_author["institution"][elem])
96
-
97
- for elem in dic_geo:
98
- folium.Marker([float(elem.split()[1]), float(elem.split()[0])], popup="Author: " + ", ".join(list(dic_geo[elem]["authors"])) + ", Institution: " + ", ".join(list(dic_geo[elem]["institutions"])), tooltip=", ".join(list(dic_geo[elem]["authors"]))).add_to(m)
99
- folium_static(m)
100
-
101
-
102
-
103
-
104
- #except:
105
- # st.write("No scientist corresponding to this name was found.")
106
-
107
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/__init__.py DELETED
@@ -1 +0,0 @@
1
- __all__ = ["functions","paper_functions","patent_functions", "others"]
 
 
Climate_site/python_scripts/__pycache__/__init__.cpython-311.pyc DELETED
Binary file (246 Bytes)
 
Climate_site/python_scripts/__pycache__/__init__.cpython-38.pyc DELETED
Binary file (232 Bytes)
 
Climate_site/python_scripts/__pycache__/functions.cpython-311.pyc DELETED
Binary file (9.61 kB)
 
Climate_site/python_scripts/__pycache__/functions.cpython-38.pyc DELETED
Binary file (4.78 kB)
 
Climate_site/python_scripts/__pycache__/multi_input_functions.cpython-38.pyc DELETED
Binary file (12 kB)
 
Climate_site/python_scripts/__pycache__/others.cpython-311.pyc DELETED
Binary file (537 Bytes)
 
Climate_site/python_scripts/__pycache__/others.cpython-38.pyc DELETED
Binary file (400 Bytes)
 
Climate_site/python_scripts/__pycache__/paper_functions.cpython-38.pyc DELETED
Binary file (23.8 kB)
 
Climate_site/python_scripts/__pycache__/patent_functions.cpython-38.pyc DELETED
Binary file (12 kB)
 
Climate_site/python_scripts/__pycache__/test_script.cpython-311.pyc DELETED
Binary file (9.54 kB)
 
Climate_site/python_scripts/__pycache__/test_script.cpython-38.pyc DELETED
Binary file (3.59 kB)
 
Climate_site/python_scripts/big_ideas_contest.tsv DELETED
The diff for this file is too large to render. See raw diff
 
Climate_site/python_scripts/functions.py DELETED
@@ -1,125 +0,0 @@
1
- ##packages code
2
- import pandas as pd
3
- import numpy as np
4
- import json, requests
5
- import pandas as pd
6
-
7
- #import spacy
8
- #!python -m spacy download en_core_web_lg
9
- #spacy_nlp = spacy.load("en_core_web_lg")
10
-
11
- #import en_core_web_lg
12
- #spacy_nlp = en_core_web_lg.load()
13
-
14
- #################### Test Scripts #############################
15
-
16
- def URL(base_URL , entity_type , filters):
17
- url = base_URL + entity_type + filters
18
- return url
19
-
20
-
21
- def get_data(url):
22
- url = requests.get(url)
23
- text = url.text
24
- import json
25
- data = json.loads(text)
26
- return data
27
-
28
- ## encoding the abstract
29
-
30
-
31
- def reconstruction_abstract(abstract_inverted_index):
32
- # return the abstract is the abstract exists in the database, else, return None
33
-
34
- if abstract_inverted_index != None:
35
-
36
- list_values = list(abstract_inverted_index.values())
37
- list_keys = list(abstract_inverted_index.keys())
38
- #from the words in the abstract (keys of abstract_inverted_index) and their position in the text (values of abstract_inverted_index), reconstruct the abstract
39
-
40
- size_abstract = max([ max(elem) for elem in abstract_inverted_index.values() ] )
41
-
42
- abstract = [""]*(size_abstract +1)
43
-
44
- for i in range(len(list_values)):
45
- for pos in list_values[i]:
46
- abstract[pos] = list_keys[i]
47
-
48
- return " ".join(list(abstract))
49
-
50
- else:
51
- return None
52
-
53
-
54
- ## calculate efficiently the dot product between two vectors
55
-
56
- def norm(vector):
57
- return np.sqrt(sum(x * x for x in vector))
58
-
59
- def cosine_similarity2(vec_a, vec_b):
60
- norm_a = norm(vec_a)
61
- norm_b = norm(vec_b)
62
- dot = sum(a * b for a, b in zip(vec_a, vec_b))
63
- return dot / (norm_a * norm_b)
64
-
65
- ################################### Extracted texts ###############################################################
66
-
67
- def extract_quantitative_data_paper( work_id):
68
-
69
-
70
- try:
71
- url = "https://api.openalex.org/works/" + str(work_id)
72
- data = get_data(url)
73
- date = data["publication_date"]
74
- title = data["title"]
75
- abstract = reconstruction_abstract(data["abstract_inverted_index"])
76
- concepts = ", ".join( [elem["display_name"] for elem in data["concepts"]] )
77
- authors = ", ".join( [elem["author"]["display_name"] for elem in data["authorships"]] )
78
- institutions = ", ".join( set([elem["institutions"][0]["display_name"] for elem in data["authorships"]]) )
79
- print("\033[96mFROM OpenAlex: ")
80
- print("\033[92mPaper link: " + url)
81
- print(" ")
82
- print("\033[92mTitle: \x1b[0m" + title)
83
- print(" ")
84
- print("\033[92mConcepts: \x1b[0m" + concepts)
85
- print(" ")
86
- print("\033[92mDate: \x1b[0m" + date)
87
- print(" ")
88
- print("\033[92mAuthors: \x1b[0m" + authors)
89
- print(" ")
90
- print("\033[92mInstitutions: \x1b[0m" + institutions)
91
- print(" ")
92
- # sentences = extract_sentences_with_numbers(abstract , "\033[92mAbstract\x1b[0m")
93
- return [url, date, title, abstract, concepts, authors, institutions]
94
- except:
95
- print("Enter a valid work id from OpenAlex")
96
-
97
-
98
- def extract_quantitative_data_patent( patent_id):
99
-
100
- try:
101
- url = "https://api.patentsview.org/patents/query?q={%22patent_id%22:%22" + str(patent_id) + "%22}&f=[%22patent_number%22,%22patent_title%22,%22patent_abstract%22,%22patent_date%22,%22inventor_last_name%22,%22inventor_first_name%22,%22assignee_organization%22]"
102
- data = get_data(url)["patents"][0]
103
- title = data["patent_title"]
104
- abstract = data["patent_abstract"]
105
- print("\033[96mFROM PATENTSVIEW:")
106
- print("\033[92mPatent link: \x1b[0m" + url)
107
- print(" ")
108
- print("\033[92mTitle: \x1b[0m" + title)
109
- print(" ")
110
- print("\033[92mAbstract: \x1b[0m" + abstract)
111
- print(" ")
112
- print("\033[92mDate: \x1b[0m" + data["patent_date"])
113
- print(" ")
114
- print("\033[92mInventors: \x1b[0m" , ", ".join([ data["inventors"][i]["inventor_first_name"] + " " + data["inventors"][i]["inventor_last_name"] for i in range(len(data["inventors"])) ]) )
115
- print(" ")
116
- print("\033[92mAssignee: \x1b[0m" , ", ".join( [ str(data["assignees"][i]["assignee_organization"]) for i in range(len(data["assignees"])) ] ) )
117
- assignees = ', '.join( [ str(data["assignees"][i]["assignee_organization"]) for i in range(len(data["assignees"])) ] )
118
- inventors = ", ".join([ data["inventors"][i]["inventor_first_name"] + " " + data["inventors"][i]["inventor_last_name"] for i in range(len(data["inventors"])) ])
119
- except:
120
- print("Enter a valid patent_id from PatentsView")
121
-
122
- return data, url, assignees, inventors
123
-
124
-
125
- #print("Do you want the quantitative information corresponding to a paper?")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/functions_companies.py DELETED
@@ -1,447 +0,0 @@
1
- ##packages code
2
-
3
- import streamlit as st
4
- from shapely.geometry import Point
5
- import pandas as pd
6
- import re
7
- import json
8
-
9
- def load_dic():
10
- f = open("Synapse_project/Climate_site/python_scripts/related_companies.json","r")
11
- dic_companies = json.load(f)
12
- return dic_companies
13
-
14
-
15
- def load_data():
16
- url = "Synapse_project/Climate_site/python_scripts/preqin_companies_IEA.tsv"
17
- table = pd.read_csv(url, delimiter = "\t" , index_col = 0)
18
- table = table.astype({'portfolio_company_id': 'str'})
19
-
20
- return table
21
-
22
- table_companies = load_data()
23
- dic_companies = load_dic()
24
-
25
-
26
- #################### General Functions #############################
27
-
28
-
29
-
30
- def print_extracted_text(name_file):
31
-
32
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
33
- lines = file.readlines()
34
- count = 0
35
- for index, line in enumerate(lines):
36
- read_line = line.strip()
37
- print(read_line)
38
-
39
- file.close()
40
-
41
-
42
- iea.txt
43
-
44
- def details(name_file , display):
45
-
46
- file = open("Synapse_project/Climate_site/python_scripts/iea.txt", "r")
47
- lines = file.readlines()
48
-
49
- mark = 0
50
- dic_details = {}
51
- count = -1
52
- for index, line in enumerate(lines):
53
-
54
- line = line.strip()
55
- if line == "Close explanation":
56
- break
57
-
58
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
59
- count += 1
60
-
61
-
62
- if mark == 1 and line != "" and line[0] == "*":
63
-
64
- if display == True:
65
- print(count)
66
- print(text)
67
- print(" ")
68
- dic_details[count] = text
69
- mark = 0
70
-
71
-
72
- if mark == 1:
73
- text = text + line + " "
74
-
75
- if line.split(" ")[-1] == "Details" or line.split(" ")[-1] == "Hide":
76
- mark = 1
77
- text = ""
78
-
79
- return dic_details
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
- def key_initiatives(name_file , display ):
88
-
89
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
90
- lines = file.readlines()
91
-
92
-
93
- mark = 0
94
- dic_key_initiatives = {}
95
- count = -1
96
- for index, line in enumerate(lines):
97
-
98
- line = line.strip()
99
- if line == "Close explanation":
100
- break
101
-
102
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
103
-
104
- count += 1
105
-
106
-
107
-
108
- if mark == 1 and line != "" and ( (line[0].isnumeric() and ">" in line and " " in line) or line == "*Deployment targets:*" or line == "*Announced development targets:*"):
109
- if display == True:
110
- print(count)
111
- print(text)
112
- print(" ")
113
-
114
- dic_key_initiatives[count] = text
115
- mark = 0
116
-
117
-
118
- if mark == 1:
119
- text = text + line + " "
120
-
121
- if line == "*Key initiatives:*":
122
-
123
-
124
- mark = 1
125
- text = ""
126
-
127
- return dic_key_initiatives
128
-
129
-
130
-
131
-
132
- def deployment_target(name_file , display):
133
-
134
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
135
- lines = file.readlines()
136
-
137
-
138
- mark = 0
139
- dic_target = {}
140
- count = -1
141
- for index, line in enumerate(lines):
142
-
143
- line = line.strip()
144
- if line == "Close explanation":
145
- break
146
-
147
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
148
- count += 1
149
-
150
-
151
-
152
- if mark == 1 and line != "" and ((line[0].isnumeric() and ">" in line and " " in line) or line == "*Announced cost reduction targets:*" or line == "*Announced development targets:*"):
153
-
154
- if display == True:
155
- print(count)
156
- print(text)
157
- print(" ")
158
-
159
- dic_target[count] = text
160
- mark = 0
161
-
162
-
163
- if mark == 1:
164
- text = text + line + " "
165
-
166
- if line == "*Deployment targets:*" or line == "*Announced development targets:*":
167
-
168
- mark = 1
169
- text = ""
170
-
171
- return dic_target
172
-
173
-
174
-
175
-
176
- def cost_reduction_target(name_file , display):
177
-
178
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
179
- lines = file.readlines()
180
-
181
- mark = 0
182
- dic_cost = {}
183
- count = -1
184
- for index, line in enumerate(lines):
185
-
186
- line = line.strip()
187
-
188
- if line == "Close explanation":
189
- break
190
-
191
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
192
-
193
-
194
- count += 1
195
-
196
-
197
-
198
- if mark == 1 and line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
199
-
200
- if display == True:
201
- print(count)
202
- print(text)
203
- print(" ")
204
-
205
- dic_cost[count] = text
206
- mark = 0
207
-
208
-
209
- if mark == 1:
210
- text = text + line + " "
211
-
212
- if line == "*Announced cost reduction targets:*":
213
-
214
- mark = 1
215
- text = ""
216
-
217
- return dic_cost
218
-
219
-
220
-
221
- def key_words(name_file, display ):
222
-
223
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
224
-
225
- lines = file.readlines()
226
-
227
- list_categories = []
228
- count = -1
229
- for index, line in enumerate(lines):
230
-
231
- line = line.strip()
232
-
233
- if line == "Close explanation":
234
- break
235
-
236
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
237
- count += 1
238
-
239
- if display == True:
240
- print("Technologies" , count+1 , ":")
241
-
242
- if line != "":
243
-
244
- if line[0].isnumeric() and ">" in line and " " in line:
245
- i = 0
246
- try:
247
- line = line.split(" ")[2]
248
- except:
249
- print(line)
250
- break
251
-
252
- if "Details" not in lines[index] and "Moderate" not in lines[index]:
253
-
254
- while " " not in line:
255
- i += 1
256
- if "Details"==lines[index + i][:7] or "End-use"==lines[index + i][:7]:
257
- break
258
- else:
259
- line = line + " " + lines[index + i]
260
-
261
- #if " Production" in line:
262
- #line = line.replace(" Production" , "")
263
-
264
- line = line.replace("\n" , " ")
265
- line = line.replace("/" , " ")
266
- line = line.replace("-" , " ")
267
- line = line.split(" ")[0]
268
-
269
- if " " in line:
270
- line = line.replace(" ", " ")
271
- line = line.split(">")
272
-
273
-
274
- if "(" in line[-1]:
275
- line[-1] = line[-1].split("(")[0]
276
-
277
-
278
- for i in range(len(line)):
279
-
280
- # remove multiple spaces
281
- line[i] = re.sub(' +', ' ', line[i])
282
- # remove trailing spaces
283
- line[i] = line[i].strip()
284
-
285
-
286
-
287
- if display == True:
288
- print(line)
289
- print(" ")
290
-
291
- if '' in line:
292
- line.remove('')
293
-
294
- list_categories.append([count , line])
295
-
296
- return list_categories
297
-
298
-
299
-
300
- def technology(name_file, display ):
301
- # Filepath too specific, need to change to relative path
302
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
303
- lines = file.readlines()
304
-
305
- list_categories = []
306
- count = -1
307
- for index, line in enumerate(lines):
308
-
309
- line = line.strip()
310
-
311
- if line == "Close explanation":
312
- break
313
-
314
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
315
- count += 1
316
-
317
- if display == True:
318
- print("Technologies" , count+1 , ":")
319
-
320
- if line != "":
321
-
322
- if line[0].isnumeric() and ">" in line and " " in line:
323
- i = 0
324
- try:
325
- line = line.split(" ")[1]
326
- except:
327
- print(line)
328
- break
329
-
330
-
331
- line = line.replace("\n" , " ")
332
- line = line.replace("/" , " ")
333
- line = line.replace("-" , " ")
334
- line = line.strip()
335
- line = re.sub(' +', ' ', line)
336
- line = line.split(" ")[0]
337
- line = line.split(">")
338
-
339
-
340
- if "(" in line[-1]:
341
- line[-1] = line[-1].split("(")[0]
342
-
343
-
344
- for i in range(len(line)):
345
-
346
- # remove multiple spaces
347
- line[i] = re.sub(' +', ' ', line[i])
348
- # remove trailing spaces
349
- line[i] = line[i].strip()
350
-
351
-
352
-
353
- if display == True:
354
- print(line)
355
- print(" ")
356
-
357
-
358
- list_categories.append([count , line])
359
-
360
- return list_categories
361
-
362
-
363
- #################### Companies Functions #############################
364
-
365
-
366
- def extract_quantitative_data_technology(technologies, number_technology):
367
-
368
-
369
- name_file = "iea"
370
- dic_target = deployment_target(name_file , False)
371
- dic_cost = cost_reduction_target(name_file , False)
372
- dic_details = details(name_file , False)
373
- cost_target_text = 'No information'
374
- cost_text = 'No information'
375
-
376
- if number_technology in dic_details:
377
- reference_text = dic_details[number_technology]
378
-
379
-
380
- if number_technology in dic_target:
381
- cost_target_text = dic_target[number_technology]
382
-
383
- if number_technology in dic_cost:
384
- cost_text = dic_cost[number_technology]
385
-
386
- return reference_text, cost_target_text, cost_text
387
-
388
-
389
- def related_VC_deals(category , number_technology , size):
390
-
391
- number_technology = str(number_technology)
392
-
393
-
394
- list_results = list(dic_companies[number_technology].keys())
395
- res = table_companies[table_companies["portfolio_company_id"].isin(list_results)].set_index("portfolio_company_id")
396
-
397
- table = res.copy()
398
- for elem in table.index:
399
- table.loc[ elem , "score" ] = dic_companies[number_technology][str(elem)]
400
-
401
- table = table.sort_values("score" , ascending = False).head(size)
402
- table = table[['portfolio_company_name', 'year_established','portfolio_company_website','firm_about',
403
- 'portfolio_company_country', 'portfolio_company_state',
404
- 'firm_othernames', 'industry_classification',
405
- 'primary_industry', 'sub_industries', 'score']]
406
-
407
-
408
- table["year_established"] = table["year_established"].replace(",", "", regex=True).astype(int, errors='ignore')
409
-
410
-
411
-
412
- return table
413
-
414
-
415
-
416
-
417
- ################################### Extracted texts ###############################################################
418
-
419
- #@title Which patents are related to the technology?
420
-
421
-
422
- def finder():
423
- name_file = 'iea'
424
- res = technology("iea", False )
425
- list_categories_tech = []
426
- list_categories = key_words("iea" , False)
427
- list_technologies = [ ( ", ".join(list_categories[i][1]) , i ) for i in range(len(list_categories)) ]
428
- dic_technologies = {}
429
- for i in range(len(res)):
430
- names = res[i][1]
431
- if ", ".join(names) not in list_categories_tech:
432
- list_categories_tech.append(", ".join(names))
433
- dic_technologies[", ".join(names)] = []
434
- dic_technologies[", ".join(names)].append( (", ".join(list_categories[i][1]) , i ))
435
-
436
-
437
- list_climate = [ ("Any related papers" , False ) , ("Climate related papers" , True)]
438
-
439
- dic_categories = {}
440
- for elem in list_technologies:
441
- list_words = elem[0].split(",")[-3:]
442
- for i in range(len(list_words)):
443
- if "CCUS" in list_words[i]:
444
- list_words[i] = list_words[i].replace("CCUS" , "carbon capture storage")
445
- dic_categories[elem[1]] = [ ", ".join([ " ".join(words.split()[:3]) for words in list_words ] ) , ", ".join([ " ".join(words.split()[:3]) for words in list_words[:-1] ]) , ", ".join([ " ".join(words.split()[:3]) for words in list_words[1:] ] ) ]
446
-
447
- return dic_technologies, dic_categories, list_categories_tech, list_technologies
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/functions_contest.py DELETED
@@ -1,478 +0,0 @@
1
- ##packages code
2
-
3
- import streamlit as st
4
- from shapely.geometry import Point
5
- from math import radians, cos, sin, asin, sqrt
6
- import pandas as pd
7
- import re
8
- import json
9
-
10
- from sentence_transformers import SentenceTransformer, util
11
-
12
- @st.cache_resource
13
- def model_nlp():
14
- model = SentenceTransformer('all-mpnet-base-v2')
15
- return model
16
-
17
-
18
- def load_data():
19
- url = "Synapse_project/Climate_site/python_scripts/big_ideas_contest.tsv"
20
- dic = pd.read_csv(url, delimiter = "\t" , index_col = 0).to_dict('index')
21
- return dic
22
-
23
-
24
-
25
- #################### General Functions #############################
26
-
27
- def clean_encoding(encoded_text):
28
- if encoded_text == None:
29
- return None
30
- else:
31
- if "\n" in encoded_text:
32
- encoded_text = encoded_text.replace("\n" , "")
33
- encoded_text = encoded_text[1:-1]
34
- encoded_text = list(map(float , encoded_text.split(", ")))
35
- return encoded_text
36
-
37
-
38
- def norm(vector):
39
- return sqrt(sum(x * x for x in vector))
40
-
41
- def cosine_similarity2(vec_a, vec_b):
42
- norm_a = norm(vec_a)
43
- norm_b = norm(vec_b)
44
- dot = sum(a * b for a, b in zip(vec_a, vec_b))
45
- return dot / (norm_a * norm_b)
46
-
47
- def print_extracted_text(name_file):
48
-
49
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
50
- lines = file.readlines()
51
- count = 0
52
- for index, line in enumerate(lines):
53
- read_line = line.strip()
54
- print(read_line)
55
-
56
- file.close()
57
-
58
-
59
- iea.txt
60
-
61
- def details(name_file , display):
62
-
63
- file = open("Synapse_project/Climate_site/python_scripts/iea.txt", "r")
64
- lines = file.readlines()
65
-
66
- mark = 0
67
- dic_details = {}
68
- count = -1
69
- for index, line in enumerate(lines):
70
-
71
- line = line.strip()
72
- if line == "Close explanation":
73
- break
74
-
75
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
76
- count += 1
77
-
78
-
79
- if mark == 1 and line != "" and line[0] == "*":
80
-
81
- if display == True:
82
- print(count)
83
- print(text)
84
- print(" ")
85
- dic_details[count] = text
86
- mark = 0
87
-
88
-
89
- if mark == 1:
90
- text = text + line + " "
91
-
92
- if line.split(" ")[-1] == "Details" or line.split(" ")[-1] == "Hide":
93
- mark = 1
94
- text = ""
95
-
96
- return dic_details
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
- def key_initiatives(name_file , display ):
105
-
106
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
107
- lines = file.readlines()
108
-
109
-
110
- mark = 0
111
- dic_key_initiatives = {}
112
- count = -1
113
- for index, line in enumerate(lines):
114
-
115
- line = line.strip()
116
- if line == "Close explanation":
117
- break
118
-
119
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
120
-
121
- count += 1
122
-
123
-
124
-
125
- if mark == 1 and line != "" and ( (line[0].isnumeric() and ">" in line and " " in line) or line == "*Deployment targets:*" or line == "*Announced development targets:*"):
126
- if display == True:
127
- print(count)
128
- print(text)
129
- print(" ")
130
-
131
- dic_key_initiatives[count] = text
132
- mark = 0
133
-
134
-
135
- if mark == 1:
136
- text = text + line + " "
137
-
138
- if line == "*Key initiatives:*":
139
-
140
-
141
- mark = 1
142
- text = ""
143
-
144
- return dic_key_initiatives
145
-
146
-
147
-
148
-
149
- def deployment_target(name_file , display):
150
-
151
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
152
- lines = file.readlines()
153
-
154
-
155
- mark = 0
156
- dic_target = {}
157
- count = -1
158
- for index, line in enumerate(lines):
159
-
160
- line = line.strip()
161
- if line == "Close explanation":
162
- break
163
-
164
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
165
- count += 1
166
-
167
-
168
-
169
- if mark == 1 and line != "" and ((line[0].isnumeric() and ">" in line and " " in line) or line == "*Announced cost reduction targets:*" or line == "*Announced development targets:*"):
170
-
171
- if display == True:
172
- print(count)
173
- print(text)
174
- print(" ")
175
-
176
- dic_target[count] = text
177
- mark = 0
178
-
179
-
180
- if mark == 1:
181
- text = text + line + " "
182
-
183
- if line == "*Deployment targets:*" or line == "*Announced development targets:*":
184
-
185
- mark = 1
186
- text = ""
187
-
188
- return dic_target
189
-
190
-
191
-
192
-
193
- def cost_reduction_target(name_file , display):
194
-
195
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
196
- lines = file.readlines()
197
-
198
- mark = 0
199
- dic_cost = {}
200
- count = -1
201
- for index, line in enumerate(lines):
202
-
203
- line = line.strip()
204
-
205
- if line == "Close explanation":
206
- break
207
-
208
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
209
-
210
-
211
- count += 1
212
-
213
-
214
-
215
- if mark == 1 and line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
216
-
217
- if display == True:
218
- print(count)
219
- print(text)
220
- print(" ")
221
-
222
- dic_cost[count] = text
223
- mark = 0
224
-
225
-
226
- if mark == 1:
227
- text = text + line + " "
228
-
229
- if line == "*Announced cost reduction targets:*":
230
-
231
- mark = 1
232
- text = ""
233
-
234
- return dic_cost
235
-
236
-
237
-
238
- def key_words(name_file, display ):
239
-
240
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
241
-
242
- lines = file.readlines()
243
-
244
- list_categories = []
245
- count = -1
246
- for index, line in enumerate(lines):
247
-
248
- line = line.strip()
249
-
250
- if line == "Close explanation":
251
- break
252
-
253
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
254
- count += 1
255
-
256
- if display == True:
257
- print("Technologies" , count+1 , ":")
258
-
259
- if line != "":
260
-
261
- if line[0].isnumeric() and ">" in line and " " in line:
262
- i = 0
263
- try:
264
- line = line.split(" ")[2]
265
- except:
266
- print(line)
267
- break
268
-
269
- if "Details" not in lines[index] and "Moderate" not in lines[index]:
270
-
271
- while " " not in line:
272
- i += 1
273
- if "Details"==lines[index + i][:7] or "End-use"==lines[index + i][:7]:
274
- break
275
- else:
276
- line = line + " " + lines[index + i]
277
-
278
- #if " Production" in line:
279
- #line = line.replace(" Production" , "")
280
-
281
- line = line.replace("\n" , " ")
282
- line = line.replace("/" , " ")
283
- line = line.replace("-" , " ")
284
- line = line.split(" ")[0]
285
-
286
- if " " in line:
287
- line = line.replace(" ", " ")
288
- line = line.split(">")
289
-
290
-
291
- if "(" in line[-1]:
292
- line[-1] = line[-1].split("(")[0]
293
-
294
-
295
- for i in range(len(line)):
296
-
297
- # remove multiple spaces
298
- line[i] = re.sub(' +', ' ', line[i])
299
- # remove trailing spaces
300
- line[i] = line[i].strip()
301
-
302
-
303
-
304
- if display == True:
305
- print(line)
306
- print(" ")
307
-
308
- if '' in line:
309
- line.remove('')
310
-
311
- list_categories.append([count , line])
312
-
313
- return list_categories
314
-
315
-
316
-
317
- def technology(name_file, display ):
318
- # Filepath too specific, need to change to relative path
319
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
320
- lines = file.readlines()
321
-
322
- list_categories = []
323
- count = -1
324
- for index, line in enumerate(lines):
325
-
326
- line = line.strip()
327
-
328
- if line == "Close explanation":
329
- break
330
-
331
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
332
- count += 1
333
-
334
- if display == True:
335
- print("Technologies" , count+1 , ":")
336
-
337
- if line != "":
338
-
339
- if line[0].isnumeric() and ">" in line and " " in line:
340
- i = 0
341
- try:
342
- line = line.split(" ")[1]
343
- except:
344
- print(line)
345
- break
346
-
347
-
348
- line = line.replace("\n" , " ")
349
- line = line.replace("/" , " ")
350
- line = line.replace("-" , " ")
351
- line = line.strip()
352
- line = re.sub(' +', ' ', line)
353
- line = line.split(" ")[0]
354
- line = line.split(">")
355
-
356
-
357
- if "(" in line[-1]:
358
- line[-1] = line[-1].split("(")[0]
359
-
360
-
361
- for i in range(len(line)):
362
-
363
- # remove multiple spaces
364
- line[i] = re.sub(' +', ' ', line[i])
365
- # remove trailing spaces
366
- line[i] = line[i].strip()
367
-
368
-
369
-
370
- if display == True:
371
- print(line)
372
- print(" ")
373
-
374
-
375
- list_categories.append([count , line])
376
-
377
- return list_categories
378
-
379
-
380
-
381
-
382
- #################### Companies Functions #############################
383
-
384
-
385
- def extract_quantitative_data_technology(technologies, number_technology):
386
-
387
-
388
- name_file = "iea"
389
- dic_target = deployment_target(name_file , False)
390
- dic_cost = cost_reduction_target(name_file , False)
391
- dic_details = details(name_file , False)
392
- cost_target_text = 'No information'
393
- cost_text = 'No information'
394
-
395
- if number_technology in dic_details:
396
- reference_text = dic_details[number_technology]
397
-
398
-
399
- if number_technology in dic_target:
400
- cost_target_text = dic_target[number_technology]
401
-
402
- if number_technology in dic_cost:
403
- cost_text = dic_cost[number_technology]
404
-
405
- return reference_text, cost_target_text, cost_text
406
-
407
-
408
-
409
- def big_ideas_encoding(number_technology):
410
-
411
- model = model_nlp()
412
-
413
- dic_big_ideas = load_data()
414
-
415
- dic_matches = {}
416
-
417
-
418
- name_file = 'iea'
419
- dic_details = details(name_file , False)
420
- k = 0
421
-
422
-
423
-
424
- IEA_encoding = model.encode(dic_details[number_technology] , convert_to_tensor=False , show_progress_bar = False).tolist()
425
- for count_contest in dic_big_ideas:
426
- if pd.isna(dic_big_ideas[count_contest]['encoded_description']) != True:
427
- score = cosine_similarity2(IEA_encoding, clean_encoding(dic_big_ideas[count_contest]['encoded_description']))
428
- if score > 0.45:
429
- dic_matches[k] = dic_big_ideas[count_contest]
430
- dic_matches[k]["score"] = score
431
- k += 1
432
-
433
-
434
-
435
- if len(dic_matches) > 0:
436
- return pd.DataFrame(dic_matches).T.sort_values("score" , ascending = False)[["Project_name" , "Description" ,"Project_date" , "University" , "Field" , "Team_members", "score" ]]
437
- else:
438
- return "No related project found"
439
-
440
-
441
-
442
-
443
-
444
-
445
-
446
-
447
-
448
- ################################### Extracted texts ###############################################################
449
-
450
- #@title Which patents are related to the technology?
451
-
452
-
453
- def finder():
454
- name_file = 'iea'
455
- res = technology("iea", False )
456
- list_categories_tech = []
457
- list_categories = key_words("iea" , False)
458
- list_technologies = [ ( ", ".join(list_categories[i][1]) , i ) for i in range(len(list_categories)) ]
459
- dic_technologies = {}
460
- for i in range(len(res)):
461
- names = res[i][1]
462
- if ", ".join(names) not in list_categories_tech:
463
- list_categories_tech.append(", ".join(names))
464
- dic_technologies[", ".join(names)] = []
465
- dic_technologies[", ".join(names)].append( (", ".join(list_categories[i][1]) , i ))
466
-
467
-
468
- list_climate = [ ("Any related papers" , False ) , ("Climate related papers" , True)]
469
-
470
- dic_categories = {}
471
- for elem in list_technologies:
472
- list_words = elem[0].split(",")[-3:]
473
- for i in range(len(list_words)):
474
- if "CCUS" in list_words[i]:
475
- list_words[i] = list_words[i].replace("CCUS" , "carbon capture storage")
476
- dic_categories[elem[1]] = [ ", ".join([ " ".join(words.split()[:3]) for words in list_words ] ) , ", ".join([ " ".join(words.split()[:3]) for words in list_words[:-1] ]) , ", ".join([ " ".join(words.split()[:3]) for words in list_words[1:] ] ) ]
477
-
478
- return dic_technologies, dic_categories, list_categories_tech, list_technologies
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/iea.txt DELETED
The diff for this file is too large to render. See raw diff
 
Climate_site/python_scripts/institutions.tsv DELETED
The diff for this file is too large to render. See raw diff
 
Climate_site/python_scripts/others.py DELETED
@@ -1,7 +0,0 @@
1
- import numpy as np
2
-
3
- def other(list):
4
- return np.sum(list)
5
-
6
- def add(x,y):
7
- return x+y
 
 
 
 
 
 
 
 
Climate_site/python_scripts/paper_functions.py DELETED
@@ -1,1220 +0,0 @@
1
- ##packages code
2
- import streamlit as st
3
- from shapely.geometry import Point
4
- import pandas as pd
5
- from tqdm import tqdm
6
-
7
- import numpy as np
8
- import json, requests
9
- import pandas as pd
10
- #from pandas.io.json import json_normalize
11
-
12
- import matplotlib.pyplot as plt
13
- import seaborn as sns
14
- from math import radians, cos, sin, asin, sqrt
15
-
16
- #import spacy
17
- #spacy_nlp = spacy.load("en_core_web_lg")
18
-
19
- #@st.cache_resource
20
- #def spacy_func():
21
- # spacy_nlp = spacy.load("en_core_web_lg")
22
- # return spacy_nlp
23
-
24
- from sentence_transformers import SentenceTransformer, util
25
-
26
- @st.cache_resource
27
- def model_nlp():
28
- model = SentenceTransformer('all-MiniLM-L6-v2')
29
- return model
30
-
31
-
32
- @st.cache_data # 👈 Add the caching decorator
33
- def load_data():
34
- url = "Synapse_project/Climate_site/python_scripts/institutions.tsv"
35
- dic = pd.read_csv(url, delimiter = "\t" , index_col = 1).to_dict('index')
36
- return dic
37
-
38
- dic_institutions = load_data()
39
-
40
-
41
- import unicodedata
42
-
43
- from metaphone import doublemetaphone
44
- from fuzzywuzzy import fuzz
45
- from difflib import SequenceMatcher
46
- import re
47
-
48
- import geopandas as gpd
49
- from geopandas import GeoDataFrame
50
- #################### General Functions #############################
51
-
52
- def URL(base_URL , entity_type , filters):
53
- url = base_URL + entity_type + filters
54
- return url
55
-
56
-
57
- def get_data(url):
58
- url = requests.get(url)
59
- text = url.text
60
- import json
61
- data = json.loads(text)
62
- return data
63
-
64
- ## encoding the abstract
65
-
66
-
67
- def reconstruction_abstract(abstract_inverted_index):
68
- # return the abstract is the abstract exists in the database, else, return None
69
-
70
- if abstract_inverted_index != None:
71
-
72
- list_values = list(abstract_inverted_index.values())
73
- list_keys = list(abstract_inverted_index.keys())
74
- #from the words in the abstract (keys of abstract_inverted_index) and their position in the text (values of abstract_inverted_index), reconstruct the abstract
75
-
76
- size_abstract = max([ max(elem) for elem in abstract_inverted_index.values() ] )
77
-
78
- abstract = [""]*(size_abstract +1)
79
-
80
- for i in range(len(list_values)):
81
- for pos in list_values[i]:
82
- abstract[pos] = list_keys[i]
83
-
84
- return " ".join(list(abstract))
85
-
86
- else:
87
- return None
88
-
89
-
90
- ## calculate efficiently the dot product between two vectors
91
-
92
- def norm(vector):
93
- return np.sqrt(sum(x * x for x in vector))
94
-
95
- def cosine_similarity2(vec_a, vec_b):
96
- norm_a = norm(vec_a)
97
- norm_b = norm(vec_b)
98
- dot = sum(a * b for a, b in zip(vec_a, vec_b))
99
- return dot / (norm_a * norm_b)
100
-
101
- ## Extracted texts
102
-
103
- def print_extracted_text(name_file):
104
-
105
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
106
- lines = file.readlines()
107
- count = 0
108
- for index, line in enumerate(lines):
109
- read_line = line.strip()
110
- print(read_line)
111
-
112
- file.close()
113
-
114
-
115
- iea.txt
116
-
117
- def details(name_file , display):
118
-
119
- file = open("Synapse_project/Climate_site/python_scripts/iea.txt", "r")
120
- lines = file.readlines()
121
-
122
- mark = 0
123
- dic_details = {}
124
- count = -1
125
- for index, line in enumerate(lines):
126
-
127
- line = line.strip()
128
- if line == "Close explanation":
129
- break
130
-
131
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
132
- count += 1
133
-
134
-
135
- if mark == 1 and line != "" and line[0] == "*":
136
-
137
- if display == True:
138
- print(count)
139
- print(text)
140
- print(" ")
141
- dic_details[count] = text
142
- mark = 0
143
-
144
-
145
- if mark == 1:
146
- text = text + line + " "
147
-
148
- if line.split(" ")[-1] == "Details" or line.split(" ")[-1] == "Hide":
149
- mark = 1
150
- text = ""
151
-
152
- return dic_details
153
-
154
-
155
-
156
-
157
-
158
-
159
-
160
- def key_initiatives(name_file , display ):
161
-
162
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
163
- lines = file.readlines()
164
-
165
-
166
- mark = 0
167
- dic_key_initiatives = {}
168
- count = -1
169
- for index, line in enumerate(lines):
170
-
171
- line = line.strip()
172
- if line == "Close explanation":
173
- break
174
-
175
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
176
-
177
- count += 1
178
-
179
-
180
-
181
- if mark == 1 and line != "" and ( (line[0].isnumeric() and ">" in line and " " in line) or line == "*Deployment targets:*" or line == "*Announced development targets:*"):
182
- if display == True:
183
- print(count)
184
- print(text)
185
- print(" ")
186
-
187
- dic_key_initiatives[count] = text
188
- mark = 0
189
-
190
-
191
- if mark == 1:
192
- text = text + line + " "
193
-
194
- if line == "*Key initiatives:*":
195
-
196
-
197
- mark = 1
198
- text = ""
199
-
200
- return dic_key_initiatives
201
-
202
-
203
-
204
-
205
- def deployment_target(name_file , display):
206
-
207
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
208
- lines = file.readlines()
209
-
210
-
211
- mark = 0
212
- dic_target = {}
213
- count = -1
214
- for index, line in enumerate(lines):
215
-
216
- line = line.strip()
217
- if line == "Close explanation":
218
- break
219
-
220
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
221
- count += 1
222
-
223
-
224
-
225
- if mark == 1 and line != "" and ((line[0].isnumeric() and ">" in line and " " in line) or line == "*Announced cost reduction targets:*" or line == "*Announced development targets:*"):
226
-
227
- if display == True:
228
- print(count)
229
- print(text)
230
- print(" ")
231
-
232
- dic_target[count] = text
233
- mark = 0
234
-
235
-
236
- if mark == 1:
237
- text = text + line + " "
238
-
239
- if line == "*Deployment targets:*" or line == "*Announced development targets:*":
240
-
241
- mark = 1
242
- text = ""
243
-
244
- return dic_target
245
-
246
-
247
-
248
-
249
- def cost_reduction_target(name_file , display):
250
-
251
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
252
- lines = file.readlines()
253
-
254
- mark = 0
255
- dic_cost = {}
256
- count = -1
257
- for index, line in enumerate(lines):
258
-
259
- line = line.strip()
260
-
261
- if line == "Close explanation":
262
- break
263
-
264
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
265
-
266
-
267
- count += 1
268
-
269
-
270
-
271
- if mark == 1 and line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
272
-
273
- if display == True:
274
- print(count)
275
- print(text)
276
- print(" ")
277
-
278
- dic_cost[count] = text
279
- mark = 0
280
-
281
-
282
- if mark == 1:
283
- text = text + line + " "
284
-
285
- if line == "*Announced cost reduction targets:*":
286
-
287
- mark = 1
288
- text = ""
289
-
290
- return dic_cost
291
-
292
-
293
-
294
- def key_words(name_file, display ):
295
-
296
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
297
-
298
- lines = file.readlines()
299
-
300
- list_categories = []
301
- count = -1
302
- for index, line in enumerate(lines):
303
-
304
- line = line.strip()
305
-
306
- if line == "Close explanation":
307
- break
308
-
309
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
310
- count += 1
311
-
312
- if display == True:
313
- print("Technologies" , count+1 , ":")
314
-
315
- if line != "":
316
-
317
- if line[0].isnumeric() and ">" in line and " " in line:
318
- i = 0
319
- try:
320
- line = line.split(" ")[2]
321
- except:
322
- print(line)
323
- break
324
-
325
- if "Details" not in lines[index] and "Moderate" not in lines[index]:
326
-
327
- while " " not in line:
328
- i += 1
329
- if "Details"==lines[index + i][:7] or "End-use"==lines[index + i][:7]:
330
- break
331
- else:
332
- line = line + " " + lines[index + i]
333
-
334
- #if " Production" in line:
335
- #line = line.replace(" Production" , "")
336
-
337
- line = line.replace("\n" , " ")
338
- line = line.replace("/" , " ")
339
- line = line.replace("-" , " ")
340
- line = line.split(" ")[0]
341
-
342
- if " " in line:
343
- line = line.replace(" ", " ")
344
- line = line.split(">")
345
-
346
-
347
- if "(" in line[-1]:
348
- line[-1] = line[-1].split("(")[0]
349
-
350
-
351
- for i in range(len(line)):
352
-
353
- # remove multiple spaces
354
- line[i] = re.sub(' +', ' ', line[i])
355
- # remove trailing spaces
356
- line[i] = line[i].strip()
357
-
358
-
359
-
360
- if display == True:
361
- print(line)
362
- print(" ")
363
-
364
- if '' in line:
365
- line.remove('')
366
-
367
- list_categories.append([count , line])
368
-
369
- return list_categories
370
-
371
-
372
-
373
- def technology(name_file, display ):
374
- # Filepath too specific, need to change to relative path
375
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
376
- lines = file.readlines()
377
-
378
- list_categories = []
379
- count = -1
380
- for index, line in enumerate(lines):
381
-
382
- line = line.strip()
383
-
384
- if line == "Close explanation":
385
- break
386
-
387
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
388
- count += 1
389
-
390
- if display == True:
391
- print("Technologies" , count+1 , ":")
392
-
393
- if line != "":
394
-
395
- if line[0].isnumeric() and ">" in line and " " in line:
396
- i = 0
397
- try:
398
- line = line.split(" ")[1]
399
- except:
400
- print(line)
401
- break
402
-
403
-
404
- line = line.replace("\n" , " ")
405
- line = line.replace("/" , " ")
406
- line = line.replace("-" , " ")
407
- line = line.strip()
408
- line = re.sub(' +', ' ', line)
409
- line = line.split(" ")[0]
410
- line = line.split(">")
411
-
412
-
413
- if "(" in line[-1]:
414
- line[-1] = line[-1].split("(")[0]
415
-
416
-
417
- for i in range(len(line)):
418
-
419
- # remove multiple spaces
420
- line[i] = re.sub(' +', ' ', line[i])
421
- # remove trailing spaces
422
- line[i] = line[i].strip()
423
-
424
-
425
-
426
- if display == True:
427
- print(line)
428
- print(" ")
429
-
430
-
431
- list_categories.append([count , line])
432
-
433
- return list_categories
434
-
435
-
436
- #################### Paper Functions #############################
437
-
438
- def related_papers(number_technology , carbon_related , display , key_words ):
439
- """Returns a dictionary of data related to the papers the user chooses
440
-
441
- This is done through generating URLs to connect with OpenAlex API and parsing through the json file
442
-
443
- Parameters
444
- ----------
445
- number_technology : int, the index of the technology with respect to the 23 IEA technologies
446
- list_categories : str, an array of all the technologies related to the 23 IEA technologies
447
- carbon_related: bool, a setting to select papers related to carbon capture
448
- display:
449
- key_words: str, an array of keywords selected based off technology/ user input
450
-
451
- """
452
- dic = {}
453
-
454
- max_count = 0
455
- base_URL_OA = f'https://api.openalex.org/'
456
- filter_works = f'works?'
457
-
458
-
459
- filter_openalex = f"search=" + key_words
460
-
461
-
462
- if carbon_related == True:
463
- filter_openalex += "&filter=concepts.id:https://openalex.org/C132651083|https://openalex.org/C115343472|https://openalex.org/C530467964&per_page=100&mailto=emma_scharfmann@berkeley.edu"
464
-
465
- else:
466
- filter_openalex += "&per_page=100&mailto=emma_scharfmann@berkeley.edu"
467
-
468
-
469
- filter_openalex = filter_openalex.replace(" " , "%20")
470
-
471
- url = URL(base_URL_OA , filter_works, filter_openalex)
472
- data = get_data(url)
473
- count = data["meta"]["count"]
474
-
475
-
476
-
477
- if display == True:
478
- print( data["meta"]["count"] , [elem[i] for i in range(1,len(elem))] )
479
- print(url)
480
-
481
- for i in range(len(data["results"])):
482
- dic[ data["results"][i]["id"]] = {}
483
- dic[ data["results"][i]["id"]]["title"] = data["results"][i]["title"]
484
- dic[ data["results"][i]["id"]]["abstract"] = reconstruction_abstract(data["results"][i]["abstract_inverted_index"])
485
- dic[ data["results"][i]["id"]]["concepts"] = data["results"][i]["concepts"]
486
- dic[ data["results"][i]["id"]]["date"] = data["results"][i]["publication_date"]
487
- dic[ data["results"][i]["id"]]["authorships"] = data["results"][i]["authorships"]
488
- dic[ data["results"][i]["id"]]["cited_by_count"] = data["results"][i]["cited_by_count"]
489
-
490
- if len(data["results"][i]["authorships"]) > 0:
491
- if data["results"][i]["authorships"][0]["institutions"] != []:
492
- dic[ data["results"][i]["id"]]["countries"] = data["results"][i]["authorships"][0]["institutions"][0]["country_code"]
493
- dic[ data["results"][i]["id"]]["institutions"] = data["results"][i]["authorships"][0]["institutions"][0]["display_name"]
494
- else:
495
- dic[ data["results"][i]["id"]]["countries"] = ""
496
- dic[ data["results"][i]["id"]]["institutions"] = ""
497
- dic[ data["results"][i]["id"]]["authors"] = data["results"][i]["authorships"][0]["author"]["display_name"]
498
-
499
- for j in range(1 , len(data["results"][i]["authorships"])):
500
- if data["results"][i]["authorships"][j]["institutions"] != []:
501
- dic[ data["results"][i]["id"]]["institutions"] += ", " + data["results"][i]["authorships"][j]["institutions"][0]["display_name"]
502
- dic[ data["results"][i]["id"]]["countries"] = data["results"][i]["authorships"][j]["institutions"][0]["country_code"]
503
- dic[ data["results"][i]["id"]]["authors"] += ", " + data["results"][i]["authorships"][j]["author"]["display_name"]
504
-
505
- if display == True:
506
- print(" ")
507
-
508
- return dic
509
-
510
-
511
- ## Ranking Papers
512
-
513
- def ranking_papers(number_technology, dic_details , display , size , carbon_related , search_words ):
514
- """Returns a dictionary of data related to the papers the user chooses
515
-
516
- This is done through generating URLs to connect with OpenAlex API and parsing through the json file
517
-
518
- Parameters
519
- ----------
520
- number_technology : int, the index of the technology with respect to the 500+ IEA technologies
521
- dic_details : str, dictionary where key is index of technology with respect to 500+ IEA technolgies and values are the details related to the technologies
522
-
523
- dic: bool, a setting to select papers related to carbon capture
524
- list_categories: str, an array of keywords selected based off technology/ user input
525
- display: bool, chooses to display information or not
526
- size: str, an array of keywords selected based off technology/ user input
527
-
528
- """
529
- model = model_nlp()
530
- dic = related_papers(number_technology , carbon_related , display , search_words )
531
-
532
-
533
- dic_scores_papers = {}
534
-
535
-
536
-
537
- if display == True:
538
- print("Technology " + str(number_technology))
539
- print("Key words: " , list_categories[number_technology][1])
540
-
541
- if number_technology in dic_details:
542
- reference_text = dic_details[number_technology]
543
-
544
- if display== True:
545
- print("Technology details: " , reference_text)
546
- print(" ")
547
- encoded_text = model.encode(reference_text, convert_to_tensor=False).tolist()
548
-
549
-
550
- if len(dic) == 0:
551
- return "No paper found, select other key words"
552
-
553
-
554
- for ids in list(dic.keys()):
555
-
556
- dic_scores_papers[ids] = {}
557
-
558
- if dic[ids]["title"] != None:
559
- encoded_title = model.encode(dic[ids]["title"], convert_to_tensor=False).tolist()
560
- score_title = cosine_similarity2(encoded_title, encoded_text)
561
- else:
562
- score_title = None
563
-
564
-
565
-
566
- if dic[ids]["abstract"] != None:
567
- encoded_abstract = model.encode(dic[ids]["abstract"], convert_to_tensor=False).tolist()
568
- score_abstract = cosine_similarity2(encoded_abstract, encoded_text)
569
- else:
570
- score_abstract = None
571
-
572
-
573
- #concepts = ""
574
- #for elem in dic[ids]["concepts"]:
575
- # concepts += elem["display_name"] + " "
576
- #encoded_concepts = model.encode(concepts, convert_to_tensor=False).tolist()
577
- #score_concepts = cosine_similarity2(encoded_concepts, encoded_text)
578
-
579
- dic_scores_papers[ids]["title comparison"] = score_title
580
- dic_scores_papers[ids]["abstract comparison"] = score_abstract
581
- #dic_scores_papers[ids]["concepts comparison"] = score_concepts
582
-
583
- dic_scores_papers[ids]["title"] = dic[ids]["title"]
584
- dic_scores_papers[ids]["citations"] = dic[ids]["cited_by_count"]
585
-
586
-
587
- dic_scores_papers[ids]["date"] = dic[ids]["date"][:4]
588
- if "institutions" in dic[ids]:
589
- dic_scores_papers[ids]["institutions"] = dic[ids]["institutions"]
590
- # dic_scores_papers[ids]["countries"] = dic[ids]["countries"]
591
-
592
- else:
593
- dic_scores_papers[ids]["institutions"] = None
594
- # dic_scores_papers[ids]["countries"] = None
595
-
596
- if "authors" in dic[ids] and dic[ids]["authors"] != None:
597
- dic_scores_papers[ids]["number of co-authors"] = len(dic[ids]["authors"].split(","))
598
- dic_scores_papers[ids]["authors"] = dic[ids]["authors"]
599
- else:
600
- dic_scores_papers[ids]["number of co-authors"] = None
601
- dic_scores_papers[ids]["authors"] = None
602
-
603
-
604
- return dic , dic_scores_papers
605
-
606
-
607
-
608
-
609
-
610
- def get_ranking_related_papers( technologies , number_technology , carbon_related , size , research_words):
611
- name_file = "iea"
612
- dic_details = details(name_file , False)
613
- dic , dic_scores_papers = ranking_papers(number_technology, dic_details , False , size , carbon_related , research_words )
614
-
615
- if dic_scores_papers == {}:
616
- return "No paper found"
617
-
618
- elif type(dic_scores_papers) == str:
619
- return dic_scores_papers
620
-
621
- else:
622
- return pd.DataFrame(dic_scores_papers).T.sort_values(by="abstract comparison" , ascending = False).head(size)
623
-
624
-
625
- ## Extract quantitative data
626
-
627
- def extract_sentences_with_numbers(text , text_name):
628
- if text != None:
629
- text = text.replace("CO 2" , "CO2")
630
- text = text.replace("CO 3" , "CO3")
631
- text = text.replace("CO(2)" , "CO2")
632
- text = text.replace("CO(3)" , "CO3")
633
-
634
- print(text_name + ": " , text)
635
- print(" ")
636
-
637
-
638
-
639
- list_text = list(text)
640
- for i in range(1,len(list_text)-1):
641
- if list_text[i] == " " and list_text[i-1] == "." and list_text[i+1].isupper():
642
- list_text[i] = "~"
643
-
644
- text = "".join(list_text)
645
- text = text.split("~")
646
- for sentence in text:
647
-
648
- if any(char.isdigit() for char in sentence):
649
-
650
-
651
-
652
- if "CO2" in sentence:
653
- print("\x1b[31mCARBON RELATED:\x1b[0m", sentence)
654
- print(" ")
655
-
656
-
657
-
658
- if "GJ" in sentence or "MJ" in sentence:
659
- print("\x1b[31mENERGY:\x1b[0m" , sentence)
660
- print(" ")
661
-
662
-
663
-
664
- ##price
665
- if "€" in sentence or "$" in sentence or "EUR" in sentence or "dollars" in sentence.lower():
666
- print("\x1b[31mPRICE:\x1b[0m" , sentence)
667
- print(" ")
668
-
669
-
670
-
671
- ##dates
672
- digits = []
673
- for word in sentence.replace("," , "").replace("%" , "").replace("." , " ").split():
674
- if word.isdigit() and 1850 < int(word) < 2200 :
675
- digits.append(word)
676
- if digits != []:
677
- print("\x1b[31mDATE:\x1b[0m" , sentence)
678
- print(" ")
679
-
680
-
681
-
682
- ##CO quantity
683
- if "Mt" in sentence or "tC" in sentence or "t-C" in sentence:
684
- print("\x1b[31mCARBON QUANTITY:\x1b[0m" , sentence)
685
- print(" ")
686
-
687
- print(" ")
688
-
689
-
690
- def extract_quantitative_data_technology(technologies, number_technology):
691
-
692
- model = model_nlp()
693
- count = 0
694
-
695
- name_file = "iea"
696
- dic_target = deployment_target(name_file , False)
697
- dic_cost = cost_reduction_target(name_file , False)
698
- dic_details = details(name_file , False)
699
- cost_target_text = 'No information'
700
- cost_text = 'No information'
701
-
702
- if number_technology in dic_details:
703
- reference_text = dic_details[number_technology]
704
-
705
- #print("\033[96mFROM IEA website: ")
706
- #print("\033[92mTechnology details: \x1b[0m" , reference_text)
707
- #print(" ")
708
- #encoded_text = model.encode(reference_text, convert_to_tensor=False).tolist()
709
-
710
- if number_technology in dic_target:
711
- cost_target_text = dic_target[number_technology]
712
- #print("\033[96mFROM IEA website: ")
713
- #sentences = extract_sentences_with_numbers(cost_target_text , "\033[92mDeployment target and Announced development target\x1b[0m")
714
-
715
- if number_technology in dic_cost:
716
- cost_text = dic_cost[number_technology]
717
- #print("\033[96mFROM IEA website: ")
718
- #sentences = extract_sentences_with_numbers(cost_text , "\033[92mAnnounced cost reduction targets\x1b[0m")
719
-
720
- return reference_text, cost_target_text, cost_text
721
-
722
-
723
- def extract_quantitative_data_paper(work_id):
724
-
725
- url = "https://api.openalex.org/works/" + str(work_id)
726
- url_google = "https://explore.openalex.org/works/" + str(work_id)
727
-
728
- data = get_data(url)
729
- date = data["publication_date"]
730
- title = data["title"]
731
- abstract = reconstruction_abstract(data["abstract_inverted_index"])
732
- concepts = ", ".join( [elem["display_name"] for elem in data["concepts"]] )
733
- authors = ", ".join( [elem["author"]["display_name"] for elem in data["authorships"]] )
734
- institutions = ", ".join( set([elem["institutions"][0]["display_name"] for elem in data["authorships"] if len(elem["institutions"]) > 0]) )
735
- return url_google , title , abstract , date , authors , institutions
736
-
737
-
738
-
739
-
740
- ## Get papers related to cited projects
741
-
742
- def related_projects(technologies, number_technology , carbon_related , size):
743
-
744
- spacy_nlp = spacy_func()
745
- model = model_nlp()
746
-
747
- name_file = "iea"
748
- dic_details = details(name_file , False)
749
- dic_key_initiatives = key_initiatives(name_file , False )
750
-
751
-
752
- dic2 = {}
753
-
754
- reference_text = dic_details[number_technology]
755
- print("\033[92mTechnology details: \x1b[0m" , reference_text)
756
- print(" ")
757
- encoded_text = model.encode(reference_text, convert_to_tensor=False).tolist()
758
- # reference_text key_initiative location_entities
759
- if number_technology in dic_key_initiatives:
760
- key_initiative = dic_key_initiatives[number_technology]
761
- print("\033[92mTechnology key initiatives: \x1b[0m" , key_initiative)
762
-
763
- location_entities = set()
764
- doc = spacy_nlp(key_initiative.strip())
765
- for j in doc.ents:
766
- entry = str(j.lemma_).lower()
767
- key_initiative = key_initiative.replace(str(j).lower(), "")
768
- if j.label_ in ["ORG"]:
769
- location_entities.add(j)
770
- print(" ")
771
- print("\033[92mExtracted projects and organizations names: \x1b[0m", location_entities)
772
-
773
-
774
- base_URL_OA = f'https://api.openalex.org/'
775
- filter_works = f'works?'
776
- for element in location_entities:
777
-
778
- filter_openalex = f"search="
779
- filter_openalex += str(element)
780
- if carbon_related == True:
781
- filter_openalex += "&filter=concepts.id:https://openalex.org/C2780021121&per_page=50&mailto=emma_scharfmann@berkeley.edu"
782
- else:
783
- filter_openalex += "&per_page=50&mailto=emma_scharfmann@berkeley.edu"
784
-
785
- filter_openalex = filter_openalex.replace(" " , "%20")
786
-
787
- url = URL(base_URL_OA , filter_works, filter_openalex)
788
-
789
- data = get_data(url)
790
- count = len(data["results"])
791
- if count < 40:
792
-
793
- for k in range(count):
794
-
795
- if data["results"][k]["abstract_inverted_index"] != None:
796
- encoded_abstract = model.encode(reconstruction_abstract(data["results"][k]["abstract_inverted_index"]) , convert_to_tensor=False).tolist()
797
- abstract_similarity = cosine_similarity2(encoded_abstract, encoded_text)
798
- else:
799
- abstract_similarity = None
800
-
801
- if data["results"][k]["title"] != None:
802
- encoded_title = model.encode(data["results"][k]["title"] , convert_to_tensor=False).tolist()
803
- title_similarity = cosine_similarity2(encoded_title, encoded_text)
804
- else:
805
- title_similarity = None
806
-
807
- work_id = data["results"][k]["id"]
808
- dic2[work_id] = {}
809
- dic2[work_id]["project/institution name"] = str(element)
810
- dic2[work_id]["title comparison"] = title_similarity
811
- dic2[work_id]["abstract comparison"] = abstract_similarity
812
- dic2[work_id]["title"] = data["results"][k]["title"]
813
- #dic2[work_id]["abstract"] = reconstruction_abstract(data["results"][k]["abstract_inverted_index"])
814
- dic2[work_id]["date"] = data["results"][k]["publication_date"]
815
-
816
- else:
817
- list_categories = key_words( name_file, False)
818
- key_word = list_categories[number_technology]
819
- elem = key_word[1]
820
-
821
- string = ""
822
- for j in range(1,len(elem)):
823
- if elem[j] == "CCUS":
824
- elem[j] = "Carbon capture and storage"
825
- string += elem[j] + " "
826
-
827
-
828
- string += str(element)
829
- filter_openalex = f"search=" + string
830
-
831
- if carbon_related == True:
832
- filter_openalex += "&filter=concepts.id:https://openalex.org/C2780021121&per_page=50&mailto=emma_scharfmann@berkeley.edu"
833
- else:
834
- filter_openalex += "&per_page=50&mailto=emma_scharfmann@berkeley.edu"
835
- filter_openalex = filter_openalex.replace(" " , "%20")
836
- url = URL(base_URL_OA , filter_works, filter_openalex)
837
- data = get_data(url)
838
- count = len(data["results"])
839
- for k in range(count):
840
-
841
- if data["results"][k]["abstract_inverted_index"] != None:
842
- encoded_abstract = model.encode(reconstruction_abstract(data["results"][k]["abstract_inverted_index"]) , convert_to_tensor=False).tolist()
843
- abstract_similarity = cosine_similarity2(encoded_abstract, encoded_text)
844
- else:
845
- abstract_similarity = None
846
-
847
- if data["results"][k]["title"] != None:
848
- encoded_title = model.encode(data["results"][k]["title"] , convert_to_tensor=False).tolist()
849
- title_similarity = cosine_similarity2(encoded_title, encoded_text)
850
- else:
851
- title_similarity = None
852
-
853
- work_id = data["results"][k]["id"]
854
- dic2[work_id] = {}
855
- dic2[work_id]["project/institution name"] = str(element)
856
- dic2[work_id]["title comparison"] = title_similarity
857
- dic2[work_id]["abstract comparison"] = abstract_similarity
858
- dic2[work_id]["title"] = data["results"][k]["title"]
859
- #dic2[work_id]["abstract"] = reconstruction_abstract(data["results"][k]["abstract_inverted_index"])
860
- dic2[work_id]["date"] = data["results"][k]["publication_date"]
861
-
862
-
863
-
864
-
865
- if dic2 != {}:
866
- return reference_text,key_initiative,location_entities,pd.DataFrame(dic2).T.sort_values(by="abstract comparison" , ascending = False).head(size)
867
- else:
868
- return reference_text,key_initiative,location_entities, "No paper found"
869
-
870
-
871
- ## Mapping the authors
872
-
873
- #merge the nobiliary particles with the last name
874
- #ln_suff file can be modified if more or less nobiliary particles want to be suppressed
875
-
876
- ln_suff = ['oster',
877
- 'nordre',
878
- 'vaster',
879
- 'aust',
880
- 'vesle',
881
- 'da',
882
- 'van t',
883
- 'af',
884
- 'al',
885
- 'setya',
886
- 'zu',
887
- 'la',
888
- 'na',
889
- 'mic',
890
- 'ofver',
891
- 'el',
892
- 'vetle',
893
- 'van het',
894
- 'dos',
895
- 'ui',
896
- 'vest',
897
- 'ab',
898
- 'vste',
899
- 'nord',
900
- 'van der',
901
- 'bin',
902
- 'ibn',
903
- 'war',
904
- 'fitz',
905
- 'alam',
906
- 'di',
907
- 'erch',
908
- 'fetch',
909
- 'nga',
910
- 'ka',
911
- 'soder',
912
- 'lille',
913
- 'upp',
914
- 'ua',
915
- 'te',
916
- 'ni',
917
- 'bint',
918
- 'von und zu',
919
- 'vast',
920
- 'vestre',
921
- 'over',
922
- 'syd',
923
- 'mac',
924
- 'nin',
925
- 'nic',
926
- 'putri',
927
- 'bet',
928
- 'verch',
929
- 'norr',
930
- 'bath',
931
- 'della',
932
- 'van',
933
- 'ben',
934
- 'du',
935
- 'stor',
936
- 'das',
937
- 'neder',
938
- 'abu',
939
- 'degli',
940
- 'vre',
941
- 'ait',
942
- 'ny',
943
- 'opp',
944
- 'pour',
945
- 'kil',
946
- 'der',
947
- 'oz',
948
- 'von',
949
- 'at',
950
- 'nedre',
951
- 'van den',
952
- 'setia',
953
- 'ap',
954
- 'gil',
955
- 'myljom',
956
- 'van de',
957
- 'stre',
958
- 'dele',
959
- 'mck',
960
- 'de',
961
- 'mellom',
962
- 'mhic',
963
- 'binti',
964
- 'ath',
965
- 'binte',
966
- 'snder',
967
- 'sre',
968
- 'ned',
969
- 'ter',
970
- 'bar',
971
- 'le',
972
- 'mala',
973
- 'ost',
974
- 'syndre',
975
- 'sr',
976
- 'bat',
977
- 'sndre',
978
- 'austre',
979
- 'putra',
980
- 'putera',
981
- 'av',
982
- 'lu',
983
- 'vetch',
984
- 'ver',
985
- 'puteri',
986
- 'mc',
987
- 'tre',
988
- 'st']
989
-
990
- #suppress all the unwanted suffixes from a string.
991
- #name_del file can be modified if more or less suffixes want to be suppressed
992
-
993
- name_del = ['2nd', '3rd', 'Jr', 'Jr.', 'Junior', 'Sr', 'Sr.', 'Senior']
994
-
995
-
996
- def name_delete(string):
997
- for elmt in name_del:
998
- if f" {elmt}" in string:
999
- return string.replace(f" {elmt}","")
1000
- return string
1001
-
1002
- def ln_suff_merge(string):
1003
- for suff in ln_suff:
1004
- if f" {suff} " in string or string.startswith(f"{suff} "):
1005
- return string.replace(f"{suff} ",suff.replace(" ",""))
1006
- return string
1007
-
1008
- #normalize a string dat that represents often a name.
1009
-
1010
- def normalize(data):
1011
- normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore')
1012
- val = normal.decode("utf-8")
1013
- # delete unwanted elmt
1014
- val = name_delete(val)
1015
- # lower full name in upper
1016
- val = re.sub(r"[A-Z]{3,}", lambda x: x.group().lower(), val)
1017
- # add space in front of upper case
1018
- val = re.sub(r"(\w)([A-Z])", r"\1 \2", val)
1019
- # Lower case
1020
- val = val.lower()
1021
- # remove special characters
1022
- val = re.sub('[^A-Za-z0-9 ]+', ' ', val)
1023
- # remove multiple spaces
1024
- val = re.sub(' +', ' ', val)
1025
- # remove trailing spaces
1026
- val = val.strip()
1027
- # suffix merge
1028
- val = ln_suff_merge(val)
1029
-
1030
- return val
1031
-
1032
-
1033
- def main_authors(technologies,number_technology , carbon_related , size , research_words):
1034
-
1035
- name_file = "iea"
1036
- list_categories = key_words( name_file, False)
1037
- dic_details = details(name_file , False)
1038
- dic_papers , dic_papers_ranked = ranking_papers(number_technology, dic_details , False , size , carbon_related , research_words )
1039
-
1040
- dic_papers_co_authors = {}
1041
-
1042
-
1043
-
1044
- for paper in list(dic_papers_ranked.keys())[:size]:
1045
-
1046
- for k in range(len(dic_papers[paper]["authorships"])):
1047
- coauthor_id = dic_papers[paper]["authorships"][k]["author"]["id"]
1048
-
1049
-
1050
- author_name = dic_papers[paper]["authorships"][k]["author"]["display_name"]
1051
- author_name_norm = normalize(dic_papers[paper]["authorships"][k]["author"]["display_name"]).split()
1052
-
1053
- if len(author_name_norm ) > 0:
1054
- author_name_norm = author_name_norm[0] + " " + author_name_norm[-1]
1055
-
1056
- if author_name_norm not in dic_papers_co_authors:
1057
- dic_papers_co_authors[author_name_norm] = {}
1058
- dic_papers_co_authors[author_name_norm]["Author's name(s)"] = author_name
1059
- if coauthor_id != None :
1060
- dic_papers_co_authors[author_name_norm]["Author's id(s)"] = coauthor_id[21:]
1061
- else:
1062
- dic_papers_co_authors[author_name_norm]["Author's id(s)"] = ""
1063
- dic_papers_co_authors[author_name_norm]["Number of occurence within the " + str(size) + " most related papers"] = 1
1064
- dic_papers_co_authors[author_name_norm]["Number of related citations"] = dic_papers[paper]["cited_by_count"]
1065
- else:
1066
- dic_papers_co_authors[author_name_norm]["Number of occurence within the " + str(size) + " most related papers"] += 1
1067
- if author_name not in dic_papers_co_authors[author_name_norm]["Author's name(s)"]:
1068
- dic_papers_co_authors[author_name_norm]["Author's name(s)"] += ", " + author_name[0]
1069
- if coauthor_id != None and coauthor_id[21:] not in dic_papers_co_authors[author_name_norm]["Author's id(s)"]:
1070
- dic_papers_co_authors[author_name_norm]["Author's id(s)"] += ", " + coauthor_id[21:]
1071
- dic_papers_co_authors[author_name_norm]["Number of related citations"] += dic_papers[paper]["cited_by_count"]
1072
-
1073
-
1074
-
1075
- if dic_papers_co_authors != {}:
1076
- dic_papers_co_authors = {k: v for k, v in sorted(dic_papers_co_authors.items(), key=lambda item: item[1]["Number of occurence within the " + str(size) + " most related papers"] , reverse = True)}
1077
-
1078
- for author_name_norm in list(dic_papers_co_authors.keys())[:size]:
1079
- list_ids = dic_papers_co_authors[author_name_norm]["Author's id(s)"].split(", ")
1080
- work_count = 0
1081
- cited_by_count = 0
1082
- institutions = ''
1083
- for elem in list_ids:
1084
- if len(elem) > 3:
1085
- url = 'https://api.openalex.org/authors?filter=openalex_id:' + elem + "&page=1&per_page=200&mailto=emma_scharfmann@berkeley.edu"
1086
- try:
1087
- data = get_data(url)["results"][0]
1088
- except:
1089
- continue
1090
-
1091
- work_count += data["works_count"]
1092
- cited_by_count += data["cited_by_count"]
1093
- if data["last_known_institution"] != None and len(data["last_known_institution"]) > 0 and data["last_known_institution"]["display_name"] != None:
1094
- institutions += data["last_known_institution"]["display_name"]
1095
-
1096
- dic_papers_co_authors[author_name_norm]["Last Known Institution"] = institutions
1097
- dic_papers_co_authors[author_name_norm]["Number of works"] = work_count
1098
- dic_papers_co_authors[author_name_norm]["Number of citations"] = cited_by_count
1099
-
1100
-
1101
- return pd.DataFrame(dic_papers_co_authors, index = [ "Author's name(s)" , "Number of occurence within the " + str(size) + " most related papers" , "Last Known Institution" , "Number of works" , "Number of citations" , "Number of related citations", "Author's id(s)"]).T
1102
-
1103
- else:
1104
- return ("Select another category")
1105
-
1106
-
1107
- def map_authors(technologies, number_technology , carbon_related , size , research_words):
1108
-
1109
- name_file = "iea"
1110
- dic_details = details(name_file , False)
1111
- dic_papers , dic_papers_ranked = ranking_papers(number_technology, dic_details , False , size , carbon_related , research_words )
1112
-
1113
- dic_papers_co_authors = {}
1114
- count = 0
1115
-
1116
- for paper in list(dic_papers_ranked.keys())[:size]:
1117
-
1118
-
1119
- for k in range(len(dic_papers[paper]["authorships"])):
1120
-
1121
- if dic_papers[paper]["authorships"][k]["institutions"] != [] and "id" in dic_papers[paper]["authorships"][k]["institutions"][0] and dic_papers[paper]["authorships"][k]["institutions"][0]["id"] != None:
1122
- institution_id = dic_papers[paper]["authorships"][k]["institutions"][0]["id"][21:]
1123
- if institution_id in dic_institutions:
1124
- data = dic_institutions[institution_id]
1125
-
1126
- dic_papers_co_authors[count] = {}
1127
- dic_papers_co_authors[count]["longitude"] = data["longitude"]
1128
- dic_papers_co_authors[count]["latitude"] = data["latitude"]
1129
- dic_papers_co_authors[count]["abstract comparison"] = dic_papers_ranked[paper]["abstract comparison"]
1130
- dic_papers_co_authors[count]["author"] = dic_papers[paper]["authorships"][k]["author"]["display_name"]
1131
- dic_papers_co_authors[count]["institution"] = dic_papers[paper]["authorships"][k]["institutions"][0]["display_name"]
1132
- dic_papers_co_authors[count]["date"] = dic_papers[paper]["date"]
1133
-
1134
- count += 1
1135
-
1136
-
1137
- if dic_papers_co_authors == {}:
1138
- return "No papers"
1139
-
1140
-
1141
-
1142
- map_df = pd.DataFrame(dic_papers_co_authors).T
1143
- map_df["longitude"]=map_df['longitude'].astype(float)
1144
- map_df['latitude']=map_df['latitude'].astype(float)
1145
- map_df = map_df[map_df["latitude"].notnull()]
1146
-
1147
- return map_df
1148
-
1149
-
1150
- ################################### Extracted texts ###############################################################
1151
-
1152
- #@title Which patents are related to the technology?
1153
- def finder():
1154
- name_file = 'iea'
1155
- res = technology("iea", False )
1156
- list_categories_tech = []
1157
- list_categories = key_words("iea" , False)
1158
- list_technologies = [ ( ", ".join(list_categories[i][1]) , i ) for i in range(len(list_categories)) ]
1159
- dic_technologies = {}
1160
- for i in range(len(res)):
1161
- names = res[i][1]
1162
- if ", ".join(names) not in list_categories_tech:
1163
- list_categories_tech.append(", ".join(names))
1164
- dic_technologies[", ".join(names)] = []
1165
- dic_technologies[", ".join(names)].append( (", ".join(list_categories[i][1]) , i ))
1166
-
1167
-
1168
- list_climate = [ ("Any related papers" , False ) , ("Climate related papers" , True)]
1169
-
1170
- dic_categories = {}
1171
- for elem in list_technologies:
1172
- list_words = elem[0].split(",")[-3:]
1173
- for i in range(len(list_words)):
1174
- if "CCUS" in list_words[i]:
1175
- list_words[i] = list_words[i].replace("CCUS" , "carbon capture storage")
1176
- dic_categories[elem[1]] = [ ", ".join([ " ".join(words.split()[:3]) for words in list_words ] ) , ", ".join([ " ".join(words.split()[:3]) for words in list_words[:-1] ]) , ", ".join([ " ".join(words.split()[:3]) for words in list_words[1:] ] ) ]
1177
-
1178
- return dic_technologies, dic_categories, list_categories_tech, list_technologies
1179
-
1180
- # technologies_widget = widgets.Dropdown(options=list_categories_tech,
1181
- # description="Choose the category:" ,
1182
- # style = {'description_width':'initial' } ,
1183
- # layout=Layout(width='500px'));
1184
-
1185
- # category_widget = widgets.RadioButtons( values = 1,
1186
- # description='Patents where the abstract contains:' ,
1187
- # style = {'description_width':'initial' } ,
1188
- # layout=Layout(width='1000px'));
1189
-
1190
- # number_technology_widget = widgets.Dropdown(options=list_technologies,
1191
- # description="Choose the technology:" ,
1192
- # style = {'description_width':'initial' } ,
1193
- # layout=Layout(width='500px'));
1194
-
1195
- # def update_category(*args):
1196
- # category_widget.options = dic_categories[number_technology_widget.value]
1197
-
1198
- # def update_technology(*args):
1199
- # number_technology_widget.options = dic_technologies[technologies_widget.value]
1200
-
1201
-
1202
- # number_technology_widget.observe(update_category)
1203
- # technologies_widget.observe(update_technology)
1204
-
1205
- # print("Which patents are related to the technology?")
1206
- # interact_manual(get_ranking_patents,
1207
- # technologies=technologies_widget,
1208
- # number_technology= number_technology_widget ,
1209
- # carbon_related=widgets.Dropdown(options=list_climate,
1210
- # description="Select the type of patents:" ,
1211
- # style = {'description_width':'initial' } ,
1212
- # layout=Layout(width='500px') ) ,
1213
- # size = widgets.IntSlider(min=3,
1214
- # max=100,
1215
- # value=10,
1216
- # step=1,
1217
- # description="Select the number of patents:" ,
1218
- # style = {'description_width':'initial' } ,
1219
- # layout=Layout(width='500px')),
1220
- # category = category_widget);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/paper_functions_own_details.py DELETED
@@ -1,542 +0,0 @@
1
- ##packages code
2
- from shapely.geometry import Point
3
- import pandas as pd
4
- from tqdm import tqdm
5
- import streamlit as st
6
- import numpy as np
7
- import json, requests
8
- import pandas as pd
9
- #from pandas.io.json import json_normalize
10
-
11
- import matplotlib.pyplot as plt
12
- import seaborn as sns
13
- from math import radians, cos, sin, asin, sqrt
14
-
15
- import spacy
16
- #!python -m spacy download en_core_web_lg
17
-
18
-
19
- from sentence_transformers import SentenceTransformer, util
20
-
21
- @st.cache_resource
22
- def model_nlp():
23
- model = SentenceTransformer('all-MiniLM-L6-v2')
24
- return model
25
-
26
- import unicodedata
27
-
28
- from metaphone import doublemetaphone
29
- from fuzzywuzzy import fuzz
30
- from difflib import SequenceMatcher
31
- import re
32
-
33
- import geopandas as gpd
34
- from geopandas import GeoDataFrame
35
-
36
-
37
- @st.cache_data # 👈 Add the caching decorator
38
- def load_data():
39
- url = "Synapse_project/Climate_site/python_scripts/institutions.tsv"
40
- dic = pd.read_csv(url, delimiter = "\t" , index_col = 1).to_dict('index')
41
- return dic
42
-
43
- dic_institutions = load_data()
44
-
45
-
46
- #################### General Functions #############################
47
-
48
- def URL(base_URL , entity_type , filters):
49
- url = base_URL + entity_type + filters
50
- return url
51
-
52
-
53
- def get_data(url):
54
- url = requests.get(url)
55
- text = url.text
56
- import json
57
- data = json.loads(text)
58
- return data
59
-
60
- ## encoding the abstract
61
-
62
-
63
- def reconstruction_abstract(abstract_inverted_index):
64
- # return the abstract is the abstract exists in the database, else, return None
65
-
66
- if abstract_inverted_index != None:
67
-
68
- list_values = list(abstract_inverted_index.values())
69
- list_keys = list(abstract_inverted_index.keys())
70
- #from the words in the abstract (keys of abstract_inverted_index) and their position in the text (values of abstract_inverted_index), reconstruct the abstract
71
-
72
- size_abstract = max([ max(elem) for elem in abstract_inverted_index.values() ] )
73
-
74
- abstract = [""]*(size_abstract +1)
75
-
76
- for i in range(len(list_values)):
77
- for pos in list_values[i]:
78
- abstract[pos] = list_keys[i]
79
-
80
- return " ".join(list(abstract))
81
-
82
- else:
83
- return None
84
-
85
-
86
- ## calculate efficiently the dot product between two vectors
87
-
88
- def norm(vector):
89
- return np.sqrt(sum(x * x for x in vector))
90
-
91
- def cosine_similarity2(vec_a, vec_b):
92
- norm_a = norm(vec_a)
93
- norm_b = norm(vec_b)
94
- dot = sum(a * b for a, b in zip(vec_a, vec_b))
95
- return dot / (norm_a * norm_b)
96
-
97
-
98
-
99
-
100
- #################### Paper Functions #############################
101
-
102
- def related_papers_own_research( research_key_words , display ):
103
-
104
- dic = {}
105
-
106
- max_count = 0
107
- base_URL_OA = f'https://api.openalex.org/'
108
- filter_works = f'works?'
109
-
110
-
111
-
112
- filter_openalex = f"search=" + research_key_words + "&per_page=200&mailto=emma_scharfmann@berkeley.edu"
113
-
114
-
115
- filter_openalex = filter_openalex.replace(" " , "%20")
116
-
117
- url = URL(base_URL_OA , filter_works, filter_openalex)
118
- data = get_data(url)
119
- count = data["meta"]["count"]
120
-
121
-
122
-
123
- if display == True:
124
- print( data["meta"]["count"] , [elem[i] for i in range(1,len(elem))] )
125
- print(url)
126
-
127
- for i in range(len(data["results"])):
128
- dic[ data["results"][i]["id"]] = {}
129
- dic[ data["results"][i]["id"]]["title"] = data["results"][i]["title"]
130
- dic[ data["results"][i]["id"]]["abstract"] = reconstruction_abstract(data["results"][i]["abstract_inverted_index"])
131
- dic[ data["results"][i]["id"]]["concepts"] = data["results"][i]["concepts"]
132
- dic[ data["results"][i]["id"]]["date"] = data["results"][i]["publication_date"]
133
- dic[ data["results"][i]["id"]]["authorships"] = data["results"][i]["authorships"]
134
- dic[ data["results"][i]["id"]]["cited_by_count"] = data["results"][i]["cited_by_count"]
135
-
136
- if len(data["results"][i]["authorships"]) > 0:
137
- if data["results"][i]["authorships"][0]["institutions"] != []:
138
- dic[ data["results"][i]["id"]]["countries"] = data["results"][i]["authorships"][0]["institutions"][0]["country_code"]
139
- dic[ data["results"][i]["id"]]["institutions"] = data["results"][i]["authorships"][0]["institutions"][0]["display_name"]
140
- else:
141
- dic[ data["results"][i]["id"]]["countries"] = ""
142
- dic[ data["results"][i]["id"]]["institutions"] = ""
143
- dic[ data["results"][i]["id"]]["authors"] = data["results"][i]["authorships"][0]["author"]["display_name"]
144
-
145
- for j in range(1 , len(data["results"][i]["authorships"])):
146
- if data["results"][i]["authorships"][j]["institutions"] != []:
147
- dic[ data["results"][i]["id"]]["institutions"] += ", " + data["results"][i]["authorships"][j]["institutions"][0]["display_name"]
148
- dic[ data["results"][i]["id"]]["countries"] = data["results"][i]["authorships"][j]["institutions"][0]["country_code"]
149
- dic[ data["results"][i]["id"]]["authors"] += ", " + data["results"][i]["authorships"][j]["author"]["display_name"]
150
-
151
- if display == True:
152
- print(" ")
153
-
154
- return dic
155
-
156
-
157
-
158
-
159
- ## Ranking Papers
160
-
161
- def ranking_own_research(research_key_words, details , display):
162
-
163
- model = model_nlp()
164
-
165
- dic_scores_papers = {}
166
- dic = related_papers_own_research( research_key_words , False)
167
-
168
- reference_text = details
169
-
170
- if display== True:
171
- print("Technology details: " , reference_text)
172
- print(" ")
173
- encoded_text = model.encode(reference_text, convert_to_tensor=False , show_progress_bar = False).tolist()
174
-
175
-
176
-
177
- for ids in list(dic.keys()):
178
-
179
- dic_scores_papers[ids] = {}
180
-
181
- if dic[ids]["title"] != None:
182
- encoded_title = model.encode(dic[ids]["title"], convert_to_tensor=False , show_progress_bar = False).tolist()
183
- score_title = cosine_similarity2(encoded_title, encoded_text)
184
- else:
185
- score_title = None
186
-
187
-
188
-
189
- if dic[ids]["abstract"] != None:
190
- encoded_abstract = model.encode(dic[ids]["abstract"], convert_to_tensor=False , show_progress_bar = False).tolist()
191
- score_abstract = cosine_similarity2(encoded_abstract, encoded_text)
192
- else:
193
- score_abstract = None
194
-
195
-
196
- #concepts = ""
197
- #for elem in dic[ids]["concepts"]:
198
- # concepts += elem["display_name"] + " "
199
- #encoded_concepts = model.encode(concepts, convert_to_tensor=False).tolist()
200
- #score_concepts = cosine_similarity2(encoded_concepts, encoded_text)
201
-
202
- dic_scores_papers[ids]["title comparison"] = score_title
203
- dic_scores_papers[ids]["abstract comparison"] = score_abstract
204
- #dic_scores_papers[ids]["concepts comparision"] = score_concepts
205
-
206
- dic_scores_papers[ids]["title"] = dic[ids]["title"]
207
- dic_scores_papers[ids]["citations"] = dic[ids]["cited_by_count"]
208
-
209
-
210
- dic_scores_papers[ids]["date"] = dic[ids]["date"][:4]
211
- if "institutions" in dic[ids]:
212
- dic_scores_papers[ids]["institutions"] = dic[ids]["institutions"]
213
- # dic_scores_papers[ids]["countries"] = dic[ids]["countries"]
214
-
215
- else:
216
- dic_scores_papers[ids]["institutions"] = None
217
- # dic_scores_papers[ids]["countries"] = None
218
-
219
- if "authors" in dic[ids]:
220
- dic_scores_papers[ids]["number of co-authors"] = len(dic[ids]["authors"].split(","))
221
- dic_scores_papers[ids]["authors"] = dic[ids]["authors"]
222
-
223
- return dic , dic_scores_papers
224
-
225
-
226
-
227
-
228
-
229
-
230
-
231
- def get_ranking_own_research(research_key_words, details , display , size):
232
-
233
- dic , dic_scores_papers = ranking_own_research(research_key_words, details , display)
234
-
235
- if dic_scores_papers == {}:
236
- return "No paper found"
237
-
238
- elif type(dic_scores_papers) == str:
239
- return dic_scores_papers
240
-
241
- else:
242
- return pd.DataFrame(dic_scores_papers).T.sort_values(by="abstract comparison" , ascending = False).head(size)
243
-
244
-
245
-
246
-
247
-
248
-
249
-
250
- def extract_quantitative_data_paper(work_id):
251
-
252
- url = "https://api.openalex.org/works/" + str(work_id)
253
- url_google = "https://explore.openalex.org/works/" + str(work_id)
254
-
255
- data = get_data(url)
256
- date = data["publication_date"]
257
- title = data["title"]
258
- abstract = reconstruction_abstract(data["abstract_inverted_index"])
259
- concepts = ", ".join( [elem["display_name"] for elem in data["concepts"]] )
260
- authors = ", ".join( [elem["author"]["display_name"] for elem in data["authorships"]] )
261
- institutions = ", ".join( set([elem["institutions"][0]["display_name"] for elem in data["authorships"] if len(elem["institutions"]) > 0]) )
262
- return url_google , title , abstract , date , authors , institutions
263
-
264
-
265
-
266
-
267
-
268
- ## Mapping the authors
269
-
270
- #merge the nobiliary particles with the last name
271
- #ln_suff file can be modified if more or less nobiliary particles want to be suppressed
272
-
273
- ln_suff = ['oster',
274
- 'nordre',
275
- 'vaster',
276
- 'aust',
277
- 'vesle',
278
- 'da',
279
- 'van t',
280
- 'af',
281
- 'al',
282
- 'setya',
283
- 'zu',
284
- 'la',
285
- 'na',
286
- 'mic',
287
- 'ofver',
288
- 'el',
289
- 'vetle',
290
- 'van het',
291
- 'dos',
292
- 'ui',
293
- 'vest',
294
- 'ab',
295
- 'vste',
296
- 'nord',
297
- 'van der',
298
- 'bin',
299
- 'ibn',
300
- 'war',
301
- 'fitz',
302
- 'alam',
303
- 'di',
304
- 'erch',
305
- 'fetch',
306
- 'nga',
307
- 'ka',
308
- 'soder',
309
- 'lille',
310
- 'upp',
311
- 'ua',
312
- 'te',
313
- 'ni',
314
- 'bint',
315
- 'von und zu',
316
- 'vast',
317
- 'vestre',
318
- 'over',
319
- 'syd',
320
- 'mac',
321
- 'nin',
322
- 'nic',
323
- 'putri',
324
- 'bet',
325
- 'verch',
326
- 'norr',
327
- 'bath',
328
- 'della',
329
- 'van',
330
- 'ben',
331
- 'du',
332
- 'stor',
333
- 'das',
334
- 'neder',
335
- 'abu',
336
- 'degli',
337
- 'vre',
338
- 'ait',
339
- 'ny',
340
- 'opp',
341
- 'pour',
342
- 'kil',
343
- 'der',
344
- 'oz',
345
- 'von',
346
- 'at',
347
- 'nedre',
348
- 'van den',
349
- 'setia',
350
- 'ap',
351
- 'gil',
352
- 'myljom',
353
- 'van de',
354
- 'stre',
355
- 'dele',
356
- 'mck',
357
- 'de',
358
- 'mellom',
359
- 'mhic',
360
- 'binti',
361
- 'ath',
362
- 'binte',
363
- 'snder',
364
- 'sre',
365
- 'ned',
366
- 'ter',
367
- 'bar',
368
- 'le',
369
- 'mala',
370
- 'ost',
371
- 'syndre',
372
- 'sr',
373
- 'bat',
374
- 'sndre',
375
- 'austre',
376
- 'putra',
377
- 'putera',
378
- 'av',
379
- 'lu',
380
- 'vetch',
381
- 'ver',
382
- 'puteri',
383
- 'mc',
384
- 'tre',
385
- 'st']
386
-
387
- #suppress all the unwanted suffixes from a string.
388
- #name_del file can be modified if more or less suffixes want to be suppressed
389
-
390
- name_del = ['2nd', '3rd', 'Jr', 'Jr.', 'Junior', 'Sr', 'Sr.', 'Senior']
391
-
392
-
393
- def name_delete(string):
394
- for elmt in name_del:
395
- if f" {elmt}" in string:
396
- return string.replace(f" {elmt}","")
397
- return string
398
-
399
- def ln_suff_merge(string):
400
- for suff in ln_suff:
401
- if f" {suff} " in string or string.startswith(f"{suff} "):
402
- return string.replace(f"{suff} ",suff.replace(" ",""))
403
- return string
404
-
405
- #normalize a string dat that represents often a name.
406
-
407
- def normalize(data):
408
- normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore')
409
- val = normal.decode("utf-8")
410
- # delete unwanted elmt
411
- val = name_delete(val)
412
- # lower full name in upper
413
- val = re.sub(r"[A-Z]{3,}", lambda x: x.group().lower(), val)
414
- # add space in front of upper case
415
- val = re.sub(r"(\w)([A-Z])", r"\1 \2", val)
416
- # Lower case
417
- val = val.lower()
418
- # remove special characters
419
- val = re.sub('[^A-Za-z0-9 ]+', ' ', val)
420
- # remove multiple spaces
421
- val = re.sub(' +', ' ', val)
422
- # remove trailing spaces
423
- val = val.strip()
424
- # suffix merge
425
- val = ln_suff_merge(val)
426
-
427
- return val
428
-
429
-
430
- def main_authors( research_key_words , details , size):
431
-
432
- dic_papers , dic_papers_ranked = ranking_own_research( research_key_words , details , False )
433
-
434
- dic_papers_co_authors = {}
435
-
436
- for paper in list(dic_papers_ranked.keys())[:size]:
437
-
438
- for k in range(len(dic_papers[paper]["authorships"])):
439
- coauthor_id = dic_papers[paper]["authorships"][k]["author"]["id"]
440
-
441
-
442
- author_name = dic_papers[paper]["authorships"][k]["author"]["display_name"]
443
- author_name_norm = normalize(dic_papers[paper]["authorships"][k]["author"]["display_name"]).split()
444
- if len (author_name_norm) > 0:
445
-
446
- author_name_norm = author_name_norm[0] + " " + author_name_norm[-1]
447
-
448
- if author_name_norm not in dic_papers_co_authors:
449
- dic_papers_co_authors[author_name_norm] = {}
450
- dic_papers_co_authors[author_name_norm]["Author's name(s)"] = author_name
451
- if coauthor_id != None:
452
- dic_papers_co_authors[author_name_norm]["Author's id(s)"] = coauthor_id[21:]
453
- else:
454
- dic_papers_co_authors[author_name_norm]["Author's id(s)"] = ""
455
- dic_papers_co_authors[author_name_norm]["Number of occurence within the " + str(size) + " most related papers"] = 1
456
- dic_papers_co_authors[author_name_norm]["Number of related citations"] = dic_papers[paper]["cited_by_count"]
457
- else:
458
- dic_papers_co_authors[author_name_norm]["Number of occurence within the " + str(size) + " most related papers"] += 1
459
- if author_name not in dic_papers_co_authors[author_name_norm]["Author's name(s)"]:
460
- dic_papers_co_authors[author_name_norm]["Author's name(s)"] += ", " + author_name
461
- if coauthor_id != None and coauthor_id[21:] not in dic_papers_co_authors[author_name_norm]["Author's id(s)"]:
462
- dic_papers_co_authors[author_name_norm]["Author's id(s)"] += ", " + coauthor_id[21:]
463
- dic_papers_co_authors[author_name_norm]["Number of related citations"] += dic_papers[paper]["cited_by_count"]
464
-
465
-
466
-
467
- if dic_papers_co_authors != {}:
468
- dic_papers_co_authors = {k: v for k, v in sorted(dic_papers_co_authors.items(), key=lambda item: item[1]["Number of occurence within the " + str(size) + " most related papers"] , reverse = True)}
469
-
470
- for author_name_norm in list(dic_papers_co_authors.keys())[:size]:
471
- list_ids = dic_papers_co_authors[author_name_norm]["Author's id(s)"].split(", ")
472
- work_count = 0
473
- cited_by_count = 0
474
- institutions = ''
475
- for elem in list_ids:
476
- if len(elem) > 3:
477
-
478
- data = get_data("https://api.openalex.org/people/" + elem)
479
- work_count += data["works_count"]
480
- cited_by_count += data["cited_by_count"]
481
- if data["last_known_institution"] != None and data["last_known_institution"]["display_name"] != None:
482
- if institutions == '':
483
- institutions += data["last_known_institution"]["display_name"]
484
- else:
485
- institutions += ", " + data["last_known_institution"]["display_name"]
486
-
487
- dic_papers_co_authors[author_name_norm]["Last Known Institution"] = institutions
488
- dic_papers_co_authors[author_name_norm]["Number of works"] = work_count
489
- dic_papers_co_authors[author_name_norm]["Number of citations"] = cited_by_count
490
-
491
-
492
- return pd.DataFrame(dic_papers_co_authors, index = [ "Author's name(s)" , "Author's id(s)" , "Number of occurence within the " + str(size) + " most related papers" , "Last Known Institution" , "Number of works" , "Number of citations" , "Number of related citations"]).T.style.hide(axis="index")
493
-
494
- else:
495
- return ("Select another category")
496
-
497
-
498
- def map_authors(research_key_words , details , size):
499
-
500
- dic_papers , dic_papers_ranked = ranking_own_research( research_key_words , details , False )
501
-
502
-
503
- dic_papers_co_authors = {}
504
- count = 0
505
-
506
-
507
- for paper in list(dic_papers_ranked.keys())[:size]:
508
-
509
- for k in range(len(dic_papers[paper]["authorships"])):
510
-
511
- if dic_papers[paper]["authorships"][k]["institutions"] != [] and "id" in dic_papers[paper]["authorships"][k]["institutions"][0] and dic_papers[paper]["authorships"][k]["institutions"][0]["id"] != None:
512
- institution_id = dic_papers[paper]["authorships"][k]["institutions"][0]["id"][21:]
513
- if institution_id in dic_institutions:
514
- data = dic_institutions[institution_id]
515
-
516
- dic_papers_co_authors[count] = {}
517
- dic_papers_co_authors[count]["longitude"] = data["longitude"]
518
- dic_papers_co_authors[count]["latitude"] = data["latitude"]
519
- dic_papers_co_authors[count]["abstract comparison"] = dic_papers_ranked[paper]["abstract comparison"]
520
- dic_papers_co_authors[count]["author"] = dic_papers[paper]["authorships"][k]["author"]["display_name"]
521
- dic_papers_co_authors[count]["institution"] = dic_papers[paper]["authorships"][k]["institutions"][0]["display_name"]
522
- dic_papers_co_authors[count]["date"] = dic_papers[paper]["date"]
523
-
524
- count += 1
525
-
526
- map_df = pd.DataFrame(dic_papers_co_authors).T
527
-
528
- if dic_papers_co_authors == {}:
529
- return map_df
530
-
531
-
532
-
533
-
534
- map_df["longitude"]=map_df['longitude'].astype(float)
535
- map_df['latitude']=map_df['latitude'].astype(float)
536
- map_df = map_df[map_df["latitude"].notnull()]
537
-
538
- return map_df
539
-
540
-
541
-
542
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/patent_functions.py DELETED
@@ -1,892 +0,0 @@
1
- ##packages code
2
- import streamlit as st
3
- from shapely.geometry import Point
4
- import pandas as pd
5
- from tqdm import tqdm
6
-
7
- import numpy as np
8
- import json, requests
9
- import pandas as pd
10
- #from pandas.io.json import json_normalize
11
-
12
- import matplotlib.pyplot as plt
13
- import seaborn as sns
14
- from math import radians, cos, sin, asin, sqrt
15
-
16
-
17
- from sentence_transformers import SentenceTransformer, util
18
-
19
- @st.cache_resource
20
- def model_nlp():
21
- model = SentenceTransformer('all-MiniLM-L6-v2')
22
- return model
23
-
24
-
25
- @st.cache_data # 👈 Add the caching decorator
26
- def load_data():
27
- url = "Synapse_project/Climate_site/python_scripts/institutions.tsv"
28
- dic = pd.read_csv(url, delimiter = "\t" , index_col = 0).to_dict('index')
29
- return dic
30
-
31
- dic_institutions = load_data()
32
-
33
-
34
- import unicodedata
35
-
36
- from metaphone import doublemetaphone
37
- from fuzzywuzzy import fuzz
38
- from difflib import SequenceMatcher
39
- import re
40
-
41
- import geopandas as gpd
42
- from geopandas import GeoDataFrame
43
- #################### General Functions #############################
44
-
45
- def URL(base_URL , entity_type , filters):
46
- url = base_URL + entity_type + filters
47
- return url
48
-
49
-
50
- def get_data(url):
51
- url = requests.get(url)
52
- text = url.text
53
- import json
54
- data = json.loads(text)
55
- return data
56
-
57
- ## encoding the abstract
58
-
59
-
60
- def reconstruction_abstract(abstract_inverted_index):
61
- # return the abstract is the abstract exists in the database, else, return None
62
-
63
- if abstract_inverted_index != None:
64
-
65
- list_values = list(abstract_inverted_index.values())
66
- list_keys = list(abstract_inverted_index.keys())
67
- #from the words in the abstract (keys of abstract_inverted_index) and their position in the text (values of abstract_inverted_index), reconstruct the abstract
68
-
69
- size_abstract = max([ max(elem) for elem in abstract_inverted_index.values() ] )
70
-
71
- abstract = [""]*(size_abstract +1)
72
-
73
- for i in range(len(list_values)):
74
- for pos in list_values[i]:
75
- abstract[pos] = list_keys[i]
76
-
77
- return " ".join(list(abstract))
78
-
79
- else:
80
- return None
81
-
82
-
83
- ## calculate efficiently the dot product between two vectors
84
-
85
- def norm(vector):
86
- return np.sqrt(sum(x * x for x in vector))
87
-
88
- def cosine_similarity2(vec_a, vec_b):
89
- norm_a = norm(vec_a)
90
- norm_b = norm(vec_b)
91
- dot = sum(a * b for a, b in zip(vec_a, vec_b))
92
- return dot / (norm_a * norm_b)
93
-
94
- ## Extracted texts
95
-
96
- def print_extracted_text(name_file):
97
-
98
- file = open('iea.txt', "r", encoding='utf8')
99
- lines = file.readlines()
100
- count = 0
101
- for index, line in enumerate(lines):
102
- read_line = line.strip()
103
- print(read_line)
104
-
105
- file.close()
106
-
107
-
108
- iea.txt
109
-
110
-
111
- def details(name_file , display):
112
-
113
- file = open("Synapse_project/Climate_site/python_scripts/iea.txt", "r")
114
- lines = file.readlines()
115
-
116
- mark = 0
117
- dic_details = {}
118
- count = -1
119
- for index, line in enumerate(lines):
120
-
121
- line = line.strip()
122
- if line == "Close explanation":
123
- break
124
-
125
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
126
- count += 1
127
-
128
-
129
- if mark == 1 and line != "" and line[0] == "*":
130
-
131
- if display == True:
132
- print(count)
133
- print(text)
134
- print(" ")
135
- dic_details[count] = text
136
- mark = 0
137
-
138
-
139
- if mark == 1:
140
- text = text + line + " "
141
-
142
- if line.split(" ")[-1] == "Details" or line.split(" ")[-1] == "Hide":
143
- mark = 1
144
- text = ""
145
-
146
- return dic_details
147
-
148
-
149
-
150
-
151
-
152
- def key_initiatives(name_file , display ):
153
-
154
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
155
- lines = file.readlines()
156
-
157
-
158
- mark = 0
159
- dic_key_initiatives = {}
160
- count = -1
161
- for index, line in enumerate(lines):
162
-
163
- line = line.strip()
164
- if line == "Close explanation":
165
- break
166
-
167
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
168
-
169
- count += 1
170
-
171
-
172
-
173
- if mark == 1 and line != "" and ( (line[0].isnumeric() and ">" in line and " " in line) or line == "*Deployment targets:*" or line == "*Announced development targets:*"):
174
- if display == True:
175
- print(count)
176
- print(text)
177
- print(" ")
178
-
179
- dic_key_initiatives[count] = text
180
- mark = 0
181
-
182
-
183
- if mark == 1:
184
- text = text + line + " "
185
-
186
- if line == "*Key initiatives:*":
187
-
188
-
189
- mark = 1
190
- text = ""
191
-
192
- return dic_key_initiatives
193
-
194
-
195
-
196
-
197
- def deployment_target(name_file , display):
198
-
199
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
200
- lines = file.readlines()
201
-
202
-
203
- mark = 0
204
- dic_target = {}
205
- count = -1
206
- for index, line in enumerate(lines):
207
-
208
- line = line.strip()
209
- if line == "Close explanation":
210
- break
211
-
212
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
213
- count += 1
214
-
215
-
216
-
217
- if mark == 1 and line != "" and ((line[0].isnumeric() and ">" in line and " " in line) or line == "*Announced cost reduction targets:*" or line == "*Announced development targets:*"):
218
-
219
- if display == True:
220
- print(count)
221
- print(text)
222
- print(" ")
223
-
224
- dic_target[count] = text
225
- mark = 0
226
-
227
-
228
- if mark == 1:
229
- text = text + line + " "
230
-
231
- if line == "*Deployment targets:*" or line == "*Announced development targets:*":
232
-
233
- mark = 1
234
- text = ""
235
-
236
- return dic_target
237
-
238
-
239
-
240
-
241
- def cost_reduction_target(name_file , display):
242
-
243
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
244
- lines = file.readlines()
245
-
246
- mark = 0
247
- dic_cost = {}
248
- count = -1
249
- for index, line in enumerate(lines):
250
-
251
- line = line.strip()
252
-
253
- if line == "Close explanation":
254
- break
255
-
256
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
257
-
258
-
259
- count += 1
260
-
261
-
262
-
263
- if mark == 1 and line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
264
-
265
- if display == True:
266
- print(count)
267
- print(text)
268
- print(" ")
269
-
270
- dic_cost[count] = text
271
- mark = 0
272
-
273
-
274
- if mark == 1:
275
- text = text + line + " "
276
-
277
- if line == "*Announced cost reduction targets:*":
278
-
279
- mark = 1
280
- text = ""
281
-
282
- return dic_cost
283
-
284
-
285
-
286
- def key_words(name_file, display ):
287
-
288
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
289
-
290
- lines = file.readlines()
291
-
292
- list_categories = []
293
- count = -1
294
- for index, line in enumerate(lines):
295
-
296
- line = line.strip()
297
-
298
- if line == "Close explanation":
299
- break
300
-
301
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
302
- count += 1
303
-
304
- if display == True:
305
- print("Technologies" , count+1 , ":")
306
-
307
- if line != "":
308
-
309
- if line[0].isnumeric() and ">" in line and " " in line:
310
- i = 0
311
- try:
312
- line = line.split(" ")[2]
313
- except:
314
- print(line)
315
- break
316
-
317
- if "Details" not in lines[index] and "Moderate" not in lines[index]:
318
-
319
- while " " not in line:
320
- i += 1
321
- if "Details"==lines[index + i][:7] or "End-use"==lines[index + i][:7]:
322
- break
323
- else:
324
- line = line + " " + lines[index + i]
325
-
326
- #if " Production" in line:
327
- #line = line.replace(" Production" , "")
328
-
329
- line = line.replace("\n" , " ")
330
- line = line.replace("/" , " ")
331
- line = line.replace("-" , " ")
332
- line = line.split(" ")[0]
333
-
334
- if " " in line:
335
- line = line.replace(" ", " ")
336
- line = line.split(">")
337
-
338
-
339
- if "(" in line[-1]:
340
- line[-1] = line[-1].split("(")[0]
341
-
342
-
343
- for i in range(len(line)):
344
-
345
- # remove multiple spaces
346
- line[i] = re.sub(' +', ' ', line[i])
347
- # remove trailing spaces
348
- line[i] = line[i].strip()
349
-
350
-
351
-
352
- if display == True:
353
- print(line)
354
- print(" ")
355
-
356
- if '' in line:
357
- line.remove('')
358
-
359
- list_categories.append([count , line])
360
-
361
- return list_categories
362
-
363
-
364
-
365
- def technology(name_file, display ):
366
- # Filepath too specific, need to change to relative path
367
- file = open('Synapse_project/Climate_site/python_scripts/iea.txt', "r", encoding='utf8')
368
- lines = file.readlines()
369
-
370
- list_categories = []
371
- count = -1
372
- for index, line in enumerate(lines):
373
-
374
- line = line.strip()
375
-
376
- if line == "Close explanation":
377
- break
378
-
379
- if line != "" and (line[0].isnumeric() and ">" in line and " " in line) :
380
- count += 1
381
-
382
-
383
- if display == True:
384
- print("Technologies" , count+1 , ":")
385
-
386
- if line != "":
387
-
388
- if line[0].isnumeric() and ">" in line and " " in line:
389
- i = 0
390
- try:
391
- line = line.split(" ")[1]
392
- except:
393
- print(line)
394
- break
395
-
396
-
397
- line = line.replace("\n" , " ")
398
- line = line.replace("/" , " ")
399
- line = line.replace("-" , " ")
400
- line = line.strip()
401
- line = re.sub(' +', ' ', line)
402
- line = line.split(" ")[0]
403
- line = line.split(">")
404
-
405
-
406
- if "(" in line[-1]:
407
- line[-1] = line[-1].split("(")[0]
408
-
409
-
410
- for i in range(len(line)):
411
-
412
- # remove multiple spaces
413
- line[i] = re.sub(' +', ' ', line[i])
414
- # remove trailing spaces
415
- line[i] = line[i].strip()
416
-
417
-
418
-
419
- if display == True:
420
- print(line)
421
- print(" ")
422
-
423
-
424
- list_categories.append([count , line])
425
-
426
- return list_categories
427
-
428
-
429
- #################### Patent Functions #############################
430
-
431
- def related_patents(number_technology , research_words, carbon_related , display):
432
-
433
- name_file = "iea"
434
- list_categories = key_words( name_file, False)
435
-
436
- dic_patents = {}
437
-
438
- max_count = 0
439
- base_URL_PV = "https://api.patentsview.org/"
440
- filter_works = "patents/query?"
441
- filter_PV = "q={%22_and%22:[{%22_text_any%22:{%22patent_abstract%22:%22"
442
- filter_PV += research_words.replace("," , "")
443
-
444
- if carbon_related == True:
445
- filter_PV += "%22}},{%22_eq%22:{%22cpc_group_id%22:%22Y02E%22}}]}&f=[%22patent_number%22,%22patent_title%22,%22assignee_country%22,%22patent_date%22,%22inventor_id%22,%22assignee_organization%22,%22inventor_longitude%22,%22inventor_latitude%22,%22inventor_last_name%22,%22inventor_first_name%22,%22cpc_subsection_title%22,%22assignee_city%22,%22patent_abstract%22,%22patent_kind%22,%22cpc_group_id%22,%22assignee_organization%22,%22citedby_patent_number%22]"
446
-
447
- else:
448
- filter_PV += "%22}}]}&f=[%22patent_number%22,%22patent_title%22,%22assignee_country%22,%22patent_date%22,%22assignee_organization%22,%22inventor_longitude%22,%22inventor_latitude%22,%22inventor_last_name%22,%22inventor_id%22,%22inventor_first_name%22,%22cpc_subsection_title%22,%22assignee_city%22,%22patent_abstract%22,%22patent_kind%22,%22cpc_group_id%22,%22assignee_organization%22,%22citedby_patent_number%22]"
449
-
450
-
451
- filter_PV = filter_PV.replace(" " , "%20")
452
-
453
-
454
-
455
- url = URL(base_URL_PV , filter_works, filter_PV)
456
- data = get_data(url)
457
-
458
-
459
- if display == True:
460
- print( data["total_patent_count"] , elem[-1] )
461
- print(url)
462
-
463
-
464
-
465
-
466
- for i in range(data["count"]):
467
- dic_patents[ "US-" + data["patents"][i]["patent_number"]] = {}
468
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["title"] = data["patents"][i]["patent_title"]
469
- dic_patents["US-" + data["patents"][i]["patent_number"]]["abstract"] = data["patents"][i]["patent_abstract"]
470
-
471
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["assignee"] = str(data["patents"][i]["assignees"][0]["assignee_organization"])
472
- dic_patents["US-" + data["patents"][i]["patent_number"]]["assignee_city"] = str(data["patents"][i]["assignees"][0]["assignee_city"])
473
- dic_patents["US-" + data["patents"][i]["patent_number"]]["assignee_country"] = str(data["patents"][i]["assignees"][0]["assignee_country"])
474
- for j in range(1, len(data["patents"][i]["assignees"])):
475
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["assignee"] += ", " + str(data["patents"][i]["assignees"][j]["assignee_organization"])
476
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["assignee_city"] += ", " + str(data["patents"][i]["assignees"][j]["assignee_city"])
477
- dic_patents["US-" + data["patents"][i]["patent_number"]]["assignee_country"] += ", " + str(data["patents"][i]["assignees"][j]["assignee_country"])
478
-
479
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["list_inventors"] = data["patents"][i]["inventors"]
480
-
481
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["inventors"] = str(data["patents"][i]["inventors"][0]["inventor_first_name"]) + " " + str(data["patents"][i]["inventors"][0]["inventor_last_name"])
482
- for j in range(1, len(data["patents"][i]["inventors"])):
483
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["inventors"] += ", " + str(data["patents"][i]["inventors"][j]["inventor_first_name"]) + " " + str(data["patents"][i]["inventors"][j]["inventor_last_name"])
484
-
485
-
486
- dic_patents["US-" + data["patents"][i]["patent_number"]]["date"] = data["patents"][i]["patent_date"]
487
- dic_patents["US-" + data["patents"][i]["patent_number"]]["number_citations"] = len(data["patents"][i]["citedby_patents"])
488
-
489
-
490
- if display == True:
491
- print(" ")
492
-
493
-
494
- return dic_patents
495
-
496
-
497
-
498
- ## Ranking Patents
499
-
500
- def ranking_patents(number_technology , research_words, carbon_related , display):
501
-
502
- model = model_nlp()
503
-
504
-
505
- name_file = "iea"
506
- list_categories = key_words( name_file, False)
507
- dic_details = details(name_file , False)
508
- dic_patents = related_patents(number_technology , research_words, carbon_related , display)
509
-
510
-
511
- dic_scores = {}
512
-
513
- if display == True:
514
- print("Key words: " , list_categories[number_technology][1])
515
-
516
- if number_technology in dic_details:
517
- reference_text = dic_details[number_technology]
518
- if display == True:
519
- print("Technology details: " , reference_text)
520
- print(" ")
521
- encoded_text = model.encode(reference_text, convert_to_tensor=False).tolist()
522
-
523
-
524
- if len(dic_patents ) == 0:
525
- return "Select other key words"
526
-
527
-
528
- else:
529
- for ids in list(dic_patents.keys()):
530
-
531
- dic_scores[ids] = {}
532
-
533
- encoded_title = model.encode(dic_patents[ids]["title"], convert_to_tensor=False).tolist()
534
- score_title = cosine_similarity2(encoded_title, encoded_text)
535
-
536
-
537
- if dic_patents[ids]["abstract"] != None:
538
- encoded_abstract = model.encode(dic_patents[ids]["abstract"], convert_to_tensor=False).tolist()
539
- score_abstract = cosine_similarity2(encoded_abstract, encoded_text)
540
- else:
541
- score_abstract = None
542
-
543
- dic_scores[ids]["title comparision"] = score_title
544
- dic_scores[ids]["abstract comparison"] = score_abstract
545
- dic_scores[ids]["title"] = dic_patents[ids]["title"]
546
- dic_scores[ids]["citations"] = dic_patents[ids]["number_citations"]
547
- dic_scores[ids]["date"] = dic_patents[ids]["date"][:4]
548
- dic_scores[ids]["assignee"] = dic_patents[ids]["assignee"]
549
- #dic_scores[ids]["assignee_city"] = dic_patents[ids]["assignee_city"]
550
- #dic_scores[ids]["assignee_country"] = dic_patents[ids]["assignee_country"]
551
- dic_scores[ids]["inventors"] = dic_patents[ids]["inventors"]
552
- dic_scores[ids]["number of co-inventors"] = len(dic_patents[ids]["inventors"].split(","))
553
- return dic_patents , dic_scores
554
-
555
-
556
- def get_ranking_patents(technologies, number_technology ,category , carbon_related , size):
557
- dic , dic_patents = ranking_patents(number_technology , category, carbon_related , False)
558
- if dic_patents == {}:
559
- return "No patent found, select other key words"
560
-
561
- elif dic_patents == "Select other key words":
562
- return dic_patents
563
-
564
- else:
565
- return pd.DataFrame(dic_patents).T.sort_values(by="abstract comparison" , ascending = False)[:size]
566
-
567
-
568
-
569
-
570
-
571
- #normalize a string dat that represents often a name.
572
-
573
- def normalize(data):
574
- normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore')
575
- val = normal.decode("utf-8")
576
-
577
- # lower full name in upper
578
- val = re.sub(r"[A-Z]{3,}", lambda x: x.group().lower(), val)
579
- # add space in front of upper case
580
- val = re.sub(r"(\w)([A-Z])", r"\1 \2", val)
581
- # Lower case
582
- val = val.lower()
583
- # remove special characters
584
- val = re.sub('[^A-Za-z0-9 ]+', ' ', val)
585
- # remove multiple spaces
586
- val = re.sub(' +', ' ', val)
587
- # remove trailing spaces
588
- val = val.strip()
589
-
590
-
591
- return val
592
-
593
-
594
- def main_inventors(technologies, number_technology , carbon_related , category , size ):
595
- display = False
596
- dic_patents , dic_ranked = ranking_patents(number_technology , category, carbon_related , display)
597
- dic_patents_co_inventors = {}
598
-
599
-
600
- for patent in list(dic_ranked.keys())[:size]:
601
- for k in range(len(dic_patents[patent]["list_inventors"])):
602
-
603
- inventor_id = dic_patents[patent]["list_inventors"][k]["inventor_id"]
604
- inventor_name = dic_patents[patent]["list_inventors"][k]["inventor_first_name"] + " " + dic_patents[patent]["list_inventors"][k]["inventor_last_name"]
605
- inventor_name_norm = normalize(inventor_name).split()
606
- inventor_name_norm = inventor_name_norm[0] + " " + inventor_name_norm[-1]
607
-
608
- if inventor_name_norm not in dic_patents_co_inventors:
609
- dic_patents_co_inventors[inventor_name_norm] = {}
610
- dic_patents_co_inventors[inventor_name_norm]["Inventor's name"] = inventor_name
611
- dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"] = inventor_id
612
- dic_patents_co_inventors[inventor_name_norm]["Number of occurence"] = 1
613
- dic_patents_co_inventors[inventor_name_norm]["Number of related citations"] = dic_patents[patent]["number_citations"]
614
-
615
- else:
616
- if inventor_id not in dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"] :
617
- dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"] += ", " + inventor_id
618
- if inventor_name not in dic_patents_co_inventors[inventor_name_norm]["Inventor's name"] :
619
- dic_patents_co_inventors[inventor_name_norm]["Inventor's name"] += ", " + inventor_name
620
- dic_patents_co_inventors[inventor_name_norm]["Number of occurence"] += 1
621
- dic_patents_co_inventors[inventor_name_norm]["Number of related citations"] += dic_patents[patent]["number_citations"]
622
-
623
-
624
- dic_patents_co_inventors = {k: v for k, v in sorted(dic_patents_co_inventors.items(), key=lambda item: item[1]["Number of occurence"] , reverse = True)}
625
-
626
- if dic_patents_co_inventors == {}:
627
-
628
-
629
- return "No patent, select other key words"
630
- else:
631
-
632
- for inventor_name_norm in list(dic_patents_co_inventors.keys()):
633
- list_inventors = dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"].split(", ")
634
- work_count = 0
635
- cited_by_count = 0
636
-
637
- for elem in list_inventors:
638
- url = "https://api.patentsview.org/inventors/query?q={%22inventor_id%22:[%22" + elem + "%22]}&f=[%22inventor_total_num_patents%22,%22patent_num_cited_by_us_patents%22]"
639
- data = get_data(url)["inventors"][0]
640
- work_count += int(data["inventor_total_num_patents"])
641
- for k in range(len(data["patents"])):
642
- cited_by_count += int(data["patents"][k]["patent_num_cited_by_us_patents"])
643
-
644
- dic_patents_co_inventors[inventor_name_norm]["Number of patents"] = work_count
645
- dic_patents_co_inventors[inventor_name_norm]["Number of US patents citations"] = cited_by_count
646
-
647
-
648
-
649
-
650
- return pd.DataFrame(dic_patents_co_inventors , index = ["Inventor's name", "PatentsView inventor's id", "Number of occurence" , "Number of patents" ,"Number of US patents citations" , "Number of related citations"]).T
651
-
652
-
653
-
654
-
655
- def map_inventors(technologies, number_technology , carbon_related , category , size):
656
- display = False
657
- dic_patents , dic_ranked = ranking_patents(number_technology , category, carbon_related , display)
658
- dic_patents_co_inventors = {}
659
- count = 0
660
-
661
- for patent in list(dic_ranked.keys())[:size]:
662
- for k in range(len(dic_patents[patent]["list_inventors"])):
663
-
664
- dic_patents_co_inventors[count] = {}
665
-
666
- dic_patents_co_inventors[count]["latitude"] = dic_patents[patent]["list_inventors"][k]["inventor_latitude"]
667
- dic_patents_co_inventors[count]["longitude"] = dic_patents[patent]["list_inventors"][k]["inventor_longitude"]
668
- dic_patents_co_inventors[count]["longitude"] = dic_patents[patent]["list_inventors"][k]["inventor_longitude"]
669
- dic_patents_co_inventors[count]["inventor_name"] = str(dic_patents[patent]["list_inventors"][k]["inventor_first_name"]) + " " + str(dic_patents[patent]["list_inventors"][k]["inventor_last_name"])
670
- dic_patents_co_inventors[count]["patent_date"] = dic_patents[patent]["date"]
671
- count += 1
672
-
673
- if dic_patents_co_inventors == {}:
674
- return "No patent, select other key words"
675
-
676
-
677
- map_df = pd.DataFrame(dic_patents_co_inventors).T
678
- map_df["longitude"]=map_df['longitude'].astype(float)
679
- map_df['latitude']=map_df['latitude'].astype(float)
680
- map_df = map_df[map_df["latitude"].notnull()]
681
-
682
- return map_df
683
-
684
- #geometry = [Point(xy) for xy in zip(map_df['Longitude'], map_df['Latitude'])]
685
- #gdf = GeoDataFrame(map_df, geometry=geometry)
686
-
687
- #this is a simple map that goes with geopandas
688
- #world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
689
- #gdf.plot(ax=world.plot( color='white', edgecolor='black' ), marker='o', color='red', markersize=15 , zorder = 1);
690
- #plt.xlim([-180, 180])
691
- #plt.ylim([-90, 90])
692
-
693
-
694
- #plt.title("Main inventors: geographic location")
695
- #plt.xlabel("Longitude")
696
- #plt.ylabel("Latitude")
697
- #plt.show()
698
-
699
-
700
- ## Extract quantitative data
701
-
702
- def extract_sentences_with_numbers(text , text_name):
703
-
704
- if text != None:
705
- text = text.replace("CO 2" , "CO2")
706
- text = text.replace("CO 3" , "CO3")
707
- text = text.replace("CO(2)" , "CO2")
708
- text = text.replace("CO(3)" , "CO3")
709
-
710
- print(text_name + ": " , text)
711
- print(" ")
712
-
713
-
714
-
715
- list_text = list(text)
716
- for i in range(1,len(list_text)-1):
717
- if list_text[i] == " " and list_text[i-1] == "." and list_text[i+1].isupper():
718
- list_text[i] = "~"
719
-
720
- text = "".join(list_text)
721
- text = text.split("~")
722
- for sentence in text:
723
-
724
- if any(char.isdigit() for char in sentence):
725
-
726
-
727
-
728
- if "CO2" in sentence:
729
- print("\x1b[31mCARBON RELATED:\x1b[0m", sentence)
730
- print(" ")
731
-
732
-
733
-
734
- if "GJ" in sentence or "MJ" in sentence:
735
- print("\x1b[31mENERGY:\x1b[0m" , sentence)
736
- print(" ")
737
-
738
-
739
-
740
- ##price
741
- if "€" in sentence or "$" in sentence or "EUR" in sentence or "dollars" in sentence.lower():
742
- print("\x1b[31mPRICE:\x1b[0m" , sentence)
743
- print(" ")
744
-
745
-
746
-
747
- ##dates
748
- digits = []
749
- for word in sentence.replace("," , "").replace("%" , "").replace("." , " ").split():
750
- if word.isdigit() and 1850 < int(word) < 2200 :
751
- digits.append(word)
752
- if digits != []:
753
- print("\x1b[31mDATE:\x1b[0m" , sentence)
754
- print(" ")
755
-
756
-
757
-
758
- ##CO quantity
759
- if "Mt" in sentence or "tC" in sentence or "t-C" in sentence:
760
- print("\x1b[31mCARBON QUANTITY:\x1b[0m" , sentence)
761
- print(" ")
762
-
763
- print(" ")
764
-
765
-
766
- def extract_quantitative_data_technology(technologies, number_technology):
767
- count = 0
768
-
769
- name_file = "iea"
770
- dic_target = deployment_target(name_file , False)
771
- dic_cost = cost_reduction_target(name_file , False)
772
- dic_details = details(name_file , False)
773
- cost_target_text = 'No information'
774
- cost_text = 'No information'
775
-
776
- if number_technology in dic_details:
777
- reference_text = dic_details[number_technology]
778
-
779
- #print("\033[96mFROM IEA website: ")
780
- #print("\033[92mTechnology details: \x1b[0m" , reference_text)
781
- #print(" ")
782
- #encoded_text = model.encode(reference_text, convert_to_tensor=False).tolist()
783
-
784
- if number_technology in dic_target:
785
- cost_target_text = dic_target[number_technology]
786
- #print("\033[96mFROM IEA website: ")
787
- #sentences = extract_sentences_with_numbers(cost_target_text , "\033[92mDeployment target and Announced development target\x1b[0m")
788
-
789
- if number_technology in dic_cost:
790
- cost_text = dic_cost[number_technology]
791
- #print("\033[96mFROM IEA website: ")
792
- #sentences = extract_sentences_with_numbers(cost_text , "\033[92mAnnounced cost reduction targets\x1b[0m")
793
-
794
- return reference_text, cost_target_text , cost_text
795
-
796
-
797
-
798
- def extract_quantitative_data_patent(patent_id):
799
-
800
-
801
- patent_id = patent_id[3:]
802
-
803
- url = "https://api.patentsview.org/patents/query?q={%22patent_id%22:%22" + str(patent_id) + "%22}&f=[%22patent_number%22,%22patent_title%22,%22patent_abstract%22,%22patent_date%22,%22inventor_last_name%22,%22inventor_first_name%22,%22assignee_organization%22]"
804
- url_google = "https://patents.google.com/patent/US" + str(patent_id)
805
-
806
- data = get_data(url)["patents"][0]
807
- title = data["patent_title"]
808
- abstract = data["patent_abstract"]
809
- co_inventors = ", ".join([ data["inventors"][i]["inventor_first_name"] + " " + data["inventors"][i]["inventor_last_name"] for i in range(len(data["inventors"])) ])
810
- assignees = ", ".join([ str(data["assignees"][i]["assignee_organization"]) for i in range(len(data["assignees"])) ] )
811
-
812
- return url_google , title , abstract , data["patent_date"] , co_inventors , assignees
813
-
814
-
815
-
816
-
817
-
818
-
819
-
820
-
821
-
822
- ################################### Extracted texts ###############################################################
823
-
824
- #@title Which patents are related to the technology?
825
- def finder():
826
- name_file = 'iea'
827
-
828
- res = technology("iea", False )
829
- list_categories_tech = []
830
- list_categories = key_words(name_file , False)
831
- list_technologies = [ ( ", ".join(list_categories[i][1]) , i ) for i in range(len(list_categories)) ]
832
-
833
- dic_technologies = {}
834
- for i in range(len(res)):
835
- names = res[i][1]
836
- if ", ".join(names) not in list_categories_tech:
837
- list_categories_tech.append(", ".join(names))
838
- dic_technologies[", ".join(names)] = []
839
- dic_technologies[", ".join(names)].append( (", ".join(list_categories[i][1]) , i ))
840
-
841
-
842
- list_climate = [ ("Any related patents" , False ) , ("Climate related patents" , True)]
843
-
844
- dic_categories = {}
845
- for elem in list_technologies:
846
- list_words = elem[0].split(",")[-3:]
847
-
848
- dic_categories[elem[1]] = [ " ".join(list_words[-1].split()[:3]) , " ".join(list_words[-2].split()[:3]) if len(list_words) > 1 else "" , " ".join(list_words[-3].split()[:3]) if len(list_words) > 2 else "" ]
849
-
850
- return dic_technologies, dic_categories, list_categories_tech, list_technologies
851
-
852
- # technologies_widget = widgets.Dropdown(options=list_categories_tech,
853
- # description="Choose the category:" ,
854
- # style = {'description_width':'initial' } ,
855
- # layout=Layout(width='500px'));
856
-
857
- # category_widget = widgets.RadioButtons( values = 1,
858
- # description='Patents where the abstract contains:' ,
859
- # style = {'description_width':'initial' } ,
860
- # layout=Layout(width='1000px'));
861
-
862
- # number_technology_widget = widgets.Dropdown(options=list_technologies,
863
- # description="Choose the technology:" ,
864
- # style = {'description_width':'initial' } ,
865
- # layout=Layout(width='500px'));
866
-
867
- # def update_category(*args):
868
- # category_widget.options = dic_categories[number_technology_widget.value]
869
-
870
- # def update_technology(*args):
871
- # number_technology_widget.options = dic_technologies[technologies_widget.value]
872
-
873
-
874
- # number_technology_widget.observe(update_category)
875
- # technologies_widget.observe(update_technology)
876
-
877
- # print("Which patents are related to the technology?")
878
- # interact_manual(get_ranking_patents,
879
- # technologies=technologies_widget,
880
- # number_technology= number_technology_widget ,
881
- # carbon_related=widgets.Dropdown(options=list_climate,
882
- # description="Select the type of patents:" ,
883
- # style = {'description_width':'initial' } ,
884
- # layout=Layout(width='500px') ) ,
885
- # size = widgets.IntSlider(min=3,
886
- # max=100,
887
- # value=10,
888
- # step=1,
889
- # description="Select the number of patents:" ,
890
- # style = {'description_width':'initial' } ,
891
- # layout=Layout(width='500px')),
892
- # category = category_widget);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/patent_functions_own_details.py DELETED
@@ -1,475 +0,0 @@
1
- ##packages code
2
- from shapely.geometry import Point
3
- import pandas as pd
4
- from tqdm import tqdm
5
- import streamlit as st
6
- import numpy as np
7
- import json, requests
8
- import pandas as pd
9
- #from pandas.io.json import json_normalize
10
-
11
- import matplotlib.pyplot as plt
12
- import seaborn as sns
13
- from math import radians, cos, sin, asin, sqrt
14
-
15
- import spacy
16
- #!python -m spacy download en_core_web_lg
17
-
18
-
19
- from sentence_transformers import SentenceTransformer, util
20
-
21
- @st.cache_resource
22
- def model_nlp():
23
- model = SentenceTransformer('all-MiniLM-L6-v2')
24
- return model
25
-
26
- import unicodedata
27
-
28
- from metaphone import doublemetaphone
29
- from fuzzywuzzy import fuzz
30
- from difflib import SequenceMatcher
31
- import re
32
-
33
- import geopandas as gpd
34
- from geopandas import GeoDataFrame
35
-
36
-
37
- @st.cache_data # 👈 Add the caching decorator
38
- def load_data():
39
- url = "Synapse_project/Climate_site/python_scripts/institutions.tsv"
40
- dic = pd.read_csv(url, delimiter = "\t" , index_col = 0).to_dict('index')
41
- return dic
42
-
43
- dic_institutions = load_data()
44
-
45
-
46
- #################### General Functions #############################
47
-
48
- def URL(base_URL , entity_type , filters):
49
- url = base_URL + entity_type + filters
50
- return url
51
-
52
-
53
- def get_data(url):
54
- url = requests.get(url)
55
- text = url.text
56
- import json
57
- data = json.loads(text)
58
- return data
59
-
60
-
61
- ## calculate efficiently the dot product between two vectors
62
-
63
- def norm(vector):
64
- return np.sqrt(sum(x * x for x in vector))
65
-
66
- def cosine_similarity2(vec_a, vec_b):
67
- norm_a = norm(vec_a)
68
- norm_b = norm(vec_b)
69
- dot = sum(a * b for a, b in zip(vec_a, vec_b))
70
- return dot / (norm_a * norm_b)
71
-
72
-
73
-
74
-
75
- #################### Patent Functions #############################
76
-
77
-
78
- def related_patents(research_words , display):
79
-
80
-
81
- dic_patents = {}
82
-
83
- max_count = 0
84
- base_URL_PV = "https://api.patentsview.org/"
85
- filter_works = "patents/query?"
86
- filter_PV = "q={%22_and%22:[{%22_text_all%22:{%22patent_abstract%22:%22"
87
- filter_PV += research_words
88
-
89
- filter_PV += "%22}}]}&f=[%22patent_number%22,%22patent_title%22,%22assignee_country%22,%22patent_date%22,%22assignee_organization%22,%22inventor_longitude%22,%22inventor_latitude%22,%22inventor_last_name%22,%22inventor_id%22,%22inventor_first_name%22,%22cpc_subsection_title%22,%22assignee_city%22,%22patent_abstract%22,%22patent_kind%22,%22cpc_group_id%22,%22assignee_organization%22,%22citedby_patent_number%22]"
90
-
91
- filter_PV = filter_PV.replace(" " , "%20")
92
-
93
-
94
-
95
- url = URL(base_URL_PV , filter_works, filter_PV)
96
- data = get_data(url)
97
-
98
-
99
- if display == True:
100
- print( data["total_patent_count"] , elem[-1] )
101
- print(url)
102
-
103
-
104
-
105
-
106
- for i in range(data["count"]):
107
- dic_patents[ "US-" + data["patents"][i]["patent_number"]] = {}
108
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["title"] = data["patents"][i]["patent_title"]
109
- dic_patents["US-" + data["patents"][i]["patent_number"]]["abstract"] = data["patents"][i]["patent_abstract"]
110
-
111
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["assignee"] = str(data["patents"][i]["assignees"][0]["assignee_organization"])
112
- dic_patents["US-" + data["patents"][i]["patent_number"]]["assignee_city"] = str(data["patents"][i]["assignees"][0]["assignee_city"])
113
- dic_patents["US-" + data["patents"][i]["patent_number"]]["assignee_country"] = str(data["patents"][i]["assignees"][0]["assignee_country"])
114
- for j in range(1, len(data["patents"][i]["assignees"])):
115
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["assignee"] += ", " + str(data["patents"][i]["assignees"][j]["assignee_organization"])
116
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["assignee_city"] += ", " + str(data["patents"][i]["assignees"][j]["assignee_city"])
117
- dic_patents["US-" + data["patents"][i]["patent_number"]]["assignee_country"] += ", " + str(data["patents"][i]["assignees"][j]["assignee_country"])
118
-
119
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["list_inventors"] = data["patents"][i]["inventors"]
120
-
121
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["inventors"] = str(data["patents"][i]["inventors"][0]["inventor_first_name"]) + " " + str(data["patents"][i]["inventors"][0]["inventor_last_name"])
122
- for j in range(1, len(data["patents"][i]["inventors"])):
123
- dic_patents[ "US-" + data["patents"][i]["patent_number"]]["inventors"] += ", " + str(data["patents"][i]["inventors"][j]["inventor_first_name"]) + " " + str(data["patents"][i]["inventors"][j]["inventor_last_name"])
124
-
125
-
126
- dic_patents["US-" + data["patents"][i]["patent_number"]]["date"] = data["patents"][i]["patent_date"]
127
- dic_patents["US-" + data["patents"][i]["patent_number"]]["number_citations"] = len(data["patents"][i]["citedby_patents"])
128
-
129
-
130
- if display == True:
131
- print(" ")
132
-
133
-
134
- return dic_patents
135
-
136
-
137
-
138
-
139
-
140
- def ranking_patents( research_words, details):
141
-
142
- model = model_nlp()
143
-
144
- dic_patents = related_patents( research_words , False)
145
-
146
-
147
- dic_scores = {}
148
-
149
-
150
-
151
- reference_text = details
152
-
153
- encoded_text = model.encode(reference_text, convert_to_tensor=False).tolist()
154
-
155
-
156
- if len(dic_patents ) == 0:
157
- return "Select other key words"
158
-
159
- else:
160
- for ids in list(dic_patents.keys()):
161
-
162
- dic_scores[ids] = {}
163
-
164
- encoded_title = model.encode(dic_patents[ids]["title"], convert_to_tensor=False).tolist()
165
- score_title = cosine_similarity2(encoded_title, encoded_text)
166
-
167
-
168
- if dic_patents[ids]["abstract"] != None:
169
- encoded_abstract = model.encode(dic_patents[ids]["abstract"], convert_to_tensor=False).tolist()
170
- score_abstract = cosine_similarity2(encoded_abstract, encoded_text)
171
- else:
172
- score_abstract = None
173
-
174
- dic_scores[ids]["title comparision"] = score_title
175
- dic_scores[ids]["abstract comparison"] = score_abstract
176
- dic_scores[ids]["title"] = dic_patents[ids]["title"]
177
- dic_scores[ids]["citations"] = dic_patents[ids]["number_citations"]
178
- dic_scores[ids]["date"] = dic_patents[ids]["date"][:4]
179
- dic_scores[ids]["assignee"] = dic_patents[ids]["assignee"]
180
- dic_scores[ids]["inventors"] = dic_patents[ids]["inventors"]
181
- dic_scores[ids]["number of co-inventors"] = len(dic_patents[ids]["inventors"].split(","))
182
-
183
- return dic_patents , dic_scores
184
-
185
-
186
-
187
-
188
- def get_ranking_own_research(research_key_words, details , size):
189
-
190
- dic , dic_scores_papers = ranking_patents(research_key_words, details )
191
-
192
- if dic_scores_papers == {}:
193
- return "No paper found"
194
-
195
- elif type(dic_scores_papers) == str:
196
- return dic_scores_papers
197
-
198
- else:
199
- return pd.DataFrame(dic_scores_papers).T.sort_values(by="abstract comparison" , ascending = False).head(size)
200
-
201
-
202
-
203
- def extract_quantitative_data_patent(patent_id):
204
-
205
-
206
- patent_id = patent_id[3:]
207
-
208
- url = "https://api.patentsview.org/patents/query?q={%22patent_id%22:%22" + str(patent_id) + "%22}&f=[%22patent_number%22,%22patent_title%22,%22patent_abstract%22,%22patent_date%22,%22inventor_last_name%22,%22inventor_first_name%22,%22assignee_organization%22]"
209
- url_google = "https://patents.google.com/patent/US" + str(patent_id)
210
-
211
- data = get_data(url)["patents"][0]
212
- title = data["patent_title"]
213
- abstract = data["patent_abstract"]
214
- co_inventors = ", ".join([ data["inventors"][i]["inventor_first_name"] + " " + data["inventors"][i]["inventor_last_name"] for i in range(len(data["inventors"])) ])
215
- assignees = ", ".join([ str(data["assignees"][i]["assignee_organization"]) for i in range(len(data["assignees"])) ] )
216
-
217
- return url_google , title , abstract , data["patent_date"] , co_inventors , assignees
218
-
219
-
220
-
221
-
222
-
223
-
224
-
225
- ## Mapping the authors
226
-
227
- #merge the nobiliary particles with the last name
228
- #ln_suff file can be modified if more or less nobiliary particles want to be suppressed
229
-
230
- ln_suff = ['oster',
231
- 'nordre',
232
- 'vaster',
233
- 'aust',
234
- 'vesle',
235
- 'da',
236
- 'van t',
237
- 'af',
238
- 'al',
239
- 'setya',
240
- 'zu',
241
- 'la',
242
- 'na',
243
- 'mic',
244
- 'ofver',
245
- 'el',
246
- 'vetle',
247
- 'van het',
248
- 'dos',
249
- 'ui',
250
- 'vest',
251
- 'ab',
252
- 'vste',
253
- 'nord',
254
- 'van der',
255
- 'bin',
256
- 'ibn',
257
- 'war',
258
- 'fitz',
259
- 'alam',
260
- 'di',
261
- 'erch',
262
- 'fetch',
263
- 'nga',
264
- 'ka',
265
- 'soder',
266
- 'lille',
267
- 'upp',
268
- 'ua',
269
- 'te',
270
- 'ni',
271
- 'bint',
272
- 'von und zu',
273
- 'vast',
274
- 'vestre',
275
- 'over',
276
- 'syd',
277
- 'mac',
278
- 'nin',
279
- 'nic',
280
- 'putri',
281
- 'bet',
282
- 'verch',
283
- 'norr',
284
- 'bath',
285
- 'della',
286
- 'van',
287
- 'ben',
288
- 'du',
289
- 'stor',
290
- 'das',
291
- 'neder',
292
- 'abu',
293
- 'degli',
294
- 'vre',
295
- 'ait',
296
- 'ny',
297
- 'opp',
298
- 'pour',
299
- 'kil',
300
- 'der',
301
- 'oz',
302
- 'von',
303
- 'at',
304
- 'nedre',
305
- 'van den',
306
- 'setia',
307
- 'ap',
308
- 'gil',
309
- 'myljom',
310
- 'van de',
311
- 'stre',
312
- 'dele',
313
- 'mck',
314
- 'de',
315
- 'mellom',
316
- 'mhic',
317
- 'binti',
318
- 'ath',
319
- 'binte',
320
- 'snder',
321
- 'sre',
322
- 'ned',
323
- 'ter',
324
- 'bar',
325
- 'le',
326
- 'mala',
327
- 'ost',
328
- 'syndre',
329
- 'sr',
330
- 'bat',
331
- 'sndre',
332
- 'austre',
333
- 'putra',
334
- 'putera',
335
- 'av',
336
- 'lu',
337
- 'vetch',
338
- 'ver',
339
- 'puteri',
340
- 'mc',
341
- 'tre',
342
- 'st']
343
-
344
- #suppress all the unwanted suffixes from a string.
345
- #name_del file can be modified if more or less suffixes want to be suppressed
346
-
347
- name_del = ['2nd', '3rd', 'Jr', 'Jr.', 'Junior', 'Sr', 'Sr.', 'Senior']
348
-
349
-
350
- def name_delete(string):
351
- for elmt in name_del:
352
- if f" {elmt}" in string:
353
- return string.replace(f" {elmt}","")
354
- return string
355
-
356
- def ln_suff_merge(string):
357
- for suff in ln_suff:
358
- if f" {suff} " in string or string.startswith(f"{suff} "):
359
- return string.replace(f"{suff} ",suff.replace(" ",""))
360
- return string
361
-
362
- #normalize a string dat that represents often a name.
363
-
364
- def normalize(data):
365
- normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore')
366
- val = normal.decode("utf-8")
367
- # delete unwanted elmt
368
- val = name_delete(val)
369
- # lower full name in upper
370
- val = re.sub(r"[A-Z]{3,}", lambda x: x.group().lower(), val)
371
- # add space in front of upper case
372
- val = re.sub(r"(\w)([A-Z])", r"\1 \2", val)
373
- # Lower case
374
- val = val.lower()
375
- # remove special characters
376
- val = re.sub('[^A-Za-z0-9 ]+', ' ', val)
377
- # remove multiple spaces
378
- val = re.sub(' +', ' ', val)
379
- # remove trailing spaces
380
- val = val.strip()
381
- # suffix merge
382
- val = ln_suff_merge(val)
383
-
384
- return val
385
-
386
-
387
- def main_inventors( research_key_words , details , size):
388
-
389
- dic_patents , dic_ranked = ranking_patents(research_key_words , details)
390
- dic_patents_co_inventors = {}
391
-
392
-
393
- for patent in list(dic_ranked.keys())[:size]:
394
- for k in range(len(dic_patents[patent]["list_inventors"])):
395
-
396
- inventor_id = dic_patents[patent]["list_inventors"][k]["inventor_id"]
397
- inventor_name = dic_patents[patent]["list_inventors"][k]["inventor_first_name"] + " " + dic_patents[patent]["list_inventors"][k]["inventor_last_name"]
398
- inventor_name_norm = normalize(inventor_name).split()
399
- inventor_name_norm = inventor_name_norm[0] + " " + inventor_name_norm[-1]
400
-
401
- if inventor_name_norm not in dic_patents_co_inventors:
402
- dic_patents_co_inventors[inventor_name_norm] = {}
403
- dic_patents_co_inventors[inventor_name_norm]["Inventor's name"] = inventor_name
404
- dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"] = inventor_id
405
- dic_patents_co_inventors[inventor_name_norm]["Number of occurence"] = 1
406
- dic_patents_co_inventors[inventor_name_norm]["Number of related citations"] = dic_patents[patent]["number_citations"]
407
-
408
- else:
409
- if inventor_id not in dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"] :
410
- dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"] += ", " + inventor_id
411
- if inventor_name not in dic_patents_co_inventors[inventor_name_norm]["Inventor's name"] :
412
- dic_patents_co_inventors[inventor_name_norm]["Inventor's name"] += ", " + inventor_name
413
- dic_patents_co_inventors[inventor_name_norm]["Number of occurence"] += 1
414
- dic_patents_co_inventors[inventor_name_norm]["Number of related citations"] += dic_patents[patent]["number_citations"]
415
-
416
-
417
- dic_patents_co_inventors = {k: v for k, v in sorted(dic_patents_co_inventors.items(), key=lambda item: item[1]["Number of occurence"] , reverse = True)}
418
-
419
- if dic_patents_co_inventors == {}:
420
-
421
-
422
- return "No patent, select other key words"
423
- else:
424
-
425
- for inventor_name_norm in list(dic_patents_co_inventors.keys()):
426
- list_inventors = dic_patents_co_inventors[inventor_name_norm]["PatentsView inventor's id"].split(", ")
427
- work_count = 0
428
- cited_by_count = 0
429
-
430
- for elem in list_inventors:
431
- url = "https://api.patentsview.org/inventors/query?q={%22inventor_id%22:[%22" + elem + "%22]}&f=[%22inventor_total_num_patents%22,%22patent_num_cited_by_us_patents%22]"
432
- data = get_data(url)["inventors"][0]
433
- work_count += int(data["inventor_total_num_patents"])
434
- for k in range(len(data["patents"])):
435
- cited_by_count += int(data["patents"][k]["patent_num_cited_by_us_patents"])
436
-
437
- dic_patents_co_inventors[inventor_name_norm]["Number of patents"] = work_count
438
- dic_patents_co_inventors[inventor_name_norm]["Number of US patents citations"] = cited_by_count
439
-
440
-
441
-
442
-
443
- return pd.DataFrame(dic_patents_co_inventors , index = ["Inventor's name", "PatentsView inventor's id", "Number of occurence" , "Number of patents" ,"Number of US patents citations" , "Number of related citations"]).T.style.hide(axis="index")
444
-
445
-
446
-
447
- def map_inventors(research_key_words , details , size):
448
- display = False
449
- dic_patents , dic_ranked = ranking_patents(research_key_words , details)
450
- dic_patents_co_inventors = {}
451
- count = 0
452
-
453
- for patent in list(dic_ranked.keys())[:size]:
454
- for k in range(len(dic_patents[patent]["list_inventors"])):
455
-
456
- dic_patents_co_inventors[count] = {}
457
-
458
- dic_patents_co_inventors[count]["latitude"] = dic_patents[patent]["list_inventors"][k]["inventor_latitude"]
459
- dic_patents_co_inventors[count]["longitude"] = dic_patents[patent]["list_inventors"][k]["inventor_longitude"]
460
- dic_patents_co_inventors[count]["longitude"] = dic_patents[patent]["list_inventors"][k]["inventor_longitude"]
461
- dic_patents_co_inventors[count]["inventor_name"] = str(dic_patents[patent]["list_inventors"][k]["inventor_first_name"]) + " " + str(dic_patents[patent]["list_inventors"][k]["inventor_last_name"])
462
- dic_patents_co_inventors[count]["patent_date"] = dic_patents[patent]["date"]
463
- count += 1
464
-
465
- if dic_patents_co_inventors == {}:
466
- return "No patent, select other key words"
467
-
468
-
469
- map_df = pd.DataFrame(dic_patents_co_inventors).T
470
- map_df["longitude"]=map_df['longitude'].astype(float)
471
- map_df['latitude']=map_df['latitude'].astype(float)
472
- map_df = map_df[map_df["latitude"].notnull()]
473
-
474
- return map_df
475
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/preqin_companies_IEA.tsv DELETED
The diff for this file is too large to render. See raw diff
 
Climate_site/python_scripts/read_me.txt DELETED
@@ -1,13 +0,0 @@
1
- ---
2
- title: SynapseProject
3
- emoji: 🌍
4
- colorFrom: yellow
5
- colorTo: blue
6
- sdk: streamlit
7
- sdk_version: 1.25.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Climate_site/python_scripts/related_companies.json DELETED
The diff for this file is too large to render. See raw diff
 
Climate_site/python_scripts/related_scientist.py DELETED
@@ -1,366 +0,0 @@
1
- ##packages code
2
-
3
-
4
- import pandas as pd
5
- import streamlit as st
6
- import numpy as np
7
- import json, requests
8
- #from pandas.io.json import json_normalize
9
- from tqdm import tqdm
10
-
11
-
12
- @st.cache_data # 👈 Add the caching decorator
13
- def load_data():
14
- url = "Synapse_project/Climate_site/python_scripts/institutions.tsv"
15
- dic = pd.read_csv(url, delimiter = "\t" , index_col = 1).to_dict('index')
16
- return dic
17
-
18
- dic_institutions = load_data()
19
-
20
-
21
- dic_country_codes = {'Europe': ['AD',
22
- 'AL',
23
- 'AT',
24
- 'BE',
25
- 'BG',
26
- 'BY',
27
- 'CZ',
28
- 'DE',
29
- 'DK',
30
- 'EE',
31
- 'FI',
32
- 'FR',
33
- 'GR',
34
- 'HU',
35
- 'IE',
36
- 'IS',
37
- 'IT',
38
- 'LI',
39
- 'LT',
40
- 'LU',
41
- 'LV',
42
- 'MK',
43
- 'MT',
44
- 'NL',
45
- 'NO',
46
- 'PL',
47
- 'PT',
48
- 'RO',
49
- 'RU',
50
- 'SE',
51
- 'SI',
52
- 'SK',
53
- 'SM',
54
- 'UA',
55
- 'VA',
56
- 'BA',
57
- 'HR',
58
- 'MD',
59
- 'MC',
60
- 'ME',
61
- 'RS',
62
- 'ES',
63
- 'CH',
64
- 'GB'],
65
- 'Asia': ['AF',
66
- 'AM',
67
- 'AZ',
68
- 'BD',
69
- 'BH',
70
- 'BN',
71
- 'BT',
72
- 'CN',
73
- 'CY',
74
- 'GE',
75
- 'ID',
76
- 'IL',
77
- 'IN',
78
- 'IQ',
79
- 'IR',
80
- 'JO',
81
- 'JP',
82
- 'KG',
83
- 'KP',
84
- 'KR',
85
- 'KW',
86
- 'LB',
87
- 'MM',
88
- 'MN',
89
- 'MV',
90
- 'MY',
91
- 'NP',
92
- 'OM',
93
- 'PH',
94
- 'PK',
95
- 'QA',
96
- 'SA',
97
- 'SG',
98
- 'SY',
99
- 'TH',
100
- 'TJ',
101
- 'TM',
102
- 'TR',
103
- 'UZ',
104
- 'VN',
105
- 'YE',
106
- 'KH',
107
- 'TL',
108
- 'KZ',
109
- 'LA',
110
- 'LK',
111
- 'AE'],
112
- 'North America': ['AG',
113
- 'BB',
114
- 'BS',
115
- 'BZ',
116
- 'CA',
117
- 'CR',
118
- 'CU',
119
- 'DM',
120
- 'DO',
121
- 'GT',
122
- 'GT',
123
- 'HN',
124
- 'JM',
125
- 'MX',
126
- 'NI',
127
- 'PA',
128
- 'TT',
129
- 'US',
130
- 'SV',
131
- 'GD',
132
- 'KN',
133
- 'LC',
134
- 'VC'],
135
- 'Africa': ['AO',
136
- 'BF',
137
- 'BI',
138
- 'BJ',
139
- 'BW',
140
- 'CD',
141
- 'CG',
142
- 'CI',
143
- 'CM',
144
- 'CV',
145
- 'DJ',
146
- 'EG',
147
- 'ER',
148
- 'ET',
149
- 'GA',
150
- 'GH',
151
- 'GM',
152
- 'GN',
153
- 'GW',
154
- 'KE',
155
- 'LR',
156
- 'LS',
157
- 'LY',
158
- 'MG',
159
- 'ML',
160
- 'MR',
161
- 'MU',
162
- 'MW',
163
- 'MZ',
164
- 'NA',
165
- 'NE',
166
- 'NG',
167
- 'RW',
168
- 'SC',
169
- 'SD',
170
- 'SL',
171
- 'SN',
172
- 'SO',
173
- 'ST',
174
- 'TG',
175
- 'TN',
176
- 'TZ',
177
- 'UG',
178
- 'ZM',
179
- 'ZW',
180
- 'DZ',
181
- 'CF',
182
- 'TD',
183
- 'KM',
184
- 'GQ',
185
- 'MA',
186
- 'ZA',
187
- 'SZ'],
188
- 'South America': ['AR',
189
- 'BO',
190
- 'BR',
191
- 'CL',
192
- 'CO',
193
- 'EC',
194
- 'GY',
195
- 'PE',
196
- 'PY',
197
- 'SR',
198
- 'UY',
199
- 'VE'],
200
- 'Oceania': ['AU',
201
- 'FJ',
202
- 'KI',
203
- 'MH',
204
- 'NR',
205
- 'NZ',
206
- 'PG',
207
- 'PW',
208
- 'SB',
209
- 'TO',
210
- 'TV',
211
- 'VU',
212
- 'FM',
213
- 'WS']}
214
-
215
-
216
- #################### General Functions #############################
217
-
218
- def URL(base_URL , entity_type , filters):
219
- url = base_URL + entity_type + filters
220
- return url
221
-
222
-
223
- def get_data(url):
224
- url = requests.get(url)
225
- text = url.text
226
- import json
227
- data = json.loads(text)
228
- return data
229
-
230
- ## selecting the ids we want
231
-
232
-
233
- def author_id_from_name(name):
234
-
235
- dic_names = {}
236
-
237
- name = name.title()
238
-
239
- url = "https://api.openalex.org/authors?search=" + name + "&per_page=200&mailto=emma_scharfmann@berkeley.edu"
240
-
241
- data = get_data(url)["results"]
242
-
243
- for k in range(len(data)):
244
- author_id = data[k]["id"][21:]
245
- dic_names[author_id] = {}
246
- dic_names[author_id]["author_name"] = data[k]["display_name"]
247
-
248
- dic_names[author_id]["number_of_works"] = data[k]["works_count"]
249
- dic_names[author_id]["number_of_citations"] = data[k]["cited_by_count"]
250
-
251
- dic_names[author_id]["field_of_study"] = ", ".join([ data[k]["x_concepts"][j]["display_name"] for j in range(min(5,len(data[k]["x_concepts"])))])
252
-
253
- dic_names[author_id]["last_known_institution"] = None
254
- dic_names[author_id]["country_code"] = None
255
-
256
- if data[k]["last_known_institution"] != None:
257
- dic_names[author_id]["last_known_institution"] = data[k]["last_known_institution"]["display_name"]
258
- dic_names[author_id]["country_code"] = data[k]["last_known_institution"]["country_code"]
259
-
260
- dic_names[author_id]["orcid"] = data[k]["orcid"]
261
-
262
-
263
- return pd.DataFrame(dic_names).T , [ ( k , ", ".join([ elem["author_name"] , str(elem["last_known_institution"]) , str(elem["field_of_study"].split(", ")[0]) , "Number of works: " + str(elem["number_of_works"]) ] ) ) for k , elem in dic_names.items()]
264
-
265
-
266
-
267
-
268
-
269
- def from_author_id(main_author_ids, year, country_code , size):
270
-
271
- dic_main_workers = {}
272
-
273
-
274
- for main_author_id in main_author_ids:
275
-
276
- url = "https://api.openalex.org/works?filter=author.id:" + main_author_id + ",publication_year:>" + str(year) + "&per_page=200&mailto=emma_scharfmann@berkeley.edu"
277
-
278
- data = get_data(url)["results"]
279
-
280
- for k in tqdm(range(len(data))):
281
- work_id = data[k]["id"][21:]
282
- for j in range(len(data[k]["authorships"])):
283
- author_id = data[k]["authorships"][j]["author"]["id"][21:]
284
-
285
- if author_id != main_author_id:
286
- if author_id not in dic_main_workers:
287
- dic_main_workers[author_id] = {}
288
- dic_main_workers[author_id]["author_name"] = data[k]["authorships"][j]["author"]["display_name"]
289
- dic_main_workers[author_id]["co_authors"] = 0
290
- dic_main_workers[author_id]["citations"] = 0
291
- dic_main_workers[author_id]["institution"] = None
292
- dic_main_workers[author_id]["country_code"] = None
293
- dic_main_workers[author_id]["id"] = None
294
- dic_main_workers[author_id]["longitude"] = None
295
- dic_main_workers[author_id]["latitude"] = None
296
-
297
- if dic_main_workers[author_id]["institution"] == None and data[k]["authorships"][j]["institutions"] != [] and "display_name" in data[k]["authorships"][j]["institutions"][0]:
298
- dic_main_workers[author_id]["institution"] = data[k]["authorships"][j]["institutions"][0]["display_name"]
299
- if dic_main_workers[author_id]["country_code"] == None and data[k]["authorships"][j]["institutions"] != [] and "country_code" in data[k]["authorships"][j]["institutions"][0]:
300
- dic_main_workers[author_id]["country_code"] = data[k]["authorships"][j]["institutions"][0]["country_code"]
301
- if dic_main_workers[author_id]["id"] == None and data[k]["authorships"][j]["institutions"] != [] and "id" in data[k]["authorships"][j]["institutions"][0] and data[k]["authorships"][j]["institutions"][0]["id"] != None:
302
- dic_main_workers[author_id]["id"] = data[k]["authorships"][j]["institutions"][0]["id"][21:]
303
-
304
-
305
-
306
- dic_main_workers[author_id]["co_authors"] += 1
307
-
308
- url = "https://api.openalex.org/works?filter=referenced_works:" + work_id + ",publication_year:>" + str(year) + "&per_page=200&mailto=emma_scharfmann@berkeley.edu"
309
-
310
-
311
-
312
- citations_data = get_data(url)["results"]
313
- for i in range(len(citations_data)):
314
- citing_work_id = citations_data[i]["id"][21:]
315
- for j in range(len(citations_data[i]["authorships"])):
316
- citing_author_id = citations_data[i]["authorships"][j]["author"]["id"][21:]
317
-
318
- if citing_author_id != main_author_id:
319
- if citing_author_id not in dic_main_workers:
320
- dic_main_workers[citing_author_id] = {}
321
- dic_main_workers[citing_author_id]["author_name"] = citations_data[i]["authorships"][j]["author"]["display_name"]
322
- dic_main_workers[citing_author_id]["co_authors"] = 0
323
- dic_main_workers[citing_author_id]["citations"] = 0
324
- dic_main_workers[citing_author_id]["institution"] = None
325
- dic_main_workers[citing_author_id]["country_code"] = None
326
- dic_main_workers[citing_author_id]["id"] = None
327
- dic_main_workers[citing_author_id]["longitude"] = None
328
- dic_main_workers[citing_author_id]["latitude"] = None
329
-
330
- if dic_main_workers[citing_author_id]["institution"] == None and (citations_data[i]["authorships"][j]["institutions"] != [] and "display_name" in citations_data[i]["authorships"][j]["institutions"][0]):
331
- dic_main_workers[citing_author_id]["institution"] = citations_data[i]["authorships"][j]["institutions"][0]["display_name"]
332
- if dic_main_workers[citing_author_id]["country_code"] == None and (citations_data[i]["authorships"][j]["institutions"] != [] and "country_code" in citations_data[i]["authorships"][j]["institutions"][0] ):
333
- dic_main_workers[citing_author_id]["country_code"] = citations_data[i]["authorships"][j]["institutions"][0]["country_code"]
334
- if dic_main_workers[citing_author_id]["id"] == None and ( citations_data[i]["authorships"][j]["institutions"] != [] and "id" in citations_data[i]["authorships"][j]["institutions"][0] and citations_data[i]["authorships"][j]["institutions"][0]["id"] != None):
335
- dic_main_workers[citing_author_id]["id"] = citations_data[i]["authorships"][j]["institutions"][0]["id"][21:]
336
-
337
-
338
-
339
- dic_main_workers[citing_author_id]["citations"] += 1
340
-
341
-
342
- for author_id in dic_main_workers:
343
- if dic_main_workers[author_id]["id"] != None:
344
- institution_id = dic_main_workers[author_id]["id"]
345
- if institution_id in dic_institutions:
346
- geo_data = dic_institutions[institution_id]
347
- dic_main_workers[author_id]["longitude"] = geo_data["longitude"]
348
- dic_main_workers[author_id]["latitude"] = geo_data["latitude"]
349
-
350
-
351
- res = pd.DataFrame(dic_main_workers).T.sort_values("citations" , ascending = False)[['author_name', 'co_authors', 'citations', 'institution', 'country_code']]
352
-
353
- res_geo = pd.DataFrame(dic_main_workers).T.sort_values("citations" , ascending = False)[['author_name', 'co_authors', 'citations', 'institution', 'country_code','longitude', 'latitude']]
354
- res_geo = res_geo[res_geo["longitude"].notnull()]
355
- if country_code != False:
356
-
357
- if country_code in [ "Europe" , "North America" , "Asia" , "South America", "Oceania" , "Africa" ]:
358
-
359
- return res[res["country_code"].isin(dic_country_codes[country_code])].head(size) , res_geo[res_geo["country_code"].isin(dic_country_codes[country_code])].head(size)
360
-
361
- else:
362
- return res[res["country_code"] == country_code].head(size) , res_geo[res_geo["country_code"] == country_code].head(size)
363
- else:
364
- return res.head(size), res_geo.head(size)
365
-
366
-