Page MenuHomec4science

utils.js
No OneTemporary

File Metadata

Created
Tue, Jan 28, 17:07

utils.js

'use client'
import * as d3 from "d3";
import {useRef} from "react";
function freeTextSearch(
searchTerm,
num_results = 30,
searchEntity = 'research',
callback,
conceptsOrVectors,
searchData,
setSearchData
) {
console.log('freetextSearch')
console.log("searchEntity", searchEntity)
console.log("searchData", searchData)
console.log('conceptsOrVectors', conceptsOrVectors)
let freeTextSearchURL;
const BASE_URL = process.env.NEXT_PUBLIC_BACKEND_SERVER_ADDRESS; // Accessing the environment variable
if (conceptsOrVectors === 'concepts') {
// freeTextSearchURL = 'http://127.0.0.1:5000/concepts/submitAny';
console.log('base_url', BASE_URL)
freeTextSearchURL = `${BASE_URL}concepts/submitAny`;
} else if (conceptsOrVectors === 'vectors') {
// freeTextSearchURL = 'http://127.0.0.1:5000/vectors/freeTextSearch';
freeTextSearchURL = `${BASE_URL}vectors/freeTextSearch`;
} else {
//raise error
console.log("Error: conceptsOrVectors must be either 'concepts' or 'vectors', not ", conceptsOrVectors)
}
fetch(freeTextSearchURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: searchTerm,
num_results: num_results,
searchEntity: searchEntity
})
})
.then(response => response.json())
.then(data => callback(data, searchData, setSearchData))
.catch((error) => {
console.error('Error:', error);
});
}
export default freeTextSearch
export function getAutocompleteSuggestions(searchText, typeOfSearch) {
// console.log("searchTerm", searchTerm)
const BASE_URL = process.env.NEXT_PUBLIC_BACKEND_SERVER_ADDRESS; // Accessing the environment variable
const autocompleteURL = `${BASE_URL}concepts/autocomplete`;
console.log("autocompleteURL", autocompleteURL)
return fetch(autocompleteURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: searchText,
typeOfSearch: typeOfSearch
})
})
}
export function getDataForCollab(
callback,
defineSizeOfNodes,
yearsSelected,
checkedPublicationTypes,
arrayLabInfoRef,
) {
return new Promise((resolve, reject) => {
console.log("getSimilarities");
const BASE_URL = process.env.NEXT_PUBLIC_BACKEND_SERVER_ADDRESS; // Accessing the environment variable
// const similaritiesURL = 'http://127.0.0.1:5000/collaborations/similaritiesBetweenLabs'; // <-- Assuming this base URL
// const similaritiesURL = 'https://expert-finder.epfl.ch//collaborations/similaritiesBetweenLabs'; // <-- Assuming this base URL
const similaritiesURL = `${BASE_URL}collaborations/similaritiesBetweenLabs`;
fetch(similaritiesURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
let localData = data;
let dicoLabInfo = localData['dicoLabInfo'];
let linksData = localData['links'];
let filteredData = {}
for (let lab in dicoLabInfo) {
if (dicoLabInfo[lab].details[0].level === 'lab' ||
dicoLabInfo[lab].details[0].level === 'institute' ||
dicoLabInfo[lab].details[0].level === 'school') {
filteredData[lab] = dicoLabInfo[lab]
}
}
let filteredData2 = {}
for (let lab in filteredData) {
if (lab === filteredData[lab].newName) {
filteredData2[lab] = filteredData[lab]
}
}
dicoLabInfo = filteredData2
for (let lab in dicoLabInfo) {
dicoLabInfo[lab].id = lab
}
let arrayLabInfo = Object.keys(dicoLabInfo).map(function (key) {
return dicoLabInfo[key];
});
defineSizeOfNodes(
arrayLabInfo,
yearsSelected,
checkedPublicationTypes
);
arrayLabInfo.forEach(function (d) {
if (d.embedding2D === null) {
console.log('failed d', d)
}
d.x = d.embedding2D[0] * 50;
d.y = d.embedding2D[1] * 50;
});
let linksDataFiltered = []
for (let i = 0; i < linksData.length; i++) {
if (linksData[i].source in dicoLabInfo && linksData[i].target in dicoLabInfo) {
linksDataFiltered.push(linksData[i])
}
}
linksData = linksDataFiltered
// ... Rest of the data processing ...
arrayLabInfoRef.current = arrayLabInfo
console.log("arrayLabInfoRef.current", arrayLabInfoRef.current)
callback(linksData); // Assuming this is what you want to pass back
})
.catch(error => {
console.error("error", error);
});
})
}
export function wrap(text, width) {
text.each(function () {
var gnodeParent = d3.select(this.parentNode);
// console.log("gnodeParent", gnodeParent)
var gnodeParentData = gnodeParent._groups[0][0].__data__;
// console.log("gnodeParentData", gnodeParentData)
var text = d3.select(this),
words = text.text().split(" ").reverse(),
nwords = words.length,
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
x = text.attr("x"),
y = text.attr("y"),
dy = -(nwords + 1 / 2) * lineHeight / 2, //parseFloat(text.attr("dy")),
tspan = text.text(null)
.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", dy + "em");
while (word = words.pop()) {
// console.log("word", word)
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
// create a span with d3
tspan = text.append("tspan")
.text(word)
.attr("font-weight", "bold")
.attr("font-size", parseInt(gnodeParentData.size / 3) + "px")
.attr("dx", function () {
return -this.getComputedTextLength() / 2
})
.attr("x", 0)
.attr("y", 0)
.attr("dy", ++lineNumber * lineHeight + dy + "em");
}
}
});
}
export function callbackAddConceptsToBoxes(data, searchData, setSearchData) {
console.log('callbackAddConceptsToBoxes')
console.log('received data', data)
console.log('received searchData', searchData)
console.log('received setSearchData', setSearchData)
if (data['table'].length === 0) {
console.log('received data is empty')
return
}
let myNewConceptsToAddBoxes_with_duplicates = [
...searchData['conceptsToAddBoxes'],
...data['conceptsToAddBoxes']
]
let myNewConceptsToAddBoxes = []
const seen = new Set();
for (const item of myNewConceptsToAddBoxes_with_duplicates) {
if (!seen.has(item.id)) {
seen.add(item.id);
myNewConceptsToAddBoxes.push(item);
}
}
let myNewConceptsOfPeople = {
...searchData['conceptsOfPeople'],
...data['conceptsOfPeople']
}
let myNewTableColumnsInRightOrder = [
...new Set([
...searchData['tableColumnsInRightOrder'],
...data['tableColumnsInRightOrder']
])
]
// create new table with all rows from both tables
// Create lookup objects.
let lookupData = {};
let lookupSearchData = {};
data['table'].forEach(item => lookupData[item.ID] = item);
searchData['table'].forEach(item => lookupSearchData[item.ID] = item);
// Get the unique keys from both data sets
let setOfKeys1 = new Set(data['table'].flatMap(item => Object.keys(item)));
let setOfKeys2 = new Set(searchData['table'].flatMap(item => Object.keys(item)));
// Create a merged array
let mergedArray = [];
// Get the union of keys from both datasets
let allKeys = [...new Set([...setOfKeys1, ...setOfKeys2])];
// Iterate through the IDs in both datasets
let allIDs = [...new Set([...data['table'].map(item => item.ID), ...searchData['table'].map(item => item.ID)])];
allIDs.forEach(id => {
let baseData = lookupData[id] || {};
let searchItem = lookupSearchData[id] || {};
let mergedItem = {ID: id}; // Initialize with ID
allKeys.forEach(key => {
mergedItem[key] = baseData[key] || searchItem[key] || 0;
});
mergedArray.push(mergedItem);
});
// Now mergedArray will have your required data
let myNewData = {
...searchData,
'conceptsToAddBoxes': myNewConceptsToAddBoxes,
'conceptsOfPeople': myNewConceptsOfPeople,
'tableColumnsInRightOrder': myNewTableColumnsInRightOrder,
'table': mergedArray
}
setSearchData(myNewData)
}

Event Timeline