All Downloads are FREE. Search and download functionalities are using the official Maven repository.

numpy.core.Scalar Maven / Gradle / Ivy

There is a newer version: 1.2.8
Show newest version
/*
 * Copyright (c) 2015 Villu Ruusmann
 *
 * This file is part of JPMML-Python
 *
 * JPMML-Python is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JPMML-Python is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with JPMML-Python.  If not, see .
 */
package numpy.core;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.google.common.base.Charsets;
import com.google.common.collect.Iterables;
import numpy.DType;
import org.jpmml.python.CythonObject;
import org.jpmml.python.HasArray;
import org.jpmml.python.HasContent;

public class Scalar extends CythonObject implements HasArray, HasContent> {

	private List content = null;


	public Scalar(String module, String name){
		super(module, name);
	}

	@Override
	public void __init__(Object[] args){
		super.__setstate__(INIT_ATTRIBUTES, args);
	}

	@Override
	public List getArrayContent(){
		List content = getContent();

		return content;
	}

	@Override
	public int[] getArrayShape(){
		List content = getContent();

		return new int[]{content.size()};
	}

	@Override
	public DType getArrayType(){
		return getDType();
	}

	public Object getOnlyElement(){
		List content = getContent();

		return Iterables.getOnlyElement(content);
	}

	@Override
	public List getContent(){

		if(this.content == null){
			this.content = loadContent();
		}

		return this.content;
	}

	@Override
	public void clearContent(){
		this.content = null;
	}

	private List loadContent(){
		DType dtype = getDType();
		byte[] obj = getObj();

		try(InputStream is = new ByteArrayInputStream(obj)){
			return (List)NDArrayUtil.parseData(is, dtype, new Object[0]);
		} catch(IOException ioe){
			throw new RuntimeException(ioe);
		}
	}

	public DType getDType(){
		return getOptional("dtype", DType.class);
	}

	public byte[] getObj(){
		Object obj = getOptionalObject("obj");

		if(obj instanceof String){
			String string = (String)obj;

			return string.getBytes(Charsets.ISO_8859_1);
		}

		return (byte[])obj;
	}

	private static final String[] INIT_ATTRIBUTES = {
		"dtype",
		"obj"
	};
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy