if system == 'Linux': path = jpype.java.lang.System.getenv('LD_LIBRARY_PATH') if path: folders = path.split(os.pathsep) print('System library search path is:') for folder in folders: print(f' {folder}') print('Importing Comsol API.') from com.comsol.model.util import ModelUtil as client print('Comsol API imported.') print('Initializing stand-alone client.') t0 = now() client.initStandalone(False) client.loadPreferences() print(f'Client initialized after {now()-t0:.3f} seconds.') if 'skip_load' not in sys.argv[1:]: print('Loading Comsol model.') t0 = now() tag = client.uniquetag('model') model = client.load(tag, 'blank.mph') print(f'Loading model took {now()-t0:.3f} seconds.') # Possibly crash out of JVM. if 'force_exit' in sys.argv[1:]: print('Exiting JVM.') jpype.java.lang.Runtime.getRuntime().exit(0)
def __init__(self, cores=None, version=None, port=None, host='localhost'): # Make sure this is the first (and only) client created. if jpype.isJVMStarted(): error = 'Only one client can be instantiated at a time.' logger.error(error) raise RuntimeError(error) # Determine relevant folders of the Comsol back-end. main = backend.folder(version) arch = backend.architecture() jre = main / 'java' / arch / 'jre' / 'bin' jvm = jre / 'server' / 'jvm.dll' api = main / 'plugins' / '*' # Manipulate binary search path to only point to Comsol's JVM. path = os.environ['PATH'] os.environ['PATH'] = str(jre) # Set environment variable so Comsol will restrict cores at start-up. if cores: os.environ['COMSOL_NUM_THREADS'] = str(cores) # Start the Java virtual machine. logger.info('Starting Java virtual machine.') jpype.startJVM(str(jvm), classpath=str(api), convertStrings=False) from com.comsol.model.util import ModelUtil as java logger.info('Java virtual machine has started.') # Restore the original search path. os.environ['PATH'] = path # Connect to a server if requested. if port is not None: logger.info(f'Connecting to server "{host}" at port {port}.') java.connect(host, port) # Otherwise initialize stand-alone session. else: logger.info('Initializing stand-alone client.') graphics = False java.initStandalone(graphics) logger.info('Stand-alone client initialized.') # Log number of used processor cores as reported by Comsol instance. cores = java.getPreference('cluster.processor.numberofprocessors') cores = int(str(cores)) noun = 'core' if cores == 1 else 'cores' logger.info(f'Running on {cores} processor {noun}.') # Override the default setting of certain preferences. java.setPreference('updates.update.check', 'off') java.setPreference('tempfiles.saving.warnifoverwriteolder', 'off') java.setPreference('tempfiles.recovery.autosave', 'off') java.setPreference('tempfiles.recovery.checkforrecoveries', 'off') java.setPreference('tempfiles.saving.optimize', 'filesize') # Save setup in instance attributes. self.cores = cores self.version = version self.host = host self.port = port self.folder = main self.java = java
def __init__(self, cores=None, version=None, port=None, host='localhost'): # Make sure this is the one and only client. if jpype.isJVMStarted(): error = 'Only one client can be instantiated at a time.' logger.critical(error) raise NotImplementedError(error) # Discover Comsol back-end. backend = discovery.backend(version) # Instruct Comsol to limit number of processor cores to use. if cores: os.environ['COMSOL_NUM_THREADS'] = str(cores) # Start the Java virtual machine. logger.info(f'JPype version is {jpype.__version__}.') logger.info('Starting Java virtual machine.') jpype.startJVM(str(backend['jvm']), classpath=str(backend['root'] / 'plugins' / '*'), convertStrings=False) logger.info('Java virtual machine has started.') # Initialize a stand-alone client if no server port given. from com.comsol.model.util import ModelUtil as java if port is None: logger.info('Initializing stand-alone client.') check_environment(backend) graphics = True java.initStandalone(graphics) logger.info('Stand-alone client initialized.') # Otherwise skip stand-alone initialization and connect to server. else: logger.info(f'Connecting to server "{host}" at port {port}.') java.connect(host, port) # Log number of used processor cores as reported by Comsol instance. cores = java.getPreference('cluster.processor.numberofprocessors') cores = int(str(cores)) noun = 'core' if cores == 1 else 'cores' logger.info(f'Running on {cores} processor {noun}.') # Load Comsol settings from disk so as to not just use defaults. java.loadPreferences() # Override certain settings not useful in headless operation. java.setPreference('updates.update.check', 'off') java.setPreference('tempfiles.saving.warnifoverwriteolder', 'off') java.setPreference('tempfiles.recovery.autosave', 'off') try: java.setPreference('tempfiles.recovery.checkforrecoveries', 'off') except Exception: logger.warning('Could not turn off check for recovery files.') java.setPreference('tempfiles.saving.optimize', 'filesize') # Save useful information in instance attributes. self.version = backend['name'] self.cores = cores self.host = host self.port = port self.java = java
path = jpype.java.lang.System.getProperty('java.library.path') or '' print('Java library search path is:') for folder in path.split(os.pathsep): print(f' {folder}') path = jpype.java.lang.System.getenv('PATH') or '' print('System binary search path is:') for folder in path.split(os.pathsep): print(f' {folder}') path = jpype.java.lang.System.getenv('LD_LIBRARY_PATH') or '' print('System library search path is:') for folder in path.split(os.pathsep): print(f' {folder}') print('Starting stand-alone Comsol client.') from com.comsol.model.util import ModelUtil as client client.initStandalone(False) client.loadPreferences() print('Testing if Comsol can load shared libraries.') from com.comsol.nativejni import FlNativeUtil FlNativeUtil.ensureLibIsLoaded() print('Loading Comsol model.') tag = client.uniquetag('model') model = client.load(tag, '../tests/capacitor.mph') print('Loading external image.') tags = [str(tag) for tag in model.func().tags()] names = [model.func(tag).label() for tag in tags] tag = tags[names.index('test_function')] model.func(tag).discardData()
or install locations can be tested by editing the assignment to the `root` variable. On Linux, 'win64' has to be replaced by 'glnxa64', and on macOS by 'maci64'. """ import jpype import jpype.imports from time import sleep from pathlib import Path print(f'Starting Comsol\'s Java VM via JPype {jpype.__version__}.') root = Path(r'C:\Program Files\COMSOL\COMSOL55\Multiphysics') jvm = root / 'java' / 'win64' / 'jre' / 'bin' / 'server' / 'jvm.dll' jpype.startJVM(str(jvm), classpath=str(root / 'plugins' / '*')) print('Starting stand-alone Comsol client.') from com.comsol.model.util import ModelUtil as client client.initStandalone(False) client.loadPreferences() print('Press Ctrl+C within the next 10 seconds.') try: sleep(10) except KeyboardInterrupt: print('Test passed.') finally: print('Finally block executed.') print('All went well if you see this line in the output.')
# Display version info. print(f'JPype version: {jpype.__version__}') # Start JVM that ships with Comsol. main = Path(Comsol_root) arch = 'win64' jre = main / 'java' / arch / 'jre' / 'bin' jvm = jre / 'server' / 'jvm.dll' api = main / 'plugins' / '*' print(f'JVM path: {jvm}') jpype.startJVM(str(jvm), classpath=str(api), convertStrings=False) print('JVM started.') # Start the Comsol client. from com.comsol.model.util import ModelUtil as client client.initStandalone(False) print('Client started.') # Have user trigger a keyboard interrupt. print('Press Ctrl+C within the next 10 seconds.') try: time.sleep(10) except KeyboardInterrupt: print('User pressed Ctrl+C.') finally: print('Finally block executed.') # Success if the next line of code is reached. print('All went well if you see this line in the output.')
def __init__(self, cores=None, version=None, port=None, host='localhost'): # Make sure this is the one and only client. if jpype.isJVMStarted(): error = 'Only one client can be instantiated at a time.' logger.error(error) raise NotImplementedError(error) # Discover Comsol back-end. backend = discovery.backend(version) # Instruct Comsol to limit number of processor cores to use. if cores: os.environ['COMSOL_NUM_THREADS'] = str(cores) # On Windows, turn off fault handlers if enabled. # Without this, pyTest will crash when starting the Java VM. # See "Errors reported by Python fault handler" in JPype docs. # The problem may be the SIGSEGV signal, see JPype issue #886. if platform.system() == 'Windows' and faulthandler.is_enabled(): logger.debug('Turning off Python fault handlers.') faulthandler.disable() # Start the Java virtual machine. logger.debug(f'JPype version is {jpype.__version__}.') logger.info('Starting Java virtual machine.') java_args = [str(backend['jvm'])] if option('classkit'): java_args += ['-Dcs.ckl'] logger.debug(f'JVM arguments: {java_args}') jpype.startJVM(*java_args, classpath=str(backend['root'] / 'plugins' / '*'), convertStrings=False) logger.info('Java virtual machine has started.') # Initialize a stand-alone client if no server port given. from com.comsol.model.util import ModelUtil as java if port is None: logger.info('Initializing stand-alone client.') check_environment(backend) graphics = True java.initStandalone(graphics) logger.info('Stand-alone client initialized.') # Otherwise skip stand-alone initialization and connect to server. else: logger.info(f'Connecting to server "{host}" at port {port}.') java.connect(host, port) # Log number of used processor cores as reported by Comsol instance. cores = java.getPreference('cluster.processor.numberofprocessors') cores = int(str(cores)) noun = 'core' if cores == 1 else 'cores' logger.info(f'Running on {cores} processor {noun}.') # Load Comsol settings from disk so as to not just use defaults. java.loadPreferences() # Override certain settings not useful in headless operation. java.setPreference('updates.update.check', 'off') java.setPreference('tempfiles.saving.warnifoverwriteolder', 'off') java.setPreference('tempfiles.recovery.autosave', 'off') try: # Preference not defined on certain systems, see issue #39. java.setPreference('tempfiles.recovery.checkforrecoveries', 'off') except Exception: logger.debug('Could not turn off check for recovery files.') java.setPreference('tempfiles.saving.optimize', 'filesize') # Save useful information in instance attributes. self.version = backend['name'] self.cores = cores self.host = host self.port = port self.java = java
def __init__(self, cores=None, version=None, port=None, host='localhost'): # Make sure this is the one and only client. if jpype.isJVMStarted(): error = 'Only one client can be instantiated at a time.' logger.error(error) raise NotImplementedError(error) # Discover Comsol back-end. backend = discovery.backend(version) # Set environment variables for loading external libraries. system = platform.system() root = backend['root'] if system == 'Windows': var = 'PATH' if var in os.environ: path = os.environ[var].split(os.pathsep) else: path = [] lib = str(root / 'lib' / 'glnxa64') if lib not in path: os.environ[var] = os.pathsep.join([lib] + path) elif system == 'Linux': lib = str(root / 'lib' / 'glnxa64') gcc = str(root / 'lib' / 'glnxa64' / 'gcc') ext = str(root / 'ext' / 'graphicsmagick' / 'glnxa64') cad = str(root / 'ext' / 'cadimport' / 'glnxa64') pre = str(root / 'java' / 'glnxa64' / 'jre' / 'lib' / 'amd64' / 'libjsig.so') var = 'LD_LIBRARY_PATH' if var in os.environ: path = os.environ[var].split(os.pathsep) else: path = [] if lib not in path: os.environ[var] = os.pathsep.join([lib, gcc, ext, cad] + path) vars = ('MAGICK_CONFIGURE_PATH', 'MAGICK_CODER_MODULE_PATH', 'MAGICK_FILTER_MODULE_PATH') for var in vars: os.environ[var] = ext os.environ['LD_PRELOAD'] = pre os.environ['LC_NUMERIC'] = os.environ['LC_ALL'] = 'C' elif system == 'Darwin': var = 'DYLD_LIBRARY_PATH' if var in os.environ: path = os.environ[var].split(os.pathsep) else: path = [] lib = str(root / 'lib' / 'maci64') ext = str(root / 'ext' / 'graphicsmagick' / 'maci64') cad = str(root / 'ext' / 'cadimport' / 'maci64') if lib not in path: os.environ[var] = os.pathsep.join([lib, ext, cad] + path) # Instruct Comsol to limit number of processor cores to use. if cores: os.environ['COMSOL_NUM_THREADS'] = str(cores) # Start the Java virtual machine. logger.info(f'JPype version is {jpype.__version__}.') logger.info('Starting Java virtual machine.') jpype.startJVM(str(backend['jvm']), classpath=str(root / 'plugins' / '*'), convertStrings=False) logger.info('Java virtual machine has started.') # Initialize a stand-alone client if no server port given. from com.comsol.model.util import ModelUtil as java if port is None: logger.info('Initializing stand-alone client.') graphics = True java.initStandalone(graphics) logger.info('Stand-alone client initialized.') # Otherwise skip stand-alone initialization and connect to server. else: logger.info(f'Connecting to server "{host}" at port {port}.') java.connect(host, port) # Log number of used processor cores as reported by Comsol instance. cores = java.getPreference('cluster.processor.numberofprocessors') cores = int(str(cores)) noun = 'core' if cores == 1 else 'cores' logger.info(f'Running on {cores} processor {noun}.') # Load Comsol settings from disk so as to not just use defaults. java.loadPreferences() # Override certain settings not useful in headless operation. java.setPreference('updates.update.check', 'off') java.setPreference('tempfiles.saving.warnifoverwriteolder', 'off') java.setPreference('tempfiles.recovery.autosave', 'off') try: java.setPreference('tempfiles.recovery.checkforrecoveries', 'off') except Exception: logger.warning('Could not turn off check for recovery files.') java.setPreference('tempfiles.saving.optimize', 'filesize') # Save useful information in instance attributes. self.version = backend['name'] self.cores = cores self.host = host self.port = port self.java = java