Java Code Examples for com.jstarcraft.core.common.reflection.ReflectionUtility

The following examples show how to use com.jstarcraft.core.common.reflection.ReflectionUtility. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jstarcraft-core   Source File: ResourceAccessorProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean postProcessAfterInstantiation(final Object object, String name) throws BeansException {
    ReflectionUtility.doWithFields(object.getClass(), (field) -> {
        ResourceAccessor annotation = field.getAnnotation(ResourceAccessor.class);
        if (annotation == null) {
            return;
        }
        if (ResourceManager.class.isAssignableFrom(field.getType())) {
            // 装配仓储
            assembleStorage(object, field, annotation);
        } else {
            // 装配实例
            assembleInstance(object, field, annotation);
        }
    });
    return super.postProcessAfterInstantiation(object, name);
}
 
Example 2
Source Project: jstarcraft-core   Source File: JsonType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet resultSet, String[] names, SharedSessionContractImplementor session, Object object) throws HibernateException, SQLException {
    if (object == null) {
        return null;
    }
    String json = resultSet.getString(names[0]);
    String columnName = getColumnName(resultSet, names[0]);
    String fieldName = getFieldName(object.getClass(), columnName);
    Type type = null;
    try {
        type = ReflectionUtility.findField(object.getClass(), fieldName).getGenericType();
    } catch (Exception exception) {
        throw new StorageAccessException(exception);
    }
    Object value = JsonUtility.string2Object(json, type);
    return value;
}
 
Example 3
Source Project: jstarcraft-core   Source File: CacheAccessorProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean postProcessAfterInstantiation(final Object instance, final String name) throws BeansException {
    ReflectionUtility.doWithFields(instance.getClass(), (field) -> {
        CacheAccessor annotation = field.getAnnotation(CacheAccessor.class);
        if (annotation == null) {
            return;
        }
        if (field.getType().equals(EntityManager.class)) {
            // 注入实体单位缓存服务
            assembleEntityManager(instance, name, field);
        } else if (field.getType().equals(RegionManager.class)) {
            // 注入区域单位缓存服务
            assembleRegionManager(instance, name, field);
        } else {
            String message = StringUtility.format("无法装配Bean[{}]的属性[{}]", name, field.getName());
            LOGGER.error(message);
            throw new CacheConfigurationException(message);
        }
    });
    return super.postProcessAfterInstantiation(instance, name);
}
 
Example 4
Source Project: jstarcraft-core   Source File: ClassDefinition.java    License: Apache License 2.0 6 votes vote down vote up
private ClassDefinition(int code, Class<?> clazz, TreeSet<PropertyDefinition> properties, Specification specification) {
    this.code = code;
    this.clazz = clazz;
    this.name = clazz.getName();
    this.specification = specification;
    this.properties = properties.toArray(new PropertyDefinition[properties.size()]);
    // 不是所有类型都有无参数构造器
    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        if (constructor.getParameterTypes().length == 0) {
            ReflectionUtility.makeAccessible(constructor);
            this.constructor = constructor;
            break;
        }
    }
    // if (this.constructor == null && !this.clazz.isEnum()) {
    // String message = StringUtility.format("类型[{}]缺乏无参数构造器,不符合编解码规范",
    // clazz.getName());
    // throw new CodecException(message);
    // }
}
 
Example 5
Source Project: jstarcraft-core   Source File: LockableAspect.java    License: Apache License 2.0 6 votes vote down vote up
private Object execute(Class<? extends LockableStrategy> clazz, ProceedingJoinPoint point, Signature signature) throws Throwable {
    Method method = ((MethodSignature) signature).getMethod();
    // 获取锁策略
    LockableStrategy strategy = strategies.get(method);
    if (strategy == null) {
        synchronized (method) {
            if (strategy == null) {
                strategy = ReflectionUtility.getInstance(clazz, method);
                strategies.put(method, strategy);
            }
        }
    }
    Object[] arguments = point.getArgs();
    try (Lockable lock = strategy.getLock(arguments)) {
        lock.open();
        return point.proceed(arguments);
    }
}
 
Example 6
Source Project: jstarcraft-example   Source File: MovieModelConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
private Model getModel(Class<? extends Model> clazz, DataSpace dataSpace, DataModule dataModule) throws Exception {
    Model model = ReflectionUtility.getInstance(clazz);
    EnvironmentContext context = EnvironmentFactory.getContext();
    Future<?> task = context.doTask(() -> {
        model.prepare(configuration, dataModule, dataSpace);
        model.practice();
    });
    task.get();
    return model;
}
 
Example 7
Source Project: jstarcraft-rns   Source File: PRankDModel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * initialization
 *
 * @throws ModelException if error occurs
 */
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
    super.prepare(configuration, model, space);
    similarityFilter = configuration.getFloat("recommender.sim.filter", 4F);
    float denominator = 0F;
    itemWeights = DenseVector.valueOf(itemSize);
    for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
        float numerator = scoreMatrix.getColumnScope(itemIndex);
        denominator = denominator < numerator ? numerator : denominator;
        itemWeights.setValue(itemIndex, numerator);
    }
    // compute item relative importance
    for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
        itemWeights.setValue(itemIndex, itemWeights.getValue(itemIndex) / denominator);
    }

    // compute item correlations by cosine similarity
    // TODO 修改为配置枚举
    try {
        Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
        MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
        itemCorrelations = new SymmetryMatrix(scoreMatrix.getColumnSize());
        correlation.calculateCoefficients(scoreMatrix, true, itemCorrelations::setValue);
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
}
 
Example 8
Source Project: jstarcraft-rns   Source File: SoRegModel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
    super.prepare(configuration, model, space);
    userFactors = DenseMatrix.valueOf(userSize, factorSize);
    userFactors.iterateElement(MathCalculator.SERIAL, (scalar) -> {
        scalar.setValue(RandomUtility.randomFloat(1F));
    });
    itemFactors = DenseMatrix.valueOf(itemSize, factorSize);
    itemFactors.iterateElement(MathCalculator.SERIAL, (scalar) -> {
        scalar.setValue(RandomUtility.randomFloat(1F));
    });

    // TODO 修改为配置枚举
    try {
        Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
        MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
        socialCorrelations = new SymmetryMatrix(socialMatrix.getRowSize());
        correlation.calculateCoefficients(socialMatrix, false, socialCorrelations::setValue);
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }

    for (MatrixScalar term : socialCorrelations) {
        float similarity = term.getValue();
        if (similarity == 0F) {
            continue;
        }
        similarity = (1F + similarity) / 2F;
        term.setValue(similarity);
    }
}
 
Example 9
Source Project: jstarcraft-rns   Source File: AbstractTask.java    License: Apache License 2.0 5 votes vote down vote up
protected AbstractTask(Class<? extends Model> clazz, Configurator configurator) {
    this.configurator = configurator;
    Long seed = configurator.getLong("recommender.random.seed");
    if (seed != null) {
        RandomUtility.setSeed(seed);
    }
    this.model = (Model) ReflectionUtility.getInstance(clazz);
}
 
Example 10
Source Project: jstarcraft-ai   Source File: QualityProbability.java    License: Apache License 2.0 5 votes vote down vote up
public QualityProbability(Class<? extends RandomGenerator> randomClazz, int randomSeed, Class<? extends AbstractIntegerDistribution> distributionClazz, Object... distributionParameters) {
    this.randomSeed = randomSeed;
    this.random = ReflectionUtility.getInstance(randomClazz, randomSeed);
    this.distributionParameters = distributionParameters;
    distributionParameters = ArrayUtility.insert(0, distributionParameters, random);
    this.distribution = ReflectionUtility.getInstance(distributionClazz, distributionParameters);
}
 
Example 11
Source Project: jstarcraft-ai   Source File: QualityProbability.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterLoad() {
    try {
        random = (RandomGenerator) ReflectionUtility.getInstance(Class.forName(randomClass), randomSeed);
        Object[] parameters = ArrayUtility.insert(0, distributionParameters, random);
        distribution = (AbstractIntegerDistribution) ReflectionUtility.getInstance(Class.forName(distributionClass), parameters);
    } catch (Exception exception) {
    }
}
 
Example 12
Source Project: jstarcraft-ai   Source File: QuantityProbability.java    License: Apache License 2.0 5 votes vote down vote up
public QuantityProbability(Class<? extends RandomGenerator> randomClazz, int randomSeed, Class<? extends AbstractRealDistribution> distributionClazz, Object... distributionParameters) {
    this.randomSeed = randomSeed;
    this.random = ReflectionUtility.getInstance(randomClazz, randomSeed);
    this.distributionParameters = distributionParameters;
    distributionParameters = ArrayUtility.insert(0, distributionParameters, random);
    this.distribution = ReflectionUtility.getInstance(distributionClazz, distributionParameters);
}
 
Example 13
Source Project: jstarcraft-ai   Source File: QuantityProbability.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterLoad() {
    try {
        random = (RandomGenerator) ReflectionUtility.getInstance(Class.forName(randomClass), randomSeed);
        Object[] parameters = ArrayUtility.insert(0, distributionParameters, random);
        distribution = (AbstractRealDistribution) ReflectionUtility.getInstance(Class.forName(distributionClass), parameters);
    } catch (Exception exception) {
    }
}
 
Example 14
Source Project: jstarcraft-core   Source File: ScriptFunctionTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMethod() throws Exception {
    ScriptContext context = new ScriptContext();
    // 此处故意使用ScriptExpressionTestCase.class,测试是否冲突.
    context.useClasses(ScriptFunctionTestCase.class);
    ReflectionUtility.doWithLocalMethods(ScriptFunctionTestCase.class, (method) -> {
        if (Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers())) {
            context.useMethod(method.getName() + "Method", method);
        }
    });
    ScriptFunction function = getMethodFunction(context);
    int number = 10;
    Number fibonacci = function.doWith(Number.class, number);
    Assert.assertThat(fibonacci.doubleValue(), CoreMatchers.equalTo(fibonacci(number)));
}
 
Example 15
Source Project: jstarcraft-core   Source File: MethodAccessor.java    License: Apache License 2.0 5 votes vote down vote up
public MethodAccessor(Method method, String name, boolean unique, Comparator comparator) {
    ReflectionUtility.makeAccessible(method);
    this.method = method;
    this.name = name;
    this.unique = unique;
    this.comparator = comparator;
}
 
Example 16
Source Project: jstarcraft-core   Source File: FieldAccessor.java    License: Apache License 2.0 5 votes vote down vote up
public FieldAccessor(Field field, String name, boolean unique, Comparator comparator) {
    ReflectionUtility.makeAccessible(field);
    this.field = field;
    this.name = name;
    this.unique = unique;
    this.comparator = comparator;
}
 
Example 17
Source Project: jstarcraft-core   Source File: PropertyFormatAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <E> Iterator<E> iterator(Class<E> clazz, InputStream stream) {
    // 实例列表
    HashMap<Object, E> instanceObjects = new HashMap<>();
    try {
        Properties properties = new Properties();
        properties.load(stream);
        Constructor<E> constructor = clazz.getDeclaredConstructor();
        ReflectionUtility.makeAccessible(constructor);

        Field storageId = ReflectionUtility.uniqueField(clazz, ResourceId.class);
        storageId.setAccessible(true);

        TreeMap<?, ?> keyValues = new TreeMap<>(properties);
        for (Entry<?, ?> keyValue : keyValues.entrySet()) {
            LinkedList<String> fieldNames = new LinkedList<>(Arrays.asList(String.class.cast(keyValue.getKey()).split(dot)));
            String fieldName = fieldNames.pollFirst();
            String fieldValue = String.class.cast(keyValue.getValue());
            Object instanceId = ConversionUtility.convert(fieldName, storageId.getGenericType());
            E instanceObject = instanceObjects.get(instanceId);
            if (instanceObject == null) {
                instanceObject = constructor.newInstance();
                storageId.set(instanceObject, instanceId);
                instanceObjects.put(instanceId, instanceObject);
            }
            if (fieldNames.isEmpty()) {
                continue;
            } else {
                fieldName = fieldNames.pollFirst();
                process(instanceObject, clazz, fieldName, fieldNames, fieldValue);
            }
        }
        return instanceObjects.values().iterator();
    } catch (Exception exception) {
        throw new StorageException("遍历Properties异常", exception);
    }
}
 
Example 18
Source Project: jstarcraft-core   Source File: MongoMetadata.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构造方法
 * 
 * @param metadata
 */
MongoMetadata(Class<?> clazz) {
    Document document = clazz.getAnnotation(Document.class);
    if (document == null) {
        throw new IllegalArgumentException();
    }
    ormName = document.collection();
    if (StringUtility.isBlank(ormName)) {
        ormName = clazz.getSimpleName();
        ormName = ormName.substring(0, 1).toLowerCase() + ormName.substring(1, ormName.length());
    }
    ormClass = clazz;
    ReflectionUtility.doWithFields(ormClass, (field) -> {
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            return;
        }
        if (field.isAnnotationPresent(Version.class)) {
            versionName = field.getName();
            return;
        }
        Class<?> type = field.getType();
        fields.put(field.getName(), type);
        if (field.isAnnotationPresent(Id.class)) {
            primaryName = field.getName();
            primaryClass = type;
        }
        if (field.isAnnotationPresent(Indexed.class)) {
            indexNames.add(field.getName());
        }
    });
}
 
Example 19
Source Project: jstarcraft-core   Source File: HibernateMetadata.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构造方法
 * 
 * @param metadata
 */
HibernateMetadata(Class<?> clazz) {
    ormClass = clazz;
    ormName = clazz.getName();
    ReflectionUtility.doWithFields(ormClass, (field) -> {
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            return;
        }
        if (field.isAnnotationPresent(Version.class)) {
            versionName = field.getName();
            return;
        }
        Class<?> type = ClassUtility.primitiveToWrapper(field.getType());
        if (String.class == type) {
            fields.put(field.getName(), type);
        } else if (type.isEnum()) {
            fields.put(field.getName(), type);
        } else if (Collection.class.isAssignableFrom(type) || type.isArray()) {
            fields.put(field.getName(), List.class);
        } else if (Date.class.isAssignableFrom(type)) {
            fields.put(field.getName(), Date.class);
        } else {
            fields.put(field.getName(), Map.class);
        }
        if (field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)) {
            primaryName = field.getName();
            primaryClass = type;
        }
    });
    Table table = clazz.getAnnotation(Table.class);
    if (table != null) {
        for (Index index : table.indexes()) {
            indexNames.add(index.columnList());
        }
    }
}
 
Example 20
Source Project: jstarcraft-core   Source File: PromptPersistenceManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
	public PersistenceElement createInstance(IdentityObject<?> cacheObject) {
//		if (cacheObject instanceof ProxyObject) {
//			cacheObject = ((ProxyObject) cacheObject).getInstance();
//		}
		PersistenceElement element = new PersistenceElement(PersistenceOperation.CREATE, cacheObject.getId(), cacheObject);
		Exception exception = null;
		synchronized (cacheObject) {
			T copyInstance = copyInstances.get();
			ReflectionUtility.copyInstance(element.getCacheObject(), copyInstance);
			Lock writeLock = lock.writeLock();
			try {
				writeLock.lock();
				accessor.createInstance(cacheClass, copyInstance);
				createdCount.incrementAndGet();
			} catch (Exception throwable) {
				String message = StringUtility.format("立即策略[{}]处理元素[{}]时异常", new Object[] { name, element });
				LOGGER.error(message, throwable);
				exception = throwable;
				exceptionCount.incrementAndGet();
			} finally {
				writeLock.unlock();
			}
		}
		if (monitor != null) {
			monitor.notifyOperate(element.getOperation(), element.getCacheId(), element.getCacheObject(), exception);
		}
		return element;
	}
 
Example 21
Source Project: jstarcraft-core   Source File: PromptPersistenceManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
	public PersistenceElement updateInstance(IdentityObject<?> cacheObject) {
//		if (cacheObject instanceof ProxyObject) {
//			cacheObject = ((ProxyObject) cacheObject).getInstance();
//		}
		PersistenceElement element = new PersistenceElement(PersistenceOperation.UPDATE, cacheObject.getId(), cacheObject);
		Exception exception = null;
		synchronized (cacheObject) {
			T copyInstance = copyInstances.get();
			ReflectionUtility.copyInstance(element.getCacheObject(), copyInstance);
			Lock writeLock = lock.writeLock();
			try {
				writeLock.lock();
				accessor.updateInstance(cacheClass, copyInstance);
				updatedCount.incrementAndGet();
			} catch (Exception throwable) {
				String message = StringUtility.format("立即策略[{}]处理元素[{}]时异常", new Object[] { name, element });
				LOGGER.error(message, throwable);
				exception = throwable;
				exceptionCount.incrementAndGet();
			} finally {
				writeLock.unlock();
			}
		}
		if (monitor != null) {
			monitor.notifyOperate(element.getOperation(), element.getCacheId(), element.getCacheObject(), exception);
		}
		return element;
	}
 
