Search in sources :

Example 16 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class TypeConverters method toStringList.

/**
 * Attempts to convert the given object into a list of strings.
 * @param object element to convert
 * @return list of strings
 */
public static List<String> toStringList(Object object) {
    if (object instanceof String) {
        return Arrays.asList((String) object);
    } else if (object instanceof Number) {
        return Arrays.asList(((Number) object).toString());
    } else if (object instanceof Number[]) {
        return Arrays.stream((Number[]) object).map(Object::toString).collect(toList());
    } else if (object.getClass().isArray()) {
        final int length = Array.getLength(object);
        final List<String> result = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            result.add(Array.get(object, i).toString());
        }
        return result;
    } else if (object instanceof PySequence) {
        final int length = ((PySequence) object).__len__();
        final List<String> result = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            final PyObject item = ((PySequence) object).__finditem__(i);
            result.add(item instanceof PyNone ? "none" : item.toString());
        }
        return result;
    } else {
        return Arrays.asList(object.toString());
    }
}
Also used : PyNone(org.python.core.PyNone) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) ArrayList(java.util.ArrayList) PyString(org.python.core.PyString) PySequence(org.python.core.PySequence) PyObject(org.python.core.PyObject)

Example 17 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class NXMetaDataProvider method createNexusGroupData.

public NexusGroupData createNexusGroupData(Object object) {
    NexusGroupData groupData = null;
    if (object instanceof String) {
        groupData = new NexusGroupData((String) object);
    } else if (object instanceof PyString) {
        groupData = new NexusGroupData(((PyString) object).getString());
    } else if (object instanceof Integer) {
        groupData = new NexusGroupData((Integer) object);
    // } else if (object instanceof Long) {
    // Double dblValue = ((Number) object).doubleValue();
    // double[] dblData = new double[] { dblValue };
    // groupData = new NexusGroupData(dblData);
    } else if (object instanceof Number) {
        groupData = new NexusGroupData(((Number) object).doubleValue());
    } else if (object instanceof double[]) {
        groupData = new NexusGroupData((double[]) object);
    } else if (object instanceof int[]) {
        groupData = new NexusGroupData((int[]) object);
    } else if (object instanceof PyFloat) {
        groupData = new NexusGroupData(((PyFloat) object).asDouble());
    } else if (object instanceof PyInteger) {
        // store as NX_FLOAT64 since a lot of things may pass an int for an expect a double on readback
        groupData = new NexusGroupData((double) ((PyInteger) object).getValue());
    } else if (object instanceof long[]) {
        final long[] data = (long[]) object;
        final int dataLen = data.length;
        final double[] dblData = new double[dataLen];
        for (int i = 0; i < dataLen; i++) {
            dblData[i] = data[i];
        }
        groupData = new NexusGroupData(dblData);
    } else if (object instanceof Number[]) {
        Number[] data = (Number[]) object;
        int dataLen = data.length;
        double[] dblData = new double[dataLen];
        for (int i = 0; i < dataLen; i++) {
            dblData[i] = data[i].doubleValue();
        }
        groupData = new NexusGroupData(dblData);
    } else if (object instanceof PyList) {
        // coerce PyList into double array.
        final int dataLen = ((PyList) object).__len__();
        final double[] dblData = new double[dataLen];
        for (int i = 0; i < dataLen; i++) {
            final PyObject item = ((PyList) object).__finditem__(i);
            if (item instanceof PyNone) {
                dblData[i] = Double.NaN;
            } else {
                dblData[i] = Double.valueOf(item.toString());
            }
        }
        groupData = new NexusGroupData(dblData);
    } else if (object instanceof PySequence) {
        // coerce PySequence into double array.
        final int dataLen = ((PySequence) object).__len__();
        final double[] dblData = new double[dataLen];
        for (int i = 0; i < dataLen; i++) {
            final PyObject item = ((PySequence) object).__finditem__(i);
            if (item instanceof PyNone) {
                dblData[i] = Double.NaN;
            } else {
                dblData[i] = Double.valueOf(item.toString());
            }
        }
        groupData = new NexusGroupData(dblData);
    } else {
        logger.error("unhandled data type: {} - this dataset might not have been written correctly to Nexus file.", object.getClass().getName());
        groupData = new NexusGroupData(object.toString());
    }
    return groupData;
}
Also used : PyFloat(org.python.core.PyFloat) PyString(org.python.core.PyString) PyInteger(org.python.core.PyInteger) PyString(org.python.core.PyString) PyInteger(org.python.core.PyInteger) PyNone(org.python.core.PyNone) PyList(org.python.core.PyList) PySequence(org.python.core.PySequence) PyObject(org.python.core.PyObject) NexusGroupData(gda.data.nexus.extractor.NexusGroupData)

Example 18 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class ScriptBasedItem method getPositions.

@Override
public Map<Scannable, Object> getPositions(Properties properties) throws WorkflowException {
    PyObject argument = getFunctionArgument(properties);
    String source = readFile();
    return evaluateUserFunctions(source, argument);
}
Also used : PyObject(org.python.core.PyObject)

Example 19 with PyObject

use of org.python.core.PyObject in project gda-core by openGDA.

the class ScriptBasedItem method evaluateUserFunctions.

private Map<Scannable, Object> evaluateUserFunctions(String source, PyObject argument) throws WorkflowException {
    Map<Scannable, Object> targetPositions = new HashMap<>();
    for (Map.Entry<Scannable, String> scannableEntry : functionsPerScannable.entrySet()) {
        Scannable scannable = scannableEntry.getKey();
        String functionName = scannableEntry.getValue();
        PyObject function = getFunction(source, functionName);
        Object result = evaluateFunction(functionName, function, argument);
        targetPositions.put(scannable, result);
    }
    return targetPositions;
}
Also used : HashMap(java.util.HashMap) Scannable(gda.device.Scannable) PyObject(org.python.core.PyObject) HashMap(java.util.HashMap) Map(java.util.Map) PyObject(org.python.core.PyObject)

Example 20 with PyObject

use of org.python.core.PyObject in project DALC-team05 by nhy31.

the class RecipeController method getTest.

