Commit 9d4eeedf authored by LAMBERT Jean-charles's avatar LAMBERT Jean-charles

improve pip install process

parent 80ae99f7
include py/swig/numpy.i
include py/unsio/numpy.i
include src/uns.h src/snapshotinterface.h src/componentrange.h src/userselection.h src/snapshotinterface.h src/ctools.h src/version.h
include py/test/test_py_unsio.py
exclude py/swig/py_unsio.py
exclude py/unsio/py_unsio.py
# ============================================================================
# Copyright Jean-Charles LAMBERT - 2008-2015
# Centre de donneeS Astrophysiques de Marseille (CeSAM)
# e-mail: Jean-Charles.Lambert@lam.fr
# address: Aix Marseille Universite, CNRS, LAM
# Laboratoire d'Astrophysique de Marseille
# Pole de l'Etoile, site de Chateau-Gombert
# 38, rue Frederic Joliot-Curie
# 13388 Marseille cedex 13 France
# CNRS UMR 7326
# ============================================================================
# CMakeListst.txt file for UNS python library
# ============================================================================
# This is a CMake example for Python
cmake_minimum_required(VERSION 2.6)
# project name
project (py_unsio)
# extra path for NEMO
SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/cmake )
SET(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${PROJECT_SOURCE_DIR}/../cmake )
# load setup flags
include(SetupFlags)
# use ccache if any
find_program(CCACHE_FOUND ccache)
if(CCACHE_FOUND)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache)
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache)
endif(CCACHE_FOUND)
# required package
FIND_PACKAGE(SWIG REQUIRED)
FIND_PACKAGE(NumPy REQUIRED)
FIND_PACKAGE(UNSIO REQUIRED)
FIND_PACKAGE(SQLITE3 REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs 2 )
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
# some status
MESSAGE( STATUS "PROJECT_SOURCE_DIR: " ${PROJECT_SOURCE_DIR} )
MESSAGE( STATUS "PROJECT_BINARY_DIR: " ${PROJECT_BINARY_DIR} )
MESSAGE( STATUS "CMAKE_BUILD_TYPE =" ${CMAKE_BUILD_TYPE} )
MESSAGE( STATUS "CMAKE_CXX_FLAGS =" ${CMAKE_CXX_FLAGS} )
MESSAGE( STATUS "LIBRARY TYPE =" ${LIBTYPE} )
MESSAGE( STATUS "core OPT =" ${OPT} )
MESSAGE( STATUS "OSX detected =" ${OSX} )
MESSAGE( STATUS "BUILD_TYPE =" ${RELEASE} )
MESSAGE(STATUS "PYTHON_INCLUDE_PATH:" ${PYTHON_INCLUDE_PATH})
MESSAGE(STATUS "PYTHON_INCLUDE_DIRS:" ${PYTHON_INCLUDE_DIRS})
MESSAGE(STATUS "PYTHON_LIBRARY :" ${PYTHON_LIBRARY})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/swig ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/../src ${NUMPY_INCLUDE_DIRS})
# Set definitions
set (INTERFACE swig/py_unsio.i)
set (MODULENAME py_unsio)
# Find all LIB's sources files
FILE(GLOB execpp_sources ${CMAKE_CURRENT_SOURCE_DIR}/src/*.h )
SET(CMAKE_SWIG_FLAGS "-c++")
SET_SOURCE_FILES_PROPERTIES(${INTERFACE} PROPERTIES CPLUSPLUS ON)
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/swig)
set(CMAKE_SWIG_OUTDIR ${PROJECT_BINARY_DIR}/swig)
IF (OSX) # Mac OSX
SET(SOEXT "dylib")
ELSE (OSX) # Linux
SET(SOEXT "so")
ENDIF(OSX)
SWIG_ADD_MODULE(${MODULENAME} python ${INTERFACE} ${execpp_sources} ${UNSIOPATH}/lib/libunsio.${SOEXT} )
SWIG_LINK_LIBRARIES(${MODULENAME} ${PYTHON_LIBRARIES} ${UNSIOPATH}/lib/libunsio.${SOEXT} ${SQLITE3_LIB_PATH}/libsqlite3.${SOEXT} )
# ----------------------------------------------------------
# Install SETUP
# ----------------------------------------------------------
mark_as_advanced(CMAKE_INSTALL_PREFIX)
set (CMAKE_INSTALL_PREFIX ${UNSIOPATH})
MESSAGE( STATUS "--------> CMAKE_INSTALL_PREFIX =" ${CMAKE_INSTALL_PREFIX})
INSTALL(FILES ${PROJECT_BINARY_DIR}/_${MODULENAME}.so DESTINATION py/modules)
INSTALL(FILES ${PROJECT_BINARY_DIR}/swig/${MODULENAME}.py DESTINATION py/modules)
MESSAGE( STATUS "\nAfter running \"make install\", do no forget to set PYTHONPATH variable with command:\n export PYTHONPATH=${CMAKE_INSTALL_PREFIX}/py/modules\n\n")
#
Python unsio wrapper installation
*) Requirements
*) Pypi
=====
the easy way to install unsio python wrapper is to use pip command
pip install python-unsio
*) compilation
============
**) requirements
Before installing python unsio wrapper you must install UNSIO (see
INSTALL in UNSIO directory)
......@@ -13,73 +22,10 @@ tools can be installed directly from your distribution or downloaded
from "here :":http://www.cmake.org/cmake/resources/software.html. You
need also the SWIG library, and numpy development library.
*) Configuration
=============
(We assume that UNSIOSRC specify your UNSIO sources directory, and
UNSIOPATH your UNSIO installation path directory)
To configure python unsio wrapper, do the following :
cd UNSIOSRC/py
mkdir build
cd build
cmake ..
You can add several options to command "cmake". The most important ones are:
-DCMAKE_BUILD_TYPE=<Debug|Release> build type [Debug]
Here are different scenarios :
*) default configuration (no options added)
cd UNSIOSRC/py
mkdir build-debug
cd build-debug
cmake ..
Will configure *py_unsio* in "debug" mode
*) release mode (with optimizations enabled)
cd UNSIOSRC/py
mkdir build-release
cd build-release
cmake .. -DCMAKE_BUILD_TYPE=Release
**) setup
python setup.py install
Will configure *py_unsio* in "release" mode with shared library.
*) so forth and so on.....
Note that CMake maintains a cache name "CMakeCache.txt". If you change
options (or your environment changes), it is best to remove that file
to avoid problems.
*) Building
========
To build py_unsio library, enter
make
To install py_unsio module and library, enter
make install
note that files will be installed in _UNSIOPATH_/py/modules
directory. In order to use *py_unsio* module, you have to add path
_UNSIOPATH_/py/modules to your environment variable PYTHONPATH
export PYTHONPATH=_UNSIOPATH_/py/modules
_UNSIOPATH_ must match the asbolute path of UNSIO installed directory
A list of all available make targets can be obtained by
make help
*) PACKAGING
=========
......@@ -104,3 +50,16 @@ A list of all available make targets can be obtained by
python setup.py --command-packages=stdeb.command bdist_deb sdist_dsc --with-python2=True --with-python3=True --dist-dir=my_deb --debian-version 0ubuntu16.04
see https://pypi.org/project/stdeb/
*) to build on MacOSX
1) use clang compiler and python3
2) build
CC=/usr/bin/cc CXX=/usr/bin/c++ python3 setup.py build_ext -L ${HOME}/local/unsio/lib -R ${HOME}/local/unsio/lib
3) install locally
python3 setup.py install --user
4) set DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=${HOME}/local/unsio/lib
# - Find the NumPy libraries
# This module finds if NumPy is installed, and sets the following variables
# indicating where it is.
#
# TODO: Update to provide the libraries and paths for linking npymath lib.
#
# NUMPY_FOUND - was NumPy found
# NUMPY_VERSION - the version of NumPy found as a string
# NUMPY_VERSION_MAJOR - the major version number of NumPy
# NUMPY_VERSION_MINOR - the minor version number of NumPy
# NUMPY_VERSION_PATCH - the patch version number of NumPy
# NUMPY_VERSION_DECIMAL - e.g. version 1.6.1 is 10601
# NUMPY_INCLUDE_DIRS - path to the NumPy include files
#============================================================================
# Copyright 2012 Continuum Analytics, Inc.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
#============================================================================
# Finding NumPy involves calling the Python interpreter
if(NumPy_FIND_REQUIRED)
find_package(PythonInterp REQUIRED)
else()
find_package(PythonInterp)
endif()
if(NOT PYTHONINTERP_FOUND)
set(NUMPY_FOUND FALSE)
return()
endif()
execute_process(COMMAND "${PYTHON_EXECUTABLE}" "-c"
"import numpy as n; print(n.__version__); print(n.get_include());"
RESULT_VARIABLE _NUMPY_SEARCH_SUCCESS
OUTPUT_VARIABLE _NUMPY_VALUES_OUTPUT
ERROR_VARIABLE _NUMPY_ERROR_VALUE
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT _NUMPY_SEARCH_SUCCESS MATCHES 0)
if(NumPy_FIND_REQUIRED)
message(FATAL_ERROR
"NumPy import failure:\n${_NUMPY_ERROR_VALUE}")
endif()
set(NUMPY_FOUND FALSE)
return()
endif()
# Convert the process output into a list
string(REGEX REPLACE ";" "\\\\;" _NUMPY_VALUES ${_NUMPY_VALUES_OUTPUT})
string(REGEX REPLACE "\n" ";" _NUMPY_VALUES ${_NUMPY_VALUES})
# Just in case there is unexpected output from the Python command.
list(GET _NUMPY_VALUES -2 NUMPY_VERSION)
list(GET _NUMPY_VALUES -1 NUMPY_INCLUDE_DIRS)
string(REGEX MATCH "^[0-9]+\\.[0-9]+\\.[0-9]+" _VER_CHECK "${NUMPY_VERSION}")
if("${_VER_CHECK}" STREQUAL "")
# The output from Python was unexpected. Raise an error always
# here, because we found NumPy, but it appears to be corrupted somehow.
message(FATAL_ERROR
"Requested version and include path from NumPy, got instead:\n${_NUMPY_VALUES_OUTPUT}\n")
return()
endif()
# Make sure all directory separators are '/'
string(REGEX REPLACE "\\\\" "/" NUMPY_INCLUDE_DIRS ${NUMPY_INCLUDE_DIRS})
# Get the major and minor version numbers
string(REGEX REPLACE "\\." ";" _NUMPY_VERSION_LIST ${NUMPY_VERSION})
list(GET _NUMPY_VERSION_LIST 0 NUMPY_VERSION_MAJOR)
list(GET _NUMPY_VERSION_LIST 1 NUMPY_VERSION_MINOR)
list(GET _NUMPY_VERSION_LIST 2 NUMPY_VERSION_PATCH)
string(REGEX MATCH "[0-9]*" NUMPY_VERSION_PATCH ${NUMPY_VERSION_PATCH})
math(EXPR NUMPY_VERSION_DECIMAL
"(${NUMPY_VERSION_MAJOR} * 10000) + (${NUMPY_VERSION_MINOR} * 100) + ${NUMPY_VERSION_PATCH}")
find_package_message(NUMPY
"Found NumPy: version \"${NUMPY_VERSION}\" ${NUMPY_INCLUDE_DIRS}"
"${NUMPY_INCLUDE_DIRS}${NUMPY_VERSION}")
set(NUMPY_FOUND TRUE)
# -*-cmake-*-
# ============================================================================
# Copyright Jean-Charles LAMBERT - 2008-2015
# Centre de donneeS Astrophysiques de Marseille (CeSAM)
# e-mail: Jean-Charles.Lambert@lam.fr
# address: Aix Marseille Universite, CNRS, LAM
# Laboratoire d'Astrophysique de Marseille
# Pole de l'Etoile, site de Chateau-Gombert
# 38, rue Frederic Joliot-Curie
# 13388 Marseille cedex 13 France
# CNRS UMR 7326
# ============================================================================
# CMake module to detect UNSIO library
# ============================================================================
if (NOT UNSIO_SETUP)
set (UNSIO_SETUP 1)
typed_cache_set ( STRING "unsio setup" UNSIO_SETUP 1 )
SET(UNSIO_FOUND FALSE)
set (UNSIOLIB UNSIOLIB-NOTFOUND)
if ( UNSIOPATH ) # user configure cmake with variable -DUNSIO_INSTALLPATH="/unsio/path"
find_library(UNSIOLIB NAMES unsio PATHS ${UNSIOPATH}/lib)
MESSAGE (STATUS "UNSIOLIB = " ${UNSIOLIB})
if (NOT ${UNSIOLIB} STREQUAL UNSIOLIB-NOTFOUND)
MESSAGE(STATUS "Found UNSIOLIB =" ${UNSIOLIB})
SET(UNSIO_FOUND TRUE)
else ()
endif()
endif ()
if (NOT UNSIO_FOUND) # try NEMO
MESSAGE (STATUS "UNSIOLIB = " ${UNSIOLIB} " NEMO=" $ENV{NEMO})
find_library(UNSIOLIB NAMES unsio PATHS $ENV{NEMO}/lib)
MESSAGE (STATUS "UNSIOLIB = " ${UNSIOLIB} " NEMO=" $ENV{NEMO})
if ( NOT ${UNSIOLIB} STREQUAL UNSIOLIB-NOTFOUND)
MESSAGE(STATUS "Found UNSIOLIB in NEMO =" ${UNSIOLIB})
SET(UNSIO_FOUND TRUE)
SET(UNSIOPATH $ENV{NEMO})
MESSAGE(STATUS ">>>>>22" $ENV{NEMO})
else ()
MESSAGE(STATUS ">>>>>2")
endif()
endif()
if (NOT UNSIO_FOUND) # try $HOME/local
find_library(UNSIOLIB NAMES unsio PATHS $ENV{HOME}/local/unsio/lib)
MESSAGE (STATUS "UNSIOLIB = " ${UNSIOLIB} " -- " $ENV{HOME})
if (NOT ${UNSIOLIB} STREQUAL UNSIOLIB-NOTFOUND)
MESSAGE(STATUS "Found UNSIOLIB in $ENV{HOME}/local/unsio/ =" ${UNSIOLIB})
SET(UNSIO_FOUND TRUE)
SET(UNSIOPATH $ENV{HOME}/local/unsio)
else ()
endif()
endif()
if (NOT UNSIO_FOUND) # ABORT
message(SEND_ERROR "UNSIO not found - skipping building tests")
else()
typed_cache_set ( STRING "UNSIOPATH location" UNSIOPATH ${UNSIOPATH} )
endif()
endif () #NOT UNSIO_SETUP
This diff is collapsed.
//-*- C -*-
// ============================================================================
// Copyright Jean-Charles LAMBERT - 2008-2015
// Centre de donneeS Astrophysiques de Marseille (CeSAM)
// e-mail: Jean-Charles.Lambert@lam.fr
// address: Aix Marseille Universite, CNRS, LAM
// Laboratoire d'Astrophysique de Marseille
// Pole de l'Etoile, site de Chateau-Gombert
// 38, rue Frederic Joliot-Curie
// 13388 Marseille cedex 13 France
// CNRS UMR 7326
// ============================================================================
// Swig python interface for UNSIO
// ============================================================================
// python module name
%module py_unsio
%{
#define SWIG_FILE_WITH_INIT
#include "uns.h"
%}
%include "numpy.i"
%include "std_string.i"
%init %{
import_array();
%}
// below we change the type of dimension of numpy array.
// By default it's an "int", but we have std::vector object returning size()
// method as dimension, and which are of type "unsigned int"
// This may cause a problem with BIG simulations. Indeed a simulation with 1.1 billions particles
// store in a xyz positions array a size of 3.3 billions which overtake size of SIGNED int, which go
// only to 2^31 bits = 2.14 billons !!!!! (damn nasty bug....)
%numpy_typemaps(double, NPY_DOUBLE, unsigned int)
%numpy_typemaps(float , NPY_FLOAT , unsigned int)
%numpy_typemaps(int , NPY_INT , unsigned int)
// getArrayX return 1D numpy float array
%apply (unsigned int* DIM1, float ** ARGOUTVIEW_ARRAY1 )
{( unsigned int* size, float ** farray )};
//%apply ( int* DIM1, int ** ARGOUTVIEW_ARRAY1 )
// {( int* size, int ** iarray )};
// getArrayX return 1D numpy double array
%apply (unsigned int* DIM1, double ** ARGOUTVIEW_ARRAY1 )
{( unsigned int* size, double ** farray )};
// getArrayX return 1D numpy int array
%apply (unsigned int* DIM1, int ** ARGOUTVIEW_ARRAY1 )
{( unsigned int* size, int ** iarray )};
// getValueX return float/double/int value
%apply float *OUTPUT { float * fvalue };
%apply double *OUTPUT { double * fvalue };
%apply int *OUTPUT { int * ivalue };
// rename methods because of overloading limitations with swig c++
// IMPORTANT :
// rename statement MUST be placed before inclusion of the header "%include uns.h"
// in order to be renamed
//float
%rename(getValueF) getData(const std::string,float *);
%rename(getArrayF) getData(const std::string,const std::string,unsigned int *,float **);
%rename(getArrayF) getData(const std::string,unsigned int *,float **);
//double
%rename(getValueF) getData(const std::string,double *);
%rename(getArrayF) getData(const std::string,const std::string,unsigned int *,double **);
%rename(getArrayF) getData(const std::string,unsigned int *, double **);
//int
%rename(getValueI) getData(const std::string,int *);
%rename(getArrayI) getData(const std::string,const std::string,unsigned int *,int **);
%rename(getArrayI) getData(const std::string,unsigned int *,int **);
%apply (unsigned int DIM1 , float * INPLACE_ARRAY1) {(unsigned int size, float * farray)};
%apply (unsigned int DIM1 , double* INPLACE_ARRAY1) {(unsigned int size, double* farray)};
%apply (unsigned int DIM1 , int * INPLACE_ARRAY1) {(unsigned int size, int * iarray)};
// rename methods because of overloading limitations with swig c++
// float
%rename(setValueF) setData(const std::string,float);
%rename(setArrayF_do_not_used) setData(const std::string,const std::string,unsigned int ,float *,const bool _addr=false);
%rename(setArrayF_do_not_used) setData(const std::string,unsigned int ,float *,const bool _addr=false);
// double
%rename(setValueF) setData(const std::string,double);
%rename(setArrayF_do_not_used) setData(const std::string,const std::string, unsigned int ,double *,const bool _addr=false);
%rename(setArrayF_do_not_used) setData(const std::string,unsigned int ,double *,const bool _addr=false);
// int
%rename(setValueI) setData(const std::string,int,const bool _addr=false);
%rename(setArrayI) setData(const std::string,const std::string,unsigned int ,int *,const bool _addr=false);
%rename(setArrayI) setData(const std::string,unsigned int ,int *);
// Parse the original header file
%include "uns.h"
%extend uns::CunsOut2 {
// we rewrite setArrayF because numpy array size is different from nbody for 3D arrays
int setArrayF(const std::string comp,const std::string prop,
unsigned int size,T * farray, const bool _addr=false) {
if (prop=="pos" || prop=="vel" || prop=="acc") size /= 3;
int status = $self->snapshot->setData(comp,prop,size,farray,_addr);
return status;
}
// we rewrite setArrayF because numpy array size is different from nbody for 3D arrays
int setArrayF(const std::string prop,
unsigned int size,T * farray, const bool _addr=false) {
if (prop=="pos" || prop=="vel" || prop=="acc") size /= 3;
int status = $self->snapshot->setData(prop,size,farray,_addr);
return status;
}
};
// rename templates
// INPUT
%template(CunsIn) uns::CunsIn2<float>;
//%template(CunsInF) uns::CunsIn2<float>;
%template(CunsInD) uns::CunsIn2<double>;
// OUTPUT
//%template(CunsOutF) uns::CunsOut2<float>;
%template(CunsOut) uns::CunsOut2<float>;
%template(CunsOutD) uns::CunsOut2<double>;
export PYTHONPATH=/rldata/home/jcl/works/CVS_WORKS/SVN/unsio/trunk/py/build
python
execfile("uns_test.py")
from py_unsio import * # import py_unsio package
import numpy as np # arrays are treated as numpy arrays
import matplotlib.pyplot as plt
import scipy.interpolate
# Step 1 : create UNSIO object
file="/home/jcl/gtr118_1912" # input file (simulation name)
component="disk,stars,gas" # selected components
times="6:10" # selected times
uns=CunsIn(file,component,times) # create UNS object
# Step 2 : load frame
while uns.nextFrame(""): # load snapshot
comp="gas"
# Step 3 : get data
ok,pos=uns.getArrayF(comp,"pos") # positions of stars particles
# Step 3 : get data
ok,rho=uns.getArrayF(comp ,"rho") # gas density
# Step 3 : get data
ok,mass=uns.getArrayF(comp ,"mass") # gas density
# reshape array in x,y,z arrays
pos=np.reshape(pos,(-1,3)) # pos reshaped in a 2D array [nbody,3]
x = pos[:,0] # x coordinates
y = pos[:,1] # y coordinates
z = pos[:,2] # z coordinates
if (rho.size > 0) :
rho = np.log(rho)
else:
rho = z
# center according COM
x -= np.average(x,weights=mass)
y -= np.average(y,weights=mass)
z -= np.average(z,weights=mass)
range=20
if range>0:
xmin = -range
xmax = range
ymin = -range
ymax = range
else:
xmin = x.min()
xmax = x.max()
ymin = y.min()
ymax = y.max()
meshs=200
# Set up a regular grid of interpolation points
xi, yi = np.linspace(xmin, xmax, meshs), np.linspace(ymin, ymax, meshs)
xi, yi = np.meshgrid(xi, yi)
# Interpolate
zi = scipy.interpolate.griddata((x, y), rho,(xi, yi), method='linear')
print "Rho :",rho, rho.min(), rho.max()
print "Zi :", zi.min(), zi.max()
#CS = plt.contour(xi,yi,zi,15,linewidths=0.5,colors='k')
#CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
#plt.imshow(zi, vmin=rho.min(), vmax=rho.max(), origin='lower', interpolation='bilinear',
plt.imshow(zi, vmin=zi.min(), vmax=zi.max(), origin='lower', interpolation='bilinear',extent=[xmin, xmax, ymin, ymax])
#plt.scatter(x, y, c=rho)
plt.colorbar()
plt.show()
from py_unsio import * # import py_unsio package
import numpy as np # arrays are treated as numpy arrays
import matplotlib.pyplot as plt
# Step 1 : create UNSIO object
file="/home/jcl/gtr118_1912" # input file (simulation name)
component="disk,stars,gas" # selected components
times="6:10" # selected times
uns=CunsIn(file,component,times) # create UNS object
# Step 2 : load frame
while uns.nextFrame(""): # load snapshot
comp="gas"
# Step 3 : get data
ok,pos =uns.getArrayF(comp,"pos") # positions
# Step 3 : get data
ok,rho =uns.getArrayF(comp,"rho") # gas density
# Step 3 : get data
ok,mass=uns.getArrayF(comp,"mass") # gas density
ok,time=uns.getValueF("time");
print "time=",time
ok,id=uns.getArrayI(comp, "id")
print "ID=",id
ok,postot=uns.getArrayF("pos");
print "pos tot=", postot, postot.size, pos.size
# reshape array in x,y,z arrays
pos=np.reshape(pos,(-1,3)) # pos reshaped in a 2D array [nbody,3]
x = pos[:,0] # x coordinates
y = pos[:,1] # y coordinates
z = pos[:,2] # z coordinates
if (rho.size > 0) :
rho = np.log(rho)
print
else:
rho = z
# center according COM
x -= np.average(x,weights=mass)
y -= np.average(y,weights=mass)
z -= np.average(z,weights=mass)
range=20
if range>0:
xmin = -range
xmax = range
ymin = -range
ymax = range
else:
xmin = x.min()
xmax = x.max()
ymin = y.min()
ymax = y.max()
plt.hexbin(x,y,bins='log',gridsize=500)#, cmap=plt.cm.YlOrRd_r)
plt.axis([xmin, xmax, ymin, ymax])
plt.title("With a log color scale")
cb = plt.colorbar()
cb.set_label('log10(N)')
plt.show()
"""
Shows how to combine Normalization and Colormap instances to draw
"levels" in pcolor, pcolormesh and imshow type plots in a similar
way to the levels keyword argument to contour/contourf.
"""
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import numpy as np
from py_unsio import *
# read UNS data
file="/home/jcl/gtr118_1912"
uns=CunsIn(file,"all","all");
# load frame
ok=uns.nextFrame("")
print ok
# get data
ok,data=uns.getArrayF("gas","pos")
print ok
print data
# reshap 1D to 2D
data=np.reshape(data,(-1,3))
print data
# get col 1 to x
x = data[:,0]
# get col 2 to y
y = data[:,1]
ok,dens=uns.getArrayF("gas","rho")
print dens.max()
print dens.min()
H, xedges, yedges = np.histogram2d(x, y,bins=100,weights=dens)
print H.size
extent = [0, 40, 20, 60]
plt.imshow(H, extent=extent, interpolation='nearest')
plt.colorbar()
plt.show()
#!/usr/bin/python
#
# This program test unsio library by readind and saving same file in different output
# file format (gadget2, nemo) and comparing all arrays with original one
#
from __future__ import print_function
import sys
import argparse
import numpy as np # arrays are treated as numpy arrays
import os.path
#dirname, filename = os.path.split(os.path.abspath(__file__))
#sys.path.append(dirname+'../modules/') # trick to find modules directory
from unsio import *
import copy
import tempfile
try:
from IPython import embed
except:
pass
class snap:
time = None