Example 22
Source Project: jstarcraft-core   Source File: JavassistProxy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 转换指定类
 * 
 * @param clazz
 * @return
 * @throws Exception
 */
private Class<?> transformClass(final Class<?> clazz) throws Exception {
    CtClass proxyClass = proxyClass(clazz);
    proxyCacheFields(clazz, proxyClass);
    proxyConstructor(clazz, proxyClass);
    ReflectionUtility.doWithMethods(clazz, (method) -> {
        CacheChange cacheChange = method.getAnnotation(CacheChange.class);
        try {
            proxyMethod(clazz, proxyClass, method, cacheChange);
        } catch (Exception exception) {
            String message = StringUtility.format("缓存类型[{}]转换异常", clazz.getName());
            throw new CacheException(message, exception);
        }
    }, (method) -> {
        Class<?>[] classes = DEFAULT_METHODS.get(method.getName());
        if (classes != null && Arrays.equals(classes, method.getParameterTypes())) {
            return false;
        }
        if (Modifier.isFinal(method.getModifiers()) || Modifier.isStatic(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())) {
            return false;
        }
        if (method.isSynthetic() && method.getName().equals(METHOD_GET_ID)) {
            return false;
        }
        return true;
    });
    return proxyClass.toClass();
}
 
Example 23
Source Project: jstarcraft-core   Source File: CacheAccessorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void assembleField(Object instance, Field field, Object value) {
    ReflectionUtility.makeAccessible(field);
    try {
        field.set(instance, value);
    } catch (Exception exception) {
        String message = StringUtility.format("无法装配属性[{}]", field);
        LOGGER.error(message);
        throw new CacheConfigurationException(message);
    }
}
 
Example 24
Source Project: jstarcraft-core   Source File: CodecDefinition.java    License: Apache License 2.0 5 votes vote down vote up
private static void findDependentClasses(Class<?> clazz, Collection<Class<?>> classes) {
    ReflectionUtility.doWithFields(clazz, (field) -> {
        if (!classes.contains(field.getGenericType())) {
            findDependentClasses(field.getGenericType(), classes);
        }
    }, (field) -> {
        return !(Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()));
    });
}
 
Example 25
Source Project: jstarcraft-core   Source File: SwingAttributeNode.java    License: Apache License 2.0 5 votes vote down vote up
static SwingAttributeNode getInstance(SwingNode node, String name) {
    Container container = node.getComponent();
    Map<String, PropertyDescriptor> properties = ReflectionUtility.getPropertyDescriptors(container.getClass());
    PropertyDescriptor property = properties.get(name);
    SwingAttributeNode instance = new SwingAttributeNode(node, property);
    return instance;
}
 
Example 26
Source Project: jstarcraft-core   Source File: SwingAttributeNode.java    License: Apache License 2.0 5 votes vote down vote up
static Collection<SwingAttributeNode> getInstances(SwingNode node) {
    Container container = node.getComponent();
    Map<String, PropertyDescriptor> properties = ReflectionUtility.getPropertyDescriptors(container.getClass());
    ArrayList<SwingAttributeNode> instances = new ArrayList<>(properties.size());
    for (PropertyDescriptor property : properties.values()) {
        instances.add(new SwingAttributeNode(node, property));
    }
    return instances;
}
 