@RequestMapping(value = "/recipe/recipe_detail")
public ModelAndView getTest(HttpServletRequest request, RedirectAttributes redirect, Model model, @RequestParam("recipe_code") int recipe_code) {
    HttpSession session = request.getSession();
    Member member = (Member) session.getAttribute("loginMember");
    String allergy = member.getMember_allergy();
    System.out.println("알레르기" + allergy);
    String[] array = allergy.split(",");
    List<String> danger = new ArrayList<>();
    int alle = 0;
    ModelAndView mav = new ModelAndView();
    recipeService.hitsCount(recipe_code);
    Recipe clickRecipe = recipeService.getRecipeFromCode(recipe_code);
    clickRecipe.setOrders(recipeService.getOrders(recipe_code));
    List<rUse> useList = recipeService.getUses(recipe_code);
    clickRecipe.setUses(useList);
    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
        for (int j = 0; j < useList.size(); j++) {
            if (useList.get(j).getrUse_name().equals(array[i])) {
                System.out.println("알러지재료적발 " + array[i]);
                danger.add(array[i]);
                alle = 1;
            }
        }
    }
    System.out.println("알러지재료" + danger.toString());
    mav.addObject("danger", danger.toString());
    mav.addObject("alle", alle);
    mav.addObject("clickRecipe", clickRecipe);
    // 입력받은 recipecode -> 하윤 toString으로 변환 추가
    String inputData = Integer.toString(recipe_code);
    System.out.println("인풋데이터" + inputData);
    interpreter = new PythonInterpreter();
    // 자카드 유사도 함수
    interpreter.exec("def jaccard_similarity(s1, s2):\n" + "	s1 = set(s1)\n" + "	s2 = set(s2)\n" + "	return float(len(s1 & s2)) / float(len(s1 | s2))");
    interpreter.exec("import csv");
    // 파일 read
    // 절대경로(본인컴퓨터에 맞춰서 변경)
    interpreter.exec("f = open('/git/DALC-team05/src/main/resources/csv/recipes.csv', 'r')");
    interpreter.exec("reader = csv.reader(f)");
    interpreter.exec("header = next(reader)");
    // recipecode로 해당 내용 찾아서 input배열로 만듦
    interpreter.exec("input = list()");
    interpreter.exec("i = 0");
    interpreter.exec("for row in reader:\n" + "#	print(row)\n" + "	if row[0] == str(" + inputData + "): \n" + "		input = row \n" + "		break\n" + "	i+=1");
    interpreter.exec("#print(input)");
    // PyObject o = interpreter.eval("input");
    // System.out.println("input: "+o.toString());
    interpreter.exec("f.close()");
    // 파일 read
    // 절대경로(본인컴퓨터에 맞춰서 변경)
    interpreter.exec("f = open('/git/DALC-team05/src/main/resources/csv/recipes.csv', 'r')");
    interpreter.exec("reader = csv.reader(f)");
    interpreter.exec("header = next(reader)");
    // recipe_list: recipe csv파일에 있는 레시피들에 대한 리스트
    // sim_list: 각 레시피에 대한 자카드 유사도를 담은 리스트
    interpreter.exec("recipe_list = list()");
    interpreter.exec("sim_list = list()");
    // csv파일을 한줄씩 읽은 뒤 자카드 유사도 계산 후 리스트에 저장
    interpreter.exec("i = 0");
    interpreter.exec("for row in reader:\n" + "	recipe_list.append(row)\n" + "#	print(recipe_list[i])\n" + "	sim_list.append(jaccard_similarity(row, input))\n" + "#	print(sim_list[i])\n" + "	i+=1");
    interpreter.exec("f.close()");
    // 유사도 상위 5개 (본인 포함 6개) 인덱스 추출
    interpreter.exec("top = sorted(range(len(sim_list)), key=lambda i: sim_list[i])[-6:]");
    interpreter.exec("#print(top)");
    // PyObject ob = interpreter.eval("top");
    // System.out.println("상위1: "+ob.toString());
    // // 본인을 제외한 유사도 상위 레시피 5개
    interpreter.exec("result = []\n");
    interpreter.exec("for k in top:\n" + "#	print(k)\n" + "#	print(recipe_list[k])\n" + "	if recipe_list[k][0] != input[0]:\n" + "#		print(recipe_list[k])\n" + "		result.append(recipe_list[k][0])\n" + "#		print(recipe_list[k][0])\n");
    // obj에 들어있는 list가 추천 된 레시피코드
    PyObject obj = interpreter.eval("result[:5]");
    // System.out.println("result: "+obj.toString());
    // recipeCode는 5가지 유사한 recipecode가 들어있는 배열
    String[] recipeCode = obj.toString().split("', '");
    recipeCode[0] = recipeCode[0].split("'")[1];
    recipeCode[4] = recipeCode[4].split("'")[0];
    List<Recipe> relatedList = new ArrayList<>();
    int i = 0;
    // 하윤추가 WEB띄우기
    for (String code : recipeCode) {
        System.out.println(code);
        int realCode = Integer.parseInt(code);
        relatedList.add(recipeService.getRecipeFromCode(realCode));
        System.out.println("0226확인 " + relatedList.get(i).getRecipe_title());
        i++;
    }
    mav.addObject("relatedList", relatedList);
    return mav;
}
Also used : dongduk.dalc05.aah.domain.rUse(dongduk.dalc05.aah.domain.rUse) Recipe(dongduk.dalc05.aah.domain.Recipe) HttpSession(javax.servlet.http.HttpSession) ArrayList(java.util.ArrayList) ModelAndView(org.springframework.web.servlet.ModelAndView) PythonInterpreter(org.python.util.PythonInterpreter) Member(dongduk.dalc05.aah.domain.Member) PyObject(org.python.core.PyObject) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

PyObject (org.python.core.PyObject)61 PyString (org.python.core.PyString)20 PyException (org.python.core.PyException)11 IOException (java.io.IOException)8 PyList (org.python.core.PyList)8 HashMap (java.util.HashMap)7 PyInteger (org.python.core.PyInteger)7 Serializable (java.io.Serializable)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 PyFloat (org.python.core.PyFloat)6 PythonInterpreter (org.python.util.PythonInterpreter)6 ArrayList (java.util.ArrayList)5 Test (org.junit.Test)5 PyLong (org.python.core.PyLong)5 PyNone (org.python.core.PyNone)5 PyStringMap (org.python.core.PyStringMap)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 List (java.util.List)4 File (java.io.File)3