Example 27
Source Project: jstarcraft-core   Source File: CsvUtility.java    License: Apache License 2.0 5 votes vote down vote up
private static final CsvInformation getInformation(Class<?> clazz) {
    synchronized (clazz) {
        CsvInformation information = INFORMATIONS.get(clazz);
        try {
            if (information == null) {
                CsvConfiguration configuration = clazz.getAnnotation(CsvConfiguration.class);
                if (configuration == null || configuration.value().length == 0) {
                    return null;
                }
                Constructor<?> constructor = clazz.getDeclaredConstructor();
                ReflectionUtility.makeAccessible(constructor);
                String[] names = configuration.value();
                LinkedList<Field> fields = new LinkedList<>();
                for (String name : names) {
                    Field field = clazz.getDeclaredField(name);
                    field.setAccessible(true);
                    fields.add(field);
                }
                information = new CsvInformation(constructor, fields.toArray(new Field[fields.size()]));
                INFORMATIONS.put(clazz, information);
            }
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
        return information;
    }
}
 
Example 28
Source Project: jstarcraft-rns   Source File: ItemKNNModel.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
    super.prepare(configuration, model, space);
    neighborSize = configuration.getInteger("recommender.neighbors.knn.number", 50);
    // TODO 设置容量
    itemNeighbors = new MathVector[itemSize];
    Neighborhood<Integer2FloatKeyValue>[] knns = new Neighborhood[itemSize];
    for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
        knns[itemIndex] = new Neighborhood<>(neighborSize, comparator);
    }
    // TODO 修改为配置枚举
    try {
        Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
        MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
        correlation.calculateCoefficients(scoreMatrix, true, (leftIndex, rightIndex, coefficient) -> {
            if (leftIndex == rightIndex) {
                return;
            }
            // 忽略相似度为0的物品
            if (coefficient == 0F) {
                return;
            }
            knns[leftIndex].updateNeighbor(new Integer2FloatKeyValue(rightIndex, coefficient));
            knns[rightIndex].updateNeighbor(new Integer2FloatKeyValue(leftIndex, coefficient));
        });
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
    for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
        itemNeighbors[itemIndex] = getNeighborVector(knns[itemIndex].getNeighbors());
    }

    itemMeans = DenseVector.valueOf(itemSize);

    userVectors = new SparseVector[userSize];
    for (int userIndex = 0; userIndex < userSize; userIndex++) {
        userVectors[userIndex] = scoreMatrix.getRowVector(userIndex);
    }

    itemVectors = new SparseVector[itemSize];
    for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
        itemVectors[itemIndex] = scoreMatrix.getColumnVector(itemIndex);
    }
}
 
Example 29
Source Project: jstarcraft-rns   Source File: UserKNNModel.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void prepare(Configurator configuration, DataModule model, DataSpace space) {
    super.prepare(configuration, model, space);
    neighborSize = configuration.getInteger("recommender.neighbors.knn.number");
    // TODO 设置容量
    userNeighbors = new MathVector[userSize];
    Neighborhood<Integer2FloatKeyValue>[] knns = new Neighborhood[userSize];
    for (int userIndex = 0; userIndex < userSize; userIndex++) {
        knns[userIndex] = new Neighborhood<>(neighborSize, comparator);
    }
    // TODO 修改为配置枚举
    try {
        Class<MathCorrelation> correlationClass = (Class<MathCorrelation>) Class.forName(configuration.getString("recommender.correlation.class"));
        MathCorrelation correlation = ReflectionUtility.getInstance(correlationClass);
        correlation.calculateCoefficients(scoreMatrix, false, (leftIndex, rightIndex, coefficient) -> {
            if (leftIndex == rightIndex) {
                return;
            }
            // 忽略相似度为0的物品
            if (coefficient == 0F) {
                return;
            }
            knns[leftIndex].updateNeighbor(new Integer2FloatKeyValue(rightIndex, coefficient));
            knns[rightIndex].updateNeighbor(new Integer2FloatKeyValue(leftIndex, coefficient));
        });
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
    for (int userIndex = 0; userIndex < userSize; userIndex++) {
        userNeighbors[userIndex] = getNeighborVector(knns[userIndex].getNeighbors());
    }

    userMeans = DenseVector.valueOf(userSize);

    userVectors = new SparseVector[userSize];
    for (int userIndex = 0; userIndex < userSize; userIndex++) {
        userVectors[userIndex] = scoreMatrix.getRowVector(userIndex);
    }

    itemVectors = new SparseVector[itemSize];
    for (int itemIndex = 0; itemIndex < itemSize; itemIndex++) {
        itemVectors[itemIndex] = scoreMatrix.getColumnVector(itemIndex);
    }
}
 
Example 30
Source Project: jstarcraft-core   Source File: XlsxFormatAdapter.java    License: Apache License 2.0 4 votes vote down vote up
Attribute(Class<?> clazz, int index, String name) throws Exception {
    this.index = index;
    this.field = ReflectionUtility.findField(clazz, name);
    ReflectionUtility.makeAccessible(field);
}