text
stringlengths
0
1.05M
meta
dict
__author__ = 'Andres' import pygame from pygame.locals import * pygame.init() question = { "YES": K_y, "NO": K_n } arrow_keys = { "UP": K_UP, "DOWN": K_DOWN, "LEFT": K_LEFT, "RIGHT": K_RIGHT } system = { "QUEUE": K_q, "MUTE": K_m, "=": K_EQUALS, "K+": K_KP_PLUS, "-": K_MINUS, "K-": K_KP_MINUS, "PAUSE": K_p, "QUIT": K_q, "ESCAPE": K_ESCAPE, "ENTER": K_RETURN } weapons = { "LASER": K_SPACE, "PEW": K_x } directions = { "NONE": (0, 0), "UP": (0, -1), "DOWN": (0, 1), "LEFT": (-1, 0), "RIGHT": (1, 0), "UP_LEFT": (-1, -1), "UP_RIGHT": (1, -1), "DOWN_LEFT": (-1, 1), "DOWN_RIGHT": (1, 1) } def queue_prompt(event): #return event.type == KEYDOWN and event.key == system["QUEUE"] return False def start(event): """ Whether or not return was pressed """ return event.type == KEYDOWN and event.key == system["ENTER"] def escape_prompt(event, gameover=False): """ True if escape or red x is pressed, also true if n is pressed during a continue prompt """ red_x_pressed = event.type == QUIT escape_pressed = event.type == KEYDOWN and event.key == system["ESCAPE"] negative_answer = event.type == KEYDOWN and event.key == question["NO"] if not gameover: return red_x_pressed or escape_pressed else: return red_x_pressed or escape_pressed or negative_answer def restart(event, gameover=False): """ True if y is pressed during a continue prompt """ if gameover: return event.type == KEYDOWN and event.key == question["YES"] else: return False def pause_prompt(keys): """ Returns true if 'p' was pressed """ return keys[system["PAUSE"]] def music_prompt(keys): """ Returns true if 'm' was pressed """ return keys[system["MUTE"]] def increase_prompt(keys): """ Returns true if keypad '+' or '=' was pressed """ return keys[system["K+"]] or keys[system["="]] def decrease_prompt(keys): """ Returns true if '-' or keypad '-' was pressed """ return keys[system["-"]] or keys[system["K-"]] def laser_prompt(keys): """ Returns true if the space bar was pressed """ if keys[weapons["LASER"]]: return True return False def pew_prompt(keys): """ Returns true if 'x' was pressed """ if keys[weapons["PEW"]]: return True return False def movement(keys): """ Returns direction as a tuple based on arrow keys """ up = keys[arrow_keys["UP"]] left = keys[arrow_keys["LEFT"]] right = keys[arrow_keys["RIGHT"]] down = keys[arrow_keys["DOWN"]] direction = directions["NONE"] for d in arrow_keys: if keys[arrow_keys[d]]: direction = directions[d] #Diagonals if up and left: direction = directions["UP_LEFT"] if up and right: direction = directions["UP_RIGHT"] if down and left: direction = directions["DOWN_LEFT"] if down and right: direction = directions["DOWN_RIGHT"] return direction
{ "repo_name": "mrnoodles/AI-Pygame", "path": "keyboard.py", "copies": "1", "size": "3135", "license": "cc0-1.0", "hash": 4838398875690717000, "line_mean": 19.3571428571, "line_max": 90, "alpha_frac": 0.5636363636, "autogenerated": false, "ratio": 3.3209745762711864, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43846109398711863, "avg_score": null, "num_lines": null }
__author__ = 'AndrewAnnex' from ctypes import CDLL, POINTER, c_bool, c_int, c_double, c_char, c_char_p, c_void_p import os sitePath = os.path.dirname(__file__) sitePath = os.path.join(sitePath, 'spice.so') libspice = CDLL(sitePath) import SpiceyPy.support_types as stypes # ###################################################################################################################### # A libspice.appndc_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.appndd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.appndi_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.axisar_c.argtypes = [(c_double * 3), c_double, (c_double * 3) * 3] # ####################################################################################################################### # B libspice.b1900_c.restype = c_double libspice.b1950_c.restype = c_double libspice.bodc2n_c.argtypes = [c_int, c_int, c_char_p, POINTER(c_bool)] libspice.bodc2s_c.argtypes = [c_int, c_int, c_char_p] libspice.boddef_c.argtypes = [c_char_p, c_int] libspice.badkpv_c.argtypes = [c_char_p, c_char_p, c_char_p, c_int, c_int, c_char] libspice.badkpv_c.restype = c_bool libspice.bltfrm_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.bodfnd_c.argtypes = [c_int, c_char_p] libspice.bodfnd_c.restype = c_bool libspice.bodn2c_c.argtypes = [c_char_p, POINTER(c_int), POINTER(c_bool)] libspice.bods2c_c.argtypes = [c_char_p, POINTER(c_int), POINTER(c_bool)] libspice.bodvar_c.argtypes = [c_int, c_char_p, POINTER(c_int), c_void_p] libspice.bodvcd_c.argtypes = [c_int, c_char_p, c_int, POINTER(c_int), c_void_p] libspice.bodvrd_c.argtypes = [c_char_p, c_char_p, c_int, POINTER(c_int), c_void_p] libspice.brcktd_c.argtypes = [c_double, c_double, c_double] libspice.brcktd_c.restype = c_double libspice.brckti_c.argtypes = [c_int, c_int, c_int] libspice.brckti_c.restype = c_int libspice.bschoc_c.argtypes = [c_char_p, c_int, c_int, c_char_p, POINTER(c_int)] libspice.bschoc_c.restype = c_int libspice.bschoi_c.argtypes = [c_int, c_int, POINTER(c_int), POINTER(c_int)] libspice.bschoi_c.restype = c_int libspice.bsrchc_c.argtypes = [c_char_p, c_int, c_int, c_char_p] libspice.bsrchc_c.restype = c_int libspice.bsrchd_c.argtypes = [c_double, c_int, POINTER(c_double)] libspice.bsrchd_c.restype = c_int libspice.bsrchi_c.argtypes = [c_int, c_int, POINTER(c_int)] libspice.bsrchi_c.restype = c_int ######################################################################################################################## # C libspice.card_c.argtypes = [POINTER(stypes.SpiceCell)] libspice.card_c.restype = c_int libspice.ccifrm_c.argtypes = [c_int, c_int, c_int, POINTER(c_int), c_char_p, POINTER(c_int), POINTER(c_bool)] libspice.cgv2el_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3), POINTER(stypes.Ellipse)] libspice.chkin_c.argtypes = [c_char_p] libspice.chkout_c.argtypes = [c_char_p] libspice.cidfrm_c.argtypes = [c_int, c_int, POINTER(c_int), c_char_p, POINTER(c_bool)] libspice.ckcls_c.argtypes = [c_int] libspice.ckcov_c.argtypes = [c_char_p, c_int, c_bool, c_char_p, c_double, c_char_p, POINTER(stypes.SpiceCell)] libspice.ckobj_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.ckgp_c.argtypes = [c_int, c_double, c_double, c_char_p, ((c_double * 3) * 3), POINTER(c_double), POINTER(c_bool)] libspice.ckgpav_c.argtypes = [c_int, c_double, c_double, c_char_p, ((c_double * 3) * 3), (c_double * 3), POINTER(c_double), POINTER(c_bool)] libspice.cklpf_c.argtypes = [c_char_p, POINTER(c_int)] libspice.ckopn_c.argtypes = [c_char_p, c_char_p, c_int, POINTER(c_int)] libspice.ckupf_c.argtypes = [c_int] libspice.ckw01_c.argtypes = [c_int, c_double, c_double, c_int, c_char_p, c_bool, c_char_p, c_int, POINTER(c_double), POINTER(c_double * 4), POINTER(c_double * 3)] libspice.ckw02_c.argtypes = [c_int, c_double, c_double, c_int, c_char_p, c_char_p, c_int, POINTER(c_double), POINTER(c_double), POINTER(c_double * 4), POINTER(c_double * 3), POINTER(c_double)] libspice.ckw03_c.argtypes = [c_int, c_double, c_double, c_int, c_char_p, c_bool, c_char_p, c_int, POINTER(c_double), POINTER(c_double * 4), POINTER(c_double * 3), c_int, POINTER(c_double)] libspice.ckw05_c.argtypes = [c_int, c_int, c_double, c_double, c_int, c_char_p, c_bool, c_char_p, c_int, c_double, c_int] libspice.clight_c.argtypes = None libspice.clight_c.restype = c_double libspice.clpool_c.argtypes = None libspice.cmprss_c.argtypes = [c_char, c_int, c_char_p, c_int, c_char_p] libspice.cnmfrm_c.argtypes = [c_char_p, c_int, POINTER(c_int), c_char_p, POINTER(c_bool)] libspice.conics_c.argtypes = [(c_double * 8), c_double, (c_double * 6)] libspice.convrt_c.argtypes = [c_double, c_char_p, c_char_p, POINTER(c_double)] libspice.copy_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.cpos_c.argtypes = [c_char_p, c_char_p, c_int] libspice.cpos_c.restype = c_int libspice.cposr_c.argtypes = [c_char_p, c_char_p, c_int] libspice.cposr_c.restype = c_int libspice.cvpool_c.argtypes = [c_char_p, POINTER(c_bool)] libspice.cyllat_c.argtypes = [c_double, c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.cylrec_c.argtypes = [c_double, c_double, c_double, (c_double * 3)] libspice.cylsph_c.argtypes = [c_double, c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] ######################################################################################################################## #D libspice.dafac_c.argtypes = [c_int, c_int, c_int, c_void_p] libspice.dafbbs_c.argtypes = [c_int] libspice.dafbfs_c.argtypes = [c_int] libspice.dafcls_c.argtypes = [c_int] libspice.dafcs_c.argtypes = [c_int] libspice.dafdc_c.argtypes = [c_int] libspice.dafec_c.argtypes = [c_int, c_int, c_int, POINTER(c_int), c_void_p, POINTER(c_bool)] libspice.daffna_c.argtypes = [POINTER(c_bool)] libspice.daffpa_c.argtypes = [POINTER(c_bool)] libspice.dafgda_c.argtypes = [c_int, c_int, c_int, POINTER(c_double)] libspice.dafgh_c.argtypes = [POINTER(c_int)] libspice.dafgn_c.argtypes = [c_int, c_char_p] libspice.dafgs_c.argtypes = [POINTER(c_double)] libspice.dafgsr_c.argtypes = [c_int, c_int, c_int, c_int, POINTER(c_double), POINTER(c_bool)] libspice.dafopr_c.argtypes = [c_char_p, POINTER(c_int)] libspice.dafopw_c.argtypes = [c_char_p, POINTER(c_int)] libspice.dafps_c.argtypes = [c_int, c_int, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.dafrda_c.argtypes = [c_int, c_int, c_int, POINTER(c_double)] libspice.dafrfr_c.argtypes = [c_int, c_int, POINTER(c_int), POINTER(c_int), c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_int)] libspice.dafrs_c.argtype = [POINTER(c_double)] libspice.dafus_c.argtypes = [POINTER(c_double), c_int, c_int, POINTER(c_double), POINTER(c_int)] libspice.dasac_c.argtypes = [c_int, c_int, c_int, c_void_p] libspice.dascls_c.argtypes = [c_int] libspice.dasec_c.argtypes = [c_int, c_int, c_int, POINTER(c_int), c_void_p, POINTER(c_bool)] libspice.dasopr_c.argtypes = [c_char_p, POINTER(c_int)] libspice.dcyldr_c.argtypes = [c_double, c_double, c_double, (c_double * 3) * 3] libspice.deltet_c.argtypes = [c_double, c_char_p, POINTER(c_double)] libspice.det_c.argtypes = [(c_double * 3) * 3] libspice.det_c.restype = c_double libspice.dgeodr_c.argtypes = [c_double, c_double, c_double, c_double, c_double, (c_double * 3) * 3] libspice.diags2_c.argtypes = [(c_double * 2) * 2, (c_double * 2) * 2, (c_double * 2) * 2] libspice.diff_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.dlatdr_c.argtypes = [c_double, c_double, c_double, (c_double * 3) * 3] libspice.dp2hx_c.argtypes = [c_double, c_int, c_char_p, POINTER(c_int)] libspice.dpgrdr_c.argtypes = [c_char_p, c_double, c_double, c_double, c_double, c_double, (c_double * 3) * 3] libspice.dpmax_c.argtypes = None libspice.dpmax_c.restype = c_double libspice.dpmin_c.argtypes = None libspice.dpmin_c.restype = c_double libspice.dpr_c.restype = c_double libspice.drdcyl_c.argtypes = [c_double, c_double, c_double, (c_double * 3) * 3] libspice.drdgeo_c.argtypes = [c_double, c_double, c_double, c_double, c_double, (c_double * 3) * 3] libspice.drdlat_c.argtypes = [c_double, c_double, c_double, (c_double * 3) * 3] libspice.drdpgr_c.argtypes = [c_char_p, c_double, c_double, c_double, c_double, c_double, (c_double * 3) * 3] libspice.drdsph_c.argtypes = [c_double, c_double, c_double, (c_double * 3) * 3] libspice.dsphdr_c.argtypes = [c_double, c_double, c_double, (c_double * 3) * 3] libspice.dtpool_c.argtypes = [c_char_p, POINTER(c_bool), POINTER(c_int), POINTER(c_char)] libspice.ducrss_c.argtypes = [c_double * 6, c_double * 6, c_double * 6] libspice.dvcrss_c.argtypes = [c_double * 6, c_double * 6, c_double * 6] libspice.dvdot_c.argtypes = [c_double * 6, c_double * 6] libspice.dvdot_c.restype = c_double libspice.dvhat_c.argtypes = [c_double * 6, c_double * 6] libspice.dvnorm_c.argtypes = [c_double * 6] libspice.dvnorm_c.restype = c_double libspice.dvpool_c.argtypes = [c_char_p] libspice.dvsep_c.argtypes = [c_double * 6, c_double * 6] libspice.dvsep_c.restype = c_double ######################################################################################################################## # E libspice.edlimb_c.argtypes = [c_double, c_double, c_double, (c_double * 3), POINTER(stypes.Ellipse)] libspice.edterm_c.argtypes = [c_char_p, c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, c_int, POINTER(c_double), (c_double * 3), c_void_p] libspice.ekacec_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, c_int, c_void_p, c_bool] libspice.ekaced_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, POINTER(c_double), c_bool] libspice.ekacei_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, POINTER(c_int), c_bool] libspice.ekaclc_c.argtypes = [c_int, c_int, c_char_p, c_int, c_void_p, POINTER(c_int), POINTER(c_bool), POINTER(c_int), POINTER(c_int)] libspice.ekacld_c.argtypes = [c_int, c_int, c_char_p, POINTER(c_double), POINTER(c_int), POINTER(c_bool), POINTER(c_int), POINTER(c_int)] libspice.ekacli_c.argtypes = [c_int, c_int, c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_bool), POINTER(c_int), POINTER(c_int)] libspice.ekappr_c.argtypes = [c_int, c_int, POINTER(c_int)] libspice.ekbseg_c.argtypes = [c_int, c_char_p, c_int, c_int, c_void_p, c_int, c_void_p, POINTER(c_int)] libspice.ekccnt_c.argtypes = [c_char_p, POINTER(c_int)] libspice.ekcii_c.argtypes = [c_char_p, c_int, c_int, c_char_p, POINTER(stypes.SpiceEKAttDsc)] libspice.ekcls_c.argtypes = [c_int] libspice.ekdelr_c.argtypes = [c_int, c_int, c_int] libspice.ekffld_c.argtypes = [c_int, c_int, POINTER(c_int)] libspice.ekfind_c.argtypes = [c_char_p, c_int, POINTER(c_int), POINTER(c_bool), c_char_p] libspice.ekgc_c.argtypes = [c_int, c_int, c_int, c_int, c_char_p, POINTER(c_bool), POINTER(c_bool)] libspice.ekgd_c.argtypes = [c_int, c_int, c_int, POINTER(c_double), POINTER(c_bool), POINTER(c_bool)] libspice.ekgi_c.argtypes = [c_int, c_int, c_int, POINTER(c_int), POINTER(c_bool), POINTER(c_bool)] libspice.ekifld_c.argtypes = [c_int, c_char_p, c_int, c_int, c_int, c_void_p, c_int, c_void_p, POINTER(c_int), POINTER(c_int)] libspice.ekinsr_c.argtypes = [c_int, c_int, c_int] libspice.eklef_c.argtypes = [c_char_p, POINTER(c_int)] libspice.eknelt_c.argtypes = [c_int, c_int] libspice.eknelt_c.restype = c_int libspice.eknseg_c.argtypes = [c_int] libspice.eknseg_c.restype = c_int libspice.ekntab_c.argtypes = [POINTER(c_int)] libspice.ekopn_c.argtypes = [c_char_p, c_char_p, c_int, POINTER(c_int)] libspice.ekopr_c.argtypes = [c_char_p, POINTER(c_int)] libspice.ekops_c.argtypes = [POINTER(c_int)] libspice.ekopw_c.argtypes = [c_char_p, POINTER(c_int)] libspice.ekpsel_c.argtypes = [c_char_p, c_int, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(stypes.SpiceEKDataType), POINTER(stypes.SpiceEKExprClass), c_void_p, c_void_p, POINTER(c_bool), c_char_p] libspice.ekrcec_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, POINTER(c_int), c_char_p, POINTER(c_bool)] libspice.ekrced_c.argtypes = [c_int, c_int, c_int, c_char_p, POINTER(c_int), POINTER(c_double), POINTER(c_bool)] libspice.ekrcei_c.argtypes = [c_int, c_int, c_int, c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_bool)] libspice.ekssum_c.argtypes = [c_int, c_int, POINTER(stypes.SpiceEKSegSum)] libspice.ektnam_c.argtypes = [c_int, c_int, c_char_p] libspice.ekucec_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, c_int, c_void_p, c_bool] libspice.ekuced_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, POINTER(c_double), c_bool] libspice.ekucei_c.argtypes = [c_int, c_int, c_int, c_char_p, c_int, POINTER(c_int), c_bool] libspice.ekuef_c.argtypes = [c_int] libspice.el2cgv_c.argtypes = [POINTER(stypes.Ellipse), (c_double * 3), (c_double * 3), (c_double * 3)] libspice.elemc_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.elemc_c.restype = c_bool libspice.elemd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.elemd_c.restype = c_bool libspice.elemi_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.elemi_c.restype = c_bool libspice.eqncpv_c.argtypes = [c_double, c_double, (c_double * 9), c_double, c_double, (c_double * 6)] libspice.eqstr_c.argtypes = [c_char_p, c_char_p] libspice.eqstr_c.restype = c_bool libspice.erract_c.argtypes = [c_char_p, c_int, c_char_p] libspice.errch_c.argtypes = [c_char_p, c_char_p] libspice.errdev_c.argtypes = [c_char_p, c_int, c_char_p] libspice.errdp_c.argtypes = [c_char_p, c_double] libspice.errint_c.argtypes = [c_char_p, c_int] libspice.errprt_c.argtypes = [c_char_p, c_int, c_char_p] libspice.esrchc_c.argtypes = [c_char_p, c_int, c_int, c_void_p] libspice.esrchc_c.restype = c_int libspice.et2lst_c.argtypes = [c_double, c_int, c_double, c_char_p, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), c_char_p, c_char_p] libspice.et2utc_c.argtypes = [c_double, c_char_p, c_int, c_int, c_char_p] libspice.etcal_c.argtypes = [c_double, c_int, c_char_p] libspice.eul2m_c.argtypes = [c_double, c_double, c_double, c_int, c_int, c_int, (c_double * 3) * 3] libspice.eul2xf_c.argtypes = [(c_double * 6), c_int, c_int, c_int, (c_double * 6) * 6] libspice.exists_c.argtypes = [c_char_p] libspice.exists_c.restype = c_bool libspice.expool_c.argtypes = [c_char_p, POINTER(c_bool)] ######################################################################################################################## # F libspice.failed_c.argtypes = None libspice.failed_c.restype = c_bool libspice.fovray_c.argtypes = [c_char_p, (c_double * 3), c_char_p, c_char_p, c_char_p, POINTER(c_double), POINTER(c_bool)] libspice.fovtrg_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, POINTER(c_double), POINTER(c_bool)] libspice.frame_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.frinfo_c.argtypes = [c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_bool)] libspice.frmnam_c.argtypes = [c_int, c_int, c_char_p] libspice.ftncls_c.argtypes = [c_int] libspice.furnsh_c.argtypes = [c_char_p] ######################################################################################################################## # G libspice.gcpool_c.argtypes = [c_char_p, c_int, c_int, c_int, POINTER(c_int), c_void_p, POINTER(c_bool)] libspice.gdpool_c.argtypes = [c_char_p, c_int, c_int, POINTER(c_int), POINTER(c_double), POINTER(c_bool)] libspice.georec_c.argtypes = [c_double, c_double, c_double, c_double, c_double, (c_double * 3)] libspice.getcml_c.argtypes = [c_int, c_char_p] libspice.getelm_c.argtypes = [c_int, c_int, c_void_p, POINTER(c_double), POINTER(c_double)] libspice.getfat_c.argtypes = [c_char_p, c_int, c_int, c_char_p, c_char_p] libspice.getfov_c.argtypes = [c_int, c_int, c_int, c_int, c_char_p, c_char_p, (c_double * 3), POINTER(c_int), POINTER(c_double * 3)] libspice.getmsg_c.argtypes = [c_char_p, c_int, c_char_p] libspice.gfbail_c.restype = c_bool libspice.gfclrh_c.argtypes = None libspice.gfdist_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] # libspice.gfevnt_c.argtypes = [c_double, c_double, c_double, c_double, c_bool, c_bool, c_double, c_char_p, c_int, c_int, c_char_p, c_double, c_double, c_double, c_bool, None, c_char_p, c_char_p, c_double, c_double, c_double, c_int, c_bool, c_bool, None, None] # libspice.gffove_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_double, c_double, c_bool, c_bool, c_double, c_bool, None, c_char_p, c_char_p, c_double, c_double, c_double, c_bool, c_bool, None, None] libspice.gfinth_c.argtypes = [c_int] # libspice.gfocce_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_double, c_double, c_bool, c_bool, c_double, c_bool, None, c_char_p, c_char_p, c_double, c_double, c_double, c_bool, c_bool, None, None] libspice.gfoclt_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfpa_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfposc_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfrefn_c.argtypes = [c_double, c_double, c_bool, c_bool, POINTER(c_double)] libspice.gfrepf_c.argtypes = None libspice.gfrepi_c.argtypes = [POINTER(stypes.SpiceCell), c_char_p, c_char_p] libspice.gfrepu_c.argtypes = [c_double, c_double, c_double] libspice.gfrfov_c.argtypes = [c_char_p, (c_double * 3), c_char_p, c_char_p, c_char_p, c_double, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfrr_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfsep_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfsntc_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, (c_double * 3), c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gfsstp_c.argtypes = [c_double] libspice.gfstep_c.argtypes = [c_double, POINTER(c_double)] libspice.gfstol_c.argtypes = [c_double] libspice.gfsubc_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, c_double, c_double, c_int, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.gftfov_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] # libspice.gfuds_c.argtypes = [c_double, c_double, c_double, c_double, c_double, c_bool, c_char_p, c_double, c_double, c_double, c_int, None, None] libspice.gipool_c.argtypes = [c_char_p, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_bool)] libspice.gnpool_c.argtypes = [c_char_p, c_int, c_int, c_int, POINTER(c_int), c_void_p, POINTER(c_bool)] ######################################################################################################################## # H libspice.halfpi_c.restype = c_double libspice.hx2dp_c.argtypes = [c_char_p, c_int, POINTER(c_double), POINTER(c_bool), c_char_p] ######################################################################################################################## # I libspice.ident_c.argtypes = [(c_double * 3) * 3] libspice.illum_c.argtypes = [c_char_p, c_double, c_char_p, c_char_p, (c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.ilumin_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 3), POINTER(c_double), (c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.inedpl_c.argtypes = [c_double, c_double, c_double, POINTER(stypes.Plane), POINTER(stypes.Ellipse), POINTER(c_bool)] libspice.inelpl_c.argtypes = [POINTER(stypes.Ellipse), POINTER(stypes.Plane), POINTER(c_int), (c_double * 3), (c_double * 3)] libspice.insrtc_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.insrtd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.insrti_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.inter_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.inrypl_c.argtypes = [(c_double * 3), (c_double * 3), POINTER(stypes.Plane), POINTER(c_int), (c_double * 3)] libspice.intmax_c.restype = c_int libspice.intmin_c.restype = c_int libspice.invert_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3] libspice.invort_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3] libspice.isordv_c.argtypes = [POINTER(c_int), c_int] libspice.isordv_c.restype = c_bool libspice.isrchc_c.argtypes = [c_char_p, c_int, c_int, c_void_p] libspice.isrchc_c.restype = c_int libspice.isrchd_c.argtypes = [c_double, c_int, POINTER(c_double)] libspice.isrchd_c.restype = c_int libspice.isrchi_c.argtypes = [c_int, c_int, POINTER(c_int)] libspice.isrchi_c.restype = c_int libspice.isrot_c.argtypes = [(c_double * 3) * 3, c_double, c_double] libspice.isrot_c.restype = c_bool libspice.iswhsp_c.argtypes = [c_char_p] libspice.iswhsp_c.restype = c_bool ######################################################################################################################## # J libspice.j1900_c.restype = c_double libspice.j1950_c.restype = c_double libspice.j2000_c.restype = c_double libspice.j2100_c.restype = c_double libspice.jyear_c.restype = c_double ######################################################################################################################## # K libspice.kclear_c.restype = None libspice.kdata_c.argtypes = [c_int, c_char_p, c_int, c_int, c_int, c_char_p, c_char_p, c_char_p, POINTER(c_int), POINTER(c_bool)] libspice.kinfo_c.argtypes = [c_char_p, c_int, c_int, c_char_p, c_char_p, POINTER(c_int), POINTER(c_bool)] libspice.ktotal_c.argtypes = [c_char_p, POINTER(c_int)] libspice.kplfrm_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.kxtrct_c.argtypes = [c_char_p, c_int, c_void_p, c_int, c_int, c_int, c_char_p, POINTER(c_bool), c_char_p] ######################################################################################################################## # L libspice.lastnb_c.argtypes = [c_char_p] libspice.lastnb_c.restype = c_int libspice.latcyl_c.argtypes = [c_double, c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.latrec_c.argtypes = [c_double, c_double, c_double, (c_double) * 3] libspice.latsph_c.argtypes = [c_double, c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.lcase_c.argtypes = [c_char_p, c_int, c_char_p] libspice.ldpool_c.argtypes = [c_char_p] libspice.lmpool_c.argtypes = [c_void_p, c_int, c_int] libspice.lparse_c.argtypes = [c_char_p, c_char_p, c_int, c_int, POINTER(c_int), c_void_p] libspice.lparsm_c.argtypes = [c_char_p, c_char_p, c_int, c_int, POINTER(c_int), c_void_p] libspice.lparss_c.argtypes = [c_char_p, c_char_p, POINTER(stypes.SpiceCell)] libspice.lspcn_c.argtypes = [c_char_p, c_double, c_char_p] libspice.lspcn_c.restype = c_double libspice.ltime_c.argtypes = [c_double, c_int, c_char_p, c_int, POINTER(c_double), POINTER(c_double)] libspice.lstlec_c.argtypes = [c_char_p, c_int, c_int, c_void_p] libspice.lstlec_c.restype = c_int libspice.lstled_c.argtypes = [c_double, c_int, POINTER(c_double)] libspice.lstled_c.restype = c_int libspice.lstlei_c.argtypes = [c_int, c_int, POINTER(c_int)] libspice.lstlei_c.restype = c_int libspice.lstltc_c.argtypes = [c_char_p, c_int, c_int, c_void_p] libspice.lstltc_c.restype = c_int libspice.lstltd_c.argtypes = [c_double, c_int, POINTER(c_double)] libspice.lstltd_c.restype = c_int libspice.lstlti_c.argtypes = [c_int, c_int, POINTER(c_int)] libspice.lstlti_c.restype = c_int libspice.lx4dec_c.argtypes = [c_char_p, c_int, POINTER(c_int), POINTER(c_int)] libspice.lx4num_c.argtypes = [c_char_p, c_int, POINTER(c_int), POINTER(c_int)] libspice.lx4sgn_c.argtypes = [c_char_p, c_int, POINTER(c_int), POINTER(c_int)] libspice.lx4uns_c.argtypes = [c_char_p, c_int, POINTER(c_int), POINTER(c_int)] libspice.lxqstr_c.argtypes = [c_char_p, c_char, c_int, POINTER(c_int), POINTER(c_int)] ######################################################################################################################## # M libspice.m2eul_c.argtypes = [(c_double * 3) * 3, c_int, c_int, c_int, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.m2q_c.argtypes = [(c_double * 3) * 3, (c_double * 4)] libspice.matchi_c.argtypes = [c_char_p, c_char_p, c_char, c_char] libspice.matchi_c.restype = c_bool libspice.matchw_c.argtypes = [c_char_p, c_char_p, c_char, c_char] libspice.matchw_c.restype = c_bool libspice.maxd_c.restype = c_double libspice.mequ_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3, ] libspice.mequg_c.argtypes = [c_void_p, c_int, c_int, c_void_p] libspice.mtxm_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3, (c_double * 3) * 3] libspice.mtxmg_c.argtypes = [c_void_p, c_void_p, c_int, c_int, c_int, c_void_p] libspice.mtxv_c.argtypes = [(c_double * 3) * 3, (c_double * 3), (c_double * 3)] libspice.mtxvg_c.argtypes = [c_void_p, c_void_p, c_int, c_int, c_void_p] libspice.mxm_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3, (c_double * 3) * 3] libspice.mxmg_c.argtypes = [c_void_p, c_void_p, c_int, c_int, c_int, c_void_p] libspice.mxmt_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3, (c_double * 3) * 3] libspice.mxmtg_c.argtypes = [c_void_p, c_void_p, c_int, c_int, c_int, c_void_p] libspice.mxv_c.argtypes = [(c_double * 3) * 3, (c_double * 3), (c_double * 3)] libspice.mxvg_c.argtypes = [c_void_p, c_void_p, c_int, c_int, c_void_p] ######################################################################################################################## # N libspice.namfrm_c.argtypes = [c_char_p, POINTER(c_int)] libspice.ncpos_c.argtypes = [c_char_p, c_char_p, c_int] libspice.ncpos_c.restype = c_int libspice.ncposr_c.argtypes = [c_char_p, c_char_p, c_int] libspice.ncposr_c.restype = c_int libspice.nearpt_c.argtypes = [(c_double * 3), c_double, c_double, c_double, (c_double * 3), POINTER(c_double)] libspice.npedln_c.argtypes = [c_double, c_double, c_double, (c_double * 3), (c_double * 3), (c_double * 3), POINTER(c_double)] libspice.npelpt_c.argtypes = [(c_double * 3), POINTER(stypes.Ellipse), (c_double * 3), POINTER(c_double)] libspice.nplnpt_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3), (c_double * 3), POINTER(c_double)] libspice.nvc2pl_c.argtypes = [(c_double * 3), c_double, POINTER(stypes.Plane)] libspice.nvp2pl_c.argtypes = [(c_double * 3), (c_double * 3), POINTER(stypes.Plane)] ######################################################################################################################## # O libspice.occult_c.argtypes = [c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p, c_double, POINTER(c_int)] libspice.ordc_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.ordc_c.restype = c_int libspice.ordd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.ordd_c.restype = c_int libspice.ordi_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.ordi_c.restype = c_int libspice.orderc_c.argtypes = [c_int, c_void_p, c_int, POINTER(c_int)] libspice.orderd_c.argtypes = [POINTER(c_double), c_int, POINTER(c_int)] libspice.orderi_c.argtypes = [POINTER(c_int), c_int, POINTER(c_int)] libspice.oscelt_c.argtypes = [c_double * 6, c_double, c_double, c_double * 8] ######################################################################################################################## # P libspice.pckcov_c.argtypes = [c_char_p, c_int, POINTER(stypes.SpiceCell)] libspice.pckfrm_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.pcklof_c.argtypes = [c_char_p, POINTER(c_int)] libspice.pckuof_c.argtypes = [c_int] libspice.pcpool_c.argtypes = [c_char_p, c_int, c_int, c_void_p] libspice.pdpool_c.argtypes = [c_char_p, c_int, POINTER(c_double)] libspice.pipool_c.argtypes = [c_char_p, c_int, POINTER(c_int)] libspice.pgrrec_c.argtypes = [c_char_p, c_double, c_double, c_double, c_double, c_double, (c_double * 3)] libspice.phaseq_c.argtypes = [c_double, c_char_p, c_char_p, c_char_p, c_char_p] libspice.phaseq_c.restype = c_double libspice.pi_c.restype = c_double libspice.pjelpl_c.argtypes = [POINTER(stypes.Ellipse), POINTER(stypes.Plane), POINTER(stypes.Ellipse)] libspice.pl2nvc_c.argtypes = [POINTER(stypes.Plane), (c_double * 3), POINTER(c_double)] libspice.pl2nvp_c.argtypes = [POINTER(stypes.Plane), (c_double * 3), (c_double * 3)] libspice.pl2psv_c.argtypes = [POINTER(stypes.Plane), (c_double * 3), (c_double * 3), (c_double * 3)] libspice.pos_c.argtypes = [c_char_p, c_char_p, c_int] libspice.pos_c.restype = c_int libspice.posr_c.argtypes = [c_char_p, c_char_p, c_int] libspice.posr_c.restype = c_int # libspice.prefix_c.argtypes = [c_char_p, c_int, c_int, c_char_p] libspice.prop2b_c.argtypes = [c_double, (c_double * 6), c_double, (c_double * 6)] libspice.prsdp_c.argtypes = [c_char_p, POINTER(c_double)] libspice.prsint_c.argtypes = [c_char_p, POINTER(c_int)] libspice.psv2pl_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3), POINTER(stypes.Plane)] libspice.putcml_c.argtypes = [c_int, c_char_p] libspice.pxform_c.argtypes = [c_char_p, c_char_p, c_double, (c_double * 3) * 3] libspice.pxfrm2_c.argtypes = [c_char_p, c_char_p, c_double, c_double, (c_double * 3) * 3] ######################################################################################################################## # Q libspice.q2m_c.argtypes = [c_double * 4, (c_double * 3) * 3] libspice.qcktrc_c.argtypes = [c_int, c_char_p] libspice.qdq2av_c.argtypes = [c_double * 4, c_double * 4, c_double * 3] libspice.qxq_c.argtypes = [c_double * 4, c_double * 4, c_double * 4] ######################################################################################################################## # R libspice.radrec_c.argtypes = [c_double, c_double, c_double, (c_double * 3)] libspice.rav2xf_c.argtypes = [(c_double * 3) * 3, (c_double * 3), (c_double * 6) * 6] libspice.raxisa_c.argtypes = [(c_double * 3) * 3, (c_double * 3), POINTER(c_double)] libspice.rdtext_c.argtypes = [c_char_p, c_int, c_char_p, POINTER(c_bool)] libspice.reccyl_c.argtypes = [(c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.recgeo_c.argtypes = [(c_double * 3), c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.reclat_c.argtypes = [(c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.recpgr_c.argtypes = [c_char_p, (c_double * 3), c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.recrad_c.argtypes = [(c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.recsph_c.argtypes = [(c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.reordc_c.argtypes = [POINTER(c_int), c_int, c_int, c_void_p] libspice.reordd_c.argtypes = [POINTER(c_int), c_int, POINTER(c_double)] libspice.reordi_c.argtypes = [POINTER(c_int), c_int, POINTER(c_int)] libspice.reordl_c.argtypes = [POINTER(c_int), c_int, POINTER(c_bool)] libspice.removc_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.removd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.removi_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.repmc_c.argtypes = [c_char_p, c_char_p, c_char_p, c_int, c_char_p] libspice.repmct_c.argtypes = [c_char_p, c_char_p, c_int, c_char, c_int, c_char_p] libspice.repmd_c.argtypes = [c_char_p, c_char_p, c_double, c_int, c_int, c_char_p] libspice.repmf_c.argtypes = [c_char_p, c_char_p, c_double, c_int, c_char, c_int, c_char_p] libspice.repmi_c.argtypes = [c_char_p, c_char_p, c_int, c_int, c_char_p] libspice.repmot_c.argtypes = [c_char_p, c_char_p, c_int, c_char, c_int, c_char_p] libspice.reset_c.argtypes = None libspice.return_c.argtypes = None libspice.return_c.restype = c_bool libspice.rotate_c.argtypes = [c_double, c_int, (c_double * 3) * 3] libspice.rotmat_c.argtypes = [(c_double * 3) * 3, c_double, c_int, (c_double * 3) * 3] libspice.rotvec_c.argtypes = [(c_double * 3), c_double, c_int, (c_double * 3)] libspice.rpd_c.restype = c_double libspice.rquad_c.argtypes = [c_double, c_double, c_double, (c_double * 2), (c_double * 2)] ######################################################################################################################## # S libspice.saelgv_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3), (c_double * 3)] libspice.scard_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.scdecd_c.argtypes = [c_int, c_double, c_int, c_char_p] libspice.sce2c_c.argtypes = [c_int, c_double, POINTER(c_double)] libspice.sce2s_c.argtypes = [c_int, c_double, c_int, c_char_p] libspice.sce2t_c.argtypes = [c_int, c_double, POINTER(c_double)] libspice.scencd_c.argtypes = [c_int, c_char_p, POINTER(c_double)] libspice.scfmt_c.argtypes = [c_int, c_double, c_int, c_char_p] libspice.scpart_c.argtypes = [c_int, POINTER(c_int), POINTER(c_double), POINTER(c_double)] libspice.scs2e_c.argtypes = [c_int, c_char_p, POINTER(c_double)] libspice.sct2e_c.argtypes = [c_int, c_double, POINTER(c_double)] libspice.sctiks_c.argtypes = [c_int, c_char_p, POINTER(c_double)] libspice.sdiff_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.set_c.argtypes = [POINTER(stypes.SpiceCell), c_char_p, POINTER(stypes.SpiceCell)] libspice.set_c.restype = c_bool libspice.setmsg_c.argtypes = [c_char_p] libspice.shellc_c.argtypes = [c_int, c_int, c_void_p] libspice.shelld_c.argtypes = [c_int, POINTER(c_double)] libspice.shelli_c.argtypes = [c_int, POINTER(c_int)] libspice.sigerr_c.argtypes = [c_char_p] libspice.sincpt_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, c_char_p, (c_double * 3), (c_double * 3), POINTER(c_double), (c_double * 3), POINTER(c_bool)] libspice.spd_c.restype = c_double libspice.sphcyl_c.argtypes = [c_double, c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.sphlat_c.argtypes = [c_double, c_double, c_double, POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.sphrec_c.argtypes = [c_double, c_double, c_double, (c_double * 3)] libspice.spk14a_c.argtypes = [c_int, c_int, POINTER(c_double), POINTER(c_double)] libspice.spk14b_c.argtypes = [c_int, c_char_p, c_int, c_int, c_char_p, c_double, c_double, c_int] libspice.spk14e_c.argtypes = [c_int] libspice.spkacs_c.argtypes = [c_int, c_double, c_char_p, c_char_p, c_int, (c_double * 6), POINTER(c_double), POINTER(c_double)] libspice.spkapo_c.argtypes = [c_int, c_double, c_char_p, (c_double * 6), c_char_p, (c_double * 3), POINTER(c_double)] libspice.spkapp_c.argtypes = [c_int, c_double, c_char_p, (c_double * 6), c_char_p, (c_double * 6), POINTER(c_double)] libspice.spkaps_c.argtypes = [c_int, c_double, c_char_p, c_char_p, (c_double * 6), (c_double * 6), (c_double * 6), POINTER(c_double), POINTER(c_double)] libspice.spkcls_c.argtypes = [c_int] libspice.spkcov_c.argtypes = [c_char_p, c_int, POINTER(stypes.SpiceCell)] libspice.spkcpo_c.argtypes = [c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 3), c_char_p, c_char_p, (c_double * 6), POINTER(c_double)] libspice.spkcpt_c.argtypes = [(c_double * 3), c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, c_char_p, (c_double * 6), POINTER(c_double)] libspice.spkcvo_c.argtypes = [c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 6), c_double, c_char_p, c_char_p, (c_double * 6), POINTER(c_double)] libspice.spkcvt_c.argtypes = [(c_double * 6), c_double, c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, c_char_p, (c_double * 6), POINTER(c_double)] libspice.spkez_c.argtypes = [c_int, c_double, c_char_p, c_char_p, c_int, (c_double * 6), POINTER(c_double)] libspice.spkezp_c.argtypes = [c_int, c_double, c_char_p, c_char_p, c_int, (c_double * 3), POINTER(c_double)] libspice.spkezr_c.argtypes = [c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 6), POINTER(c_double)] libspice.spkgeo_c.argtypes = [c_int, c_double, c_char_p, c_int, (c_double * 6), POINTER(c_double)] libspice.spkgps_c.argtypes = [c_int, c_double, c_char_p, c_int, (c_double * 3), POINTER(c_double)] libspice.spklef_c.argtypes = [c_char_p, POINTER(c_int)] libspice.spkltc_c.argtypes = [c_int, c_double, c_char_p, c_char_p, (c_double * 6), (c_double * 6), POINTER(c_double), POINTER(c_double)] libspice.spkobj_c.argtypes = [c_char_p, POINTER(stypes.SpiceCell)] libspice.spkopa_c.argtypes = [c_char_p, POINTER(c_int)] libspice.spkopn_c.argtypes = [c_char_p, c_char_p, c_int, POINTER(c_int)] libspice.spkpds_c.argtypes = [c_int, c_int, c_char_p, c_int, c_double, c_double, (c_double * 5)] libspice.spkpos_c.argtypes = [c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 3), POINTER(c_double)] libspice.spkpvn_c.argtypes = [c_int, (c_double * 5), c_double, POINTER(c_int), (c_double * 6), POINTER(c_int)] libspice.spksfs_c.argtypes = [c_int, c_double, c_int, POINTER(c_int), (c_double * 5), c_char_p, POINTER(c_bool)] libspice.spkssb_c.argtypes = [c_int, c_double, c_char_p, (c_double * 6)] libspice.spksub_c.argtypes = [c_int, (c_double * 5), c_char_p, c_double, c_double, c_int] libspice.spkuds_c.argtypes = [(c_double * 5), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_double), POINTER(c_double), POINTER(c_int), POINTER(c_int)] libspice.spkuef_c.argtypes = [c_int] libspice.spkw02_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_double, c_int, c_int, POINTER(c_double), c_double] libspice.spkw03_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_double, c_int, c_int, POINTER(c_double), c_double] libspice.spkw05_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_double, c_int, POINTER(c_double * 6), POINTER(c_double)] libspice.spkw08_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_int, c_int, POINTER(c_double * 6), c_double, c_double] libspice.spkw09_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_int, c_int, POINTER(c_double * 6), POINTER(c_double)] libspice.spkw10_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, (c_double * 8), c_int, POINTER(c_double), POINTER(c_double)] libspice.spkw12_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_int, c_int, POINTER(c_double * 6), c_double, c_double] libspice.spkw13_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_int, c_int, POINTER(c_double * 6), POINTER(c_double)] libspice.spkw15_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_double, (c_double * 3), (c_double * 3), c_double, c_double, c_double, (c_double * 3), c_double, c_double, c_double] libspice.spkw17_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_double, (c_double * 9), c_double, c_double] libspice.spkw18_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_int, c_int] libspice.spkw20_c.argtypes = [c_int, c_int, c_int, c_char_p, c_double, c_double, c_char_p, c_double, c_int, c_int, POINTER(c_double), c_double, c_double, c_double, c_double] libspice.srfrec_c.argtypes = [c_int, c_double, c_double, c_double * 3] libspice.size_c.argtypes = [POINTER(stypes.SpiceCell)] libspice.size_c.restype = c_int libspice.srfxpt_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 3), (c_double * 3), POINTER(c_double), POINTER(c_double), (c_double * 3), POINTER(c_bool)] libspice.ssize_c.argtypes = [c_int, POINTER(stypes.SpiceCell)] libspice.stelab_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.stpool_c.argtypes = [c_char_p, c_int, c_char_p, c_int, c_char_p, POINTER(c_int), POINTER(c_bool)] libspice.str2et_c.argtypes = [c_char_p, POINTER(c_double)] libspice.subpnt_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 3), POINTER(c_double), (c_double * 3)] libspice.subpt_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, (c_double * 3), POINTER(c_double)] libspice.subslr_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, c_char_p, (c_double * 3), POINTER(c_double), (c_double * 3)] libspice.subsol_c.argtypes = [c_char_p, c_char_p, c_double, c_char_p, c_char_p, (c_double * 3)] libspice.sumai_c.argtypes = [POINTER(c_int), c_int] libspice.sumai_c.restype = c_int libspice.sumad_c.argtypes = [POINTER(c_double), c_int] libspice.sumad_c.restype = c_double libspice.surfnm_c.argtypes = [c_double, c_double, c_double, (c_double * 3), (c_double * 3)] libspice.surfpt_c.argtypes = [(c_double * 3), (c_double * 3), c_double, c_double, c_double, (c_double * 3), POINTER(c_bool)] libspice.surfpv_c.argtypes = [(c_double * 6), (c_double * 6), c_double, c_double, c_double, (c_double * 6), POINTER(c_bool)] libspice.swpool_c.argtypes = [c_char_p, c_int, c_int, c_void_p] libspice.sxform_c.argtypes = [c_char_p, c_char_p, c_double, (c_double * 6) * 6] libspice.szpool_c.argtypes = [c_char_p, POINTER(c_int), POINTER(c_bool)] ######################################################################################################################## # T libspice.timdef_c.argtypes = [c_char_p, c_char_p, c_int, c_char_p] libspice.timout_c.argtypes = [c_double, c_char_p, c_int, c_char_p] libspice.tipbod_c.argtypes = [c_char_p, c_int, c_double, (c_double * 3) * 3] libspice.tisbod_c.argtypes = [c_char_p, c_int, c_double, (c_double * 6) * 6] libspice.tkvrsn_c.argtypes = [c_char_p] libspice.tkvrsn_c.restype = c_char_p libspice.tparse_c.argtypes = [c_char_p, c_int, POINTER(c_double), c_char_p] libspice.tpictr_c.argtypes = [c_char_p, c_int, c_int, c_char_p, POINTER(c_bool), c_char_p] libspice.trace_c.argtypes = [(c_double * 3) * 3] libspice.trace_c.restype = c_double libspice.trcdep_c.argtypes = [POINTER(c_int)] libspice.trcnam_c.argtypes = [c_int, c_int, c_char_p] libspice.trcoff_c.argtypes = None libspice.tsetyr_c.argtypes = [c_int] libspice.twopi_c.restype = c_double libspice.twovec_c.argtypes = [(c_double * 3), c_int, (c_double * 3), c_int, (c_double * 3) * 3] libspice.tyear_c.restype = c_double ######################################################################################################################## # U libspice.ucase_c.argtypes = [c_char_p, c_int, c_char_p] libspice.ucrss_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.uddc_c.argtypes = [c_double, c_double, c_double, c_double, c_bool] libspice.uddf_c.argtypes = [c_double, c_double, c_double, c_double, c_double] libspice.union_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.udf_c.argtypes = [c_double, POINTER(c_double)] libspice.unitim_c.argtypes = [c_double, c_char_p, c_char_p] libspice.unitim_c.restype = c_double libspice.unload_c.argtypes = [c_char_p] libspice.unorm_c.argtypes = [(c_double * 3), (c_double * 3), POINTER(c_double)] libspice.unormg_c.argtypes = [POINTER(c_double), c_int, POINTER(c_double), POINTER(c_double)] libspice.utc2et_c.argtypes = [c_char_p, POINTER(c_double)] ######################################################################################################################## # V libspice.vadd_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.vaddg_c.argtypes = [POINTER(c_double), POINTER(c_double), c_int, POINTER(c_double)] libspice.valid_c.argtypes = [c_int, c_int, POINTER(stypes.SpiceCell)] libspice.vcrss_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.vdist_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vdist_c.restype = c_double libspice.vdistg_c.argtypes = [POINTER(c_double), POINTER(c_double), c_int] libspice.vdistg_c.restype = c_double libspice.vdot_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vdot_c.restype = c_double libspice.vdotg_c.argtypes = [POINTER(c_double), POINTER(c_double), c_int] libspice.vdotg_c.restype = c_double libspice.vequ_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vequg_c.argtypes = [POINTER(c_double), c_int, POINTER(c_double)] libspice.vhat_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vhatg_c.argtypes = [POINTER(c_double), c_int, POINTER(c_double)] libspice.vlcom_c.argtypes = [c_double, (c_double * 3), c_double, (c_double * 3), (c_double * 3)] libspice.vlcom3_c.argtypes = [c_double, (c_double * 3), c_double, (c_double * 3), c_double, (c_double * 3), (c_double * 3)] libspice.vlcomg_c.argtypes = [c_int, c_double, POINTER(c_double), c_double, POINTER(c_double), POINTER(c_double)] libspice.vminug_c.argtypes = [POINTER(c_double), c_int, POINTER(c_double)] libspice.vminus_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vnorm_c.restype = c_double libspice.vnorm_c.argstype = [stypes.emptyDoubleVector(3)] libspice.vnormg_c.restype = c_double libspice.vnormg_c.argstype = [POINTER(c_double), c_int] libspice.vpack_c.argtypes = [c_double, c_double, c_double, (c_double * 3)] libspice.vperp_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.vprjp_c.argtypes = [(c_double * 3), POINTER(stypes.Plane), (c_double * 3)] libspice.vprjpi_c.argtypes = [(c_double * 3), POINTER(stypes.Plane), POINTER(stypes.Plane), (c_double * 3), POINTER(c_bool)] libspice.vproj_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.vrelg_c.argtypes = [POINTER(c_double), POINTER(c_double), c_int] libspice.vrelg_c.restype = c_double libspice.vrel_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vrel_c.restype = c_double libspice.vrotv_c.argtypes = [(c_double * 3), (c_double * 3), c_double, (c_double * 3)] libspice.vscl_c.argtypes = [c_double, (c_double * 3), (c_double * 3)] libspice.vsclg_c.argtypes = [c_double, POINTER(c_double), c_int, POINTER(c_double)] libspice.vsep_c.argtypes = [(c_double * 3), (c_double * 3)] libspice.vsep_c.restype = c_double libspice.vsepg_c.argtypes = [POINTER(c_double), POINTER(c_double), c_int] libspice.vsepg_c.restype = c_double libspice.vsub_c.argtypes = [(c_double * 3), (c_double * 3), (c_double * 3)] libspice.vsubg_c.argtypes = [POINTER(c_double), POINTER(c_double), c_int, POINTER(c_double)] libspice.vtmv_c.argtypes = [(c_double * 3), (c_double * 3) * 3, (c_double * 3)] libspice.vtmv_c.restype = c_double libspice.vtmvg_c.argtypes = [POINTER(c_double), c_void_p, POINTER(c_double), c_int, c_int] libspice.vtmvg_c.restype = c_double libspice.vupack_c.argtypes = [(c_double * 3), POINTER(c_double), POINTER(c_double), POINTER(c_double)] libspice.vzero_c.argtypes = [(c_double * 3)] libspice.vzero_c.restype = c_bool libspice.vzerog_c.argtypes = [POINTER(c_double), c_int] libspice.vzerog_c.restype = c_bool ######################################################################################################################## # W libspice.wncard_c.argtypes = [POINTER(stypes.SpiceCell)] libspice.wncard_c.restype = c_int libspice.wncomd_c.argtypes = [c_double, c_double, POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.wncond_c.argtypes = [c_double, c_double, POINTER(stypes.SpiceCell)] libspice.wndifd_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.wnelmd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.wnelmd_c.restype = c_bool libspice.wnexpd_c.argtypes = [c_double, c_double, POINTER(stypes.SpiceCell)] libspice.wnextd_c.argtypes = [c_char, POINTER(stypes.SpiceCell)] libspice.wnfetd_c.argtypes = [POINTER(stypes.SpiceCell), c_int, POINTER(c_double), POINTER(c_double)] libspice.wnfild_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.wnfltd_c.argtypes = [c_double, POINTER(stypes.SpiceCell)] libspice.wnincd_c.argtypes = [c_double, c_double, POINTER(stypes.SpiceCell)] libspice.wnincd_c.restype = c_bool libspice.wninsd_c.argtypes = [c_double, c_double, POINTER(stypes.SpiceCell)] libspice.wnintd_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.wnreld_c.argtypes = [POINTER(stypes.SpiceCell), c_char_p, POINTER(stypes.SpiceCell)] libspice.wnreld_c.restype = c_bool libspice.wnsumd_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(c_double), POINTER(c_double), POINTER(c_double), POINTER(c_int), POINTER(c_int)] libspice.wnunid_c.argtypes = [POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell), POINTER(stypes.SpiceCell)] libspice.wnvald_c.argtypes = [c_int, c_int, POINTER(stypes.SpiceCell)] ######################################################################################################################## # X libspice.xf2eul_c.argtypes = [(c_double * 6) * 6, c_int, c_int, c_int, (c_double * 6), POINTER(c_bool)] libspice.xf2rav_c.argtypes = [(c_double * 6) * 6, (c_double * 3) * 3, (c_double * 3)] libspice.xfmsta_c.argtypes = [(c_double * 6), c_char_p, c_char_p, c_char_p, (c_double * 6)] libspice.xpose_c.argtypes = [(c_double * 3) * 3, (c_double * 3) * 3] libspice.xpose6_c.argtypes = [(c_double * 6) * 6, (c_double * 6) * 6] libspice.xposeg_c.argtypes = [c_void_p, c_int, c_int, c_void_p] ######################################################################################################################## # Z libspice.zzgetcml_c.argtypes = [c_int, c_char_p, c_bool] libspice.zzgfsavh_c.argtypes = [c_bool] #libspice.zzsynccl_c.argtypes = [None]
{ "repo_name": "johnnycakes79/SpiceyPy", "path": "SpiceyPy/libspice.py", "copies": "1", "size": "52181", "license": "mit", "hash": 5319636619395495000, "line_mean": 65.472611465, "line_max": 289, "alpha_frac": 0.6189992526, "autogenerated": false, "ratio": 2.440759623930025, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.8542467797844637, "avg_score": 0.0034582157370774387, "num_lines": 785 }
__author__ = 'AndrewAnnex' import os from six.moves import urllib standardKernelList = ['pck00010.tpc', 'de421.bsp', 'gm_de431.tpc', 'naif0011.tls'] cwd = os.path.realpath(os.path.dirname(__file__)) def getKernel(url): kernelName = url.split('/')[-1] print('Downloading: {0}'.format(kernelName)) with open(os.path.join(cwd, kernelName), "wb") as kernel: kernel.write(urllib.request.urlopen(url).read()) def getStandardKernels(): print("\tChecking for kernels...\n") kernelURLlist = ['http://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/pck00010.tpc', 'http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/a_old_versions/de421.bsp', 'http://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/gm_de431.tpc', 'http://naif.jpl.nasa.gov/pub/naif/generic_kernels/lsk/naif0011.tls'] for kernel in kernelURLlist: if not os.path.isfile(os.path.join(cwd, kernel.split('/')[-1])): getKernel(kernel) def getExtraTestKernels(): # these are test kernels not included in the standard meta kernel voyagerSclk = "http://naif.jpl.nasa.gov/pub/naif/VOYAGER/kernels/sclk/vg200022.tsc" getKernel(voyagerSclk) earthTopoTf = "http://naif.jpl.nasa.gov/pub/naif/generic_kernels/fk/stations/earth_topo_050714.tf" getKernel(earthTopoTf) earthStnSpk = "http://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/stations/earthstns_itrf93_050714.bsp" getKernel(earthStnSpk) earthGenPck = "http://naif.jpl.nasa.gov/pub/naif/generic_kernels/pck/earth_720101_070426.bpc" getKernel(earthGenPck) def writeTestMetaKernel(): # Update the paths! with open(os.path.join(cwd, "testKernels.txt"), 'w') as kernelFile: kernelFile.write('\\begindata\n') kernelFile.write('KERNELS_TO_LOAD = (\n') for kernel in standardKernelList: kernelFile.write('\'{0}\'\n'.format(os.path.join(cwd, kernel))) kernelFile.write(')\n') kernelFile.write('\\begintext') kernelFile.close() print('\nDone writing test meta kernel.') def downloadKernels(): # Download the kernels listed in kernelList and kernelURLlist getStandardKernels() # Now grab any extra test kernels we need getExtraTestKernels() # Now create the meta kernal file for tests writeTestMetaKernel() if __name__ == '__main__': downloadKernels() getExtraTestKernels()
{ "repo_name": "johnnycakes79/SpiceyPy", "path": "test/gettestkernels.py", "copies": "3", "size": "2464", "license": "mit", "hash": -8391637550945294000, "line_mean": 36.9076923077, "line_max": 110, "alpha_frac": 0.6655844156, "autogenerated": false, "ratio": 2.997566909975669, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012655616437756629, "num_lines": 65 }
__author__ = 'AndrewAnnex' # wrapper.py, a weak wrapper for libspice.py, # here is where all the wrapper functions are located. import ctypes import SpiceyPy.support_types as stypes from SpiceyPy.libspice import libspice import functools import numpy ################################################################################ def checkForSpiceError(f): """ Internal function to check :param f: :raise stypes.SpiceyError: """ if failed(): errorparts = { "tkvsn": tkvrsn("TOOLKIT").replace("CSPICE_", ""), "short": getmsg("SHORT", 26), "explain": getmsg("EXPLAIN", 100).strip(), "long": getmsg("LONG", 321).strip(), "traceback": qcktrc(200)} msg = stypes.errorformat.format(**errorparts) reset() raise stypes.SpiceyError(msg) def spiceErrorCheck(f): """ Decorator for SpiceyPy hooking into spice error system. If an error is detected, an output simillar to outmsg_ :type f: builtins.function :return: :rtype: """ @functools.wraps(f) def with_errcheck(*args, **kwargs): try: res = f(*args, **kwargs) checkForSpiceError(f) return res except: raise return with_errcheck ################################################################################ # A @spiceErrorCheck def appndc(item, cell): """ Append an item to a character cell. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndc_c.html :param item: The item to append. :type item: str or list :param cell: The cell to append to. :type cell: SpiceyPy.support_types.SpiceCell """ assert isinstance(cell, stypes.SpiceCell) if isinstance(item, list): for c in item: libspice.appndc_c(stypes.stringToCharP(c), cell) else: item = stypes.stringToCharP(item) libspice.appndc_c(item, cell) pass @spiceErrorCheck def appndd(item, cell): """ Append an item to a double precision cell. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndd_c.html :param item: The item to append. :type item: float or list :param cell: The cell to append to. :type cell: SpiceyPy.support_types.SpiceCell """ assert isinstance(cell, stypes.SpiceCell) if hasattr(item, "__iter__"): for d in item: libspice.appndd_c(ctypes.c_double(d), cell) else: item = ctypes.c_double(item) libspice.appndd_c(item, cell) pass @spiceErrorCheck def appndi(item, cell): """ Append an item to an integer cell. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/appndi_c.html :param item: The item to append. :type item: int or list :param cell: The cell to append to. :type cell: SpiceyPy.support_types.SpiceCell """ assert isinstance(cell, stypes.SpiceCell) if hasattr(item, "__iter__"): for i in item: libspice.appndi_c(ctypes.c_int(i), cell) else: item = ctypes.c_int(item) libspice.appndi_c(item, cell) pass @spiceErrorCheck def axisar(axis, angle): """ Construct a rotation matrix that rotates vectors by a specified angle about a specified axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/axisar_c.html :param axis: Rotation axis. :type axis: 3 Element vector (list, tuple, numpy array) :param angle: Rotation angle, in radians. :type angle: float :return: Rotation matrix corresponding to axis and angle. :rtype: numpy array ((3, 3)) """ axis = stypes.toDoubleVector(axis) angle = ctypes.c_double(angle) r = stypes.emptyDoubleMatrix() libspice.axisar_c(axis, angle, r) return stypes.matrixToList(r) ################################################################################ # B @spiceErrorCheck def b1900(): """ Return the Julian Date corresponding to Besselian Date 1900.0. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/b1900_c.html :return: The Julian Date corresponding to Besselian Date 1900.0. :rtype: float """ return libspice.b1900_c() @spiceErrorCheck def b1950(): """ Return the Julian Date corresponding to Besselian Date 1950.0. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/b1950_c.html :return: The Julian Date corresponding to Besselian Date 1950.0. :rtype: float """ return libspice.b1950_c() @spiceErrorCheck def badkpv(caller, name, comp, insize, divby, intype): """ Determine if a kernel pool variable is present and if so that it has the correct size and type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/badkpv_c.html :param caller: Name of the routine calling this routine. :type caller: str :param name: Name of a kernel pool variable. :type name: str :param comp: Comparison operator. :type comp: str :param insize: Expected size of the kernel pool variable. :type insize: int :param divby: A divisor of the size of the kernel pool variable. :type divby: int :param intype: Expected type of the kernel pool variable :type intype: str :return: returns false if the kernel pool variable is OK. :rtype: bool """ caller = stypes.stringToCharP(caller) name = stypes.stringToCharP(name) comp = stypes.stringToCharP(comp) insize = ctypes.c_int(insize) divby = ctypes.c_int(divby) intype = ctypes.c_char(intype.encode(encoding='UTF-8')) return libspice.badkpv_c(caller, name, comp, insize, divby, intype) @spiceErrorCheck def bltfrm(frmcls, outSize=126): """ Return a SPICE set containing the frame IDs of all built-in frames of a specified class. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bltfrm_c.html :param frmcls: Frame class. :type frmcls: int :param outSize: Optional size for return cell. :type outSize: SpiceyPy.support_types.SpiceCell :return: Set of ID codes of frames of the specified class. :rtype: SpiceyPy.support_types.SpiceCell """ frmcls = ctypes.c_int(frmcls) outcell = stypes.SPICEINT_CELL(outSize) libspice.bltfrm_c(frmcls, outcell) return outcell @spiceErrorCheck def bodc2n(code, lenout): """ Translate the SPICE integer code of a body into a common name for that body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2n_c.html :param code: Integer ID code to be translated into a name. :type code: int :param lenout: Maximum length of output name. :type lenout: int :return: A common name for the body identified by code, Found flag. :rtype: tuple """ code = ctypes.c_int(code) name = stypes.stringToCharP(" " * lenout) lenout = ctypes.c_int(lenout) found = ctypes.c_bool() libspice.bodc2n_c(code, lenout, name, ctypes.byref(found)) return stypes.toPythonString(name), found.value @spiceErrorCheck def bodc2s(code, lenout): """ Translate a body ID code to either the corresponding name or if no name to ID code mapping exists, the string representation of the body ID value. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodc2s_c.html :param code: Integer ID code to translate to a string. :type code: int :param lenout: Maximum length of output name. :type lenout: int :return: String corresponding to 'code'. :rtype: str """ code = ctypes.c_int(code) name = stypes.stringToCharP(" " * lenout) lenout = ctypes.c_int(lenout) libspice.bodc2s_c(code, lenout, name) return stypes.toPythonString(name) @spiceErrorCheck def boddef(name, code): """ Define a body name/ID code pair for later translation via :func:`bodn2c` or :func:`bodc2n`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/boddef_c.html :param name: Common name of some body. :type name: str :param code: Integer code for that body. :type code: int """ name = stypes.stringToCharP(name) code = ctypes.c_int(code) libspice.boddef_c(name, code) pass @spiceErrorCheck def bodfnd(body, item): """ Determine whether values exist for some item for any body in the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodfnd_c.html :param body: ID code of body. :type body: int :param item: Item to find ("RADII", "NUT_AMP_RA", etc.). :type item: str :return: True if the item is in the kernel pool, and is False if it is not. :rtype: bool """ body = ctypes.c_int(body) item = stypes.stringToCharP(item) return libspice.bodfnd_c(body, item) @spiceErrorCheck def bodn2c(name): """ Translate the name of a body or object to the corresponding SPICE integer ID code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodn2c_c.html :param name: Body name to be translated into a SPICE ID code. :type name: str :return: SPICE integer ID code for the named body, Found Flag. :rtype: tuple """ name = stypes.stringToCharP(name) code = ctypes.c_int(0) found = ctypes.c_bool(0) libspice.bodn2c_c(name, ctypes.byref(code), ctypes.byref(found)) return code.value, found.value @spiceErrorCheck def bods2c(name): """ Translate a string containing a body name or ID code to an integer code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bods2c_c.html :param name: String to be translated to an ID code. :type name: str :return: Integer ID code corresponding to name, Found Flag. :rtype: tuple """ name = stypes.stringToCharP(name) code = ctypes.c_int(0) found = ctypes.c_bool(0) libspice.bods2c_c(name, ctypes.byref(code), ctypes.byref(found)) return code.value, found.value @spiceErrorCheck def bodvar(body, item, dim): """ Deprecated: This routine has been superseded by :func:`bodvcd` and :func:`bodvrd`. This routine is supported for purposes of backward compatibility only. Return the values of some item for any body in the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvar_c.html :param body: ID code of body. :type body: int :param item: Item for which values are desired, ("RADII", "NUT_PREC_ANGLES", etc.) :type item: str :param dim: Number of values returned. :type dim: int :return: values :rtype: N-Element Array of floats. """ body = ctypes.c_int(body) dim = ctypes.c_int(dim) item = stypes.stringToCharP(item) values = stypes.emptyDoubleVector(dim.value) libspice.bodvar_c(body, item, ctypes.byref(dim), values) return stypes.vectorToList(values) @spiceErrorCheck def bodvcd(bodyid, item, maxn): """ Fetch from the kernel pool the double precision values of an item associated with a body, where the body is specified by an integer ID code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvcd_c.html :param bodyid: Body ID code. :type bodyid: int :param item: Item for which values are desired, ("RADII", "NUT_PREC_ANGLES", etc.) :type item: str :param maxn: Maximum number of values that may be returned. :type maxn: int :return: dim, values :rtype: tuple """ bodyid = ctypes.c_int(bodyid) item = stypes.stringToCharP(item) dim = ctypes.c_int() values = stypes.emptyDoubleVector(maxn) maxn = ctypes.c_int(maxn) libspice.bodvcd_c(bodyid, item, maxn, ctypes.byref(dim), values) return dim.value, stypes.vectorToList(values) @spiceErrorCheck def bodvrd(bodynm, item, maxn): """ Fetch from the kernel pool the double precision values of an item associated with a body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodvrd_c.html :param bodynm: Body name. :type bodynm: str :param item: Item for which values are desired, ("RADII", "NUT_PREC_ANGLES", etc.) :type item: str :param maxn: Maximum number of values that may be returned. :type maxn: int :return: tuple of (dim, values) :rtype: tuple """ bodynm = stypes.stringToCharP(bodynm) item = stypes.stringToCharP(item) dim = ctypes.c_int() values = stypes.emptyDoubleVector(maxn) maxn = ctypes.c_int(maxn) libspice.bodvrd_c(bodynm, item, maxn, ctypes.byref(dim), values) return dim.value, stypes.vectorToList(values) @spiceErrorCheck def brcktd(number, end1, end2): """ Bracket a number. That is, given a number and an acceptable interval, make sure that the number is contained in the interval. (If the number is already in the interval, leave it alone. If not, set it to the nearest endpoint of the interval.) http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/brcktd_c.html :param number: Number to be bracketed. :type number: float :param end1: One of the bracketing endpoints for number. :type end1: float :param end2: The other bracketing endpoint for number. :type end2: float :return: value within an interval :rtype: float """ number = ctypes.c_double(number) end1 = ctypes.c_double(end1) end2 = ctypes.c_double(end2) return libspice.brcktd_c(number, end1, end2) @spiceErrorCheck def brckti(number, end1, end2): """ Bracket a number. That is, given a number and an acceptable interval, make sure that the number is contained in the interval. (If the number is already in the interval, leave it alone. If not, set it to the nearest endpoint of the interval.) http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/brckti_c.html :param number: Number to be bracketed. :type number: int :param end1: One of the bracketing endpoints for number. :type end1: int :param end2: The other bracketing endpoint for number. :type end2: int :return: value within an interval :rtype: int """ number = ctypes.c_int(number) end1 = ctypes.c_int(end1) end2 = ctypes.c_int(end2) return libspice.brckti_c(number, end1, end2) @spiceErrorCheck def bschoc(value, ndim, lenvals, array, order): """ Do a binary search for a given value within a character string array, accompanied by an order vector. Return the index of the matching array entry, or -1 if the key value is not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoc_c.html :param value: Key value to be found in array. :type value: str :param ndim: Dimension of array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: Character string array to search. :type array: list of strings :param order: Order vector. :type order: N-Element Array of ints. :return: index :rtype: int """ value = stypes.stringToCharP(value) ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(lenvals) array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim) order = stypes.toIntVector(order) return libspice.bschoc_c(value, ndim, lenvals, array, order) @spiceErrorCheck def bschoi(value, ndim, array, order): """ Do a binary search for a given value within an integer array, accompanied by an order vector. Return the index of the matching array entry, or -1 if the key value is not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bschoi_c.html :param value: Key value to be found in array. :type value: int :param ndim: Dimension of array. :type ndim: int :param array: Integer array to search. :type array: N-Element Array of ints. :param order: Order vector. :type order: N-Element Array of ints. :return: index :rtype: int """ value = ctypes.c_int(value) ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) order = stypes.toIntVector(order) return libspice.bschoi_c(value, ndim, array, order) @spiceErrorCheck def bsrchc(value, ndim, lenvals, array): """ Do a binary earch for a given value within a character string array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchc_c.html :param value: Key value to be found in array. :type value: str :param ndim: Dimension of array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: Character string array to search. :type array: list of strings :return: index :rtype: int """ value = stypes.stringToCharP(value) ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(lenvals) array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim) return libspice.bsrchc_c(value, ndim, lenvals, array) @spiceErrorCheck def bsrchd(value, ndim, array): """ Do a binary search for a key value within a double precision array, assumed to be in increasing order. Return the index of the matching array entry, or -1 if the key value is not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchd_c.html :param value: Value to find in array. :type value: float :param ndim: Dimension of array. :type ndim: int :param array: Array to be searched. :type array: N-Element Array of floats. :return: index :rtype: int """ value = ctypes.c_double(value) ndim = ctypes.c_int(ndim) array = stypes.toDoubleVector(array) return libspice.bsrchd_c(value, ndim, array) @spiceErrorCheck def bsrchi(value, ndim, array): """ Do a binary search for a key value within an integer array, assumed to be in increasing order. Return the index of the matching array entry, or -1 if the key value is not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html :param value: Value to find in array. :type value: int :param ndim: Dimension of array. :type ndim: int :param array: Array to be searched. :type array: N-Element Array of ints. :return: index :rtype: int """ value = ctypes.c_int(value) ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) return libspice.bsrchi_c(value, ndim, array) ################################################################################ # C @spiceErrorCheck def card(cell): """ Return the cardinality (current number of elements) in a cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/card_c.html :param cell: Input cell. :type cell: SpiceyPy.support_types.SpiceCell :return: the number of elements in a cell of any data type. :rtype: int """ return libspice.card_c(ctypes.byref(cell)) @spiceErrorCheck def ccifrm(frclss, clssid, lenout): """ Return the frame name, frame ID, and center associated with a given frame class and class ID. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ccifrm_c.html :param frclss: Class of frame. :type frclss: int :param clssid: Class ID of frame. :type clssid: int :param lenout: Maximum length of output string. :type lenout: int :return: the frame name, frame ID, center, and found. :rtype: tuple """ frclss = ctypes.c_int(frclss) clssid = ctypes.c_int(clssid) lenout = ctypes.c_int(lenout) frcode = ctypes.c_int() frname = stypes.stringToCharP(lenout) center = ctypes.c_int() found = ctypes.c_bool() libspice.ccifrm_c(frclss, clssid, lenout, ctypes.byref(frcode), frname, ctypes.byref(center), ctypes.byref(found)) return frcode.value, stypes.toPythonString(frname), center.value, found.value @spiceErrorCheck def cgv2el(center, vec1, vec2): """ Form a SPICE ellipse from a center vector and two generating vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cgv2el_c.html :param center: Center Vector :type center: 3-Element Array of floats :param vec1: Vector 1 :type vec1: 3-Element Array of floats :param vec2: Vector 2 :type vec2: 3-Element Array of floats :return: Ellipse :rtype: SpiceyPy.support_types.Ellipse """ center = stypes.toDoubleVector(center) vec1 = stypes.toDoubleVector(vec1) vec2 = stypes.toDoubleVector(vec2) ellipse = stypes.Ellipse() libspice.cgv2el_c(center, vec1, vec2, ctypes.byref(ellipse)) return ellipse @spiceErrorCheck def chkin(module): """ Inform the SPICE error handling mechanism of entry into a routine. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/chkin_c.html :param module: The name of the calling routine. :type module: str """ module = stypes.stringToCharP(module) libspice.chkin_c(module) pass @spiceErrorCheck def chkout(module): """ Inform the SPICE error handling mechanism of exit from a routine. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/chkout_c.html :param module: The name of the calling routine. :type module: str """ module = stypes.stringToCharP(module) libspice.chkout_c(module) pass @spiceErrorCheck def cidfrm(cent, lenout): """ Retrieve frame ID code and name to associate with a frame center. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cidfrm_c.html :param cent: An object to associate a frame with. :type cent: int :param lenout: Available space in output string frname. :type lenout: int :return: frame ID code, name to associate with a frame center, Found Flag. :rtype: tuple """ cent = ctypes.c_int(cent) lenout = ctypes.c_int(lenout) frcode = ctypes.c_int() frname = stypes.stringToCharP(lenout) found = ctypes.c_bool() libspice.cidfrm_c(cent, lenout, ctypes.byref(frcode), frname, ctypes.byref(found)) return frcode.value, stypes.toPythonString(frname), found.value @spiceErrorCheck def ckcls(handle): """ Close an open CK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckcls_c.html :param handle: Handle of the CK file to be closed. :type handle: int """ handle = ctypes.c_int(handle) libspice.ckcls_c(handle) pass @spiceErrorCheck def ckcov(ck, idcode, needav, level, tol, timsys, cover=None): # Todo: test ckcov """ Find the coverage window for a specified object in a specified CK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckcov_c.html :param ck: Name of CK file. :type ck: str :param idcode: ID code of object. :type idcode: int :param needav: Flag indicating whether angular velocity is needed. :type needav: bool :param level: Coverage level: (SEGMENT OR INTERVAL) :type level: str :param tol: Tolerance in ticks. :type tol: float :param timsys: Time system used to represent coverage. :type timsys: str :param cover: Window giving coverage for idcode. :type cover: Optional SpiceCell :return: coverage window for a specified object in a specified CK file :rtype: SpiceyPy.support_types.SpiceCell """ ck = stypes.stringToCharP(ck) idcode = ctypes.c_int(idcode) needav = ctypes.c_bool(needav) level = stypes.stringToCharP(level) tol = ctypes.c_double(tol) timsys = stypes.stringToCharP(timsys) if not cover: cover = stypes.SPICEDOUBLE_CELL(2000) assert isinstance(cover, stypes.SpiceCell) assert cover.dtype == 1 libspice.ckcov_c(ck, idcode, needav, level, tol, timsys, ctypes.byref(cover)) return cover @spiceErrorCheck def ckgp(inst, sclkdp, tol, ref): # Todo: test ckgp """ Get pointing (attitude) for a specified spacecraft clock time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgp_c.html :param inst: NAIF ID of instrument, spacecraft, or structure. :type inst: int :param sclkdp: Encoded spacecraft clock time. :type sclkdp: float :param tol: Time tolerance. :type tol: float :param ref: Reference frame. :type ref: str :return: C-matrix pointing data, Output encoded spacecraft clock time, True when requested pointing is available. :rtype: tuple """ inst = ctypes.c_int(inst) sclkdp = ctypes.c_double(sclkdp) tol = ctypes.c_double(tol) ref = stypes.stringToCharP(ref) cmat = stypes.emptyDoubleMatrix() clkout = ctypes.c_double() found = ctypes.c_bool() libspice.ckgp_c(inst, sclkdp, tol, ref, cmat, ctypes.byref(clkout), ctypes.byref(found)) return stypes.matrixToList(cmat), clkout.value, found.value @spiceErrorCheck def ckgpav(inst, sclkdp, tol, ref): # Todo: test ckgpav """ Get pointing (attitude) and angular velocity for a specified spacecraft clock time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgpav_c.html :param inst: NAIF ID of instrument, spacecraft, or structure. :type inst: int :param sclkdp: Encoded spacecraft clock time. :type sclkdp: float :param tol: Time tolerance. :type tol: float :param ref: Reference frame. :type ref: str :return: C-matrix pointing data, Angular velocity vector, Output encoded spacecraft clock time, True when requested pointing is available. :rtype: tuple """ inst = ctypes.c_int(inst) sclkdp = ctypes.c_double(sclkdp) tol = ctypes.c_double(tol) ref = stypes.stringToCharP(ref) cmat = stypes.emptyDoubleMatrix() av = stypes.emptyDoubleVector(3) clkout = ctypes.c_double() found = ctypes.c_bool() libspice.ckgpav_c(inst, sclkdp, tol, ref, cmat, av, ctypes.byref(clkout), ctypes.byref(found)) return stypes.matrixToList(cmat), stypes.vectorToList( av), clkout.value, found.value @spiceErrorCheck def cklpf(filename): # Todo: test cklpf """ Load a CK pointing file for use by the CK readers. Return that file's handle, to be used by other CK routines to refer to the file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cklpf_c.html :param filename: Name of the CK file to be loaded. :type filename: str :return: Loaded file's handle. :rtype: int """ filename = stypes.stringToCharP(filename) handle = ctypes.c_int() libspice.cklpf_c(filename, ctypes.byref(handle)) return handle.value @spiceErrorCheck def ckobj(ck, ids=None): # Todo: test ckobj """ Find the set of ID codes of all objects in a specified CK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html :param ck: Name of CK file. :type ck: str :param ids: Optional user provided spicecell. :type ids: Optional SpiceyPy.support_types.SpiceCell :return: Set of ID codes of objects in CK file. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(ck, str) ck = stypes.stringToCharP(ck) if not ids: ids = stypes.SPICEINT_CELL(1000) assert isinstance(ids, stypes.SpiceCell) assert ids.dtype == 2 libspice.ckobj_c(ck, ctypes.byref(ids)) return ids @spiceErrorCheck def ckopn(filename, ifname, ncomch): """ Open a new CK file, returning the handle of the opened file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckopn_c.html :param filename: The name of the CK file to be opened. :type filename: str :param ifname: The internal filename for the CK. :type ifname: str :param ncomch: The number of characters to reserve for comments. :type ncomch: int :return: The handle of the opened CK file. :rtype: int """ filename = stypes.stringToCharP(filename) ifname = stypes.stringToCharP(ifname) ncomch = ctypes.c_int(ncomch) handle = ctypes.c_int() libspice.ckopn_c(filename, ifname, ncomch, ctypes.byref(handle)) return handle.value @spiceErrorCheck def ckupf(handle): # Todo: test ckupf """ Unload a CK pointing file so that it will no longer be searched by the readers. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckupf_c.html :param handle: Handle of CK file to be unloaded :type handle: int """ handle = ctypes.c_int(handle) libspice.ckupf_c(handle) pass @spiceErrorCheck def ckw01(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats, avvs): """ Add a type 1 segment to a C-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw01_c.html :param handle: Handle of an open CK file. :type handle: int :param begtim: The beginning encoded SCLK of the segment. :type begtim: float :param endtim: The ending encoded SCLK of the segment. :type endtim: float :param inst: The NAIF instrument ID code. :type inst: int :param ref: The reference frame of the segment. :type ref: str :param avflag: True if the segment will contain angular velocity. :type avflag: bool :param segid: Segment identifier. :type segid: str :param nrec: Number of pointing records. :type nrec: int :param sclkdp: Encoded SCLK times. :type sclkdp: N-Element Array of floats. :param quats: Quaternions representing instrument pointing. :type quats: Nx4-Element Array of floats. :param avvs: Angular velocity vectors. :type avvs: Nx3-Element Array of floats. """ handle = ctypes.c_int(handle) begtim = ctypes.c_double(begtim) endtim = ctypes.c_double(endtim) inst = ctypes.c_int(inst) ref = stypes.stringToCharP(ref) avflag = ctypes.c_bool(avflag) segid = stypes.stringToCharP(segid) sclkdp = stypes.toDoubleVector(sclkdp) quats = stypes.toDoubleMatrix(quats) avvs = stypes.toDoubleMatrix(avvs) nrec = ctypes.c_int(nrec) libspice.ckw01_c(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats, avvs) pass @spiceErrorCheck def ckw02(handle, begtim, endtim, inst, ref, segid, nrec, start, stop, quats, avvs, rates): """ Write a type 2 segment to a C-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw02_c.html :param handle: Handle of an open CK file. :type handle: int :param begtim: The beginning encoded SCLK of the segment. :type begtim: float :param endtim: The ending encoded SCLK of the segment. :type endtim: float :param inst: The NAIF instrument ID code. :type inst: int :param ref: The reference frame of the segment. :type ref: str :param segid: Segment identifier. :type segid: str :param nrec: Number of pointing records. :type nrec: int :param start: Encoded SCLK interval start times. :type start: N-Element Array of floats. :param stop: Encoded SCLK interval stop times. :type stop: N-Element Array of floats. :param quats: Quaternions representing instrument pointing. :type quats: Nx4-Element Array of floats. :param avvs: Angular velocity vectors. :type avvs: Nx3-Element Array of floats. :param rates: Number of seconds per tick for each interval. :type rates: N-Element Array of floats. """ handle = ctypes.c_int(handle) begtim = ctypes.c_double(begtim) endtim = ctypes.c_double(endtim) inst = ctypes.c_int(inst) ref = stypes.stringToCharP(ref) segid = stypes.stringToCharP(segid) start = stypes.toDoubleVector(start) stop = stypes.toDoubleVector(stop) rates = stypes.toDoubleVector(rates) quats = stypes.toDoubleMatrix(quats) avvs = stypes.toDoubleMatrix(avvs) nrec = ctypes.c_int(nrec) libspice.ckw02_c(handle, begtim, endtim, inst, ref, segid, nrec, start, stop, quats, avvs, rates) pass @spiceErrorCheck def ckw03(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats, avvs, nints, starts): """ Add a type 3 segment to a C-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw03_c.html :param handle: Handle of an open CK file. :type handle: int :param begtim: The beginning encoded SCLK of the segment. :type begtim: float :param endtim: The ending encoded SCLK of the segment. :type endtim: float :param inst: The NAIF instrument ID code. :type inst: int :param ref: The reference frame of the segment. :type ref: str :param avflag: True if the segment will contain angular velocity. :type avflag: bool :param segid: Segment identifier. :type segid: str :param nrec: Number of pointing records. :type nrec: int :param sclkdp: Encoded SCLK times. :type sclkdp: N-Element Array of floats. :param quats: Quaternions representing instrument pointing. :type quats: Nx4-Element Array of floats. :param avvs: Angular velocity vectors. :type avvs: Nx3-Element Array of floats. :param nints: Number of intervals. :type nints: int :param starts: Encoded SCLK interval start times. :type starts: N-Element Array of floats. """ handle = ctypes.c_int(handle) begtim = ctypes.c_double(begtim) endtim = ctypes.c_double(endtim) inst = ctypes.c_int(inst) ref = stypes.stringToCharP(ref) avflag = ctypes.c_bool(avflag) segid = stypes.stringToCharP(segid) sclkdp = stypes.toDoubleVector(sclkdp) quats = stypes.toDoubleMatrix(quats) avvs = stypes.toDoubleMatrix(avvs) nrec = ctypes.c_int(nrec) starts = stypes.toDoubleVector(starts) nints = ctypes.c_int(nints) libspice.ckw03_c(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats, avvs, nints, starts) pass # ckw05, skipping, ck05subtype? @spiceErrorCheck def clight(): """ Return the speed of light in a vacuum (IAU official value, in km/sec). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/clight_c.html :return: The function returns the speed of light in vacuum (km/sec). :rtype: float """ return libspice.clight_c() @spiceErrorCheck def clpool(): """ Remove all variables from the kernel pool. Watches on kernel variables are retained. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/clpool_c.html """ libspice.clpool_c() pass @spiceErrorCheck def cmprss(delim, n, instr, lenout=None): """ Compress a character string by removing occurrences of more than N consecutive occurrences of a specified character. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cmprss_c.html :param delim: Delimiter to be compressed. :type delim: str :param n: Maximum consecutive occurrences of delim. :type n: int :param instr: Input string. :type instr: str :param lenout: Optional available space in output string. :type lenout: Optional int :return: Compressed string. :rtype: str """ if lenout is None: lenout = ctypes.c_int(len(instr) + 1) delim = ctypes.c_char(delim.encode(encoding='UTF-8')) n = ctypes.c_int(n) instr = stypes.stringToCharP(instr) output = stypes.stringToCharP(lenout) libspice.cmprss_c(delim, n, instr, lenout, output) return stypes.toPythonString(output) @spiceErrorCheck def cnmfrm(cname, lenout): """ Retrieve frame ID code and name to associate with an object. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cnmfrm_c.html :param cname: Name of the object to find a frame for. :type cname: int :param lenout: Maximum length available for frame name. :type lenout: int :return: The ID code of the frame associated with cname, The name of the frame with ID frcode, Found flag. :rtype: tuple """ lenout = ctypes.c_int(lenout) frname = stypes.stringToCharP(lenout) cname = stypes.stringToCharP(cname) found = ctypes.c_bool() frcode = ctypes.c_int() libspice.cnmfrm_c(cname, lenout, ctypes.byref(frcode), frname, ctypes.byref(found)) return frcode.value, stypes.toPythonString(frname), found.value @spiceErrorCheck def conics(elts, et): """ Determine the state (position, velocity) of an orbiting body from a set of elliptic, hyperbolic, or parabolic orbital elements. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/conics_c.html :param elts: Conic elements. :type elts: 8-Element Array of floats :param et: Input time. :type et: float :return: State of orbiting body at et. :rtype: 6-Element Array of floats """ elts = stypes.toDoubleVector(elts) et = ctypes.c_double(et) state = stypes.emptyDoubleVector(6) libspice.conics_c(elts, et, state) return stypes.vectorToList(state) @spiceErrorCheck def convrt(x, inunit, outunit): """ Take a measurement X, the units associated with X, and units to which X should be converted; return Y the value of the measurement in the output units. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/convrt_c.html :param x: Number representing a measurement in some units. :type x: float :param inunit: The units in which x is measured. :type inunit: str :param outunit: Desired units for the measurement. :type outunit: str :return: The measurment in the desired units. :rtype: float """ x = ctypes.c_double(x) inunit = stypes.stringToCharP(inunit) outunit = stypes.stringToCharP(outunit) y = ctypes.c_double() libspice.convrt_c(x, inunit, outunit, ctypes.byref(y)) return y.value @spiceErrorCheck def copy(cell): """ Copy the contents of a SpiceCell of any data type to another cell of the same type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html :param cell: Cell to be copied. :type cell: SpiceyPy.support_types.SpiceCell :return: New cell :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(cell, stypes.SpiceCell) assert cell.dtype == 0 or cell.dtype == 1 or cell.dtype == 2 if cell.dtype is 0: newcopy = stypes.SPICECHAR_CELL(cell.size, cell.length) elif cell.dtype is 1: newcopy = stypes.SPICEDOUBLE_CELL(cell.size) elif cell.dtype is 2: newcopy = stypes.SPICEINT_CELL(cell.size) else: raise NotImplementedError libspice.copy_c(ctypes.byref(cell), ctypes.byref(newcopy)) return newcopy @spiceErrorCheck def cpos(string, chars, start): """ Find the first occurrence in a string of a character belonging to a collection of characters, starting at a specified location, searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cpos_c.html :param string: Any character string. :type string: str :param chars: A collection of characters. :type chars: str :param start: Position to begin looking for one of chars. :type start: int :return: The index of the first character of str at or following index start that is in the collection chars. :rtype: int """ string = stypes.stringToCharP(string) chars = stypes.stringToCharP(chars) start = ctypes.c_int(start) return libspice.cpos_c(string, chars, start) @spiceErrorCheck def cposr(string, chars, start): """ Find the first occurrence in a string of a character belonging to a collection of characters, starting at a specified location, searching in reverse. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cposr_c.html :param string: Any character string. :type string: str :param chars: A collection of characters. :type chars: str :param start: Position to begin looking for one of chars. :type start: int :return: The index of the last character of str at or before index start that is in the collection chars. :rtype: int """ string = stypes.stringToCharP(string) chars = stypes.stringToCharP(chars) start = ctypes.c_int(start) return libspice.cposr_c(string, chars, start) @spiceErrorCheck def cvpool(agent): # Todo: test cvpool """ Indicate whether or not any watched kernel variables that have a specified agent on their notification list have been updated. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cvpool_c.html :param agent: Name of the agent to check for notices. :type agent: str :return: True if variables for "agent" have been updated. :rtype: bool """ agent = stypes.stringToCharP(agent) update = ctypes.c_bool() libspice.cvpool_c(agent, ctypes.byref(update)) return update.value @spiceErrorCheck def cyllat(r, lonc, z): """ Convert from cylindrical to latitudinal coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cyllat_c.html :param r: Distance of point from z axis. :type r: float :param lonc: Cylindrical angle of point from XZ plane(radians). :type lonc: float :param z: Height of point above XY plane. :type z: float :return: Distance, Longitude (radians), and Latitude of point (radians). :rtype: tuple """ r = ctypes.c_double(r) lonc = ctypes.c_double(lonc) z = ctypes.c_double(z) radius = ctypes.c_double() lon = ctypes.c_double() lat = ctypes.c_double() libspice.cyllat_c(r, lonc, z, ctypes.byref(radius), ctypes.byref(lon), ctypes.byref(lat)) return radius.value, lon.value, lat.value @spiceErrorCheck def cylrec(r, lon, z): """ Convert from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html :param r: Distance of a point from z axis. :type r: float :param lon: Angle (radians) of a point from xZ plane. :type lon: float :param z: Height of a point above xY plane. :type z: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of floats. """ r = ctypes.c_double(r) lon = ctypes.c_double(lon) z = ctypes.c_double(z) rectan = stypes.emptyDoubleVector(3) libspice.cylrec_c(r, lon, z, rectan) return stypes.vectorToList(rectan) @spiceErrorCheck def cylsph(r, lonc, z): """ Convert from cylindrical to spherical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylsph_c.html :param r: Rectangular coordinates of the point. :type r: float :param lonc: Angle (radians) of point from XZ plane. :type lonc: float :param z: Height of point above XY plane. :type z: float :return: Distance of point from origin, Polar angle (co-latitude in radians) of point, Azimuthal angle (longitude) of point (radians). :rtype: tuple """ r = ctypes.c_double(r) lonc = ctypes.c_double(lonc) z = ctypes.c_double(z) radius = ctypes.c_double() colat = ctypes.c_double() lon = ctypes.c_double() libspice.cyllat_c(r, lonc, z, ctypes.byref(radius), ctypes.byref(colat), ctypes.byref(lon)) return radius.value, colat.value, lon.value ################################################################################ # D @spiceErrorCheck def dafac(handle, n, lenvals, buffer): # Todo: test dafac """ Add comments from a buffer of character strings to the comment area of a binary DAF file, appending them to any comments which are already present in the file's comment area. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafac_c.html :param handle: handle of a DAF opened with write access. :type handle: int :param n: Number of comments to put into the comment area. :type n: int :param lenvals: Length of elements :type lenvals: int :param buffer: Buffer of comments to put into the comment area. :type buffer: N-Element Array of str """ handle = ctypes.c_int(handle) buffer = stypes.listToCharArrayPtr(buffer) n = ctypes.c_int(n) lenvals = ctypes.c_int(lenvals) libspice.dafac_c(handle, n, lenvals, ctypes.byref(buffer)) pass @spiceErrorCheck def dafbbs(handle): """ Begin a backward search for arrays in a DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafbbs_c.html :param handle: Handle of DAF to be searched. :type handle: int """ handle = ctypes.c_int(handle) libspice.dafbbs_c(handle) pass @spiceErrorCheck def dafbfs(handle): """ Begin a forward search for arrays in a DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafbfs_c.html :param handle: Handle of file to be searched. :type handle: int """ handle = ctypes.c_int(handle) libspice.dafbfs_c(handle) pass @spiceErrorCheck def dafcls(handle): """ Close the DAF associated with a given handle. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafcls_c.html :param handle: Handle of DAF to be closed. :type handle: int """ handle = ctypes.c_int(handle) libspice.dafcls_c(handle) pass @spiceErrorCheck def dafcs(handle): """ Select a DAF that already has a search in progress as the one to continue searching. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafcs_c.html :param handle: Handle of DAF to continue searching. :type handle: int """ handle = ctypes.c_int(handle) libspice.dafcs_c(handle) pass @spiceErrorCheck def dafdc(handle): # Todo: test dafdc """ Delete the entire comment area of a specified DAF file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafdc_c.html :param handle: The handle of a binary DAF opened for writing. :type handle: int """ handle = ctypes.c_int(handle) libspice.dafcc_c(handle) pass @spiceErrorCheck def dafec(handle, bufsiz, lenout): """ Extract comments from the comment area of a binary DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafec_c.html :param handle: Handle of binary DAF opened with read access. :type handle: int :param bufsiz: Maximum size, in lines, of buffer. :type bufsiz: int :param lenout: Length of strings in output buffer. :type lenout: int :return: Number of extracted comment lines, buffer where extracted comment lines are placed, Indicates whether all comments have been extracted. :rtype: tuple """ handle = ctypes.c_int(handle) buffer = stypes.charvector(bufsiz, lenout) bufsiz = ctypes.c_int(bufsiz) lenout = ctypes.c_int(lenout) n = ctypes.c_int() done = ctypes.c_bool() libspice.dafec_c(handle, bufsiz, lenout, ctypes.byref(n), ctypes.byref(buffer), ctypes.byref(done)) return n.value, stypes.vectorToList(buffer), done.value @spiceErrorCheck def daffna(): """ Find the next (forward) array in the current DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffna_c.html :return: True if an array was found. :rtype: bool """ found = ctypes.c_bool() libspice.daffna_c(ctypes.byref(found)) return found.value @spiceErrorCheck def daffpa(): """ Find the previous (backward) array in the current DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/daffpa_c.html :return: True if an array was found. :rtype: bool """ found = ctypes.c_bool() libspice.daffpa_c(ctypes.byref(found)) return found.value @spiceErrorCheck def dafgda(handle, begin, end): """ Read the double precision data bounded by two addresses within a DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgda_c.html :param handle: Handle of a DAF. :type handle: int :param begin: Initial address within file. :type begin: int :param end: Final address within file. :type end: int :return: Data contained between begin and end. :rtype: N-Element Array of floats. """ handle = ctypes.c_int(handle) data = stypes.emptyDoubleVector(abs(end - begin)) begin = ctypes.c_int(begin) end = ctypes.c_int(end) libspice.dafgda_c(handle, begin, end, data) return stypes.vectorToList(data) @spiceErrorCheck def dafgh(): """ Return (get) the handle of the DAF currently being searched. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgh_c.html :return: Handle for current DAF. :rtype: int """ outvalue = ctypes.c_int() libspice.dafgh_c(ctypes.byref(outvalue)) return outvalue.value @spiceErrorCheck def dafgn(lenout): """ Return (get) the name for the current array in the current DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgn_c.html :param lenout: Length of array name string. :type lenout: int :return: Name of current array. :rtype: str """ lenout = ctypes.c_int(lenout) name = stypes.stringToCharP(lenout) libspice.dafgn_c(lenout, name) return stypes.toPythonString(name) @spiceErrorCheck def dafgs(n=125): # The 125 may be a hard set, # I got strange errors that occasionally happend without it """ Return (get) the summary for the current array in the current DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgs_c.html :param n: Optional length N for result Array. :return: Summary for current array. :rtype: N-Element Array of floats. """ retarray = stypes.emptyDoubleVector(125) # libspice.dafgs_c(ctypes.cast(retarray, ctypes.POINTER(ctypes.c_double))) libspice.dafgs_c(retarray) return stypes.vectorToList(retarray)[0:n] @spiceErrorCheck def dafgsr(handle, recno, begin, end): # Todo test dafgsr """ Read a portion of the contents of a summary record in a DAF file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgsr_c.html :param handle: Handle of DAF. :type handle: int :param recno: Record number. :type recno: int :param begin: First word to read from record. :type begin: int :param end: Last word to read from record. :type end: int :return: Contents of record, True if record is found. :rtype: tuple """ handle = ctypes.c_int(handle) recno = ctypes.c_int(recno) begin = ctypes.c_int(begin) end = ctypes.c_int(end) data = ctypes.c_double() found = ctypes.c_bool() libspice.dafgsr_c(handle, recno, begin, end, ctypes.byref(data), ctypes.byref(found)) return data.value, found.value @spiceErrorCheck def dafopr(fname): """ Open a DAF for subsequent read requests. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafopr_c.html :param fname: Name of DAF to be opened. :type fname: str :return: Handle assigned to DAF. :rtype: int """ fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.dafopr_c(fname, ctypes.byref(handle)) return handle.value @spiceErrorCheck def dafopw(fname): """ Open a DAF for subsequent write requests. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafopw_c.html :param fname: Name of DAF to be opened. :type fname: str :return: Handle assigned to DAF. :rtype: int """ fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.dafopw_c(fname, ctypes.byref(handle)) return handle.value @spiceErrorCheck def dafps(nd, ni, dc, ic): # Todo: test dafps """ Pack (assemble) an array summary from its double precision and integer components. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafps_c.html :param nd: Number of double precision components. :type nd: int :param ni: Number of integer components. :type ni: int :param dc: Double precision components. :type dc: N-Element Array of floats. :param ic: Integer components. :type ic: N-Element Array of ints. :return: Array summary. :rtype: N-Element Array of floats. """ dc = stypes.toDoubleVector(dc) ic = stypes.toIntVector(ic) outsum = stypes.emptyDoubleVector(nd + ni) nd = ctypes.c_int(nd) ni = ctypes.c_int(ni) libspice.dafps_c(nd, ni, ctypes.byref(dc), ctypes.byref(ic), ctypes.byref(outsum)) return stypes.vectorToList(outsum) @spiceErrorCheck def dafrda(handle, begin, end): # Todo: test dafrda """ Read the double precision data bounded by two addresses within a DAF. Deprecated: This routine has been superseded by :func:`dafgda` and :func:`dafgsr`. This routine is supported for purposes of backward compatibility only. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafrda_c.html :param handle: Handle of a DAF. :type handle: int :param begin: Initial address within file. :type begin: int :param end: Final address within file. :type end: int :return: Data contained between begin and end. :rtype: N-Element Array of floats. """ handle = ctypes.c_int(handle) begin = ctypes.c_int(begin) end = ctypes.c_int(end) data = stypes.emptyDoubleVector(8) # value of 8 from help file libspice.dafrda_c(handle, begin, end, ctypes.byref(data)) return stypes.vectorToList(data) @spiceErrorCheck def dafrfr(handle, lenout): """ Read the contents of the file record of a DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafrfr_c.html :param handle: Handle of an open DAF file. :type handle: int :param lenout: Available room in the output string :type lenout: int :return: Number of double precision components in summaries, Number of integer components in summaries, Internal file name, Forward list pointer, Backward list pointer, Free address pointer. :rtype: tuple """ handle = ctypes.c_int(handle) lenout = ctypes.c_int(lenout) nd = ctypes.c_int() ni = ctypes.c_int() ifname = stypes.stringToCharP(lenout) fward = ctypes.c_int() bward = ctypes.c_int() free = ctypes.c_int() libspice.dafrfr_c(handle, lenout, ctypes.byref(nd), ctypes.byref(ni), ifname, ctypes.byref(fward), ctypes.byref(bward), ctypes.byref(free)) return nd.value, ni.value, stypes.toPythonString( ifname), fward.value, bward.value, free.value @spiceErrorCheck def dafrs(insum): # Todo: test dafrs """ Change the summary for the current array in the current DAF. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafrs_c.html :param insum: New summary for current array. :type insum: N-Element Array of floats. """ insum = stypes.toDoubleVector(insum) libspice.dafrs_c(ctypes.byref(insum)) pass @spiceErrorCheck def dafus(insum, nd, ni): """ Unpack an array summary into its double precision and integer components. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafus_c.html :param insum: Array summary. :type insum: N-Element Array of floats. :param nd: Number of double precision components. :type nd: int :param ni: Number of integer components. :type ni: int :return: Double precision components, Integer components. :rtype: tuple """ insum = stypes.toDoubleVector(insum) dc = stypes.emptyDoubleVector(nd) ic = stypes.emptyIntVector(ni) nd = ctypes.c_int(nd) ni = ctypes.c_int(ni) libspice.dafus_c(insum, nd, ni, dc, ic) return stypes.vectorToList(dc), stypes.vectorToList(ic) @spiceErrorCheck def dasac(handle, n, buflen, buffer): # Todo: test dasac """ Add comments from a buffer of character strings to the comment area of a binary DAS file, appending them to any comments which are already present in the file's comment area. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasac_c.html :param handle: DAS handle of a file opened with write access. :type handle: int :param n: Number of comments to put into the comment area. :type n: int :param buflen: Line length associated with buffer. :type buflen: int :param buffer: Buffer of lines to be put into the comment area. :type buffer: Array of strs. :return: :rtype: """ handle = ctypes.c_int(handle) buffer = stypes.charvector(n, buflen) n = ctypes.c_int(n) buflen = ctypes.c_int(buflen) libspice.dasac_c(handle, n, buflen, ctypes.byref(buffer)) return stypes.vectorToList(buffer) @spiceErrorCheck def dascls(handle): # Todo: test dafdc """ Close a DAS file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dascls_c.html :param handle: Handle of an open DAS file. :type handle: int """ handle = ctypes.c_int(handle) libspice.dascls_c(handle) pass @spiceErrorCheck def dasec(handle, bufsiz, buflen): # Todo: test dasec """ Extract comments from the comment area of a binary DAS file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasec_c.html :param handle: Handle of binary DAS file open with read access. :type handle: int :param bufsiz: Maximum size, in lines, of buffer. :type bufsiz: int :param buflen: Line length associated with buffer. :type buflen: int :return: Number of comments extracted from the DAS file, Buffer in which extracted comments are placed, Indicates whether all comments have been extracted. :rtype: tuple """ handle = ctypes.c_int(handle) buffer = stypes.charvector(bufsiz, buflen) bufsiz = ctypes.c_int(bufsiz) buflen = ctypes.c_int(buflen) n = ctypes.c_int() done = ctypes.c_bool() libspice.dafec_c(handle, bufsiz, buflen, ctypes.byref(n), ctypes.byref(buffer), ctypes.byref(done)) return n.value, stypes.vectorToList(buffer), done.value @spiceErrorCheck def dasopr(fname): # Todo: test dasopr """ Open a DAS file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. :rtype: int """ fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.dasopr_c(fname, ctypes.byref(handle)) return handle.value @spiceErrorCheck def dcyldr(x, y, z): """ This routine computes the Jacobian of the transformation from rectangular to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dcyldr_c.html :param x: X-coordinate of point. :type x: float :param y: Y-coordinate of point. :type y: float :param z: Z-coordinate of point. :type z: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ x = ctypes.c_double(x) y = ctypes.c_double(y) z = ctypes.c_double(z) jacobi = stypes.emptyDoubleMatrix() libspice.dcyldr_c(x, y, z, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def deltet(epoch, eptype): """ Return the value of Delta ET (ET-UTC) for an input epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/deltet_c.html :param epoch: Input epoch (seconds past J2000). :type epoch: float :param eptype: Type of input epoch ("UTC" or "ET"). :type eptype: str :return: Delta ET (ET-UTC) at input epoch. :rtype: float """ epoch = ctypes.c_double(epoch) eptype = stypes.stringToCharP(eptype) delta = ctypes.c_double() libspice.deltet_c(epoch, eptype, ctypes.byref(delta)) return delta.value @spiceErrorCheck def det(m1): """ Compute the determinant of a double precision 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/det_c.html :param m1: Matrix whose determinant is to be found. :type m1: 3x3-Element Array of Floats. :return: The determinant of the matrix. :rtype: float """ m1 = stypes.listtodoublematrix(m1) return libspice.det_c(m1) @spiceErrorCheck def dgeodr(x, y, z, re, f): """ This routine computes the Jacobian of the transformation from rectangular to geodetic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dgeodr_c.html :param x: X-coordinate of point. :type x: float :param y: Y-coordinate of point. :type y: float :param z: Z-coord :type z: float :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ x = ctypes.c_double(x) y = ctypes.c_double(y) z = ctypes.c_double(z) re = ctypes.c_double(re) f = ctypes.c_double(f) jacobi = stypes.emptyDoubleMatrix() libspice.dgeodr_c(x, y, z, re, f, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def diags2(symmat): """ Diagonalize a symmetric 2x2 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/diags2_c.html :param symmat: A symmetric 2x2 matrix. :type symmat: 2x2-Element Array of Floats. :return: A diagonal matrix similar to symmat, A rotation used as the similarity transformation. :rtype: tuple """ symmat = stypes.listtodoublematrix(symmat, x=2, y=2) diag = stypes.emptyDoubleMatrix(x=2, y=2) rotateout = stypes.emptyDoubleMatrix(x=2, y=2) libspice.diags2_c(symmat, diag, rotateout) return stypes.matrixToList(diag), stypes.matrixToList(rotateout) @spiceErrorCheck def diff(a, b): """ Take the difference of two sets of any data type to form a third set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/diff_c.html :param a: First input set. :type a: SpiceyPy.support_types.SpiceCell :param b: Second input set. :type b: SpiceyPy.support_types.SpiceCell :return: Difference of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert isinstance(b, stypes.SpiceCell) assert a.dtype == b.dtype assert a.dtype == 0 or a.dtype == 1 or a.dtype == 2 if a.dtype is 0: c = stypes.SPICECHAR_CELL(max(a.size, b.size), max(a.length, b.length)) elif a.dtype is 1: c = stypes.SPICEDOUBLE_CELL(max(a.size, b.size)) elif a.dtype is 2: c = stypes.SPICEINT_CELL(max(a.size, b.size)) else: raise NotImplementedError libspice.diff_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def dlatdr(x, y, z): """ This routine computes the Jacobian of the transformation from rectangular to latitudinal coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dlatdr_c.html :param x: X-coordinate of point. :type x: float :param y: Y-coordinate of point. :type y: float :param z: Z-coord :type z: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ x = ctypes.c_double(x) y = ctypes.c_double(y) z = ctypes.c_double(z) jacobi = stypes.emptyDoubleMatrix() libspice.dlatdr_c(x, y, z, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def dp2hx(number, lenout=None): """ Convert a double precision number to an equivalent character string using base 16 "scientific notation." http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dp2hx_c.html :param number: D.p. number to be converted. :type number: float :param lenout: Available space for output string. :return: Equivalent character string, left justified. :rtype: str """ if lenout is None: lenout = 255 number = ctypes.c_double(number) lenout = ctypes.c_int(lenout) string = stypes.stringToCharP(lenout) length = ctypes.c_int() libspice.dp2hx_c(number, lenout, string, ctypes.byref(length)) return stypes.toPythonString(string) @spiceErrorCheck def dpgrdr(body, x, y, z, re, f): """ This routine computes the Jacobian matrix of the transformation from rectangular to planetographic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpgrdr_c.html :param body: Body with which coordinate system is associated. :type body: str :param x: X-coordinate of point. :type x: float :param y: Y-coordinate of point. :type y: float :param z: Z-coordinate of point. :type z: float :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ body = stypes.stringToCharP(body) x = ctypes.c_double(x) y = ctypes.c_double(y) z = ctypes.c_double(z) re = ctypes.c_double(re) f = ctypes.c_double(f) jacobi = stypes.emptyDoubleMatrix() libspice.dpgrdr_c(body, x, y, z, re, f, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def dpmax(): """ Return the value of the largest (positive) number representable in a double precision variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpmax_c.html :return: The largest (positive) number representable in a double precision variable. :rtype: float """ return libspice.dpmax_c() @spiceErrorCheck def dpmin(): """ Return the value of the smallest (negative) number representable in a double precision variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpmin_c.html :return: The smallest (negative) number that can be represented in a double precision variable. :rtype: float """ return libspice.dpmin_c() @spiceErrorCheck def dpr(): """ Return the number of degrees per radian. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpr_c.html :return: The number of degrees per radian. :rtype: float """ return libspice.dpr_c() @spiceErrorCheck def drdcyl(r, lon, z): """ This routine computes the Jacobian of the transformation from cylindrical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdcyl_c.html :param r: Distance of a point from the origin. :type r: float :param lon: Angle of the point from the xz plane in radians. :type lon: float :param z: Height of the point above the xy plane. :type z: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ r = ctypes.c_double(r) lon = ctypes.c_double(lon) z = ctypes.c_double(z) jacobi = stypes.emptyDoubleMatrix() libspice.drdcyl_c(r, lon, z, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def drdgeo(lon, lat, alt, re, f): """ This routine computes the Jacobian of the transformation from geodetic to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdgeo_c.html :param lon: Geodetic longitude of point (radians). :type lon: float :param lat: Geodetic latitude of point (radians). :type lat: float :param alt: Altitude of point above the reference spheroid. :type alt: float :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) alt = ctypes.c_double(alt) re = ctypes.c_double(re) f = ctypes.c_double(f) jacobi = stypes.emptyDoubleMatrix() libspice.drdgeo_c(lon, lat, alt, re, f, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def drdlat(r, lon, lat): """ Compute the Jacobian of the transformation from latitudinal to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdlat_c.html :param r: Distance of a point from the origin. :type r: float :param lon: Angle of the point from the XZ plane in radians. :type lon: float :param lat: Angle of the point from the XY plane in radians. :type lat: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ r = ctypes.c_double(r) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) jacobi = stypes.emptyDoubleMatrix() libspice.drdsph_c(r, lon, lat, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def drdpgr(body, lon, lat, alt, re, f): """ This routine computes the Jacobian matrix of the transformation from planetographic to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdpgr_c.html :param body: Body with which coordinate system is associated. :type body: str :param lon: Planetographic longitude of a point (radians). :type lon: float :param lat: Planetographic latitude of a point (radians). :type lat: float :param alt: Altitude of a point above reference spheroid. :type alt: float :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ body = stypes.stringToCharP(body) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) alt = ctypes.c_double(alt) re = ctypes.c_double(re) f = ctypes.c_double(f) jacobi = stypes.emptyDoubleMatrix() libspice.drdpgr_c(body, lon, lat, alt, re, f, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def drdsph(r, colat, lon): """ This routine computes the Jacobian of the transformation from spherical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdsph_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the point from the positive z-axis. :type colat: float :param lon: Angle of the point from the xy plane. :type lon: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ r = ctypes.c_double(r) colat = ctypes.c_double(colat) lon = ctypes.c_double(lon) jacobi = stypes.emptyDoubleMatrix() libspice.drdsph_c(r, colat, lon, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def dsphdr(x, y, z): """ This routine computes the Jacobian of the transformation from rectangular to spherical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dsphdr_c.html :param x: X-coordinate of point. :type x: float :param y: Y-coordinate of point. :type y: float :param z: Z-coordinate of point. :type z: float :return: Matrix of partial derivatives. :rtype: 3x3-Element Array of Floats. """ x = ctypes.c_double(x) y = ctypes.c_double(y) z = ctypes.c_double(z) jacobi = stypes.emptyDoubleMatrix() libspice.dsphdr_c(x, y, z, jacobi) return stypes.matrixToList(jacobi) @spiceErrorCheck def dtpool(name): """ Return the data about a kernel pool variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :return: True if variable is in pool, Number of values returned for name, Type of the variable "C", "N", or "X". :rtype: tuple """ name = stypes.stringToCharP(name) found = ctypes.c_bool() n = ctypes.c_int() typeout = ctypes.c_char() libspice.dtpool_c(name, ctypes.byref(found), ctypes.byref(n), ctypes.byref(typeout)) return found.value, n.value, stypes.toPythonString(typeout.value) @spiceErrorCheck def ducrss(s1, s2): """ Compute the unit vector parallel to the cross product of two 3-dimensional vectors and the derivative of this unit vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ducrss_c.html :param s1: Left hand state for cross product and derivative. :type s1: 6-Element Array of Floats. :param s2: Right hand state for cross product and derivative. :type s2: 6-Element Array of Floats. :return: Unit vector and derivative of the cross product. :rtype: 6-Element Array of Floats. """ assert len(s1) is 6 and len(s2) is 6 s1 = stypes.toDoubleVector(s1) s2 = stypes.toDoubleVector(s2) sout = stypes.emptyDoubleVector(6) libspice.ducrss_c(s1, s2, sout) return stypes.vectorToList(sout) @spiceErrorCheck def dvcrss(s1, s2): """ Compute the cross product of two 3-dimensional vectors and the derivative of this cross product. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvcrss_c.html :param s1: Left hand state for cross product and derivative. :type s1: 6-Element Array of Floats. :param s2: Right hand state for cross product and derivative. :type s2: 6-Element Array of Floats. :return: State associated with cross product of positions. :rtype: 6-Element Array of Floats. """ assert len(s1) is 6 and len(s2) is 6 s1 = stypes.toDoubleVector(s1) s2 = stypes.toDoubleVector(s2) sout = stypes.emptyDoubleVector(6) libspice.dvcrss_c(s1, s2, sout) return stypes.vectorToList(sout) @spiceErrorCheck def dvdot(s1, s2): """ Compute the derivative of the dot product of two double precision position vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvdot_c.html :param s1: First state vector in the dot product. :type s1: 6-Element Array of Floats. :param s2: Second state vector in the dot product. :type s2: 6-Element Array of Floats. :return: The derivative of the dot product. :rtype: float """ assert len(s1) is 6 and len(s2) is 6 s1 = stypes.toDoubleVector(s1) s2 = stypes.toDoubleVector(s2) return libspice.dvdot_c(s1, s2) @spiceErrorCheck def dvhat(s1): """ Find the unit vector corresponding to a state vector and the derivative of the unit vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvhat_c.html :param s1: State to be normalized. :type s1: 6-Element Array of Floats. :return: Unit vector s1 / abs(s1), and its time derivative. :rtype: 6-Element Array of Floats. """ assert len(s1) is 6 s1 = stypes.toDoubleVector(s1) sout = stypes.emptyDoubleVector(6) libspice.dvhat_c(s1, sout) return stypes.vectorToList(sout) @spiceErrorCheck def dvnorm(state): """ Function to calculate the derivative of the norm of a 3-vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvnorm_c.html :param state: A 6-vector composed of three coordinates and their derivatives. :type state: 6-Element Array of Floats. :return: The derivative of the norm of a 3-vector. :rtype: float """ assert len(state) is 6 state = stypes.toDoubleVector(state) return libspice.dvnorm_c(state) @spiceErrorCheck def dvpool(name): """ Delete a variable from the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvpool_c.html :param name: Name of the kernel variable to be deleted. :type name: str """ name = stypes.stringToCharP(name) libspice.dvpool_c(name) pass @spiceErrorCheck def dvsep(s1, s2): """ Calculate the time derivative of the separation angle between two input states, S1 and S2. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvsep_c.html :param s1: State vector of the first body. :type s1: 6-Element Array of Floats. :param s2: State vector of the second body. :type s2: 6-Element Array of Floats. :return: The time derivative of the angular separation between S1 and S2. :rtype: float """ assert len(s1) is 6 and len(s2) is 6 s1 = stypes.toDoubleVector(s1) s2 = stypes.toDoubleVector(s2) return libspice.dvsep_c(s1, s2) ################################################################################ # E @spiceErrorCheck def edlimb(a, b, c, viewpt): """ Find the limb of a triaxial ellipsoid, viewed from a specified point. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edlimb_c.html :param a: Length of ellipsoid semi-axis lying on the x-axis. :type a: float :param b: Length of ellipsoid semi-axis lying on the y-axis. :type b: float :param c: Length of ellipsoid semi-axis lying on the z-axis. :type c: float :param viewpt: Location of viewing point. :type viewpt: 3-Element Array of Floats. :return: Limb of ellipsoid as seen from viewing point. :rtype: SpiceyPy.support_types.Ellipse """ limb = stypes.Ellipse() a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) viewpt = stypes.toDoubleVector(viewpt) libspice.edlimb_c(a, b, c, viewpt, ctypes.byref(limb)) return limb @spiceErrorCheck def edterm(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts): """ Compute a set of points on the umbral or penumbral terminator of a specified target body, where the target shape is modeled as an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/edterm_c.html :param trmtyp: Terminator type. :type trmtyp: str :param source: Light source. :type source: str :param target: Target body. :type target: str :param et: Observation epoch. :type et: str :param fixref: Body-fixed frame associated with target. :type fixref: str :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Observer. :type obsrvr: str :param npts: Number of points in terminator set. :type npts: int :return: Epoch associated with target center, Position of observer in body-fixed frame, Terminator point set. :rtype: tuple """ trmtyp = stypes.stringToCharP(trmtyp) source = stypes.stringToCharP(source) target = stypes.stringToCharP(target) et = ctypes.c_double(et) fixref = stypes.stringToCharP(fixref) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) trgepc = ctypes.c_double() obspos = stypes.emptyDoubleVector(3) trmpts = stypes.emptyDoubleMatrix(x=3, y=npts) npts = ctypes.c_int(npts) libspice.edterm_c(trmtyp, source, target, et, fixref, abcorr, obsrvr, npts, ctypes.byref(trgepc), obspos, trmpts) return trgepc.value, stypes.vectorToList(obspos), stypes.matrixToList( trmpts) @spiceErrorCheck def ekacec(handle, segno, recno, column, nvals, vallen, cvals, isnull): """ Add data to a character column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacec_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be added. :type recno: int :param column: Column name. :type column: str :param nvals: Number of values to add to column. :type nvals: int :param vallen: Declared length of character values. :type vallen: int :param cvals: Character values to add to column. :type cvals: List of str. :param isnull: Flag indicating whether column entry is null. :type isnull: bool """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int(nvals) vallen = ctypes.c_int(vallen) cvals = stypes.listToCharArrayPtr(cvals) isnull = ctypes.c_bool(isnull) libspice.ekacec_c(handle, segno, recno, column, nvals, vallen, cvals, isnull) pass @spiceErrorCheck def ekaced(handle, segno, recno, column, nvals, dvals, isnull): """ Add data to an double precision column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekaced_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be added. :type recno: int :param column: Column name. :type column: str :param nvals: Number of values to add to column. :type nvals: int :param dvals: Double precision values to add to column. :type dvals: N-Element Array of Floats. :param isnull: Flag indicating whether column entry is null. :type isnull: bool """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int(nvals) dvals = stypes.toDoubleVector(dvals) isnull = ctypes.c_bool(isnull) libspice.ekaced_c(handle, segno, recno, column, nvals, dvals, isnull) pass @spiceErrorCheck def ekacei(handle, segno, recno, column, nvals, ivals, isnull): """ Add data to an integer column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacei_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be added. :type recno: int :param column: Column name. :type column: str :param nvals: Number of values to add to column. :type nvals: int :param ivals: Integer values to add to column. :type ivals: N-Element Array of Ints. :param isnull: Flag indicating whether column entry is null. :type isnull: bool """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int(nvals) ivals = stypes.toIntVector(ivals) isnull = ctypes.c_bool(isnull) libspice.ekacei_c(handle, segno, recno, column, nvals, ivals, isnull) @spiceErrorCheck def ekaclc(handle, segno, column, vallen, cvals, entszs, nlflgs, rcptrs, wkindx): """ Add an entire character column to an EK segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekaclc_c.html :param handle: EK file handle. :type handle: int :param segno: Number of segment to add column to. :type segno: int :param column: Column name. :type column: str :param vallen: Length of character values. :type vallen: int :param cvals: Character values to add to column. :type cvals: List of str. :param entszs: Array of sizes of column entries. :type entszs: N-Element Array of Ints. :param nlflgs: Array of null flags for column entries. :type nlflgs: N-Element Array of Bools. :param rcptrs: Record pointers for segment. :type rcptrs: N-Element Array of Ints. :param wkindx: Work space for column index. :type wkindx: N-Element Array of Ints. :return: Work space for column index. :rtype: N-Element Array of Ints. """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) column = stypes.stringToCharP(column) vallen = ctypes.c_int(vallen) cvals = stypes.listToCharArrayPtr(cvals) entszs = stypes.toIntVector(entszs) nlflgs = stypes.toBoolVector(nlflgs) rcptrs = stypes.toIntVector(rcptrs) wkindx = stypes.toIntVector(wkindx) libspice.ekaclc_c(handle, segno, column, vallen, cvals, entszs, nlflgs, rcptrs, wkindx) return stypes.vectorToList(wkindx) @spiceErrorCheck def ekacld(handle, segno, column, dvals, entszs, nlflgs, rcptrs, wkindx): """ Add an entire double precision column to an EK segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html :param handle: EK file handle. :type handle: int :param segno: Number of segment to add column to. :type segno: int :param column: Column name. :type column: str :param dvals: Double precision values to add to column. :type dvals: N-Element Array of Floats. :param entszs: Array of sizes of column entries. :type entszs: N-Element Array of Ints. :param nlflgs: Array of null flags for column entries. :type nlflgs: N-Element Array of Bools. :param rcptrs: Record pointers for segment. :type rcptrs: N-Element Array of Ints. :param wkindx: Work space for column index. :type wkindx: N-Element Array of Ints. :return: Work space for column index. :rtype: N-Element Array of Ints. """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) column = stypes.stringToCharP(column) dvals = stypes.toDoubleVector(dvals) entszs = stypes.toIntVector(entszs) nlflgs = stypes.toBoolVector(nlflgs) rcptrs = stypes.toIntVector(rcptrs) wkindx = stypes.toIntVector(wkindx) libspice.ekacld_c(handle, segno, column, dvals, entszs, nlflgs, rcptrs, wkindx) return stypes.vectorToList(wkindx) @spiceErrorCheck def ekacli(handle, segno, column, ivals, entszs, nlflgs, rcptrs, wkindx): """ Add an entire integer column to an EK segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacli_c.html :param handle: EK file handle. :type handle: int :param segno: Number of segment to add column to. :type segno: int :param column: Column name. :type column: str :param ivals: Integer values to add to column. :type ivals: N-Element Array of Ints. :type entszs: N-Element Array of Ints. :param nlflgs: Array of null flags for column entries. :type nlflgs: N-Element Array of Bools. :param rcptrs: Record pointers for segment. :type rcptrs: N-Element Array of Ints. :param wkindx: Work space for column index. :type wkindx: N-Element Array of Ints. :return: Work space for column index. :rtype: N-Element Array of Ints. """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) column = stypes.stringToCharP(column) ivals = stypes.toIntVector(ivals) entszs = stypes.toIntVector(entszs) nlflgs = stypes.toBoolVector(nlflgs) rcptrs = stypes.toIntVector(rcptrs) wkindx = stypes.toIntVector(wkindx) libspice.ekacli_c(handle, segno, column, ivals, entszs, nlflgs, rcptrs, wkindx) return stypes.vectorToList(wkindx) @spiceErrorCheck def ekappr(handle, segno): """ Append a new, empty record at the end of a specified E-kernel segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekappr_c.html :param handle: File handle. :type handle: int :param segno: Segment number. :type segno: int :return: Number of appended record. :rtype: int """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int() libspice.ekappr_c(handle, segno, ctypes.byref(recno)) return recno.value @spiceErrorCheck def ekbseg(handle, tabnam, ncols, cnmlen, cnames, declen, decls): # if 'cnmlen' in kwargs: # cnmlen = kwargs['cnmlen'] # else: # cnmlen = len(max(cnames, key=len)) + 1 # if 'declen' in kwargs: # declen = kwargs['declen'] # else: # declen = len(max(decls, key=len)) + 1 # if 'ncols' in kwargs: # ncols = kwargs['ncols'] # else: # ncols = len(cnames) """ Start a new segment in an E-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekbseg_c.html :param handle: File handle. :type handle: int :param tabnam: Table name. :type tabnam: str :param ncols: Number of columns in the segment. :type ncols: int :param cnmlen: Length of names in in column name array. :type cnmlen: int :param cnames: Names of columns. :type cnames: List of str. :param declen: Length of declaration strings in declaration array. :type declen: int :param decls: Declarations of columns. :type decls: List of str. :return: Segment number. :rtype: int """ handle = ctypes.c_int(handle) tabnam = stypes.stringToCharP(tabnam) cnmlen = ctypes.c_int(cnmlen) cnames = stypes.listToCharArray(cnames) # not sure if this works declen = ctypes.c_int(declen) decls = stypes.listToCharArray(decls) segno = ctypes.c_int() libspice.ekbseg_c(handle, tabnam, ncols, cnmlen, cnames, declen, decls, ctypes.byref(segno)) return segno.value @spiceErrorCheck def ekccnt(table): """ Return the number of distinct columns in a specified, currently loaded table. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekccnt_c.html :param table: Name of table. :type table: str :return: Count of distinct, currently loaded columns. :rtype: int """ table = stypes.stringToCharP(table) ccount = ctypes.c_int() libspice.ekccnt_c(table, ctypes.byref(ccount)) return ccount.value @spiceErrorCheck def ekcii(table, cindex, lenout): """ Return attribute information about a column belonging to a loaded EK table, specifying the column by table and index. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcii_c.html :param table: Name of table containing column. :type table: str :param cindex: Index of column whose attributes are to be found. :type cindex: int :param lenout: Maximum allowed length of column name. :return: Name of column, Column attribute descriptor. :rtype: tuple """ table = stypes.stringToCharP(table) cindex = ctypes.c_int(cindex) lenout = ctypes.c_int(lenout) column = stypes.stringToCharP(lenout) attdsc = stypes.SpiceEKAttDsc() libspice.ekcii_c(table, cindex, lenout, column, ctypes.byref(attdsc)) return stypes.toPythonString(column), attdsc @spiceErrorCheck def ekcls(handle): """ Close an E-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcls_c.html :param handle: EK file handle. :type handle: int """ handle = ctypes.c_int(handle) libspice.ekcls_c(handle) pass @spiceErrorCheck def ekdelr(handle, segno, recno): """ Delete a specified record from a specified E-kernel segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekdelr_c.html :param handle: File handle. :type handle: int :param segno: Segment number. :type segno: int :param recno: Record number. :type recno: int """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) libspice.ekdelr_c(handle, segno, recno) pass @spiceErrorCheck def ekffld(handle, segno, rcptrs): """ Complete a fast write operation on a new E-kernel segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekffld_c.html :param handle: File handle. :type handle: int :param segno: Segment number. :type segno: int :param rcptrs: Record pointers. :type rcptrs: N-Element Array of Ints. """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) rcptrs = stypes.toIntVector(rcptrs) libspice.ekffld_c(handle, segno, ctypes.cast(rcptrs, ctypes.POINTER(ctypes.c_int))) pass @spiceErrorCheck def ekfind(query, lenout): """ Find E-kernel data that satisfy a set of constraints. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekfind_c.html :param query: Query specifying data to be found. :type query: str :param lenout: Declared length of output error message string. :type lenout: int :return: Number of matching rows, Flag indicating whether query parsed correctly, Parse error description. :rtype: tuple """ query = stypes.stringToCharP(query) lenout = ctypes.c_int(lenout) nmrows = ctypes.c_int() error = ctypes.c_bool() errmsg = stypes.stringToCharP(lenout) libspice.ekfind_c(query, lenout, ctypes.byref(nmrows), ctypes.byref(error), errmsg) return nmrows.value, error.value, stypes.toPythonString(errmsg) @spiceErrorCheck def ekgc(selidx, row, element, lenout): # ekgc has issues grabbing last element/row in column """ Return an element of an entry in a column of character type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgc_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row to fetch from. :type row: int :param element: Index of element, within column entry, to fetch. :type element: int :param lenout: Maximum length of column element. :type lenout: int :return: Character string element of column entry, Flag indicating whether column entry was null, Flag indicating whether column was present in row. :rtype: tuple """ selidx = ctypes.c_int(selidx) row = ctypes.c_int(row) element = ctypes.c_int(element) lenout = ctypes.c_int(lenout) null = ctypes.c_bool() found = ctypes.c_bool() cdata = stypes.stringToCharP(lenout) libspice.ekgc_c(selidx, row, element, lenout, cdata, ctypes.byref(null), ctypes.byref(found)) return stypes.toPythonString(cdata), null.value, found.value @spiceErrorCheck def ekgd(selidx, row, element): """ Return an element of an entry in a column of double precision type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgd_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row to fetch from. :type row: int :param element: Index of element, within column entry, to fetch. :type element: int :return: Double precision element of column entry, Flag indicating whether column entry was null, Flag indicating whether column was present in row. :rtype: tuple """ selidx = ctypes.c_int(selidx) row = ctypes.c_int(row) element = ctypes.c_int(element) ddata = ctypes.c_double() null = ctypes.c_bool() found = ctypes.c_bool() libspice.ekgd_c(selidx, row, element, ctypes.byref(ddata), ctypes.byref(null), ctypes.byref(found)) return ddata.value, null.value, found.value @spiceErrorCheck def ekgi(selidx, row, element): """ Return an element of an entry in a column of integer type in a specified row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekgi_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row to fetch from. :type row: int :param element: Index of element, within column entry, to fetch. :type element: int :return: Integer element of column entry, Flag indicating whether column entry was null, Flag indicating whether column was present in row. :rtype: tuple """ selidx = ctypes.c_int(selidx) row = ctypes.c_int(row) element = ctypes.c_int(element) idata = ctypes.c_int() null = ctypes.c_bool() found = ctypes.c_bool() libspice.ekgi_c(selidx, row, element, ctypes.byref(idata), ctypes.byref(null), ctypes.byref(found)) return idata.value, null.value, found.value @spiceErrorCheck def ekifld(handle, tabnam, ncols, nrows, cnmlen, cnames, declen, decls): """ Initialize a new E-kernel segment to allow fast writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekifld_c.html :param handle: File handle. :type handle: int :param tabnam: Table name. :type tabnam: str :param ncols: Number of columns in the segment. :type ncols: int :param nrows: Number of rows in the segment. :type nrows: int :param cnmlen: Length of names in in column name array. :type cnmlen: int :param cnames: Names of columns. :type cnames: List of str. :param declen: Length of declaration strings in declaration array. :type declen: int :param decls: Declarations of columns. :type decls: List of str. :return: Segment number, Array of record pointers. :rtype: tuple """ handle = ctypes.c_int(handle) tabnam = stypes.stringToCharP(tabnam) ncols = ctypes.c_int(ncols) nrows = ctypes.c_int(nrows) cnmlen = ctypes.c_int(cnmlen) cnames = stypes.listToCharArray(cnames) declen = ctypes.c_int(declen) recptrs = stypes.emptyIntVector(nrows) decls = stypes.listToCharArray(decls) segno = ctypes.c_int() libspice.ekifld_c(handle, tabnam, ncols, nrows, cnmlen, cnames, declen, decls, ctypes.byref(segno), recptrs) return segno.value, stypes.vectorToList(recptrs) @spiceErrorCheck def ekinsr(handle, segno, recno): # Todo: test ekinsr """ Add a new, empty record to a specified E-kernel segment at a specified index. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekinsr_c.html :param handle: File handle. :type handle: int :param segno: Segment number. :type segno: int :param recno: Record number. :type recno: int """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) libspice.ekinsr_c(handle, segno, recno) pass @spiceErrorCheck def eklef(fname): """ Load an EK file, making it accessible to the EK readers. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eklef_c.html :param fname: Name of EK file to load. :type fname: str :return: File handle of loaded EK file. :rtype: int """ fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.eklef_c(fname, handle) return handle.value @spiceErrorCheck def eknelt(selidx, row): # Todo: test eknelt """ Return the number of elements in a specified column entry in the current row. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eknelt_c.html :param selidx: Index of parent column in SELECT clause. :type selidx: int :param row: Row containing element. :type row: int :return: The number of elements in entry in current row. :rtype: int """ selidx = ctypes.c_int(selidx) row = ctypes.c_int(row) return libspice.eknelt_c(selidx, row) @spiceErrorCheck def eknseg(handle): """ Return the number of segments in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eknseg_c.html :param handle: EK file handle. :type handle: int :return: The number of segments in the specified E-kernel. :rtype: int """ handle = ctypes.c_int(handle) return libspice.eknseg_c(handle) @spiceErrorCheck def ekntab(): """ Return the number of loaded EK tables. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html :return: The number of loaded EK tables. :rtype: int """ n = ctypes.c_int(0) libspice.ekntab_c(ctypes.byref(n)) return n.value @spiceErrorCheck def ekopn(fname, ifname, ncomch): """ Open a new E-kernel file and prepare the file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopn_c.html :param fname: Name of EK file. :type fname: str :param ifname: Internal file name. :type ifname: str :param ncomch: The number of characters to reserve for comments. :type ncomch: int :return: Handle attached to new EK file. :rtype: int """ fname = stypes.stringToCharP(fname) ifname = stypes.stringToCharP(ifname) ncomch = ctypes.c_int(ncomch) handle = ctypes.c_int() libspice.ekopn_c(fname, ifname, ncomch, handle) return handle.value @spiceErrorCheck def ekopr(fname): """ Open an existing E-kernel file for reading. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopr_c.html :param fname: Name of EK file. :type fname: str :return: Handle attached to EK file. :rtype: int """ fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.ekopr_c(fname, ctypes.byref(handle)) return handle.value @spiceErrorCheck def ekops(): """ Open a scratch (temporary) E-kernel file and prepare the file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekops_c.html :return: Handle attached to new EK file. :rtype: int """ handle = ctypes.c_int() libspice.ekops_c(ctypes.byref(handle)) return handle.value @spiceErrorCheck def ekopw(fname): """ Open an existing E-kernel file for writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopw_c.html :param fname: Name of EK file. :type fname: str :return: Handle attached to EK file. :rtype: int """ fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.ekopw_c(fname, ctypes.byref(handle)) return handle.value @spiceErrorCheck def ekpsel(query, msglen, tablen, collen): # Todo: test ekpsel """ Parse the SELECT clause of an EK query, returning full particulars concerning each selected item. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekpsel_c.html note: oddly docs at url are incomplete/incorrect. :param query: EK query. :type query: str :param msglen: Available space in the output error message string. :type msglen: int :param tablen: UNKNOWN? Length of Table? :type tablen: int :param collen: UNKOWN? Length of Colunn? :return: Number of items in SELECT clause of query, Begin positions of expressions in SELECT clause, End positions of expressions in SELECT clause, Data types of expressions, Classes of expressions, Names of tables qualifying SELECT columns, Names of columns in SELECT clause of query, Error flag, Parse error message. :rtype: tuple """ query = stypes.stringToCharP(query) msglen = ctypes.c_int(msglen) tablen = ctypes.c_int(tablen) collen = ctypes.c_int(collen) n = ctypes.c_int() xbegs = ctypes.c_int() xends = ctypes.c_int() xtypes = stypes.SpiceEKDataType() xclass = stypes.SpiceEKExprClass() tabs = stypes.charvector(100, 33) cols = stypes.charvector(100, 65) error = ctypes.c_bool() errmsg = stypes.stringToCharP(msglen) libspice.ekpsel_c(query, msglen, tablen, collen, ctypes.byref(n), ctypes.byref(xbegs), ctypes.byref(xends), ctypes.byref(xtypes), ctypes.byref(xclass), ctypes.byref(tabs), ctypes.byref(cols), ctypes.byref(error), ctypes.byref(errmsg)) return n.value, xbegs.value, xends.value, xtypes.value, xclass.value,\ stypes.vectorToList(tabs), stypes.vectorToList(cols), error.value,\ stypes.toPythonString(errmsg) @spiceErrorCheck def ekrcec(handle, segno, recno, column, lenout, nelts=3): # Todo: test ekrcec , possible new way to get back 2d char arrays """ Read data from a character column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrcec_c.html :param handle: Handle attached to EK file. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record from which data is to be read. :type recno: int :param column: Column name. :type column: str :param lenout: Maximum length of output strings. :type lenout: int :param nelts: ??? :type nelts: int :return: Number of values in column entry, Character values in column entry, Flag indicating whether column entry is null. :rtype: tuple """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) lenout = ctypes.c_int(lenout) nvals = ctypes.c_int() cvals = stypes.charvector(ndim=nelts, lenvals=lenout) isnull = ctypes.c_bool() libspice.ekrcec_c(handle, segno, recno, column, lenout, ctypes.byref(nvals), ctypes.byref(cvals), ctypes.byref(isnull)) return nvals.value, stypes.vectorToList(cvals), isnull.value @spiceErrorCheck def ekrced(handle, segno, recno, column): # Todo: test ekrced """ Read data from a double precision column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrced_c.html :param handle: Handle attached to EK file. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record from which data is to be read. :type recno: int :param column: Column name. :type column: str :return: Number of values in column entry, Float values in column entry, Flag indicating whether column entry is null. :rtype: tuple """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int() dvals = ctypes.POINTER(ctypes.c_double) # array of length nvals isnull = ctypes.c_bool() libspice.ekrced_c(handle, segno, recno, column, ctypes.byref(nvals), ctypes.byref(dvals), ctypes.byref(isnull)) return nvals.value, stypes.vectorToList(dvals), isnull.value @spiceErrorCheck def ekrcei(handle, segno, recno, column): # Todo: test ekrcei """ Read data from an integer column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrcei_c.html :param handle: Handle attached to EK file. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record from which data is to be read. :type recno: int :param column: Column name. :type column: str :return: Number of values in column entry, Integer values in column entry, Flag indicating whether column entry is null. :rtype: tuple """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int() ivals = ctypes.pointer(ctypes.c_int) # array of length nvals isnull = ctypes.c_bool() libspice.ekrcei_c(handle, segno, recno, column, ctypes.byref(nvals), ivals, ctypes.byref(isnull)) return nvals.value, stypes.vectorToList(ivals), isnull.value @spiceErrorCheck def ekssum(handle, segno): """ Return summary information for a specified segment in a specified EK. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html :param handle: Handle of EK. :type handle: int :param segno: Number of segment to be summarized. :type segno: int :return: EK segment summary. :rtype: SpicePy.support_types.SpiceEKSegSum """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) segsum = stypes.SpiceEKSegSum() libspice.ekssum_c(handle, segno, ctypes.byref(segsum)) return segsum @spiceErrorCheck def ektnam(n, lenout): """ Return the name of a specified, loaded table. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ektnam_c.html :param n: Index of table. :type n: int :param lenout: Maximum table name length. :type lenout: int :return: Name of table. :rtype: str """ n = ctypes.c_int(n) lenout = ctypes.c_int(lenout) table = stypes.stringToCharP(lenout) libspice.ektnam_c(n, lenout, table) return stypes.toPythonString(table) @spiceErrorCheck def ekucec(handle, segno, recno, column, nvals, vallen, cvals, isnull): # Todo: test ekucec """ Update a character column entry in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekucec_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be updated. :type recno: int :param column: Column name. :type column: str :param nvals: Number of values in new column entry. :type nvals: int :param vallen: Declared length of character values. :type vallen: int :param cvals: Character values comprising new column entry. :type cvals: List of str. :param isnull: Flag indicating whether column entry is null. :type isnull: bool """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int(nvals) vallen = ctypes.c_int(vallen) isnull = ctypes.c_bool(isnull) cvals = stypes.listToCharArrayPtr(cvals, xLen=vallen, yLen=nvals) libspice.ekucec_c(handle, segno, recno, column, nvals, vallen, cvals, isnull) pass @spiceErrorCheck def ekuced(handle, segno, recno, column, nvals, dvals, isnull): # Todo: test ekucei """ Update a double precision column entry in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekuced_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be updated. :type recno: int :param column: Column name. :type column: str :param nvals: Number of values in new column entry. :type nvals: int :param dvals: Double precision values comprising new column entry. :type dvals: N-Element Array of Floats. :param isnull: Flag indicating whether column entry is null. :type isnull: bool """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int(nvals) isnull = ctypes.c_bool(isnull) dvals = stypes.toDoubleVector(dvals) libspice.ekuced_c(handle, segno, recno, column, nvals, ctypes.byref(dvals), isnull) pass @spiceErrorCheck def ekucei(handle, segno, recno, column, nvals, ivals, isnull): # Todo: test ekucei """ Update an integer column entry in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekucei_c.html :param handle: EK file handle. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record to which data is to be updated. :type recno: int :param column: Column name. :type column: str :param nvals: Number of values in new column entry. :type nvals: int :param ivals: Integer values comprising new column entry. :type ivals: N-Element Array of Ints. :param isnull: Flag indicating whether column entry is null. :type isnull: bool """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) recno = ctypes.c_int(recno) column = stypes.stringToCharP(column) nvals = ctypes.c_int(nvals) isnull = ctypes.c_bool(isnull) ivals = stypes.toIntVector(ivals) libspice.ekucei_c(handle, segno, recno, column, nvals, ctypes.byref(ivals), isnull) pass @spiceErrorCheck def ekuef(handle): """ Unload an EK file, making its contents inaccessible to the EK reader routines, and clearing space in order to allow other EK files to be loaded. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekuef_c.html :param handle: Handle of EK file. :type handle: int """ handle = ctypes.c_int(handle) libspice.ekuef_c(handle) pass @spiceErrorCheck def el2cgv(ellipse): """ Convert an ellipse to a center vector and two generating vectors. The selected generating vectors are semi-axes of the ellipse. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/el2cgv_c.html :param ellipse: An Ellipse :type ellipse: SpiceyPy.support_types.Ellipse :return: Center and semi-axes of ellipse. :rtype: tuple """ assert (isinstance(ellipse, stypes.Ellipse)) center = stypes.emptyDoubleVector(3) smajor = stypes.emptyDoubleVector(3) sminor = stypes.emptyDoubleVector(3) libspice.el2cgv_c(ctypes.byref(ellipse), center, smajor, sminor) return stypes.vectorToList(center), stypes.vectorToList( smajor), stypes.vectorToList(sminor) @spiceErrorCheck def elemc(item, inset): """ Determine whether an item is an element of a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/elemc_c.html :param item: Item to be tested. :type item: str :param inset: Set to be tested. :type inset: SpiceyPy.support_types.SpiceCell :return: True if item is an element of set. :rtype: bool """ assert isinstance(inset, stypes.SpiceCell) item = stypes.stringToCharP(item) return libspice.elemc_c(item, ctypes.byref(inset)) @spiceErrorCheck def elemd(item, inset): """ Determine whether an item is an element of a double precision set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/elemd_c.html :param item: Item to be tested. :type item: float :param inset: Set to be tested. :type inset: SpiceyPy.support_types.SpiceCell :return: True if item is an element of set. :rtype: bool """ assert isinstance(inset, stypes.SpiceCell) assert inset.dtype == 1 item = ctypes.c_double(item) return libspice.elemd_c(item, ctypes.byref(inset)) @spiceErrorCheck def elemi(item, inset): """ Determine whether an item is an element of an integer set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/elemi_c.html :param item: Item to be tested. :type item: int :param inset: Set to be tested. :type inset: SpiceyPy.support_types.SpiceCell :return: True if item is an element of set. :rtype: bool """ assert isinstance(inset, stypes.SpiceCell) assert inset.dtype == 2 item = ctypes.c_int(item) return libspice.elemi_c(item, ctypes.byref(inset)) @spiceErrorCheck def eqncpv(et, epoch, eqel, rapol, decpol): """ Compute the state (position and velocity of an object whose trajectory is described via equinoctial elements relative to some fixed plane (usually the equatorial plane of some planet). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqncpv_c.html :param et: Epoch in seconds past J2000 to find state. :type et: float :param epoch: Epoch of elements in seconds past J2000. :type epoch: float :param eqel: Array of equinoctial elements :type eqel: 9-Element Array of Floats. :param rapol: Right Ascension of the pole of the reference plane. :type rapol: float :param decpol: Declination of the pole of the reference plane. :type decpol: float :return: State of the object described by eqel. :rtype: 6-Element Array of Floats. """ et = ctypes.c_double(et) epoch = ctypes.c_double(epoch) eqel = stypes.toDoubleVector(eqel) rapol = ctypes.c_double(rapol) decpol = ctypes.c_double(decpol) state = stypes.emptyDoubleVector(6) libspice.eqncpv_c(et, epoch, eqel, rapol, decpol, state) return stypes.vectorToList(state) @spiceErrorCheck def eqstr(a, b): """ Determine whether two strings are equivalent. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html :param a: Arbitrary character string. :type a: str :param b: Arbitrary character string. :type b: str :return: True if A and B are equivalent. :rtype: bool """ return libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)) def erract(op, lenout, action=None): """ Retrieve or set the default error action. SpiceyPy sets the default error action to "report" on init. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/erract_c.html :param op: peration, "GET" or "SET". :type op: str :param lenout: Length of list for output. :type lenout: int :param action: Error response action. :type action: str :return: Error response action. :rtype: str """ if action is None: action = "" lenout = ctypes.c_int(lenout) op = stypes.stringToCharP(op) action = ctypes.create_string_buffer(str.encode(action), lenout.value) actionptr = ctypes.c_char_p(ctypes.addressof(action)) libspice.erract_c(op, lenout, actionptr) return stypes.toPythonString(actionptr) def errch(marker, string): """ Substitute a character string for the first occurrence of a marker in the current long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errch_c.html :param marker: A substring of the error message to be replaced. :type marker: str :param string: The character string to substitute for marker. :type string: str """ marker = stypes.stringToCharP(marker) string = stypes.stringToCharP(string) libspice.errch_c(marker, string) pass def errdev(op, lenout, device): """ Retrieve or set the name of the current output device for error messages. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errdev_c.html :param op: The operation, "GET" or "SET". :type op: str :param lenout: Length of device for output. :type lenout: int :param device: The device name. :type device: str :return: The device name. :rtype: str """ lenout = ctypes.c_int(lenout) op = stypes.stringToCharP(op) device = ctypes.create_string_buffer(str.encode(device), lenout.value) deviceptr = ctypes.c_char_p(ctypes.addressof(device)) libspice.errdev_c(op, lenout, deviceptr) return stypes.toPythonString(deviceptr) def errdp(marker, number): """ Substitute a double precision number for the first occurrence of a marker found in the current long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errdp_c.html :param marker: A substring of the error message to be replaced. :type marker: str :param number: The d.p. number to substitute for marker. :type number: float """ marker = stypes.stringToCharP(marker) number = ctypes.c_double(number) libspice.errdp_c(marker, number) pass def errint(marker, number): """ Substitute an integer for the first occurrence of a marker found in the current long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errint_c.html :param marker: A substring of the error message to be replaced. :type marker: str :param number: The integer to substitute for marker. :type number: int """ marker = stypes.stringToCharP(marker) number = ctypes.c_int(number) libspice.errint_c(marker, number) pass def errprt(op, lenout, inlist): """ Retrieve or set the list of error message items to be output when an error is detected. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errprt_c.html :param op: The operation, "GET" or "SET". :type op: str :param lenout: Length of list for output. :type lenout: int :param inlist: Specification of error messages to be output. :type inlist: List of str. :return: A list of error message items. :rtype: List of str. """ lenout = ctypes.c_int(lenout) op = stypes.stringToCharP(op) inlist = ctypes.create_string_buffer(str.encode(inlist), lenout.value) inlistptr = ctypes.c_char_p(ctypes.addressof(inlist)) libspice.errdev_c(op, lenout, inlistptr) return stypes.toPythonString(inlistptr) def esrchc(value, array): """ Search for a given value within a character string array. Return the index of the first equivalent array entry, or -1 if no equivalent element is found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/esrchc_c.html :param value: Key value to be found in array. :type value: str :param array: Character string array to search. :type array: List of str. :return: The index of the first array entry equivalent to value, or -1 if none is found. :rtype: int """ value = stypes.stringToCharP(value) ndim = ctypes.c_int(len(array)) lenvals = ctypes.c_int(len(max(array, key=len)) + 1) array = stypes.listToCharArray(array, xLen=lenvals, yLen=ndim) return libspice.esrchc_c(value, ndim, lenvals, array) @spiceErrorCheck def et2lst(et, body, lon, typein, timlen, ampmlen): """ Given an ephemeris epoch, compute the local solar time for an object on the surface of a body at a specified longitude. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html :param et: Epoch in seconds past J2000 epoch. :type et: float :param body: ID-code of the body of interest. :type body: int :param lon: Longitude of surface point (RADIANS). :type lon: float :param typein: Type of longitude "PLANETOCENTRIC", etc. :type typein: str :param timlen: Available room in output time string. :type timlen: int :param ampmlen: Available room in output ampm string. :type ampmlen: int :return: Local hour on a "24 hour" clock, Minutes past the hour, Seconds past the minute, String giving local time on 24 hour clock, String giving time on A.M. / P.M. scale. :rtype: tuple """ et = ctypes.c_double(et) body = ctypes.c_int(body) lon = ctypes.c_double(lon) typein = stypes.stringToCharP(typein) timlen = ctypes.c_int(timlen) ampmlen = ctypes.c_int(ampmlen) hr = ctypes.c_int() mn = ctypes.c_int() sc = ctypes.c_int() time = stypes.stringToCharP(timlen) ampm = stypes.stringToCharP(ampmlen) libspice.et2lst_c(et, body, lon, typein, timlen, ampmlen, ctypes.byref(hr), ctypes.byref(mn), ctypes.byref(sc), time, ampm) return hr.value, mn.value, sc.value, stypes.toPythonString( time), stypes.toPythonString(ampm) @spiceErrorCheck def et2utc(et, formatStr, prec, lenout): """ Convert an input time from ephemeris seconds past J2000 to Calendar, Day-of-Year, or Julian Date format, UTC. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html :param et: Input epoch, given in ephemeris seconds past J2000. :type et: float :param formatStr: Format of output epoch. :type formatStr: str :param prec: Digits of precision in fractional seconds or days. :type prec: int :param lenout: The length of the output string plus 1. :type lenout: int :return: Output time string in UTC :rtype: str """ et = ctypes.c_double(et) prec = ctypes.c_int(prec) lenout = ctypes.c_int(lenout) formatStr = stypes.stringToCharP(formatStr) utcstr = stypes.stringToCharP(lenout) libspice.et2utc_c(et, formatStr, prec, lenout, utcstr) return stypes.toPythonString(utcstr) @spiceErrorCheck def etcal(et, lenout): """ Convert from an ephemeris epoch measured in seconds past the epoch of J2000 to a calendar string format using a formal calendar free of leapseconds. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/etcal_c.html :param et: Ephemeris time measured in seconds past J2000. :type et: float :param lenout: Length of output string. :type lenout: int :return: A standard calendar representation of et. :rtype: str """ et = ctypes.c_double(et) lenout = ctypes.c_int(lenout) string = stypes.stringToCharP(lenout) libspice.etcal_c(et, lenout, string) return stypes.toPythonString(string) @spiceErrorCheck def eul2m(angle3, angle2, angle1, axis3, axis2, axis1): """ Construct a rotation matrix from a set of Euler angles. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2m_c.html :param angle3: Rotation angle about third rotation axis (radians). :type angle3: float :param angle2: Rotation angle about second rotation axis (radians). :type angle2: float :param angle1: Rotation angle about first rotation axis (radians). :type angle1: float :param axis3: Axis number of third rotation axis. :type axis3: int :param axis2: Axis number of second rotation axis. :type axis2: int :param axis1: Axis number of first rotation axis.] :type axis1: int :return: Product of the 3 rotations. :rtype: 3x3-Element Array of Floats. """ angle3 = ctypes.c_double(angle3) angle2 = ctypes.c_double(angle2) angle1 = ctypes.c_double(angle1) axis3 = ctypes.c_int(axis3) axis2 = ctypes.c_int(axis2) axis1 = ctypes.c_int(axis1) r = stypes.emptyDoubleMatrix() libspice.eul2m_c(angle3, angle2, angle1, axis3, axis2, axis1, r) return stypes.matrixToList(r) @spiceErrorCheck def eul2xf(eulang, axisa, axisb, axisc): """ This routine computes a state transformation from an Euler angle factorization of a rotation and the derivatives of those Euler angles. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eul2xf_c.html :param eulang: An array of Euler angles and their derivatives. :type eulang: 6-Element Array of Floats. :param axisa: Axis A of the Euler angle factorization. :type axisa: int :param axisb: Axis B of the Euler angle factorization. :type axisb: int :param axisc: Axis C of the Euler angle factorization. :type axisc: int :return: A state transformation matrix. :rtype: 6x6-Element Array of Floats. """ assert len(eulang) is 6 eulang = stypes.toDoubleVector(eulang) axisa = ctypes.c_int(axisa) axisb = ctypes.c_int(axisb) axisc = ctypes.c_int(axisc) xform = stypes.emptyDoubleMatrix(x=6, y=6) libspice.eul2xf_c(eulang, axisa, axisb, axisc, xform) return stypes.matrixToList(xform) @spiceErrorCheck def exists(fname): """ Determine whether a file exists. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/exists_c.html :param fname: Name of the file in question. :return: True if the file exists, False otherwise. :rtype: bool """ fname = stypes.stringToCharP(fname) return libspice.exists_c(fname) @spiceErrorCheck def expool(name): """ Confirm the existence of a kernel variable in the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/expool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :return: True when the variable is in the pool. :rtype: bool """ name = stypes.stringToCharP(name) found = ctypes.c_bool() libspice.expool_c(name, ctypes.byref(found)) return found.value ################################################################################ # F def failed(): """ True if an error condition has been signalled via sigerr_c. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/failed_c.html :return: a boolean :rtype: bool """ return libspice.failed_c() @spiceErrorCheck def fovray(inst, raydir, rframe, abcorr, observer, et): # Unsure if et is returned or not (I vs I/O) """ Determine if a specified ray is within the field-of-view (FOV) of a specified instrument at a given time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/fovray_c.html :param inst: Name or ID code string of the instrument. :type inst: str :param raydir: Ray's direction vector. :type raydir: 3-Element Array of Floats. :param rframe: Body-fixed, body-centered frame for target body. :type rframe: str :param abcorr: Aberration correction flag. :type abcorr: str :param observer: Name or ID code string of the observer. :type observer: str :param et: Time of the observation (seconds past J2000). :type et: float :return: Visibility flag :rtype: bool """ inst = stypes.stringToCharP(inst) raydir = stypes.toDoubleVector(raydir) rframe = stypes.stringToCharP(rframe) abcorr = stypes.stringToCharP(abcorr) observer = stypes.stringToCharP(observer) et = ctypes.c_double(et) visible = ctypes.c_bool() libspice.fovray_c(inst, raydir, rframe, abcorr, observer, ctypes.byref(et), ctypes.byref(visible)) return visible.value @spiceErrorCheck def fovtrg(inst, target, tshape, tframe, abcorr, observer, et): # Unsure if et is returned or not (I vs I/O) """ Determine if a specified ephemeris object is within the field-of-view (FOV) of a specified instrument at a given time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/fovtrg_c.html :param inst: Name or ID code string of the instrument. :type inst: str :param target: Name or ID code string of the target. :type target: str :param tshape: Type of shape model used for the target. :type tshape: str :param tframe: Body-fixed, body-centered frame for target body. :type tframe: str :param abcorr: Aberration correction flag. :type abcorr: str :param observer: Name or ID code string of the observer. :type observer: str :param et: Time of the observation (seconds past J2000). :type et: float :return: Visibility flag :rtype: bool """ inst = stypes.stringToCharP(inst) target = stypes.stringToCharP(target) tshape = stypes.stringToCharP(tshape) tframe = stypes.stringToCharP(tframe) abcorr = stypes.stringToCharP(abcorr) observer = stypes.stringToCharP(observer) et = ctypes.c_double(et) visible = ctypes.c_bool() libspice.fovtrg_c(inst, target, tshape, tframe, abcorr, observer, ctypes.byref(et), ctypes.byref(visible)) return visible.value @spiceErrorCheck def frame(x): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frame_c.html :param x: Input vector. A parallel unit vector on output. :type x: 3-Element Array of Floats. :return: a tuple of 3 list[3] :rtype: tuple """ x = stypes.toDoubleVector(x) y = stypes.emptyDoubleVector(3) z = stypes.emptyDoubleVector(3) libspice.frame_c(x, y, z) return stypes.vectorToList(x), stypes.vectorToList(y), stypes.vectorToList( z) @spiceErrorCheck def frinfo(frcode): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frinfo_c.html :param frcode: the idcode for some frame :type frcode: int :return: a tuple of attributes associated with the frame :rtype: tuple """ frcode = ctypes.c_int(frcode) cent = ctypes.c_int() frclss = ctypes.c_int() clssid = ctypes.c_int() found = ctypes.c_bool() libspice.frinfo_c(frcode, ctypes.byref(cent), ctypes.byref(frclss), ctypes.byref(clssid), ctypes.byref(found)) return cent.value, frclss.value, clssid.value, found.value @spiceErrorCheck def frmnam(frcode, lenout=125): """ Retrieve the name of a reference frame associated with a SPICE ID code. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frmnam_c.html :param frcode: an integer code for a reference frame :type frcode: int :param lenout: Maximum length of output string. :type lenout: int :return: the name associated with the reference frame. :rtype: str """ frcode = ctypes.c_int(frcode) lenout = ctypes.c_int(lenout) frname = stypes.stringToCharP(lenout) libspice.frmnam_c(frcode, lenout, frname) return stypes.toPythonString(frname) @spiceErrorCheck def ftncls(unit): """ Close a file designated by a Fortran-style integer logical unit. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ftncls_c.html :param unit: Fortran-style logical unit. :type unit: int """ unit = ctypes.c_int(unit) libspice.ftncls_c(unit) pass @spiceErrorCheck def furnsh(path): """ Load one or more SPICE kernels into a program. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/furnsh_c.html :param path: one or more paths to kernels :type path: str or list of str """ if isinstance(path, list): for p in path: libspice.furnsh_c(stypes.stringToCharP(p)) else: path = stypes.stringToCharP(path) libspice.furnsh_c(path) pass ################################################################################ # G @spiceErrorCheck def gcpool(name, start, room, lenout): """ Return the character value of a kernel variable from the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gcpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :param start: Which component to start retrieving for name. :type start: int :param room: The largest number of values to return. :type room: int :param lenout: The length of the output string. :type lenout: int :return: Values associated with name, Found flag. :rtype: tuple """ name = stypes.stringToCharP(name) start = ctypes.c_int(start) room = ctypes.c_int(room) lenout = ctypes.c_int(lenout) n = ctypes.c_int() cvals = stypes.emptyCharArray(lenout, room) found = ctypes.c_bool() libspice.gcpool_c(name, start, room, lenout, ctypes.byref(n), ctypes.byref(cvals), ctypes.byref(found)) return [stypes.toPythonString(x.value) for x in cvals[0:n.value]], found.value @spiceErrorCheck def gdpool(name, start, room): """ Return the d.p. value of a kernel variable from the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gdpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :param start: Which component to start retrieving for name. :type start: int :param room: The largest number of values to return. :type room: int :return: Values associated with name, Found flag. :rtype: tuple """ name = stypes.stringToCharP(name) start = ctypes.c_int(start) values = stypes.emptyDoubleVector(room) room = ctypes.c_int(room) n = ctypes.c_int() found = ctypes.c_bool() libspice.gdpool_c(name, start, room, ctypes.byref(n), ctypes.cast(values, ctypes.POINTER(ctypes.c_double)), ctypes.byref(found)) return stypes.vectorToList(values)[0:n.value], found.value @spiceErrorCheck def georec(lon, lat, alt, re, f): """ Convert geodetic coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/georec_c.html :param lon: Geodetic longitude of point (radians). :type lon: float :param lat: Geodetic latitude of point (radians). :type lat: float :param alt: Altitude of point above the reference spheroid. :type alt: float :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Rectangular coordinates of point. :rtype: 3-Element Array of Floats. """ lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) alt = ctypes.c_double(alt) re = ctypes.c_double(re) f = ctypes.c_double(f) rectan = stypes.emptyDoubleVector(3) libspice.georec_c(lon, lat, alt, re, f, rectan) return stypes.vectorToList(rectan) # getcml not really needed @spiceErrorCheck def getelm(frstyr, lineln, lines): """ Given a the "lines" of a two-line element set, parse the lines and return the elements in units suitable for use in SPICE software. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/getelm_c.html :param frstyr: Year of earliest representable two-line elements. :type frstyr: int :param lineln: Length of strings in lines array. :type lineln: int :param lines: A pair of "lines" containing two-line elements. :type lines: List of str :return: The epoch of the elements in seconds past J2000, The elements converted to SPICE units. :rtype: tuple """ frstyr = ctypes.c_int(frstyr) lineln = ctypes.c_int(lineln) lines = stypes.listToCharArrayPtr(lines, xLen=lineln, yLen=2) epoch = ctypes.c_double() elems = stypes.emptyDoubleVector(10) # guess for length libspice.getelm_c(frstyr, lineln, lines, ctypes.byref(epoch), elems) return epoch.value, stypes.vectorToList(elems) @spiceErrorCheck def getfat(file): """ Determine the file architecture and file type of most SPICE kernel files. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/getfat_c.html :param file: The name of a file to be examined. :type file: str :return: The architecture of the kernel file, The type of the kernel file. :rtype: tuple """ file = stypes.stringToCharP(file) arclen = ctypes.c_int(4) typlen = ctypes.c_int(4) arch = stypes.stringToCharP(arclen) rettype = stypes.stringToCharP(typlen) libspice.getfat_c(file, arclen, typlen, arch, rettype) return stypes.toPythonString(arch), stypes.toPythonString(rettype) @spiceErrorCheck def getfov(instid, room, shapelen, framelen): """ This routine returns the field-of-view (FOV) parameters for a specified instrument. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/getfov_c.html :param instid: NAIF ID of an instrument. :type instid: int :param room: Maximum number of vectors that can be returned. :type room: int :param shapelen: Space available in the string shape. :type shapelen: int :param framelen: Space available in the string frame. :type framelen: int :return: Instrument FOV shape, Name of the frame in which FOV vectors are defined, Boresight vector, Number of boundary vectors returned, FOV boundary vectors. :rtype: tuple """ instid = ctypes.c_int(instid) shape = stypes.stringToCharP(" " * shapelen) framen = stypes.stringToCharP(" " * framelen) shapelen = ctypes.c_int(shapelen) framelen = ctypes.c_int(framelen) bsight = stypes.emptyDoubleVector(3) n = ctypes.c_int() bounds = stypes.emptyDoubleMatrix(x=3, y=room) room = ctypes.c_int(room) libspice.getfov_c(instid, room, shapelen, framelen, shape, framen, bsight, ctypes.byref(n), bounds) return stypes.toPythonString(shape), stypes.toPythonString( framen), stypes.vectorToList( bsight), n.value, stypes.matrixToList(bounds)[0:n.value] def getmsg(option, lenout): """ Retrieve the current short error message, the explanation of the short error message, or the long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/getmsg_c.html :param option: Indicates type of error message. :type option: str :param lenout: Available space in the output string msg. :type lenout: int :return: The error message to be retrieved. :rtype: str """ option = stypes.stringToCharP(option) lenout = ctypes.c_int(lenout) msg = stypes.stringToCharP(lenout) libspice.getmsg_c(option, lenout, msg) return stypes.toPythonString(msg) @spiceErrorCheck def gfbail(): """ Indicate whether an interrupt signal (SIGINT) has been received. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfbail_c.html :return: True if an interrupt signal has been received by the GF handler. :rtype: bool """ return libspice.gfbail_c() @spiceErrorCheck def gfclrh(): """ Clear the interrupt signal handler status, so that future calls to :func:`gfbail` will indicate no interrupt was received. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfclrh_c.html """ libspice.gfclrh_c() pass @spiceErrorCheck def gfdist(target, abcorr, obsrvr, relate, refval, adjust, step, nintvls, cnfine, result): """ Return the time window over which a specified constraint on observer-target distance is met. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfdist_c.html :param target: Name of the target body. :type target: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Adjustment value for absolute extrema searches. :type adjust: float :param step: Step size used for locating extrema and roots. :type step: float :param nintvls: Workspace window interval count. :type nintvls: int :param cnfine: SPICE window to which the search is confined. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() target = stypes.stringToCharP(target) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvls = ctypes.c_int(nintvls) libspice.gfdist_c(target, abcorr, obsrvr, relate, refval, adjust, step, nintvls, ctypes.byref(cnfine), ctypes.byref(result)) # gdevnt callbacks? cells # gffove callbacks? cells # gfilum @spiceErrorCheck def gfinth(sigcode): # Todo: test gfinth """ Respond to the interrupt signal SIGINT: save an indication that the signal has been received. This routine restores itself as the handler for SIGINT. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfinth_c.html :param sigcode: Interrupt signal ID code. :type sigcode: int """ sigcode = ctypes.c_int(sigcode) libspice.gfinth_c(sigcode) pass # gfocce callbacks? cells @spiceErrorCheck def gfoclt(occtyp, front, fshape, fframe, back, bshape, bframe, abcorr, obsrvr, step, cnfine, result): """ Determine time intervals when an observer sees one target occulted by, or in transit across, another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfoclt_c.html :param occtyp: Type of occultation. :type occtyp: str :param front: Name of body occulting the other. :type front: str :param fshape: Type of shape model used for front body. :type fshape: str :param fframe: Body-fixed, body-centered frame for front body. :type fframe: str :param back: Name of body occulted by the other. :type back: str :param bshape: Type of shape model used for back body. :type bshape: str :param bframe: Body-fixed, body-centered frame for back body. :type bframe: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param step: Step size in seconds for finding occultation events. :type step: float :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() occtyp = stypes.stringToCharP(occtyp) front = stypes.stringToCharP(front) fshape = stypes.stringToCharP(fshape) fframe = stypes.stringToCharP(fframe) back = stypes.stringToCharP(back) bshape = stypes.stringToCharP(bshape) bframe = stypes.stringToCharP(bframe) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) step = ctypes.c_double(step) libspice.gfoclt_c(occtyp, front, fshape, fframe, back, bshape, bframe, abcorr, obsrvr, step, ctypes.byref(cnfine), ctypes.byref(result)) @spiceErrorCheck def gfpa(target, illmin, abcorr, obsrvr, relate, refval, adjust, step, nintvals, cnfine, result): """ Determine time intervals for which a specified constraint on the phase angle between an illumination source, a target, and observer body centers is met. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfpa_c.html :param target: Name of the target body. :type target: str :param illmin: Name of the illuminating body. :type illmin: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Adjustment value for absolute extrema searches. :type adjust: float :param step: Step size used for locating extrema and roots. :type step: float :param nintvals: Workspace window interval count. :type nintvals: int :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() target = stypes.stringToCharP(target) illmin = stypes.stringToCharP(illmin) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvals = ctypes.c_int(nintvals) libspice.gfpa_c(target, illmin, abcorr, obsrvr, relate, refval, adjust, step, nintvals, ctypes.byref(cnfine), ctypes.byref(result)) pass @spiceErrorCheck def gfposc(target, inframe, abcorr, obsrvr, crdsys, coord, relate, refval, adjust, step, nintvals, cnfine, result): """ Determine time intervals for which a coordinate of an observer-target position vector satisfies a numerical constraint. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfposc_c.html :param target: Name of the target body. :type target: str :param inframe: Name of the reference frame for coordinate calculations. :type inframe: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param crdsys: Name of the coordinate system containing COORD :type crdsys: str :param coord: Name of the coordinate of interest :type coord: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Adjustment value for absolute extrema searches. :type adjust: float :param step: Step size used for locating extrema and roots. :type step: float :param nintvals: Workspace window interval count. :type nintvals: int :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() target = stypes.stringToCharP(target) inframe = stypes.stringToCharP(inframe) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) crdsys = stypes.stringToCharP(crdsys) coord = stypes.stringToCharP(coord) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvals = ctypes.c_int(nintvals) libspice.gfposc_c(target, inframe, abcorr, obsrvr, crdsys, coord, relate, refval, adjust, step, nintvals, ctypes.byref(cnfine), ctypes.byref(result)) pass @spiceErrorCheck def gfrefn(t1, t2, s1, s2): # Todo: test gfrefn """ For those times when we can't do better, we use a bisection method to find the next time at which to test for state change. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrefn_c.html :param t1: One of two values bracketing a state change. :type t1: float :param t2: The other value that brackets a state change. :type t2: float :param s1: State at t1. :type s1: bool :param s2: State at t2. :type s2: bool :return: New value at which to check for transition. :rtype: bool """ t1 = ctypes.c_double(t1) t2 = ctypes.c_double(t2) s1 = ctypes.c_bool(s1) s2 = ctypes.c_bool(s2) t = ctypes.c_bool() libspice.gfrefn_c(t1, t2, s1, s2, ctypes.byref(t)) return t.value @spiceErrorCheck def gfrepf(): # Todo: test gfrepf """ Finish a GF progress report. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrepf_c.html """ libspice.gfrepf_c() pass @spiceErrorCheck def gfrepi(window, begmss, endmss): # Todo: test gfrepi """ This entry point initializes a search progress report. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrepi_c.html :param window: A window over which a job is to be performed. :type window: SpiceyPy.support_types.SpiceCell :param begmss: Beginning of the text portion of the output message. :type begmss: str :param endmss: End of the text portion of the output message. :type endmss: str """ assert isinstance(window, stypes.SpiceCell) assert window.is_double() begmss = stypes.stringToCharP(begmss) endmss = stypes.stringToCharP(endmss) libspice.gfrepi_c(ctypes.byref(window), begmss, endmss) pass @spiceErrorCheck def gfrepu(ivbeg, ivend, time): # Todo: test gfrepu """ This function tells the progress reporting system how far a search has progressed. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrepu_c.html :param ivbeg: Start time of work interval. :type ivbeg: float :param ivend: End time of work interval. :type ivend: float :param time: Current time being examined in the search process. :type time: float """ ivbeg = ctypes.c_double(ivbeg) ivend = ctypes.c_double(ivend) time = ctypes.c_double(time) libspice.gfrepu_c(ivbeg, ivend, time) pass @spiceErrorCheck def gfrfov(inst, raydir, rframe, abcorr, obsrvr, step, cnfine, result): # Todo: test gfrfov """ Determine time intervals when a specified ray intersects the space bounded by the field-of-view (FOV) of a specified instrument. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrfov_c.html :param inst: Name of the instrument. :type inst: str :param raydir: Ray's direction vector. :type raydir: 3-Element Array of Float. :param rframe: Reference frame of ray's direction vector. :type rframe: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param step: Step size in seconds for finding FOV events. :type step: float :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() inst = stypes.stringToCharP(inst) raydir = stypes.toDoubleVector(raydir) rframe = stypes.stringToCharP(rframe) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) step = ctypes.c_double(step) libspice.gfrfov_c(inst, raydir, rframe, abcorr, obsrvr, step, ctypes.byref(cnfine), ctypes.byref(result)) @spiceErrorCheck def gfrr(target, abcorr, obsrvr, relate, refval, adjust, step, nintvals, cnfine, result): """ Determine time intervals for which a specified constraint on the observer-target range rate is met. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrr_c.html :param target: Name of the target body. :type target: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Adjustment value for absolute extrema searches. :type adjust: float :param step: Step size used for locating extrema and roots. :type step: float :param nintvals: Workspace window interval count. :type nintvals: int :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() target = stypes.stringToCharP(target) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvals = ctypes.c_int(nintvals) libspice.gfrr_c(target, abcorr, obsrvr, relate, refval, adjust, step, nintvals, ctypes.byref(cnfine), ctypes.byref(result)) @spiceErrorCheck def gfsep(targ1, shape1, inframe1, targ2, shape2, inframe2, abcorr, obsrvr, relate, refval, adjust, step, nintvals, cnfine, result): """ Determine time intervals when the angular separation between the position vectors of two target bodies relative to an observer satisfies a numerical relationship. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfsep_c.html :param targ1: Name of first body. :type targ1: str :param shape1: Name of shape model describing the first body. :type shape1: str :param inframe1: The body-fixed reference frame of the first body. :type inframe1: str :param targ2: Name of second body. :type targ2: str :param shape2: Name of the shape model describing the second body. :type shape2: str :param inframe2: The body-fixed reference frame of the second body :type inframe2: str :param abcorr: Aberration correction flag :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Absolute extremum adjustment value. :type adjust: float :param step: Step size in seconds for finding angular separation events. :type step: float :param nintvals: Workspace window interval count. :type nintvals: int :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() targ1 = stypes.stringToCharP(targ1) shape1 = stypes.stringToCharP(shape1) inframe1 = stypes.stringToCharP(inframe1) targ2 = stypes.stringToCharP(targ2) shape2 = stypes.stringToCharP(shape2) inframe2 = stypes.stringToCharP(inframe2) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvals = ctypes.c_int(nintvals) libspice.gfsep_c(targ1, shape1, inframe1, targ2, shape2, inframe2, abcorr, obsrvr, relate, refval, adjust, step, nintvals, ctypes.byref(cnfine), ctypes.byref(result)) @spiceErrorCheck def gfsntc(target, fixref, method, abcorr, obsrvr, dref, dvec, crdsys, coord, relate, refval, adjust, step, nintvals, cnfine, result): """ Determine time intervals for which a coordinate of an surface intercept position vector satisfies a numerical constraint. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfsntc_c.html :param target: Name of the target body. :type target: str :param fixref: Body fixed frame associated with the target. :type fixref: str :param method: Name of method type for surface intercept calculation. :type method: str :param abcorr: Aberration correction flag :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param dref: Reference frame of direction vector of dvec. :type dref: str :param dvec: Pointing direction vector from the observer. :type dvec: 3-Element Array of Floats. :param crdsys: Name of the coordinate system containing COORD. :type crdsys: str :param coord: Name of the coordinate of interest :type coord: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Absolute extremum adjustment value. :type adjust: float :param step: Step size in seconds for finding angular separation events. :type step: float :param nintvals: Workspace window interval count. :type nintvals: int :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() target = stypes.stringToCharP(target) fixref = stypes.stringToCharP(fixref) method = stypes.stringToCharP(method) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) dref = stypes.stringToCharP(dref) dvec = stypes.toDoubleVector(dvec) crdsys = stypes.stringToCharP(crdsys) coord = stypes.stringToCharP(coord) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvals = ctypes.c_int(nintvals) libspice.gfsntc_c(target, fixref, method, abcorr, obsrvr, dref, dvec, crdsys, coord, relate, refval, adjust, step, nintvals, ctypes.byref(cnfine), ctypes.byref(result)) @spiceErrorCheck def gfsstp(step): """ Set the step size to be returned by :func:`gfstep`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfsstp_c.html :param step: Time step to take. :type step: float """ step = ctypes.c_double(step) libspice.gfsstp_c(step) pass @spiceErrorCheck def gfstep(time): """ Return the time step set by the most recent call to :func:`gfsstp`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstep_c.html :param time: Ignored ET value. :type time: float :return: Time step to take. :rtype: float """ time = ctypes.c_double(time) step = ctypes.c_double() libspice.gfstep_c(time, ctypes.byref(step)) return step.value @spiceErrorCheck def gfstol(value): """ Override the default GF convergence value used in the high level GF routines. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstol_c.html :param value: Double precision value returned or to store. :type value: float """ value = ctypes.c_double(value) libspice.gfstol_c(value) pass @spiceErrorCheck def gfsubc(target, fixref, method, abcorr, obsrvr, crdsys, coord, relate, refval, adjust, step, nintvals, cnfine, result): """ Determine time intervals for which a coordinate of an subpoint position vector satisfies a numerical constraint. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfsubc_c.html :param target: Name of the target body. :type target: str :param fixref: Body fixed frame associated with the target. :type fixref: str :param method: Name of method type for subpoint calculation. :type method: str :param abcorr: Aberration correction flag :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param crdsys: Name of the coordinate system containing COORD. :type crdsys: str :param coord: Name of the coordinate of interest :type coord: str :param relate: Relational operator. :type relate: str :param refval: Reference value. :type refval: float :param adjust: Adjustment value for absolute extrema searches. :type adjust: float :param step: Step size used for locating extrema and roots. :type step: float :param nintvals: Workspace window interval count. :type nintvals: int :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell :param result: SPICE window containing results. :type result: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() assert isinstance(result, stypes.SpiceCell) assert result.is_double() target = stypes.stringToCharP(target) fixref = stypes.stringToCharP(fixref) method = stypes.stringToCharP(method) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) crdsys = stypes.stringToCharP(crdsys) coord = stypes.stringToCharP(coord) relate = stypes.stringToCharP(relate) refval = ctypes.c_double(refval) adjust = ctypes.c_double(adjust) step = ctypes.c_double(step) nintvals = ctypes.c_int(nintvals) libspice.gfsubc_c(target, fixref, method, abcorr, obsrvr, crdsys, coord, relate, refval, adjust, step, nintvals, ctypes.byref(cnfine), ctypes.byref(result)) @spiceErrorCheck def gftfov(inst, target, tshape, tframe, abcorr, obsrvr, step, cnfine): # Todo: test gftfov """ Determine time intervals when a specified ephemeris object intersects the space bounded by the field-of-view (FOV) of a specified instrument. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gftfov_c.html :param inst: Name of the instrument. :type inst: str :param target: Name of the target body. :type target: str :param tshape: Type of shape model used for target body. :type tshape: str :param tframe: Body-fixed, body-centered frame for target body. :type tframe: str :param abcorr: Aberration correction flag. :type abcorr: str :param obsrvr: Name of the observing body. :type obsrvr: str :param step: Step size in seconds for finding FOV events. :type step: float :param cnfine: SPICE window to which the search is restricted. :type cnfine: SpiceyPy.support_types.SpiceCell """ assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() target = stypes.stringToCharP(target) tshape = stypes.stringToCharP(tshape) tframe = stypes.stringToCharP(tframe) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) step = ctypes.c_double(step) result = stypes.SPICEDOUBLE_CELL(cnfine.size) libspice.gftfov_c(inst, target, tshape, tframe, abcorr, obsrvr, step, ctypes.byref(cnfine), ctypes.byref(result)) # gfudb has call backs # gfuds has call backs @spiceErrorCheck def gipool(name, start, room): """ Return the integer value of a kernel variable from the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gipool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :param start: Which component to start retrieving for name. :type start: int :param room: The largest number of values to return. :type room: int :return: Values associated with name, Found Flag. :rtype: tuple """ name = stypes.stringToCharP(name) start = ctypes.c_int(start) ivals = stypes.emptyIntVector(room) room = ctypes.c_int(room) n = ctypes.c_int() found = ctypes.c_bool() libspice.gipool_c(name, start, room, ctypes.byref(n), ivals, ctypes.byref(found)) return stypes.vectorToList(ivals)[0:n.value], found.value @spiceErrorCheck def gnpool(name, start, room, lenout): """ Return names of kernel variables matching a specified template. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gnpool_c.html :param name: Template that names should match. :type name: str :param start: Index of first matching name to retrieve. :type start: int :param room: The largest number of values to return. :type room: int :param lenout: Length of strings in output array kvars. :type lenout: int :return: Kernel pool variables whose names match name, found. :rtype: tuple """ name = stypes.stringToCharP(name) start = ctypes.c_int(start) kvars = stypes.charvector(room, lenout) room = ctypes.c_int(room) lenout = ctypes.c_int(lenout) n = ctypes.c_int() found = ctypes.c_bool() libspice.gnpool_c(name, start, room, lenout, ctypes.byref(n), kvars, ctypes.byref(found)) return stypes.vectorToList(kvars)[0:n.value], found.value ################################################################################ # H @spiceErrorCheck def halfpi(): """ Return half the value of pi (the ratio of the circumference of a circle to its diameter). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/halfpi_c.html :return: Half the value of pi. :rtype: float """ return libspice.halfpi_c() @spiceErrorCheck def hx2dp(string): """ Convert a string representing a double precision number in a base 16 scientific notation into its equivalent double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hx2dp_c.html :param string: Hex form string to convert to double precision. :type string: str :return: Double precision value to be returned, Or Error Message. :rtype: float or str """ string = stypes.stringToCharP(string) lenout = ctypes.c_int(80) errmsg = stypes.stringToCharP(lenout) number = ctypes.c_double() error = ctypes.c_bool() libspice.hx2dp_c(string, lenout, ctypes.byref(number), ctypes.byref(error), errmsg) if not error.value: return number.value else: return stypes.toPythonString(errmsg) ################################################################################ # I @spiceErrorCheck def ident(): """ This routine returns the 3x3 identity matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ident_c.html :return: The 3x3 identity matrix. :rtype: 3x3-Element Array of Floats """ matrix = stypes.emptyDoubleMatrix() libspice.ident_c(matrix) return stypes.matrixToList(matrix) @spiceErrorCheck def illum(target, et, abcorr, obsrvr, spoint): """ Deprecated: This routine has been superseded by the CSPICE routine ilumin. This routine is supported for purposes of backward compatibility only. Find the illumination angles at a specified surface point of a target body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/illum_c.html :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000. :type et: float :param abcorr: Desired aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :param spoint: Body-fixed coordinates of a target surface point. :type spoint: 3-Element Array of Floats :return: Phase angle, Solar incidence angle, and Emission angle at the surface point. :rtype: tuple """ target = stypes.stringToCharP(target) et = ctypes.c_double(et) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) spoint = stypes.toDoubleVector(spoint) phase = ctypes.c_double(0) solar = ctypes.c_double(0) emissn = ctypes.c_double(0) libspice.illum_c(target, et, abcorr, obsrvr, spoint, ctypes.byref(phase), ctypes.byref(solar), ctypes.byref(emissn)) return phase.value, solar.value, emissn.value @spiceErrorCheck def ilumin(method, target, et, fixref, abcorr, obsrvr, spoint): """ Find the illumination angles (phase, solar incidence, and emission) at a specified surface point of a target body. This routine supersedes illum. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ilumin_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000. :type et: float :param fixref: Body-fixed, body-centered target body frame. :type fixref: str :param abcorr: Desired aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :param spoint: Body-fixed coordinates of a target surface point. :type spoint: 3-Element Array of Floats :return: Target surface point epoch, Vector from observer to target surface point, Phase angle, Solar incidence angle, and Emission angle at the surface point. :rtype: tuple """ method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) fixref = stypes.stringToCharP(fixref) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) spoint = stypes.toDoubleVector(spoint) trgepc = ctypes.c_double(0) srfvec = stypes.emptyDoubleVector(3) phase = ctypes.c_double(0) solar = ctypes.c_double(0) emissn = ctypes.c_double(0) libspice.ilumin_c(method, target, et, fixref, abcorr, obsrvr, spoint, ctypes.byref(trgepc), srfvec, ctypes.byref(phase), ctypes.byref(solar), ctypes.byref(emissn)) return trgepc.value, stypes.vectorToList( srfvec), phase.value, solar.value, emissn.value @spiceErrorCheck def inedpl(a, b, c, plane): """ Find the intersection of a triaxial ellipsoid and a plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inedpl_c.html :param a: Length of ellipsoid semi-axis lying on the x-axis. :type a: float :param b: Length of ellipsoid semi-axis lying on the y-axis. :type b: float :param c: Length of ellipsoid semi-axis lying on the z-axis. :type c: float :param plane: Plane that intersects ellipsoid :type plane: SpiceyPy.support_types.Plane :return: Intersection ellipse, Found Flag. :rtype: SpiceyPy.support_types.Ellipse, bool """ assert (isinstance(plane, stypes.Plane)) ellipse = stypes.Ellipse() a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) found = ctypes.c_bool() libspice.inedpl_c(a, b, c, ctypes.byref(plane), ctypes.byref(ellipse), ctypes.byref(found)) return ellipse, found.value @spiceErrorCheck def inelpl(ellips, plane): """ Find the intersection of an ellipse and a plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inelpl_c.html :param ellips: A SPICE ellipse. :type plane: SpiceyPy.support_types.Ellipse :param plane: A SPICE plane. :type plane: SpiceyPy.support_types.Plane :return: Number of intersection points of plane and ellipse, Point 1, Point 2. :rtype: tuple """ assert (isinstance(plane, stypes.Plane)) assert (isinstance(ellips, stypes.Ellipse)) nxpts = ctypes.c_int() xpt1 = stypes.emptyDoubleVector(3) xpt2 = stypes.emptyDoubleVector(3) libspice.inelpl_c(ctypes.byref(ellips), ctypes.byref(plane), ctypes.byref(nxpts), xpt1, xpt2) return nxpts.value, stypes.vectorToList(xpt1), stypes.vectorToList(xpt2) @spiceErrorCheck def inrypl(vertex, direct, plane): """ Find the intersection of a ray and a plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inrypl_c.html :param vertex: Vertex vector of ray. :type vertex: 3-Element Array of Floats :param direct: Direction vector of ray. :type direct: 3-Element Array of Floats :param plane: A SPICE plane. :type plane: SpiceyPy.support_types.Plane :return: Number of intersection points of ray and plane, Intersection point, if nxpts == 1. :rtype: tuple """ assert (isinstance(plane, stypes.Plane)) vertex = stypes.toDoubleVector(vertex) direct = stypes.toDoubleVector(direct) nxpts = ctypes.c_int() xpt = stypes.emptyDoubleVector(3) libspice.inrypl_c(vertex, direct, ctypes.byref(plane), ctypes.byref(nxpts), xpt) return nxpts.value, stypes.vectorToList(xpt) @spiceErrorCheck def insrtc(item, inset): """ Insert an item into a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html :param item: Item to be inserted. :type item: str or list of str :param inset: Insertion set. :type inset: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) if isinstance(item, list): for c in item: libspice.insrtc_c(stypes.stringToCharP(c), ctypes.byref(inset)) else: item = stypes.stringToCharP(item) libspice.insrtc_c(item, ctypes.byref(inset)) pass @spiceErrorCheck def insrtd(item, inset): """ Insert an item into a double precision set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtd_c.html :param item: Item to be inserted. :type item: float or list of floats :param inset: Insertion set. :type inset: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) if hasattr(item, "__iter__"): for d in item: libspice.insrtd_c(ctypes.c_double(d), ctypes.byref(inset)) else: item = ctypes.c_double(item) libspice.insrtd_c(item, ctypes.byref(inset)) pass @spiceErrorCheck def insrti(item, inset): """ Insert an item into an integer set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrti_c.html :param item: Item to be inserted. :type item: int or list of ints :param inset: Insertion set. :type inset: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) if hasattr(item, "__iter__"): for i in item: libspice.insrti_c(ctypes.c_int(i), ctypes.byref(inset)) else: item = ctypes.c_int(item) libspice.insrti_c(item, ctypes.byref(inset)) pass @spiceErrorCheck def inter(a, b): """ Intersect two sets of any data type to form a third set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/inter_c.html :param a: First input set. :type a: SpiceyPy.support_types.SpiceCell :param b: Second input set. :type b: SpiceyPy.support_types.SpiceCell :return: Intersection of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert isinstance(b, stypes.SpiceCell) assert a.dtype == b.dtype assert a.dtype == 0 or a.dtype == 1 or a.dtype == 2 if a.dtype is 0: c = stypes.SPICECHAR_CELL(max(a.size, b.size), max(a.length, b.length)) elif a.dtype is 1: c = stypes.SPICEDOUBLE_CELL(max(a.size, b.size)) elif a.dtype is 2: c = stypes.SPICEINT_CELL(max(a.size, b.size)) else: raise NotImplementedError libspice.inter_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def intmax(): """ Return the value of the largest (positive) number representable in a int variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/intmax_c.html :return: The largest (positive) number representablein a Int variable. :rtype: int """ return libspice.intmax_c() @spiceErrorCheck def intmin(): """ Return the value of the smallest (negative) number representable in a SpiceInt variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/intmin_c.html :return: The smallest (negative) number representablein a Int variable. :rtype: int """ return libspice.intmin_c() @spiceErrorCheck def invert(m): """ Generate the inverse of a 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/invert_c.html :param m: Matrix to be inverted. :type m: 3x3-Element Array of Floats :return: Inverted matrix (m1)^-1 :rtype: 3x3-Element Array of Floats """ m = stypes.listtodoublematrix(m) mout = stypes.emptyDoubleMatrix() libspice.invert_c(m, mout) return stypes.matrixToList(mout) @spiceErrorCheck def invort(m): """ Given a matrix, construct the matrix whose rows are the columns of the first divided by the length squared of the the corresponding columns of the input matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/invort_c.html :param m: A 3x3 Matrix. :type m: 3x3-Element Array of Floats :return: m after transposition and scaling of rows. :rtype: 3x3-Element Array of Floats """ m = stypes.listtodoublematrix(m) mout = stypes.emptyDoubleMatrix() libspice.invort_c(m, mout) return stypes.matrixToList(mout) @spiceErrorCheck def isordv(array, n): """ Determine whether an array of n items contains the integers 0 through n-1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isordv_c.html :param array: Array of integers. :type array: Array of ints :param n: Number of integers in array. :type n: int :return: The function returns True if the array contains the integers 0 through n-1, otherwise it returns False. :rtype: bool """ array = stypes.toIntVector(array) n = ctypes.c_int(n) return libspice.isordv_c(array, n) @spiceErrorCheck def isrchc(value, ndim, lenvals, array): """ Search for a given value within a character string array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchc_c.html :param value: Key value to be found in array. :type value: str :param ndim: Dimension of array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: Character string array to search. :type array: Array of str :return: The index of the first matching array element or -1 if the value is not found. :rtype: int """ value = stypes.stringToCharP(value) array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=ndim) ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(lenvals) return libspice.isrchc_c(value, ndim, lenvals, array) @spiceErrorCheck def isrchd(value, ndim, array): """ Search for a given value within a double precision array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchd_c.html :param value: Key value to be found in array. :type value: float :param ndim: Dimension of array. :type ndim: int :param array: Double Precision array to search. :type array: Array of Floats :return: The index of the first matching array element or -1 if the value is not found. :rtype: int """ value = ctypes.c_double(value) ndim = ctypes.c_int(ndim) array = stypes.toDoubleVector(array) return libspice.isrchd_c(value, ndim, array) @spiceErrorCheck def isrchi(value, ndim, array): """ Search for a given value within an integer array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html :param value: Key value to be found in array. :type value: int :param ndim: Dimension of array. :type ndim: int :param array: Integer array to search. :type array: Array of Ints :return: The index of the first matching array element or -1 if the value is not found. :rtype: int """ value = ctypes.c_int(value) ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) return libspice.isrchi_c(value, ndim, array) @spiceErrorCheck def isrot(m, ntol, dtol): """ Indicate whether a 3x3 matrix is a rotation matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrot_c.html :param m: A matrix to be tested. :type m: 3x3-Element Array of Floats :param ntol: Tolerance for the norms of the columns of m. :type ntol: float :param dtol: Tolerance for the determinant of a matrix whose columns are the unitized columns of m. :type dtol: float :return: True if and only if m is a rotation matrix. :rtype: bool """ m = stypes.listtodoublematrix(m) ntol = ctypes.c_double(ntol) dtol = ctypes.c_double(dtol) return libspice.isrot_c(m, ntol, dtol) @spiceErrorCheck def iswhsp(string): """ Return a boolean value indicating whether a string contains only white space characters. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/iswhsp_c.html :param string: String to be tested. :type string: str :return: the boolean value True if the string is empty or contains only white space characters; otherwise it returns the value False. :rtype: bool """ string = stypes.stringToCharP(string) return libspice.iswhsp_c(string) ################################################################################ # J @spiceErrorCheck def j1900(): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/j1900_c.html :return: Julian Date of 1899 DEC 31 12:00:00 :rtype: float """ return libspice.j1900_c() @spiceErrorCheck def j1950(): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/j1950_c.html :return: Julian Date of 1950 JAN 01 00:00:00 :rtype: float """ return libspice.j1950_c() @spiceErrorCheck def j2000(): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/j2000_c.html :return: Julian Date of 2000 JAN 01 12:00:00 :rtype: float """ return libspice.j2000_c() @spiceErrorCheck def j2100(): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/j2100_c.html :return: Julian Date of 2100 JAN 01 12:00:00 :rtype: float """ return libspice.j2100_c() @spiceErrorCheck def jyear(): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/jyear_c.html :return: number of seconds in a julian year :rtype: float """ return libspice.jyear_c() ################################################################################ # K @spiceErrorCheck def kclear(): """ Clear the KEEPER subsystem: unload all kernels, clear the kernel pool, and re-initialize the subsystem. Existing watches on kernel variables are retained. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/kclear_c.html """ libspice.kclear_c() pass @spiceErrorCheck def kdata(which, kind, fillen, typlen, srclen): """ Return data for the nth kernel that is among a list of specified kernel types. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/kdata_c.html :param which: Index of kernel to fetch from the list of kernels. :type which: int :param kind: The kind of kernel to which fetches are limited. :type kind: str :param fillen: Available space in output file string. :type fillen: int :param typlen: Available space in output kernel type string. :type typlen: int :param srclen: Available space in output source string. :type srclen: int :return: The name of the kernel file, The type of the kernel, Name of the source file used to load file, The handle attached to file, True if the specified file could be located :rtype: tuple """ which = ctypes.c_int(which) kind = stypes.stringToCharP(kind) fillen = ctypes.c_int(fillen) typlen = ctypes.c_int(typlen) srclen = ctypes.c_int(srclen) file = stypes.stringToCharP(fillen) filtyp = stypes.stringToCharP(typlen) source = stypes.stringToCharP(srclen) handle = ctypes.c_int() found = ctypes.c_bool() libspice.kdata_c(which, kind, fillen, typlen, srclen, file, filtyp, source, ctypes.byref(handle), ctypes.byref(found)) return stypes.toPythonString(file), stypes.toPythonString( filtyp), stypes.toPythonString(source), handle.value, found.value @spiceErrorCheck def kinfo(file, typlen, srclen): """ Return information about a loaded kernel specified by name. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/kinfo_c.html :param file: Name of a kernel to fetch information for :type file: str :param typlen: Available space in output kernel type string. :type typlen: int :param srclen: Available space in output source string. :type srclen: int :return: The type of the kernel, Name of the source file used to load file, The handle attached to file, True if the specified file could be located :rtype: tuple """ typlen = ctypes.c_int(typlen) srclen = ctypes.c_int(srclen) file = stypes.stringToCharP(file) filtyp = stypes.stringToCharP(" " * typlen.value) source = stypes.stringToCharP(" " * srclen.value) handle = ctypes.c_int() found = ctypes.c_bool() libspice.kinfo_c(file, typlen, srclen, filtyp, source, ctypes.byref(handle), ctypes.byref(found)) return stypes.toPythonString(filtyp), stypes.toPythonString( source), handle.value, found.value @spiceErrorCheck def kplfrm(frmcls, cell_size=1000): """ Return a SPICE set containing the frame IDs of all reference frames of a given class having specifications in the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/kplfrm_c.html :param frmcls: Frame class. :type frmcls: int :param cell_size: Optional size of the cell, default is 1000. :type cell_size: int :return: Set of ID codes of frames of the specified class. :rtype: SpiceyPy.support_types.SpiceCell """ frmcls = ctypes.c_int(frmcls) idset = stypes.SPICEINT_CELL(cell_size) libspice.kplfrm_c(frmcls, ctypes.byref(idset)) return idset @spiceErrorCheck def ktotal(kind): """ Return the current number of kernels that have been loaded via the KEEPER interface that are of a specified type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ktotal_c.html :param kind: A list of kinds of kernels to count. :type kind: str :return: The number of kernels of type kind. :rtype: int """ kind = stypes.stringToCharP(kind) count = ctypes.c_int() libspice.ktotal_c(kind, ctypes.byref(count)) return count.value @spiceErrorCheck def kxtrct(keywd, termlen, terms, nterms, stringlen, substrlen, instring): """ Locate a keyword in a string and extract the substring from the beginning of the first word following the keyword to the beginning of the first subsequent recognized terminator of a list. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/kxtrct_c.html :param keywd: Word that marks the beginning of text of interest. :type keywd: str :param termlen: Length of strings in string array term. :type termlen: int :param terms: Set of words, any of which marks the end of text. :type terms: Array of str :param nterms: Number of terms. :type nterms: int :param stringlen: Available space in argument string. :type stringlen: int :param substrlen: Available space in output substring. :type substrlen: int :param instring: String containing a sequence of words. :type instring: str :return: String containing a sequence of words, True if the keyword is found in the string, String from end of keywd to beginning of first terms item found. :rtype: tuple """ keywd = stypes.stringToCharP(keywd) termlen = ctypes.c_int(termlen) terms = stypes.listToCharArrayPtr(terms) nterms = ctypes.c_int(nterms) instring = stypes.stringToCharP(instring) substr = stypes.stringToCharP(substrlen) stringlen = ctypes.c_int(stringlen) substrlen = ctypes.c_int(substrlen) found = ctypes.c_bool() libspice.kxtrct_c(keywd, termlen, ctypes.byref(terms), nterms, stringlen, substrlen, instring, ctypes.byref(found), substr) return stypes.toPythonString(instring), found.value, stypes.toPythonString( substr) ################################################################################ # L @spiceErrorCheck def lastnb(string): """ Return the zero based index of the last non-blank character in a character string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lastnb_c.html :param string: Input character string. :type string: str :return: :rtype: """ string = stypes.stringToCharP(string) return libspice.lastnb_c(string) @spiceErrorCheck def latcyl(radius, lon, lat): """ Convert from latitudinal coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html :param radius: Distance of a point from the origin. :type radius: :param lon: Angle of the point from the XZ plane in radians. :param lat: Angle of the point from the XY plane in radians. :return: (r, lonc, z) :rtype: tuple """ radius = ctypes.c_double(radius) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) r = ctypes.c_double() lonc = ctypes.c_double() z = ctypes.c_double() libspice.latcyl_c(radius, lon, lat, ctypes.byref(r), ctypes.byref(lonc), ctypes.byref(z)) return r.value, lonc.value, z.value @spiceErrorCheck def latrec(radius, longitude, latitude): """ Convert from latitudinal coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latrec_c.html :param radius: Distance of a point from the origin. :type radius: float :param longitude: Longitude of point in radians. :type longitude: float :param latitude: Latitude of point in radians. :type latitude: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of Floats. """ radius = ctypes.c_double(radius) longitude = ctypes.c_double(longitude) latitude = ctypes.c_double(latitude) rectan = stypes.emptyDoubleVector(3) libspice.latrec_c(radius, longitude, latitude, rectan) return stypes.vectorToList(rectan) @spiceErrorCheck def latsph(radius, lon, lat): """ Convert from latitudinal coordinates to spherical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsph_c.html :param radius: Distance of a point from the origin. :param lon: Angle of the point from the XZ plane in radians. :param lat: Angle of the point from the XY plane in radians. :return: (rho colat, lons) :rtype: tuple """ radius = ctypes.c_double(radius) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) rho = ctypes.c_double() colat = ctypes.c_double() lons = ctypes.c_double() libspice.latsph_c(radius, lon, lat, ctypes.byref(rho), ctypes.byref(colat), ctypes.byref(lons)) return rho.value, colat.value, lons.value @spiceErrorCheck def lcase(instr, lenout): """ Convert the characters in a string to lowercase. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lcase_c.html :param instr: Input string. :type instr: str :param lenout: Maximum length of output string. :type lenout: int :return: Output string, all lowercase. :rtype: str """ instr = stypes.stringToCharP(instr) lenout = ctypes.c_int(lenout) outstr = stypes.stringToCharP(lenout) libspice.lcase_c(instr, lenout, outstr) return stypes.toPythonString(outstr) @spiceErrorCheck def ldpool(filename): """ Load the variables contained in a NAIF ASCII kernel file into the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ldpool_c.html :param filename: Name of the kernel file. :type filename: str """ filename = stypes.stringToCharP(filename) libspice.ldpool_c(filename) pass @spiceErrorCheck def lmpool(cvals): """ Load the variables contained in an internal buffer into the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lmpool_c.html :param cvals: list of strings :type cvals: list """ lenvals = ctypes.c_int(len(max(cvals, key=len)) + 1) n = ctypes.c_int(len(cvals)) cvals = stypes.listToCharArrayPtr(cvals, xLen=lenvals, yLen=n) libspice.lmpool_c(cvals, lenvals, n) pass @spiceErrorCheck def lparse(inlist, delim, nmax): """ Parse a list of items delimited by a single character. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lparse_c.html :param inlist: List of items delimited by delim. :type inlist: list of strings :param delim: Single character used to delimit items. :type delim: str :param nmax: Maximum number of items to return. :type nmax: int :return: Items in the list, left justified. :rtype: list of strings """ delim = stypes.stringToCharP(delim) lenout = ctypes.c_int(len(inlist)) inlist = stypes.stringToCharP(inlist) nmax = ctypes.c_int(nmax) items = stypes.emptyCharArray(lenout, nmax) n = ctypes.c_int() libspice.lparse_c(inlist, delim, nmax, lenout, ctypes.byref(n), ctypes.byref(items)) return [stypes.toPythonString(x.value) for x in items[0:n.value]] @spiceErrorCheck def lparsm(inlist, delims, nmax, lenout=None): """ Parse a list of items separated by multiple delimiters. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lparsm_c.html :param inlist: List of items delimited by delims. :type inlist: list of strings :param delims: Single characters which delimit items. :type delims: str :param nmax: Maximum number of items to return. :type nmax: int :param lenout: Optional Length of strings in item array. :type lenout: int :return: Items in the list, left justified. :rtype: list of strings """ if lenout is None: lenout = ctypes.c_int(len(inlist) + 1) inlist = stypes.stringToCharP(inlist) delims = stypes.stringToCharP(delims) items = stypes.emptyCharArray(nmax, lenout) nmax = ctypes.c_int(nmax) n = ctypes.c_int() libspice.lparsm_c(inlist, delims, nmax, lenout, ctypes.byref(n), items) return [stypes.toPythonString(x.value) for x in items][0:n.value] @spiceErrorCheck def lparss(inlist, delims, NMAX=20, LENGTH=50): """ Parse a list of items separated by multiple delimiters, placing the resulting items into a set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lparss_c.html :param inlist: List of items delimited by delims. :type inlist: :param delims: Single characters which delimit items. :type delims: str :param NMAX: Optional nmax of spice set. :type NMAX: int :param LENGTH: Optional length of strings in spice set :type LENGTH: int :return: Set containing items in the list, left justified. :rtype: """ inlist = stypes.stringToCharP(inlist) delims = stypes.stringToCharP(delims) returnSet = stypes.SPICECHAR_CELL(NMAX, LENGTH) libspice.lparss_c(inlist, delims, ctypes.byref(returnSet)) return returnSet @spiceErrorCheck def lspcn(body, et, abcorr): """ Compute L_s, the planetocentric longitude of the sun, as seen from a specified body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lspcn_c.html :param body: Name of central body. :type body: str :param et: Epoch in seconds past J2000 TDB. :type et: float :param abcorr: Aberration correction. :type abcorr: str :return: planetocentric longitude of the sun :rtype: float """ body = stypes.stringToCharP(body) et = ctypes.c_double(et) abcorr = stypes.stringToCharP(abcorr) return libspice.lspcn_c(body, et, abcorr) @spiceErrorCheck def lstlec(string, n, lenvals, array): """ Given a character string and an ordered array of character strings, find the index of the largest array element less than or equal to the given string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlec_c.html :param string: Upper bound value to search against. :type string: str :param n: Number elements in array. :type n: int :param lenvals: String length. :type lenvals: int :param array: Array of possible lower bounds. :type array: List :return: index of the last element of array that is lexically less than or equal to string. :rtype: int """ string = stypes.stringToCharP(string) array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=n) n = ctypes.c_int(n) lenvals = ctypes.c_int(lenvals) return libspice.lstlec_c(string, n, lenvals, array) @spiceErrorCheck def lstled(x, n, array): """ Given a number x and an array of non-decreasing floats, find the index of the largest array element less than or equal to x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstled_c.html :param x: Value to search against. :type x: float :param n: Number elements in array. :type n: int :param array: Array of possible lower bounds :type array: List :return: index of the last element of array that is less than or equal to x. :rtype: int """ array = stypes.toDoubleVector(array) x = ctypes.c_double(x) n = ctypes.c_int(n) return libspice.lstled_c(x, n, array) @spiceErrorCheck def lstlei(x, n, array): """ Given a number x and an array of non-decreasing ints, find the index of the largest array element less than or equal to x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlei_c.html :param x: Value to search against. :type x: int :param n: Number elements in array. :type n: int :param array: Array of possible lower bounds :type array: List :return: index of the last element of array that is less than or equal to x. :rtype: int """ array = stypes.toIntVector(array) x = ctypes.c_int(x) n = ctypes.c_int(n) return libspice.lstlei_c(x, n, array) @spiceErrorCheck def lstltc(string, n, lenvals, array): """ Given a character string and an ordered array of character strings, find the index of the largest array element less than the given string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstltc_c.html :param string: Upper bound value to search against. :type string: int :param n: Number elements in array. :type n: int :param lenvals: String length. :type lenvals: int :param array: Array of possible lower bounds :type array: List :return: index of the last element of array that is lexically less than string. :rtype: int """ string = stypes.stringToCharP(string) array = stypes.listToCharArrayPtr(array, xLen=lenvals, yLen=n) n = ctypes.c_int(n) lenvals = ctypes.c_int(lenvals) return libspice.lstltc_c(string, n, lenvals, array) @spiceErrorCheck def lstltd(x, n, array): """ Given a number x and an array of non-decreasing floats, find the index of the largest array element less than x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstltd_c.html :param x: Value to search against :type x: float :param n: Number elements in array :type n: int :param array: Array of possible lower bounds :type array: List :return: index of the last element of array that is less than x. :rtype: int """ array = stypes.toDoubleVector(array) x = ctypes.c_double(x) n = ctypes.c_int(n) return libspice.lstltd_c(x, n, array) @spiceErrorCheck def lstlti(x, n, array): """ Given a number x and an array of non-decreasing int, find the index of the largest array element less than x. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlti_c.html :param x: Value to search against :type x: int :param n: Number elements in array :type n: int :param array: Array of possible lower bounds :type array: List :return: index of the last element of array that is less than x. :rtype: int """ array = stypes.toIntVector(array) x = ctypes.c_int(x) n = ctypes.c_int(n) return libspice.lstlti_c(x, n, array) @spiceErrorCheck def ltime(etobs, obs, direct, targ): """ This routine computes the transmit (or receive) time of a signal at a specified target, given the receive (or transmit) time at a specified observer. The elapsed time between transmit and receive is also returned. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ltime_c.html :param etobs: Epoch of a signal at some observer :type etobs: float :param obs: NAIF ID of some observer :type obs: int :param direct: Direction the signal travels ( "->" or "<-" ) :type direct: str :param targ: NAIF ID of the target object :type targ: int :return: epoch and time :rtype: tuple """ etobs = ctypes.c_double(etobs) obs = ctypes.c_int(obs) direct = stypes.stringToCharP(direct) targ = ctypes.c_int(targ) ettarg = ctypes.c_double() elapsd = ctypes.c_double() libspice.ltime_c(etobs, obs, direct, targ, ctypes.byref(ettarg), ctypes.byref(elapsd)) return ettarg.value, elapsd.value @spiceErrorCheck def lx4dec(string, first): """ Scan a string from a specified starting position for the end of a decimal number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4dec_c.html :param string: Any character string. :type string: str :param first: First character to scan from in string. :type first: int :return: last and nchar :rtype: tuple """ string = stypes.stringToCharP(string) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lx4dec_c(string, first, ctypes.byref(last), ctypes.byref(nchar)) return last.value, nchar.value @spiceErrorCheck def lx4num(string, first): """ Scan a string from a specified starting position for the end of a number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4num_c.html :param string: Any character string. :type string: str :param first: First character to scan from in string. :type first: int :return: last and nchar :rtype: tuple """ string = stypes.stringToCharP(string) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lx4num_c(string, first, ctypes.byref(last), ctypes.byref(nchar)) return last.value, nchar.value @spiceErrorCheck def lx4sgn(string, first): """ Scan a string from a specified starting position for the end of a signed integer. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4sgn_c.html :param string: Any character string. :type string: str :param first: First character to scan from in string. :type first: int :return: last and nchar :rtype: tuple """ string = stypes.stringToCharP(string) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lx4sgn_c(string, first, ctypes.byref(last), ctypes.byref(nchar)) return last.value, nchar.value @spiceErrorCheck def lx4uns(string, first): """ Scan a string from a specified starting position for the end of an unsigned integer. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4uns_c.html :param string: Any character string. :type string: str :param first: First character to scan from in string. :type first: int :return: last and nchar :rtype: tuple """ string = stypes.stringToCharP(string) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lx4uns_c(string, first, ctypes.byref(last), ctypes.byref(nchar)) return last.value, nchar.value @spiceErrorCheck def lxqstr(string, qchar, first): """ Lex (scan) a quoted string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lxqstr_c.html :param string: String to be scanned. :type string: str :param qchar: Quote delimiter character. :type qchar: char (string of one char) :param first: Character position at which to start scanning. :type first: int :return: last and nchar :rtype: tuple """ string = stypes.stringToCharP(string) qchar = ctypes.c_char(qchar.encode(encoding='UTF-8')) first = ctypes.c_int(first) last = ctypes.c_int() nchar = ctypes.c_int() libspice.lxqstr_c(string, qchar, first, ctypes.byref(last), ctypes.byref(nchar)) return last.value, nchar.value ################################################################################ # M @spiceErrorCheck def m2eul(r, axis3, axis2, axis1): """ Factor a rotation matrix as a product of three rotations about specified coordinate axes. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/m2eul_c.html :param r: A rotation matrix to be factored :type r: 3x3-Element Array of Floats. :param axis3: third rotation axes. :type axis3: int :param axis2: second rotation axes. :type axis2: int :param axis1: first rotation axes. :type axis1: int :return: Third, second, and first Euler angles, in radians. :rtype: tuple """ r = stypes.listtodoublematrix(r) axis3 = ctypes.c_int(axis3) axis2 = ctypes.c_int(axis2) axis1 = ctypes.c_int(axis1) angle3 = ctypes.c_double() angle2 = ctypes.c_double() angle1 = ctypes.c_double() libspice.m2eul_c(r, axis3, axis2, axis1, ctypes.byref(angle3), ctypes.byref(angle2), ctypes.byref(angle1)) return angle3.value, angle2.value, angle1.value @spiceErrorCheck def m2q(r): """ Find a unit quaternion corresponding to a specified rotation matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/m2q_c.html :param r: A rotation matrix to be factored :type r: 3x3-Element Array of Floats. :return: A unit quaternion representing the rotation matrix :rtype: 4-Element Array of Floats. """ r = stypes.listtodoublematrix(r) q = stypes.emptyDoubleVector(4) libspice.m2q_c(r, q) return stypes.vectorToList(q) @spiceErrorCheck def matchi(string, templ, wstr, wchr): """ Determine whether a string is matched by a template containing wild cards. The pattern comparison is case-insensitive. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/matchi_c.html :param string: String to be tested. :type string: str :param templ: Template (with wild cards) to test against string. :type templ: str :param wstr: Wild string token. :type wstr: str of length 1 :param wchr: Wild character token. :type wchr: str of length 1 :return: The function returns True if string matches templ, else False :rtype: bool """ string = stypes.stringToCharP(string) templ = stypes.stringToCharP(templ) wstr = ctypes.c_char(wstr.encode(encoding='UTF-8')) wchr = ctypes.c_char(wchr.encode(encoding='UTF-8')) return libspice.matchi_c(string, templ, wstr, wchr) @spiceErrorCheck def matchw(string, templ, wstr, wchr): # ctypes.c_char(wstr.encode(encoding='UTF-8') """ Determine whether a string is matched by a template containing wild cards. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/matchw_c.html :param string: String to be tested. :type string: str :param templ: Template (with wild cards) to test against string. :type templ: str :param wstr: Wild string token. :type wstr: str of length 1 :param wchr: Wild character token. :type wchr: str of length 1 :return: The function returns True if string matches templ, else False :rtype: bool """ string = stypes.stringToCharP(string) templ = stypes.stringToCharP(templ) wstr = ctypes.c_char(wstr.encode(encoding='UTF-8')) wchr = ctypes.c_char(wchr.encode(encoding='UTF-8')) return libspice.matchw_c(string, templ, wstr, wchr) # skiping for now maxd_c, # odd as arguments must be parsed and not really important # skiping for now maxi_c, # odd as arguments must be parsed and not really important @spiceErrorCheck def mequ(m1): """ Set one double precision 3x3 matrix equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mequ_c.html :param m1: input matrix. :type m1: 3x3-Element Array of Floats. :return: Output matrix equal to m1. :rtype: 3x3-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1) mout = stypes.emptyDoubleMatrix() libspice.mequ_c(m1, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mequg(m1, nr, nc): """ Set one double precision matrix of arbitrary size equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mequg_c.html :param m1: Input matrix. :type m1: NxM-Element Array of Floats. :param nr: Row dimension of m1. :type nr: int :param nc: Column dimension of m1. :type nc: int :return: Output matrix equal to m1 :rtype: NxM-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1, x=nc, y=nr) mout = stypes.emptyDoubleMatrix(x=nc, y=nr) nc = ctypes.c_int(nc) nr = ctypes.c_int(nr) libspice.mequg_c(m1, nc, nr, mout) return stypes.matrixToList(mout) # skiping for now mind_c, # odd as arguments must be parsed and not really important # skiping for now mini_c, # odd as arguments must be parsed and not really important @spiceErrorCheck def mtxm(m1, m2): """ Multiply the transpose of a 3x3 matrix and a 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxm_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of Floats. :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Array of Floats. :return: The produce m1 transpose times m2. :rtype: 3x3-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1) m2 = stypes.listtodoublematrix(m2) mout = stypes.emptyDoubleMatrix() libspice.mtxm_c(m1, m2, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mtxmg(m1, m2, ncol1, nr1r2, ncol2): """ Multiply the transpose of a matrix with another matrix, both of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxmg_c.html :param m1: nr1r2 X ncol1 double precision matrix. :type m1: NxM-Element Array of Floats. :param m2: nr1r2 X ncol2 double precision matrix. :type m2: NxM-Element Array of Floats. :param ncol1: Column dimension of m1 and row dimension of mout. :type ncol1: int :param nr1r2: Row dimension of m1 and m2. :type nr1r2: int :param ncol2: Column dimension of m2. :type ncol2: int :return: Transpose of m1 times m2. :rtype: NxM-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1, x=ncol1, y=nr1r2) m2 = stypes.listtodoublematrix(m2, x=ncol2, y=nr1r2) mout = stypes.emptyDoubleMatrix(x=ncol2, y=ncol1) ncol1 = ctypes.c_int(ncol1) nr1r2 = ctypes.c_int(nr1r2) ncol2 = ctypes.c_int(ncol2) libspice.mtxmg_c(m1, m2, ncol1, nr1r2, ncol2, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mtxv(m1, vin): """ Multiplies the transpose of a 3x3 matrix on the left with a vector on the right. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxv_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of Floats. :param vin: 3-dimensional double precision vector. :type vin: 3-Element Array of Floats. :return: 3-dimensional double precision vector. :rtype: 3-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1) vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(3) libspice.mtxv_c(m1, vin, vout) return stypes.vectorToList(vout) @spiceErrorCheck def mtxvg(m1, v2, ncol1, nr1r2): """ Multiply the transpose of a matrix and a vector of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxvg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of Floats. :param v2: Right-hand vector to be multiplied. :type v2: N-Element Array of Floats. :param ncol1: Column dimension of m1 and length of vout. :type ncol1: int :param nr1r2: Row dimension of m1 and length of v2. :type nr1r2: int :return: Product vector m1 transpose * v2. :rtype: N-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1, x=ncol1, y=nr1r2) v2 = stypes.toDoubleVector(v2) ncol1 = ctypes.c_int(ncol1) nr1r2 = ctypes.c_int(nr1r2) vout = stypes.emptyDoubleVector(ncol1.value) libspice.mtxvg_c(m1, v2, ncol1, nr1r2, vout) return stypes.vectorToList(vout) @spiceErrorCheck def mxm(m1, m2): """ Multiply two 3x3 matrices. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxm_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of Floats. :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Array of Floats. :return: 3x3 double precision matrix. :rtype: 3x3-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1) m2 = stypes.listtodoublematrix(m2) mout = stypes.emptyDoubleMatrix() libspice.mxm_c(m1, m2, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mxmg(m1, m2, nrow1, ncol1, ncol2): """ Multiply two double precision matrices of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmg_c.html :param m1: nrow1 X ncol1 double precision matrix. :type m1: NxM-Element Array of Floats. :param m2: ncol1 X ncol2 double precision matrix. :type m2: NxM-Element Array of Floats. :param nrow1: Row dimension of m1 :type nrow1: int :param ncol1: Column dimension of m1 and row dimension of m2. :type ncol1: int :param ncol2: Column dimension of m2 :type ncol2: int :return: nrow1 X ncol2 double precision matrix. :rtype: NxM-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1, x=ncol1, y=nrow1) m2 = stypes.listtodoublematrix(m2, x=ncol2, y=ncol1) mout = stypes.emptyDoubleMatrix(x=ncol2, y=nrow1) nrow1 = ctypes.c_int(nrow1) ncol1 = ctypes.c_int(ncol1) ncol2 = ctypes.c_int(ncol2) libspice.mxmg_c(m1, m2, nrow1, ncol1, ncol2, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mxmt(m1, m2): """ Multiply a 3x3 matrix and the transpose of another 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmt_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of Floats. :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Array of Floats. :return: The product m1 times m2 transpose. :rtype: float """ m1 = stypes.listtodoublematrix(m1) m2 = stypes.listtodoublematrix(m2) mout = stypes.emptyDoubleMatrix() libspice.mxmt_c(m1, m2, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mxmtg(m1, m2, nrow1, nc1c2, nrow2): """ Multiply a matrix and the transpose of a matrix, both of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmtg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of Floats. :param m2: Right-hand matrix whose transpose is to be multiplied :type m2: NxM-Element Array of Floats. :param nrow1: Row dimension of m1 and row dimension of mout. :type nrow1: int :param nc1c2: Column dimension of m1 and column dimension of m2. :type nc1c2: int :param nrow2: Row dimension of m2 and column dimension of mout. :type nrow2: int :return: Product matrix. :rtype: NxM-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1, x=nc1c2, y=nrow1) m2 = stypes.listtodoublematrix(m2, x=nc1c2, y=nrow2) mout = stypes.emptyDoubleMatrix(x=nrow2, y=nrow1) nrow1 = ctypes.c_int(nrow1) nc1c2 = ctypes.c_int(nc1c2) nrow2 = ctypes.c_int(nrow2) libspice.mxmtg_c(m1, m2, nrow1, nc1c2, nrow2, mout) return stypes.matrixToList(mout) @spiceErrorCheck def mxv(m1, vin): """ Multiply a 3x3 double precision matrix with a 3-dimensional double precision vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxv_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of Floats. :param vin: 3-dimensional double precision vector. :type vin: 3-Element Array of Floats. :return: 3-dimensional double precision vector. :rtype: 3-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1) vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(3) libspice.mxv_c(m1, vin, vout) return stypes.vectorToList(vout) @spiceErrorCheck def mxvg(m1, v2, nrow1, nc1r2): """ Multiply a matrix and a vector of arbitrary size. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxvg_c.html :param m1: Left-hand matrix to be multiplied. :type m1: NxM-Element Array of Floats. :param v2: Right-hand vector to be multiplied. :type v2: N-Element Array of Floats. :param nrow1: Row dimension of m1 and length of vout. :type nrow1: int :param nc1r2: Column dimension of m1 and length of v2. :type nc1r2: int :return: Product vector m1*v2 :rtype: N-Element Array of Floats. """ m1 = stypes.listtodoublematrix(m1, x=nc1r2, y=nrow1) v2 = stypes.toDoubleVector(v2) nrow1 = ctypes.c_int(nrow1) nc1r2 = ctypes.c_int(nc1r2) vout = stypes.emptyDoubleVector(nrow1.value) libspice.mxvg_c(m1, v2, nrow1, nc1r2, vout) return stypes.vectorToList(vout) ################################################################################ # N @spiceErrorCheck def namfrm(frname): """ Look up the frame ID code associated with a string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/namfrm_c.html :param frname: The name of some reference frame. :type frname: str :return: The SPICE ID code of the frame. :rtype: int """ frname = stypes.stringToCharP(frname) frcode = ctypes.c_int() libspice.namfrm_c(frname, ctypes.byref(frcode)) return frcode.value @spiceErrorCheck def ncpos(string, chars, start): """ Find the first occurrence in a string of a character NOT belonging to a collection of characters, starting at a specified location searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ncpos_c.html :param string: Any character string. :type string: str :param chars: A collection of characters. :type chars: str :param start: Position to begin looking for one not in chars. :type start: int :return: index :rtype: int """ string = stypes.stringToCharP(string) chars = stypes.stringToCharP(chars) start = ctypes.c_int(start) return libspice.ncpos_c(string, chars, start) @spiceErrorCheck def ncposr(string, chars, start): """ Find the first occurrence in a string of a character NOT belonging to a collection of characters, starting at a specified location, searching in reverse. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ncposr_c.html :param string: Any character string. :type string: str :param chars: A collection of characters. :type chars: str :param start: Position to begin looking for one of chars. :type start: int :return: index :rtype: int """ string = stypes.stringToCharP(string) chars = stypes.stringToCharP(chars) start = ctypes.c_int(start) return libspice.ncposr_c(string, chars, start) @spiceErrorCheck def nearpt(positn, a, b, c): """ locates the point on the surface of an ellipsoid that is nearest to a specified position. It also returns the altitude of the position above the ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nearpt_c.html :param positn: Position of a point in bodyfixed frame. :type positn: 3-Element Array of Floats. :param a: Length of semi-axis parallel to x-axis. :type a: float :param b: Length of semi-axis parallel to y-axis. :type b: float :param c: Length on semi-axis parallel to z-axis. :type c: float :return: Point on the ellipsoid closest to positn, Altitude of positn above the ellipsoid. :rtype: tuple """ positn = stypes.toDoubleVector(positn) a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) npoint = stypes.emptyDoubleVector(3) alt = ctypes.c_double() libspice.nearpt_c(positn, a, b, c, npoint, ctypes.byref(alt)) return stypes.vectorToList(npoint), alt.value @spiceErrorCheck def npedln(a, b, c, linept, linedr): """ Find nearest point on a triaxial ellipsoid to a specified line and the distance from the ellipsoid to the line. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/npedln_c.html :param a: Length of ellipsoid's semi-axis in the x direction :type a: float :param b: Length of ellipsoid's semi-axis in the y direction :type b: float :param c: Length of ellipsoid's semi-axis in the z direction :type c: float :param linept: Length of ellipsoid's semi-axis in the z direction :type linept: 3-Element Array of Floats. :param linedr: Direction vector of line :type linedr: 3-Element Array of Floats. :return: Nearest point on ellipsoid to line, Distance of ellipsoid from line :rtype: tuple """ a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) linept = stypes.toDoubleVector(linept) linedr = stypes.toDoubleVector(linedr) pnear = stypes.emptyDoubleVector(3) dist = ctypes.c_double() libspice.npedln_c(a, b, c, linept, linedr, pnear, ctypes.byref(dist)) return stypes.vectorToList(pnear), dist.value @spiceErrorCheck def npelpt(point, ellips): """ Find the nearest point on an ellipse to a specified point, both in three-dimensional space, and find the distance between the ellipse and the point. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/npelpt_c.html :param point: Point whose distance to an ellipse is to be found. :type point: 3-Element Array of Floats. :param ellips: An ellipse. :type ellips: SpiceyPy.support_types.Ellipse :return: Nearest point on ellipsoid to line, Distance of ellipsoid from line :rtype: tuple """ assert (isinstance(ellips, stypes.Ellipse)) point = stypes.toDoubleVector(point) pnear = stypes.emptyDoubleVector(3) dist = ctypes.c_double() libspice.npelpt_c(point, ctypes.byref(ellips), pnear, ctypes.byref(dist)) return stypes.vectorToList(pnear), dist.value @spiceErrorCheck def nplnpt(linpt, lindir, point): """ Find the nearest point on a line to a specified point, and find the distance between the two points. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nplnpt_c.html :param linpt: Point on a line :type linpt: 3-Element Array of Floats. :param lindir: line's direction vector :type lindir: 3-Element Array of Floats. :param point: A second point. :type point: 3-Element Array of Floats. :return: Nearest point on the line to point, Distance between point and pnear :rtype: tuple """ linpt = stypes.toDoubleVector(linpt) lindir = stypes.toDoubleVector(lindir) point = stypes.toDoubleVector(point) pnear = stypes.emptyDoubleVector(3) dist = ctypes.c_double() libspice.nplnpt_c(linpt, lindir, point, pnear, ctypes.byref(dist)) return stypes.vectorToList(pnear), dist.value @spiceErrorCheck def nvc2pl(normal, constant): """ Make a plane from a normal vector and a constant. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvc2pl_c.html :param normal: A normal vector defining a plane. :type normal: 3-Element Array of Floats. :param constant: A constant defining a plane. :type constant: float :return: plane :rtype: SpiceyPy.support_types.Plane """ plane = stypes.Plane() normal = stypes.toDoubleVector(normal) constant = ctypes.c_double(constant) libspice.nvc2pl_c(normal, constant, ctypes.byref(plane)) return plane @spiceErrorCheck def nvp2pl(normal, point): """ Make a plane from a normal vector and a point. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvp2pl_c.html :param normal: A normal vector defining a plane. :type normal: 3-Element Array of Floats. :param point: A point defining a plane. :type point: 3-Element Array of Floats. :return: plane :rtype: SpiceyPy.support_types.Plane """ normal = stypes.toDoubleVector(normal) point = stypes.toDoubleVector(point) plane = stypes.Plane() libspice.nvp2pl_c(normal, point, ctypes.byref(plane)) return plane ################################################################################ # O @spiceErrorCheck def occult(target1, shape1, frame1, target2, shape2, frame2, abcorr, observer, et): """ Determines the occultation condition (not occulted, partially, etc.) of one target relative to another target as seen by an observer at a given time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/occult_c.html :param target1: Name or ID of first target. :type target1: str :param shape1: Type of shape model used for first target. :type shape1: str :param frame1: Body-fixed, body-centered frame for first body. :type frame1: str :param target2: Name or ID of second target. :type target2: str :param shape2: Type of shape model used for second target. :type shape2: str :param frame2: Body-fixed, body-centered frame for second body. :type frame2: str :param abcorr: Aberration correction flag. :type abcorr: str :param observer: Name or ID of the observer. :type observer: str :param et: Time of the observation (seconds past J2000). :type et: float :return: Occultation identification code. :rtype: int """ target1 = stypes.stringToCharP(target1) shape1 = stypes.stringToCharP(shape1) frame1 = stypes.stringToCharP(frame1) target2 = stypes.stringToCharP(target2) shape2 = stypes.stringToCharP(shape2) frame2 = stypes.stringToCharP(frame2) abcorr = stypes.stringToCharP(abcorr) observer = stypes.stringToCharP(observer) et = ctypes.c_double(et) occult_code = ctypes.c_int() libspice.occult_c(target1, shape1, frame1, target2, shape2, frame2, abcorr, observer, et, ctypes.byref(occult_code)) return occult_code.value @spiceErrorCheck def ordc(item, inset): """ The function returns the ordinal position of any given item in a character set. If the item does not appear in the set, the function returns -1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ordc_c.html :param item: An item to locate within a set. :type item: str :param inset: A set to search for a given item. :type inset: SpiceCharCell :return: the ordinal position of item within the set :rtype: int """ assert isinstance(inset, stypes.SpiceCell) assert inset.is_char() assert isinstance(item, str) item = stypes.stringToCharP(item) return libspice.ordc_c(item, ctypes.byref(inset)) @spiceErrorCheck def ordd(item, inset): """ The function returns the ordinal position of any given item in a double precision set. If the item does not appear in the set, the function returns -1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ordd_c.html :param item: An item to locate within a set. :type item: float :param inset: A set to search for a given item. :type inset: SpiceDoubleCell :return: the ordinal position of item within the set :rtype: int """ assert isinstance(inset, stypes.SpiceCell) assert inset.is_double() item = ctypes.c_double(item) return libspice.ordd_c(item, ctypes.byref(inset)) @spiceErrorCheck def ordi(item, inset): """ The function returns the ordinal position of any given item in an integer set. If the item does not appear in the set, the function returns -1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ordi_c.html :param item: An item to locate within a set. :type item: int :param inset: A set to search for a given item. :type inset: SpiceIntCell :return: the ordinal position of item within the set :rtype: int """ assert isinstance(inset, stypes.SpiceCell) assert inset.is_int() assert isinstance(item, int) item = ctypes.c_int(item) return libspice.ordi_c(item, ctypes.byref(inset)) @spiceErrorCheck def orderc(array, ndim=None): """ Determine the order of elements in an array of character strings. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/orderc_c.html :param array: Input array. :type array: Array of strings. :param ndim: Optional Length of input array :type ndim: int :return: Order vector for array. :rtype: array of ints """ if ndim is None: ndim = ctypes.c_int(len(array)) else: ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(len(max(array, key=len)) + 1) iorder = stypes.emptyIntVector(ndim) array = stypes.listToCharArray(array, lenvals, ndim) libspice.orderc_c(lenvals, array, ndim, iorder) return stypes.vectorToList(iorder) @spiceErrorCheck def orderd(array, ndim=None): """ Determine the order of elements in a double precision array. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/orderd_c.html :param array: Input array. :type array: Array of floats. :param ndim: Optional Length of input array :type ndim: int :return: Order vector for array. :rtype: array of ints """ if ndim is None: ndim = ctypes.c_int(len(array)) else: ndim = ctypes.c_int(ndim) array = stypes.toDoubleVector(array) iorder = stypes.emptyIntVector(ndim) libspice.orderd_c(array, ndim, iorder) return stypes.vectorToList(iorder) @spiceErrorCheck def orderi(array, ndim=None): """ Determine the order of elements in an integer array. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/orderi_c.html :param array: Input array. :type array: Array of ints. :param ndim: Optional Length of input array :type ndim: int :return: Order vector for array. :rtype: array of ints """ if ndim is None: ndim = ctypes.c_int(len(array)) else: ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) iorder = stypes.emptyIntVector(ndim) libspice.orderi_c(array, ndim, iorder) return stypes.vectorToList(iorder) @spiceErrorCheck def oscelt(state, et, mu): """ Determine the set of osculating conic orbital elements that corresponds to the state (position, velocity) of a body at some epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/oscelt_c.html :param state: State of body at epoch of elements. :type state: Float Array of 6 elements. :param et: Epoch of elements. :type et: float :param mu: Gravitational parameter (GM) of primary body. :type mu: float :return: Equivalent conic elements :rtype: Float Array of 8 elements. """ state = stypes.toDoubleVector(state) et = ctypes.c_double(et) mu = ctypes.c_double(mu) elts = stypes.emptyDoubleVector(8) libspice.oscelt_c(state, et, mu, elts) return stypes.vectorToList(elts) ################################################################################ # P @spiceErrorCheck def pckcov(pck, idcode, cover): """ Find the coverage window for a specified reference frame in a specified binary PCK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckcov_c.html :param pck: Name of PCK file. :type pck: str :param idcode: Class ID code of PCK reference frame. :type idcode: int :param cover: Window giving coverage in pck for idcode. :type cover: SpiceCell """ pck = stypes.stringToCharP(pck) idcode = ctypes.c_int(idcode) assert isinstance(cover, stypes.SpiceCell) assert cover.dtype == 1 libspice.pckcov_c(pck, idcode, ctypes.byref(cover)) @spiceErrorCheck def pckfrm(pck, ids): """ Find the set of reference frame class ID codes of all frames in a specified binary PCK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckfrm_c.html :param pck: Name of PCK file. :type pck: str :param ids: Set of frame class ID codes of frames in PCK file. :type ids: SpiceCell """ pck = stypes.stringToCharP(pck) assert isinstance(ids, stypes.SpiceCell) assert ids.dtype == 2 libspice.pckfrm_c(pck, ctypes.byref(ids)) @spiceErrorCheck def pcklof(filename): """ Load a binary PCK file for use by the readers. Return the handle of the loaded file which is used by other PCK routines to refer to the file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pcklof_c.html :param filename: Name of the file to be loaded. :type filename: str :return: Loaded file's handle. :rtype: int """ filename = stypes.stringToCharP(filename) handle = ctypes.c_int() libspice.pcklof_c(filename, ctypes.byref(handle)) return handle.value @spiceErrorCheck def pckuof(handle): """ Unload a binary PCK file so that it will no longer be searched by the readers. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckuof_c.html :param handle: Handle of PCK file to be unloaded :type handle: int """ handle = ctypes.c_int(handle) libspice.pckuof_c(handle) pass @spiceErrorCheck def pcpool(name, cvals): """ This entry point provides toolkit programmers a method for programmatically inserting character data into the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pcpool_c.html :param name: The kernel pool name to associate with cvals. :type name: str :param cvals: An array of strings to insert into the kernel pool. :type cvals: Array of str """ name = stypes.stringToCharP(name) lenvals = ctypes.c_int(len(max(cvals, key=len)) + 1) n = ctypes.c_int(len(cvals)) cvals = stypes.listToCharArray(cvals, lenvals, n) libspice.pcpool_c(name, n, lenvals, cvals) @spiceErrorCheck def pdpool(name, dvals): """ This entry point provides toolkit programmers a method for programmatically inserting double precision data into the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pdpool_c.html :param name: The kernel pool name to associate with dvals. :type name: str :param dvals: An array of values to insert into the kernel pool. :type dvals: SpiceCell """ name = stypes.stringToCharP(name) n = ctypes.c_int(len(dvals)) dvals = stypes.toDoubleVector(dvals) libspice.pdpool_c(name, n, dvals) @spiceErrorCheck def pgrrec(body, lon, lat, alt, re, f): """ Convert planetographic coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pgrrec_c.html :param body: Body with which coordinate system is associated. :type body: str :param lon: Planetographic longitude of a point (radians). :type lon: float :param lat: Planetographic latitude of a point (radians). :type lat: float :param alt: Altitude of a point above reference spheroid. :type alt: float :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of floats. """ body = stypes.stringToCharP(body) lon = ctypes.c_double(lon) lat = ctypes.c_double(lat) alt = ctypes.c_double(alt) re = ctypes.c_double(re) f = ctypes.c_double(f) rectan = stypes.emptyDoubleVector(3) libspice.pgrrec_c(body, lon, lat, alt, re, f, rectan) return stypes.vectorToList(rectan) @spiceErrorCheck def phaseq(et, target, illmn, obsrvr, abcorr): """ Compute the apparent phase angle for a target, observer, illuminator set of ephemeris objects. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/phaseq_c.html :param et: Ephemeris seconds past J2000 TDB. :type et: float :param target: Target body name. :type target: str :param illmn: Illuminating body name. :type illmn: str :param obsrvr: Observer body. :type obsrvr: str :param abcorr: Aberration correction flag. :type abcorr: str :return: Value of phase angle. :rtype: float """ et = ctypes.c_double(et) target = stypes.stringToCharP(target) illmn = stypes.stringToCharP(illmn) obsrvr = stypes.stringToCharP(obsrvr) abcorr = stypes.stringToCharP(abcorr) return libspice.phaseq_c(et, target, illmn, obsrvr, abcorr) @spiceErrorCheck def pi(): """ Return the value of pi (the ratio of the circumference of a circle to its diameter). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pi_c.html :return: value of pi. :rtype: float """ return libspice.pi_c() @spiceErrorCheck def pipool(name, ivals): """ This entry point provides toolkit programmers a method for programmatically inserting integer data into the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pipool_c.html :param name: The kernel pool name to associate with values. :type name: str :param ivals: An array of integers to insert into the pool. :type ivals: Array of ints """ name = stypes.stringToCharP(name) n = ctypes.c_int(len(ivals)) ivals = stypes.toIntVector(ivals) libspice.pipool_c(name, n, ivals) @spiceErrorCheck def pjelpl(elin, plane): """ Project an ellipse onto a plane, orthogonally. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pjelpl_c.html :param elin: A SPICE ellipse to be projected. :type elin: SpiceyPy.support_types.Ellipse :param plane: A plane onto which elin is to be projected. :type plane: supporttypes.Plane :return: A SPICE ellipse resulting from the projection. :rtype: SpiceyPy.support_types.Ellipse """ assert (isinstance(elin, stypes.Ellipse)) assert (isinstance(plane, stypes.Plane)) elout = stypes.Ellipse() libspice.pjelpl_c(ctypes.byref(elin), ctypes.byref(plane), ctypes.byref(elout)) return elout @spiceErrorCheck def pl2nvc(plane): """ Return a unit normal vector and constant that define a specified plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2nvc_c.html :param plane: A SPICE plane. :type plane: supporttypes.Plane :return: A normal vector and constant defining the geometric plane represented by plane. :rtype: tuple """ assert (isinstance(plane, stypes.Plane)) normal = stypes.emptyDoubleVector(3) constant = ctypes.c_double() libspice.pl2nvc_c(ctypes.byref(plane), normal, ctypes.byref(constant)) return stypes.vectorToList(normal), constant.value @spiceErrorCheck def pl2nvp(plane): """ Return a unit normal vector and point that define a specified plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2nvp_c.html :param plane: A SPICE plane. :type plane: supporttypes.Plane :return: A unit normal vector and point that define plane. :rtype: tuple """ assert (isinstance(plane, stypes.Plane)) normal = stypes.emptyDoubleVector(3) point = stypes.emptyDoubleVector(3) libspice.pl2nvp_c(ctypes.byref(plane), normal, point) return stypes.vectorToList(normal), stypes.vectorToList(point) @spiceErrorCheck def pl2psv(plane): """ Return a point and two orthogonal spanning vectors that generate a specified plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2psv_c.html :param plane: A SPICE plane. :type plane: supporttypes.Plane :return: A point in the input plane and two vectors spanning the input plane. :rtype: tuple """ assert (isinstance(plane, stypes.Plane)) point = stypes.emptyDoubleVector(3) span1 = stypes.emptyDoubleVector(3) span2 = stypes.emptyDoubleVector(3) libspice.pl2psv_c(ctypes.byref(plane), point, span1, span2) return stypes.vectorToList(point), stypes.vectorToList( span1), stypes.vectorToList(span2) @spiceErrorCheck def pos(string, substr, start): """ Find the first occurrence in a string of a substring, starting at a specified location, searching forward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pos_c.html :param string: Any character string. :type string: str :param substr: Substring to locate in the character string. :type substr: str :param start: Position to begin looking for substr in string. :type start: int :return: The index of the first occurrence of substr in string at or following index start. :rtype: int """ string = stypes.stringToCharP(string) substr = stypes.stringToCharP(substr) start = ctypes.c_int(start) return libspice.pos_c(string, substr, start) @spiceErrorCheck def posr(string, substr, start): """ Find the first occurrence in a string of a substring, starting at a specified location, searching backward. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/posr_c.html :param string: Any character string. :type string: str :param substr: Substring to locate in the character string. :type substr: str :param start: Position to begin looking for substr in string. :type start: int :return: The index of the last occurrence of substr in string at or preceding index start. :rtype: int """ string = stypes.stringToCharP(string) substr = stypes.stringToCharP(substr) start = ctypes.c_int(start) return libspice.posr_c(string, substr, start) # prompt, # skip for no as this is not really an important function for python users @spiceErrorCheck def prop2b(gm, pvinit, dt): """ Given a central mass and the state of massless body at time t_0, this routine determines the state as predicted by a two-body force model at time t_0 + dt. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prop2b_c.html :param gm: Gravity of the central mass. :type gm: float :param pvinit: Initial state from which to propagate a state. :type pvinit: 6-Element Array of Floats :param dt: Time offset from initial state to propagate to. :type dt: float :return: The propagated state. :rtype: 6-Element Array of Floats """ gm = ctypes.c_double(gm) pvinit = stypes.toDoubleVector(pvinit) dt = ctypes.c_double(dt) pvprop = stypes.emptyDoubleVector(6) libspice.prop2b_c(gm, pvinit, dt, pvprop) return stypes.vectorToList(pvprop) @spiceErrorCheck def prsdp(string): """ Parse a string as a double precision number, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsdp_c.html :param string: String representing a d.p. number. :type string: str :return: D.p. value obtained by parsing string. :rtype: float """ string = stypes.stringToCharP(string) dpval = ctypes.c_double() libspice.prsdp_c(string, ctypes.byref(dpval)) return dpval.value @spiceErrorCheck def prsint(string): """ Parse a string as an integer, encapsulating error handling. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prsint_c.html :param string: String representing an integer. :type string: str :return: Integer value obtained by parsing string. :rtype: int """ string = stypes.stringToCharP(string) intval = ctypes.c_int() libspice.prsint_c(string, ctypes.byref(intval)) return intval.value @spiceErrorCheck def psv2pl(point, span1, span2): """ Make a CSPICE plane from a point and two spanning vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/psv2pl_c.html :param point: A Point. :type point: 3-Element Array of Floats :param span1: First Spanning vector. :type span1: 3-Element Array of Floats :param span2: Second Spanning vector. :type span2: 3-Element Array of Floats :return: A SPICE plane. :rtype: supportypes.Plane """ point = stypes.toDoubleVector(point) span1 = stypes.toDoubleVector(span1) span2 = stypes.toDoubleVector(span2) plane = stypes.Plane() libspice.psv2pl_c(point, span1, span2, ctypes.byref(plane)) return plane # skip putcml, is this really needed for python users? @spiceErrorCheck def pxform(fromstr, tostr, et): """ Return the matrix that transforms position vectors from one specified frame to another at a specified epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pxform_c.html :param fromstr: Name of the frame to transform from. :type fromstr: str :param tostr: Name of the frame to transform to. :type tostr: str :param et: Epoch of the rotation matrix. :type et: float :return: A rotation matrix. :rtype: 3x3 Element Array of floats """ et = ctypes.c_double(et) tostr = stypes.stringToCharP(tostr) fromstr = stypes.stringToCharP(fromstr) rotatematrix = stypes.emptyDoubleMatrix() libspice.pxform_c(fromstr, tostr, et, rotatematrix) return stypes.matrixToList(rotatematrix) @spiceErrorCheck def pxfrm2(frame_from, frame_to, etfrom, etto): """ Return the 3x3 matrix that transforms position vectors from one specified frame at a specified epoch to another specified frame at another specified epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pxfrm2_c.html :param frame_from: Name of the frame to transform from. :type frame_from: str :param frame_to: Name of the frame to transform to. :type frame_to: str :param etfrom: Evaluation time of frame_from. :type etfrom: float :param etto: Evaluation time of frame_to. :type etto: float :return: A position transformation matrix from frame_from to frame_to :rtype: 3x3 Element Array of floats """ frame_from = stypes.stringToCharP(frame_from) frame_to = stypes.stringToCharP(frame_to) etfrom = ctypes.c_double(etfrom) etto = ctypes.c_double(etto) outmatrix = stypes.emptyDoubleMatrix() libspice.pxfrm2_c(frame_from, frame_to, etfrom, etto, outmatrix) return stypes.matrixToList(outmatrix) ################################################################################ # Q @spiceErrorCheck def q2m(q): """ Find the rotation matrix corresponding to a specified unit quaternion. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/q2m_c.html :param q: A unit quaternion. :type q: 4-Element Array of Floats. :return: A rotation matrix corresponding to q :rtype: 3x3-Element Array of Floats. """ q = stypes.toDoubleVector(q) mout = stypes.emptyDoubleMatrix() libspice.q2m_c(q, mout) return stypes.matrixToList(mout) #@spiceErrorCheck def qcktrc(tracelen): """ Return a string containing a traceback. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/qcktrc_c.html :param tracelen: Maximum length of output traceback string. :type tracelen: int :return: A traceback string. :rtype: str """ tracestr = stypes.stringToCharP(tracelen) tracelen = ctypes.c_int(tracelen) libspice.qcktrc_c(tracelen, tracestr) return stypes.toPythonString(tracestr) @spiceErrorCheck def qdq2av(q, dq): """ Derive angular velocity from a unit quaternion and its derivative with respect to time. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/qdq2av_c.html :param q: Unit SPICE quaternion. :type q: 4-Element Array of Floats. :param dq: Derivative of q with respect to time :type dq: 4-Element Array of Floats. :return: Angular velocity defined by q and dq. :rtype: 3-Element Array of Floats. """ q = stypes.toDoubleVector(q) dq = stypes.toDoubleVector(dq) vout = stypes.emptyDoubleVector(3) libspice.qdq2av_c(q, dq, vout) return stypes.vectorToList(vout) @spiceErrorCheck def qxq(q1, q2): """ Multiply two quaternions. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/qxq_c.html :param q1: First SPICE quaternion. :type q1: 4-Element Array of Floats. :param q2: Second SPICE quaternion. :type q2: 4-Element Array of Floats. :return: Product of q1 and q2. :rtype: 4-Element Array of Floats. """ q1 = stypes.toDoubleVector(q1) q2 = stypes.toDoubleVector(q2) vout = stypes.emptyDoubleVector(4) libspice.qxq_c(q1, q2, vout) return stypes.vectorToList(vout) ################################################################################ # R @spiceErrorCheck def radrec(inrange, re, dec): """ Convert from range, right ascension, and declination to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/radrec_c.html :param inrange: Distance of a point from the origin. :type inrange: float :param re: Right ascension of point in radians. :type re: float :param dec: Declination of point in radians. :type dec: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of Floats. """ inrange = ctypes.c_double(inrange) re = ctypes.c_double(re) dec = ctypes.c_double(dec) rectan = stypes.emptyDoubleVector(3) libspice.radrec_c(inrange, re, dec, rectan) return stypes.vectorToList(rectan) @spiceErrorCheck def rav2xf(rot, av): """ This routine determines a state transformation matrix from a rotation matrix and the angular velocity of the rotation. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rav2xf_c.html :param rot: Rotation matrix. :type rot: 3x3-Element Array of Floats. :param av: Angular velocity vector. :type av: 3-Element Array of Floats. :return: State transformation associated with rot and av. :rtype: 6x6-Element Array of Floats """ rot = stypes.toDoubleMatrix(rot) av = stypes.toDoubleVector(av) xform = stypes.emptyDoubleMatrix(x=6, y=6) libspice.rav2xf_c(rot, av, xform) return stypes.matrixToList(xform) @spiceErrorCheck def raxisa(matrix): """ Compute the axis of the rotation given by an input matrix and the angle of the rotation about that axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/raxisa_c.html :param matrix: Rotation matrix. :type matrix: 3x3-Element Array of Floats. :return: Axis of the rotation, Angle through which the rotation is performed :rtype: tuple """ matrix = stypes.listtodoublematrix(matrix) axis = stypes.emptyDoubleVector(3) angle = ctypes.c_double() libspice.raxisa_c(matrix, axis, ctypes.byref(angle)) return stypes.vectorToList(axis), angle.value @spiceErrorCheck def rdtext(file, lenout): # pragma: no cover """ Read the next line of text from a text file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rdtext_c.html :param file: Name of text file. :type file: str :param lenout: Available room in output line. :type lenout: int :return: Next line from the text file, End-of-file indicator :rtype: tuple """ file = stypes.stringToCharP(file) line = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) eof = ctypes.c_bool() libspice.rdtext_c(file, lenout, line, ctypes.byref(eof)) return stypes.toPythonString(line), eof.value @spiceErrorCheck def reccyl(rectan): """ Convert from rectangular to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reccyl_c.html :param rectan: Rectangular coordinates of a point. :type rectan: 3-Element Array of Floats. :return: Distance from z axis, Angle (radians) from xZ plane, Height above xY plane. :rtype: tuple """ rectan = stypes.toDoubleVector(rectan) radius = ctypes.c_double(0) lon = ctypes.c_double(0) z = ctypes.c_double(0) libspice.reccyl_c(rectan, ctypes.byref(radius), ctypes.byref(lon), ctypes.byref(z)) return radius.value, lon.value, z.value @spiceErrorCheck def recgeo(rectan, re, f): """ Convert from rectangular coordinates to geodetic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recgeo_c.html :param rectan: Rectangular coordinates of a point. :type rectan: 3-Element Array of Floats. :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Geodetic longitude (radians), Geodetic latitude (radians), Altitude above reference spheroid :rtype: tuple """ rectan = stypes.toDoubleVector(rectan) re = ctypes.c_double(re) f = ctypes.c_double(f) longitude = ctypes.c_double(0) latitude = ctypes.c_double(0) alt = ctypes.c_double(0) libspice.recgeo_c(rectan, re, f, ctypes.byref(longitude), ctypes.byref(latitude), ctypes.byref(alt)) return longitude.value, latitude.value, alt.value @spiceErrorCheck def reclat(rectan): """ Convert from rectangular coordinates to latitudinal coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reclat_c.html :param rectan: Rectangular coordinates of a point. :type rectan: 3-Element Array of Floats. :return: Distance from the origin, Longitude in radians, Latitude in radians :rtype: tuple """ rectan = stypes.toDoubleVector(rectan) radius = ctypes.c_double(0) longitude = ctypes.c_double(0) latitude = ctypes.c_double(0) libspice.reclat_c(rectan, ctypes.byref(radius), ctypes.byref(longitude), ctypes.byref(latitude)) return radius.value, longitude.value, latitude.value @spiceErrorCheck def recpgr(body, rectan, re, f): """ Convert rectangular coordinates to planetographic coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recpgr_c.html :param body: Body with which coordinate system is associated. :type body: str :param rectan: Rectangular coordinates of a point. :type rectan: 3-Element Array of Floats. :param re: Equatorial radius of the reference spheroid. :type re: float :param f: Flattening coefficient. :type f: float :return: Planetographic longitude (radians), Planetographic latitude (radians), Altitude above reference spheroid :rtype: tuple """ body = stypes.stringToCharP(body) rectan = stypes.toDoubleVector(rectan) re = ctypes.c_double(re) f = ctypes.c_double(f) lon = ctypes.c_double() lat = ctypes.c_double() alt = ctypes.c_double() libspice.recpgr_c(body, rectan, re, f, ctypes.byref(lon), ctypes.byref(lat), ctypes.byref(alt)) return lon.value, lat.value, alt.value @spiceErrorCheck def recrad(rectan): """ Convert rectangular coordinates to range, right ascension, and declination. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recrad_c.html :param rectan: Rectangular coordinates of a point. :type rectan: 3-Element Array of Floats. :return: Distance of the point from the origin, Right ascension in radians, Declination in radians :rtype: tuple """ rectan = stypes.toDoubleVector(rectan) outrange = ctypes.c_double() ra = ctypes.c_double() dec = ctypes.c_double() libspice.recrad_c(rectan, ctypes.byref(outrange), ctypes.byref(ra), ctypes.byref(dec)) return outrange.value, ra.value, dec.value @spiceErrorCheck def recsph(rectan): """ Convert from rectangular coordinates to spherical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/recrad_c.html :param rectan: Rectangular coordinates of a point. :type rectan: 3-Element Array of Floats. :return: Distance from the origin, Angle from the positive Z-axis, Longitude in radians. :rtype: tuple """ rectan = stypes.toDoubleVector(rectan) r = ctypes.c_double() colat = ctypes.c_double() lon = ctypes.c_double() libspice.recsph_c(rectan, ctypes.byref(r), ctypes.byref(colat), ctypes.byref(lon)) return r.value, colat.value, lon.value @spiceErrorCheck def removc(item, inset): """ Remove an item from a character set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removc_c.html :param item: Item to be removed. :type item: str :param inset: Set to be updated. :type inset: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) assert inset.dtype == 0 item = stypes.stringToCharP(item) libspice.removc_c(item, ctypes.byref(inset)) pass @spiceErrorCheck def removd(item, inset): """ Remove an item from a double precision set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removd_c.html :param item: Item to be removed. :type item: float :param inset: Set to be updated. :type inset: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) assert inset.dtype == 1 item = ctypes.c_double(item) libspice.removd_c(item, ctypes.byref(inset)) pass @spiceErrorCheck def removi(item, inset): """ Remove an item from an integer set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/removi_c.html :param item: Item to be removed. :type item: int :param inset: Set to be updated. :type inset: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) assert inset.dtype == 2 item = ctypes.c_int(item) libspice.removi_c(item, ctypes.byref(inset)) pass @spiceErrorCheck def reordc(iorder, ndim, lenvals, array): """ Re-order the elements of an array of character strings according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordc_c.html :param iorder: Order vector to be used to re-order array. :type iorder: N-Element Array of ints. :param ndim: Dimension of array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: Array to be re-ordered. :type array: N-Element Array of strs. :return: Re-ordered Array. :rtype: N-Element Array of strs. """ iorder = stypes.toIntVector(iorder) array = stypes.listToCharArray(array) ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(lenvals) libspice.reordc_c(iorder, ndim, lenvals, array) return [stypes.toPythonString(x.value) for x in array] @spiceErrorCheck def reordd(iorder, ndim, array): """ Re-order the elements of a double precision array according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordd_c.html :param iorder: Order vector to be used to re-order array. :type iorder: N-Element Array of ints. :param ndim: Dimension of array. :type ndim: int :param array: Array to be re-ordered. :type array: N-Element Array of floats. :return: Re-ordered Array. :rtype: N-Element Array of floats """ iorder = stypes.toIntVector(iorder) ndim = ctypes.c_int(ndim) array = stypes.toDoubleVector(array) libspice.reordd_c(iorder, ndim, array) return stypes.vectorToList(array) @spiceErrorCheck def reordi(iorder, ndim, array): """ Re-order the elements of an integer array according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordi_c.html :param iorder: Order vector to be used to re-order array. :type iorder: N-Element Array of ints. :param ndim: Dimension of array. :type ndim: int :param array: Array to be re-ordered. :type array: N-Element Array of ints. :return: Re-ordered Array. :rtype: N-Element Array of ints """ iorder = stypes.toIntVector(iorder) ndim = ctypes.c_int(ndim) array = stypes.toIntVector(array) libspice.reordi_c(iorder, ndim, array) return stypes.vectorToList(array) @spiceErrorCheck def reordl(iorder, ndim, array): """ Re-order the elements of a logical (Boolean) array according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordl_c.html :param iorder: Order vector to be used to re-order array. :type iorder: N-Element Array of ints. :param ndim: Dimension of array. :type ndim: int :param array: Array to be re-ordered. :type array: N-Element Array of ints. :return: Re-ordered Array. :rtype: N-Element Array of bools """ iorder = stypes.toIntVector(iorder) ndim = ctypes.c_int(ndim) array = stypes.toBoolVector(array) libspice.reordl_c(iorder, ndim, array) return stypes.vectorToList(array) @spiceErrorCheck def repmc(instr, marker, value, lenout=None): """ Replace a marker with a character string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmc_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: str :param lenout: Optional available space in output string :type lenout: int :return: Output string. :rtype: str """ if lenout is None: lenout = ctypes.c_int(len(instr) + len(value) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = stypes.stringToCharP(value) out = stypes.stringToCharP(lenout) libspice.repmc_c(instr, marker, value, lenout, out) return stypes.toPythonString(out) @spiceErrorCheck def repmct(instr, marker, value, repcase, lenout=None): """ Replace a marker with the text representation of a cardinal number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmc_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: int :param repcase: Case of replacement text. :type repcase: str :param lenout: Optional available space in output string :type lenout: int :return: Output string. :rtype: str """ if lenout is None: lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_int(value) repcase = ctypes.c_char(repcase.encode(encoding='UTF-8')) out = stypes.stringToCharP(lenout) libspice.repmct_c(instr, marker, value, repcase, lenout, out) return stypes.toPythonString(out) @spiceErrorCheck def repmd(instr, marker, value, sigdig): """ Replace a marker with a double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmd_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: float :param sigdig: Significant digits in replacement text. :type sigdig: int :return: Output string. :rtype: str """ lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_double(value) sigdig = ctypes.c_int(sigdig) out = stypes.stringToCharP(lenout) libspice.repmd_c(instr, marker, value, sigdig, lenout, out) return stypes.toPythonString(out) @spiceErrorCheck def repmf(instr, marker, value, sigdig, informat, lenout=None): """ Replace a marker in a string with a formatted double precision value. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmf_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: float :param sigdig: Significant digits in replacement text. :type sigdig: int :param informat: Format 'E' or 'F'. :type informat: str :param lenout: Optional available space in output string. :type lenout: int :return: Output string. :rtype: str """ if lenout is None: lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_double(value) sigdig = ctypes.c_int(sigdig) informat = ctypes.c_char(informat.encode(encoding='UTF-8')) out = stypes.stringToCharP(lenout) libspice.repmf_c(instr, marker, value, sigdig, informat, lenout, out) return stypes.toPythonString(out) @spiceErrorCheck def repmi(instr, marker, value, lenout=None): """ Replace a marker with an integer. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmi_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: int :param lenout: Optional available space in output string. :type lenout: int :return: Output string. :rtype: str """ if lenout is None: lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_int(value) out = stypes.stringToCharP(lenout) libspice.repmi_c(instr, marker, value, lenout, out) return stypes.toPythonString(out) @spiceErrorCheck def repmot(instr, marker, value, repcase, lenout=None): """ Replace a marker with the text representation of an ordinal number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmot_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: int :param repcase: Case of replacement text. :type repcase: str :param lenout: Optional available space in output string. :type lenout: int :return: Output string. :rtype: str """ if lenout is None: lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_int(value) repcase = ctypes.c_char(repcase.encode(encoding='UTF-8')) out = stypes.stringToCharP(lenout) libspice.repmot_c(instr, marker, value, repcase, lenout, out) return stypes.toPythonString(out) def reset(): """ Reset the SPICE error status to a value of "no error." As a result, the status routine, failed, will return a value of False http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reset_c.html """ libspice.reset_c() pass @spiceErrorCheck def return_c(): """ True if SPICE routines should return immediately upon entry. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/return_c.html :return: True if SPICE routines should return immediately upon entry. :rtype: bool """ return libspice.return_c() @spiceErrorCheck def rotate(angle, iaxis): """ Calculate the 3x3 rotation matrix generated by a rotation of a specified angle about a specified axis. This rotation is thought of as rotating the coordinate system. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotate_c.html :param angle: Angle of rotation (radians). :type angle: float :param iaxis: Axis of rotation X=1, Y=2, Z=3. :type iaxis: int :return: Resulting rotation matrix :rtype: 3x3-Element Array of floats. """ angle = ctypes.c_double(angle) iaxis = ctypes.c_int(iaxis) mout = stypes.emptyDoubleMatrix() libspice.rotate_c(angle, iaxis, mout) return stypes.matrixToList(mout) @spiceErrorCheck def rotmat(m1, angle, iaxis): """ Rotmat applies a rotation of angle radians about axis iaxis to a matrix. This rotation is thought of as rotating the coordinate system. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotmat_c.html :param m1: Matrix to be rotated. :type m1: 3x3-Element Array of floats. :param angle: Angle of rotation (radians). :type angle: float :param iaxis: Axis of rotation X=1, Y=2, Z=3. :type iaxis: int :return: Resulting rotated matrix. :rtype: 3x3-Element Array of floats. """ m1 = stypes.listtodoublematrix(m1) angle = ctypes.c_double(angle) iaxis = ctypes.c_int(iaxis) mout = stypes.emptyDoubleMatrix() libspice.rotmat_c(m1, angle, iaxis, mout) return stypes.matrixToList(mout) @spiceErrorCheck def rotvec(v1, angle, iaxis): """ Transform a vector to a new coordinate system rotated by angle radians about axis iaxis. This transformation rotates v1 by angle radians about the specified axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotvec_c.html :param v1: Vector whose coordinate system is to be rotated. :type v1: 3-Element Array of floats :param angle: Angle of rotation (radians). :type angle: float :param iaxis: Axis of rotation X=1, Y=2, Z=3. :type iaxis: int :return: the vector expressed in the new coordinate system. :rtype: 3-Element Array of floats. """ v1 = stypes.toDoubleVector(v1) angle = ctypes.c_double(angle) iaxis = ctypes.c_int(iaxis) vout = stypes.emptyDoubleVector(3) libspice.rotvec_c(v1, angle, iaxis, vout) return stypes.vectorToList(vout) @spiceErrorCheck def rpd(): """ Return the number of radians per degree. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rpd_c.html :return: The number of radians per degree, pi/180. :rtype: float """ return libspice.rpd_c() @spiceErrorCheck def rquad(a, b, c): """ Find the roots of a quadratic equation. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rquad_c.html :param a: Coefficient of quadratic term. :type a: float :param b: Coefficient of linear term. :type b: float :param c: Constant. :type c: float :return: Root built from positive and negative discriminant term. :rtype: tuple """ a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) root1 = stypes.emptyDoubleVector(2) root2 = stypes.emptyDoubleVector(2) libspice.rquad_c(a, b, c, root1, root2) return stypes.vectorToList(root1), stypes.vectorToList(root2) ################################################################################ # S @spiceErrorCheck def saelgv(vec1, vec2): """ Find semi-axis vectors of an ellipse generated by two arbitrary three-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/saelgv_c.html :param vec1: First vector used to generate an ellipse. :type vec1: 3-Element Array of Floats. :param vec2: Second vector used to generate an ellipse. :type vec2: 3-Element Array of Floats. :return: Semi-major axis of ellipse, Semi-minor axis of ellipse. :rtype: tuple """ vec1 = stypes.toDoubleVector(vec1) vec2 = stypes.toDoubleVector(vec2) smajor = stypes.emptyDoubleVector(3) sminor = stypes.emptyDoubleVector(3) libspice.saelgv_c(vec1, vec2, smajor, sminor) return stypes.vectorToList(smajor), stypes.vectorToList(sminor) @spiceErrorCheck def scard(incard, cell): """ Set the cardinality of a SPICE cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scard_c.html :param incard: Cardinality of (number of elements in) the cell. :type incard: int :param cell: The cell. :type cell: SpiceyPy.support_types.SpiceCell :return: The updated Cell. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(cell, stypes.SpiceCell) incard = ctypes.c_int(incard) libspice.scard_c(incard, ctypes.byref(cell)) return cell @spiceErrorCheck def scdecd(sc, sclkdp, lenout, MXPART=None): # todo: figure out how to use mxpart, and test scdecd """ Convert double precision encoding of spacecraft clock time into a character representation. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scdecd_c.html :param sc: NAIF spacecraft identification code. :type sc: int :param sclkdp: Encoded representation of a spacecraft clock count. :type sclkdp: float :param lenout: Maximum allowed length of output SCLK string. :type lenout: int :param MXPART: Maximum number of spacecraft clock partitions. :type MXPART: int :return: Character representation of a clock count. :rtype: str """ sc = ctypes.c_int(sc) sclkdp = ctypes.c_double(sclkdp) sclkch = stypes.stringToCharP(" " * lenout) lenout = ctypes.c_int(lenout) libspice.scdecd_c(sc, sclkdp, lenout, sclkch) return stypes.toPythonString(sclkch) @spiceErrorCheck def sce2c(sc, et): """ Convert ephemeris seconds past J2000 (ET) to continuous encoded spacecraft clock "ticks". Non-integral tick values may be returned. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sce2c_c.html :param sc: NAIF spacecraft ID code. :type sc: int :param et: Ephemeris time, seconds past J2000. :type et: float :return: SCLK, encoded as ticks since spacecraft clock start. sclkdp need not be integral. :rtype: float """ sc = ctypes.c_int(sc) et = ctypes.c_double(et) sclkdp = ctypes.c_double() libspice.sce2c_c(sc, et, ctypes.byref(sclkdp)) return sclkdp.value @spiceErrorCheck def sce2s(sc, et, lenout): """ Convert an epoch specified as ephemeris seconds past J2000 (ET) to a character string representation of a spacecraft clock value (SCLK). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sce2s_c.html :param sc: NAIF spacecraft clock ID code. :type sc: int :param et: Ephemeris time, specified as seconds past J2000. :type et: float :param lenout: Maximum length of output string. :type lenout: int :return: An SCLK string. :rtype: str """ sc = ctypes.c_int(sc) et = ctypes.c_double(et) sclkch = stypes.stringToCharP(" " * lenout) lenout = ctypes.c_int(lenout) libspice.sce2s_c(sc, et, lenout, sclkch) return stypes.toPythonString(sclkch) @spiceErrorCheck def sce2t(sc, et): """ Convert ephemeris seconds past J2000 (ET) to integral encoded spacecraft clock ("ticks"). For conversion to fractional ticks, (required for C-kernel production), see the routine :func:`sce2c`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sce2t_c.html :param sc: NAIF spacecraft ID code. :type sc: int :param et: Ephemeris time, seconds past J2000. :type et: float :return: SCLK, encoded as ticks since spacecraft clock start. :rtype: float """ sc = ctypes.c_int(sc) et = ctypes.c_double(et) sclkdp = ctypes.c_double() libspice.sce2t_c(sc, et, ctypes.byref(sclkdp)) return sclkdp.value @spiceErrorCheck def scencd(sc, sclkch, MXPART=None): """ Encode character representation of spacecraft clock time into a double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scencd_c.html :param sc: NAIF spacecraft identification code. :type sc: int :param sclkch: Character representation of a spacecraft clock. :type sclkch: str :param MXPART: Maximum number of spacecraft clock partitions. :type MXPART: int :return: Encoded representation of the clock count. :rtype: float """ sc = ctypes.c_int(sc) sclkch = stypes.stringToCharP(sclkch) sclkdp = ctypes.c_double() libspice.scencd_c(sc, sclkch, ctypes.byref(sclkdp)) return sclkdp.value @spiceErrorCheck def scfmt(sc, ticks, lenout): """ Convert encoded spacecraft clock ticks to character clock format. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scfmt_c.html :param sc: NAIF spacecraft identification code. :type sc: int :param ticks: Encoded representation of a spacecraft clock count. :type ticks: float :param lenout: Maximum allowed length of output string. :type lenout: int :return: Character representation of a clock count. :rtype: str """ sc = ctypes.c_int(sc) ticks = ctypes.c_double(ticks) clkstr = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) libspice.scfmt_c(sc, ticks, lenout, clkstr) return stypes.toPythonString(clkstr) @spiceErrorCheck def scpart(sc): """ Get spacecraft clock partition information from a spacecraft clock kernel file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scpart_c.html :param sc: NAIF spacecraft identification code. :type sc: int :return: The number of spacecraft clock partitions, Array of partition start times, Array of partition stop times. :rtype: tuple """ sc = ctypes.c_int(sc) nparts = ctypes.c_int() pstart = stypes.emptyDoubleVector(9999) pstop = stypes.emptyDoubleVector(9999) libspice.scpart_c(sc, nparts, pstart, pstop) return stypes.vectorToList(pstart)[0:nparts.value], stypes.vectorToList( pstop)[0:nparts.value] @spiceErrorCheck def scs2e(sc, sclkch): """ Convert a spacecraft clock string to ephemeris seconds past J2000 (ET). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scs2e_c.html :param sc: NAIF integer code for a spacecraft. :type sc: int :param sclkch: An SCLK string. :type sclkch: str :return: Ephemeris time, seconds past J2000. :rtype: float """ sc = ctypes.c_int(sc) sclkch = stypes.stringToCharP(sclkch) et = ctypes.c_double() libspice.scs2e_c(sc, sclkch, ctypes.byref(et)) return et.value @spiceErrorCheck def sct2e(sc, sclkdp): """ Convert encoded spacecraft clock ("ticks") to ephemeris seconds past J2000 (ET). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sct2e_c.html :param sc: NAIF spacecraft ID code. :type sc: int :param sclkdp: SCLK, encoded as ticks since spacecraft clock start. :type sclkdp: float :return: Ephemeris time, seconds past J2000. :rtype: float """ sc = ctypes.c_int(sc) sclkdp = ctypes.c_double(sclkdp) et = ctypes.c_double() libspice.sct2e_c(sc, sclkdp, ctypes.byref(et)) return et.value @spiceErrorCheck def sctiks(sc, clkstr): """ Convert a spacecraft clock format string to number of "ticks". http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sctiks_c.html :param sc: NAIF spacecraft identification code. :type sc: int :param clkstr: Character representation of a spacecraft clock. :type clkstr: str :return: Number of ticks represented by the clock string. :rtype: float """ sc = ctypes.c_int(sc) clkstr = stypes.stringToCharP(clkstr) ticks = ctypes.c_double() libspice.sctiks_c(sc, clkstr, ctypes.byref(ticks)) return ticks.value @spiceErrorCheck def sdiff(a, b): """ Take the symmetric difference of two sets of any data type to form a third set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sdiff_c.html :param a: First input set. :type a: SpiceyPy.support_types.SpiceCell :param b: Second input set. :type b: SpiceyPy.support_types.SpiceCell :return: Symmetric difference of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert isinstance(b, stypes.SpiceCell) assert a.dtype == b.dtype assert a.dtype == 0 or a.dtype == 1 or a.dtype == 2 if a.dtype is 0: c = stypes.SPICECHAR_CELL(a.size, a.length) elif a.dtype is 1: c = stypes.SPICEDOUBLE_CELL(a.size) elif a.dtype is 2: c = stypes.SPICEINT_CELL(a.size) else: raise NotImplementedError libspice.sdiff_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def set_c(a, op, b): """ Given a relational operator, compare two sets of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/set_c.html :param a: First set. :type a: SpiceyPy.support_types.SpiceCell :param op: Comparison operator. :type op: str :param b: Second set. :type b: SpiceyPy.support_types.SpiceCell :return: The function returns the result of the comparison. :rtype: bool """ assert isinstance(a, stypes.SpiceCell) assert isinstance(b, stypes.SpiceCell) assert a.dtype == b.dtype assert isinstance(op, str) op = stypes.stringToCharP(op) return libspice.set_c(ctypes.byref(a), op, ctypes.byref(b)) @spiceErrorCheck def setmsg(message): """ Set the value of the current long error message. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/setmsg_c.html :param message: A long error message. :type message: str """ message = stypes.stringToCharP(message) libspice.setmsg_c(message) pass @spiceErrorCheck def shellc(ndim, lenvals, array): # This works! looks like this is a mutable 2d char array """ Sort an array of character strings according to the ASCII collating sequence using the Shell Sort algorithm. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/shellc_c.html :param ndim: Dimension of the array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: The array to be sorted. :type array: List of str. :return: The sorted array. :rtype: List of str. """ array = stypes.listToCharArray(array, xLen=lenvals, yLen=ndim) ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(lenvals) libspice.shellc_c(ndim, lenvals, ctypes.byref(array)) return stypes.vectorToList(array) @spiceErrorCheck def shelld(ndim, array): # Works!, use this as example for "I/O" parameters """ Sort a double precision array using the Shell Sort algorithm. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/shelld_c.html :param ndim: Dimension of the array. :type ndim: int :param array: The array to be sorted. :type array: N-Element Array of Floats. :return: The sorted array. :rtype: N-Element Array of Floats. """ array = stypes.toDoubleVector(array) ndim = ctypes.c_int(ndim) libspice.shelld_c(ndim, ctypes.cast(array, ctypes.POINTER(ctypes.c_double))) return stypes.vectorToList(array) @spiceErrorCheck def shelli(ndim, array): # Works!, use this as example for "I/O" parameters """ Sort an integer array using the Shell Sort algorithm. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/shelli_c.html :param ndim: Dimension of the array. :type ndim: int :param array: The array to be sorted. :type array: N-Element Array of Ints. :return: The sorted array. :rtype: N-Element Array of Ints. """ array = stypes.toIntVector(array) ndim = ctypes.c_int(ndim) libspice.shelli_c(ndim, ctypes.cast(array, ctypes.POINTER(ctypes.c_int))) return stypes.vectorToList(array) def sigerr(message): """ Inform the CSPICE error processing mechanism that an error has occurred, and specify the type of error. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sigerr_c.html :param message: A short error message. :type message: str """ message = stypes.stringToCharP(message) libspice.sigerr_c(message) pass @spiceErrorCheck def sincpt(method, target, et, fixref, abcorr, obsrvr, dref, dvec): """ Given an observer and a direction vector defining a ray, compute the surface intercept of the ray on a target body at a specified epoch, optionally corrected for light time and stellar aberration. This routine supersedes :func:`srfxpt`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sincpt_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000 TDB. :type et: float :param fixref: Body-fixed, body-centered target body frame. :type fixref: str :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :param dref: Reference frame of ray's direction vector. :type dref: str :param dvec: Ray's direction vector. :type dvec: 3-Element Array of Floats. :return: Surface intercept point on the target body, Intercept epoch, Vector from observer to intercept point, Flag indicating whether intercept was found. :rtype: tuple """ method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) fixref = stypes.stringToCharP(fixref) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) dref = stypes.stringToCharP(dref) dvec = stypes.toDoubleVector(dvec) spoint = stypes.emptyDoubleVector(3) trgepc = ctypes.c_double(0) srfvec = stypes.emptyDoubleVector(3) found = ctypes.c_bool(0) libspice.sincpt_c(method, target, et, fixref, abcorr, obsrvr, dref, dvec, spoint, ctypes.byref(trgepc), srfvec, ctypes.byref(found)) return stypes.vectorToList(spoint), trgepc.value, stypes.vectorToList( srfvec), found.value @spiceErrorCheck def size(cell): """ Return the size (maximum cardinality) of a SPICE cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/size_c.html :param cell: Input cell. :type cell: SpiceyPy.support_types.SpiceCell :return: The size of the input cell. :rtype: int """ assert isinstance(cell, stypes.SpiceCell) return libspice.size_c(ctypes.byref(cell)) @spiceErrorCheck def spd(): """ Return the number of seconds in a day. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spd_c.html :return: The number of seconds in a day. :rtype: float """ return libspice.spd_c() @spiceErrorCheck def sphcyl(radius, colat, slon): """ This routine converts from spherical coordinates to cylindrical coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphcyl_c.html :param radius: Distance of point from origin. :type radius: float :param colat: Polar angle (co-latitude in radians) of point. :type colat: float :param slon: Azimuthal angle (longitude) of point (radians). :type slon: float :return: Distance of point from z axis, angle (radians) of point from XZ plane, Height of point above XY plane. :rtype: tuple """ radius = ctypes.c_double(radius) colat = ctypes.c_double(colat) slon = ctypes.c_double(slon) r = ctypes.c_double() lon = ctypes.c_double() z = ctypes.c_double() libspice.sphcyl_c(radius, colat, slon, ctypes.byref(r), ctypes.byref(lon), ctypes.byref(z)) return r.value, lon.value, z.value @spiceErrorCheck def sphlat(r, colat, lons): """ Convert from spherical coordinates to latitudinal coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphlat_c.html :param r: Distance of the point from the origin. :type r: float :param colat: Angle of the point from positive z axis (radians). :type colat: float :param lons: Angle of the point from the XZ plane (radians). :type lons: float :return: Distance of a point from the origin, Angle of the point from the XZ plane in radians, Angle of the point from the XY plane in radians. :rtype: tuple """ r = ctypes.c_double(r) colat = ctypes.c_double(colat) lons = ctypes.c_double(lons) radius = ctypes.c_double() lon = ctypes.c_double() lat = ctypes.c_double() libspice.sphcyl_c(r, colat, lons, ctypes.byref(radius), ctypes.byref(lon), ctypes.byref(lat)) return radius.value, lon.value, lat.value @spiceErrorCheck def sphrec(r, colat, lon): """ Convert from spherical coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the point from the positive Z-axis. :type colat: float :param lon: Angle of the point from the XZ plane in radians. :type lon: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of Floats. """ r = ctypes.c_double(r) colat = ctypes.c_double(colat) lon = ctypes.c_double(lon) rectan = stypes.emptyDoubleVector(3) libspice.sphrec_c(r, colat, lon, rectan) return stypes.vectorToList(rectan) @spiceErrorCheck def spkacs(targ, et, ref, abcorr, obs): """ Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time and stellar aberration, expressed relative to an inertial reference frame. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkacs_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: Inertial reference frame of output state. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param obs: Observer. :type obs: int :return: State of target, One way light time between observer and target, Derivative of light time with respect to time. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) obs = ctypes.c_int(obs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() dlt = ctypes.c_double() libspice.spkacs_c(targ, et, ref, abcorr, obs, starg, ctypes.byref(lt), ctypes.byref(dlt)) return stypes.vectorToList(starg), lt.value, dlt.value @spiceErrorCheck def spkapo(targ, et, ref, sobs, abcorr): """ Return the position of a target body relative to an observer, optionally corrected for light time and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkapo_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: Inertial reference frame of observer's state. :type ref: str :param sobs: State of observer wrt. solar system barycenter. :type sobs: 6-Element Array of Floats :param abcorr: Aberration correction flag. :type abcorr: str :return: Position of target, One way light time between observer and target. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) sobs = stypes.toDoubleVector(sobs) ptarg = stypes.emptyDoubleVector(3) lt = ctypes.c_double() libspice.spkapo_c(targ, et, ref, sobs, abcorr, ptarg, ctypes.byref(lt)) return stypes.vectorToList(ptarg), lt.value @spiceErrorCheck def spkapp(targ, et, ref, sobs, abcorr): """ Deprecated: This routine has been superseded by :func:`spkaps`. This routine is supported for purposes of backward compatibility only. Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkapp_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: Inertial reference frame of observer's state. :type ref: str :param sobs: State of observer wrt. solar system barycenter. :type sobs: 6-Element Array of Floats :param abcorr: Aberration correction flag. :type abcorr: str :return: State of target, One way light time between observer and target. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) sobs = stypes.toDoubleVector(sobs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkapp_c(targ, et, ref, sobs, abcorr, starg, ctypes.byref(lt)) return stypes.vectorToList(starg), lt.value @spiceErrorCheck def spkaps(targ, et, ref, abcorr, stobs, accobs): """ Given the state and acceleration of an observer relative to the solar system barycenter, return the state (position and velocity) of a target body relative to the observer, optionally corrected for light time and stellar aberration. All input and output vectors are expressed relative to an inertial reference frame. This routine supersedes :func:`spkapp`. SPICE users normally should call the high-level API routines :func:`spkezr` or :func:`spkez` rather than this routine. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkaps_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: Inertial reference frame of output state. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param stobs: State of the observer relative to the SSB. :type stobs: 6-Element Array of Floats :param accobs: Acceleration of the observer relative to the SSB. :type accobs: 6-Element Array of Floats :return: State of target, One way light time between observer and target, Derivative of light time with respect to time. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) stobs = stypes.toDoubleVector(stobs) accobs = stypes.toDoubleVector(accobs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() dlt = ctypes.c_double() libspice.spkaps_c(targ, et, ref, abcorr, stobs, accobs, starg, ctypes.byref(lt), ctypes.byref(dlt)) return stypes.vectorToList(starg), lt.value, dlt.value @spiceErrorCheck def spk14a(handle, ncsets, coeffs, epochs): """ Add data to a type 14 SPK segment associated with handle. See also :func:`spk14b` and :func:`spk14e`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spk14a_c.html :param handle: The handle of an SPK file open for writing. :type handle: int :param ncsets: The number of coefficient sets and epochs. :type ncsets: int :param coeffs: The collection of coefficient sets. :type coeffs: N-Element Array of Floats :param epochs: The epochs associated with the coefficient sets. :type epochs: N-Element Array of Floats """ handle = ctypes.c_int(handle) ncsets = ctypes.c_int(ncsets) coeffs = stypes.toDoubleVector(coeffs) epochs = stypes.toDoubleVector(epochs) libspice.spk14a_c(handle, ncsets, coeffs, epochs) pass @spiceErrorCheck def spk14b(handle, segid, body, center, framename, first, last, chbdeg): """ Begin a type 14 SPK segment in the SPK file associated with handle. See also :func:`spk14a` and :func:`spk14e`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spk14b_c.html :param handle: The handle of an SPK file open for writing. :type handle: int :param segid: The string to use for segment identifier. :type segid: str :param body: The NAIF ID code for the body of the segment. :type body: int :param center: The center of motion for body. :type center: int :param framename: The reference frame for this segment. :type framename: str :param first: The first epoch for which the segment is valid. :type first: float :param last: The last epoch for which the segment is valid. :type last: float :param chbdeg: The degree of the Chebyshev Polynomial used. :type chbdeg: int """ handle = ctypes.c_int(handle) segid = stypes.stringToCharP(segid) body = ctypes.c_int(body) center = ctypes.c_int(center) framename = stypes.stringToCharP(framename) first = ctypes.c_double(first) last = ctypes.c_double(last) chbdeg = ctypes.c_int(chbdeg) libspice.spk14b_c(handle, segid, body, center, framename, first, last, chbdeg) pass @spiceErrorCheck def spk14e(handle): """ End the type 14 SPK segment currently being written to the SPK file associated with handle. See also :func:`spk14a` and :func:`spk14b`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spk14e_c.html :param handle: The handle of an SPK file open for writing. :type handle: int """ handle = ctypes.c_int(handle) libspice.spk14e_c(handle) pass @spiceErrorCheck def spkcls(handle): """ Close an open SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcls_c.html :param handle: Handle of the SPK file to be closed. :type handle: int """ handle = ctypes.c_int(handle) libspice.spkcls_c(handle) pass @spiceErrorCheck def spkcov(spk, idcode, cover): """ Find the coverage window for a specified ephemeris object in a specified SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcov_c.html :param spk: Name of SPK file. :type spk: str :param idcode: ID code of ephemeris object. :type idcode: int :param cover: Window giving coverage in "spk" for "idcode". :type cover: SpiceyPy.support_types.SpiceCell """ spk = stypes.stringToCharP(spk) idcode = ctypes.c_int(idcode) assert isinstance(cover, stypes.SpiceCell) assert cover.dtype == 1 libspice.spkcov_c(spk, idcode, ctypes.byref(cover)) @spiceErrorCheck def spkcpo(target, et, outref, refloc, abcorr, obspos, obsctr, obsref): """ Return the state of a specified target relative to an "observer," where the observer has constant position in a specified reference frame. The observer's position is provided by the calling program rather than by loaded SPK files. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcpo_c.html :param target: Name of target ephemeris object. :type target: str :param et: Observation epoch. :type et: float :param outref: Reference frame of output state. :type outref: str :param refloc: Output reference frame evaluation locus. :type refloc: str :param abcorr: Aberration correction. :type abcorr: str :param obspos: Observer position relative to center of motion. :type obspos: 3-Element Array of Floats. :param obsctr: Center of motion of observer. :type obsctr: str :param obsref: Frame of observer position. :type obsref: str :return: State of target with respect to observer, One way light time between target and observer. :rtype: tuple """ target = stypes.stringToCharP(target) et = ctypes.c_double(et) outref = stypes.stringToCharP(outref) refloc = stypes.stringToCharP(refloc) abcorr = stypes.stringToCharP(abcorr) obspos = stypes.toDoubleVector(obspos) obsctr = stypes.stringToCharP(obsctr) obsref = stypes.stringToCharP(obsref) state = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkcpo_c(target, et, outref, refloc, abcorr, obspos, obsctr, obsref, state, ctypes.byref(lt)) return stypes.vectorToList(state), lt.value @spiceErrorCheck def spkcpt(trgpos, trgctr, trgref, et, outref, refloc, abcorr, obsrvr): """ Return the state, relative to a specified observer, of a target having constant position in a specified reference frame. The target's position is provided by the calling program rather than by loaded SPK files. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcpt_c.html :param trgpos: Target position relative to center of motion. :type trgpos: 3-Element Array of Floats :param trgctr: Center of motion of target. :type trgctr: str :param trgref: Observation epoch. :type trgref: str :param et: Observation epoch. :type et: float :param outref: Reference frame of output state. :type outref: str :param refloc: Output reference frame evaluation locus. :type refloc: str :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing ephemeris object. :return: State of target with respect to observer, One way light time between target and observer. :rtype: tuple """ trgpos = stypes.toDoubleVector(trgpos) trgctr = stypes.stringToCharP(trgctr) trgref = stypes.stringToCharP(trgref) et = ctypes.c_double(et) outref = stypes.stringToCharP(outref) refloc = stypes.stringToCharP(refloc) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) state = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkcpt_c(trgpos, trgctr, trgref, et, outref, refloc, abcorr, obsrvr, state, ctypes.byref(lt)) return stypes.vectorToList(state), lt.value @spiceErrorCheck def spkcvo(target, et, outref, refloc, abcorr, obssta, obsepc, obsctr, obsref): """ Return the state of a specified target relative to an "observer," where the observer has constant velocity in a specified reference frame. The observer's state is provided by the calling program rather than by loaded SPK files. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcvo_c.html :param target: Name of target ephemeris object. :type target: str :param et: Observation epoch. :type et: float :param outref: Reference frame of output state. :type outref: str :param refloc: Output reference frame evaluation locus. :type refloc: str :param abcorr: Aberration correction. :type abcorr: str :param obssta: Observer state relative to center of motion. :type obssta: 6-Element Array of Floats :param obsepc: Epoch of observer state. :type obsepc: float :param obsctr: Center of motion of observer. :type obsctr: str :param obsref: Frame of observer state. :type obsref: str :return: State of target with respect to observer, One way light time between target and observer. :rtype: tuple """ target = stypes.stringToCharP(target) et = ctypes.c_double(et) outref = stypes.stringToCharP(outref) refloc = stypes.stringToCharP(refloc) abcorr = stypes.stringToCharP(abcorr) obssta = stypes.toDoubleVector(obssta) obsepc = ctypes.c_double(obsepc) obsctr = stypes.stringToCharP(obsctr) obsref = stypes.stringToCharP(obsref) state = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkcvo_c(target, et, outref, refloc, abcorr, obssta, obsepc, obsctr, obsref, state, ctypes.byref(lt)) return stypes.vectorToList(state), lt.value @spiceErrorCheck def spkcvt(trgsta, trgepc, trgctr, trgref, et, outref, refloc, abcorr, obsrvr): """ Return the state, relative to a specified observer, of a target having constant velocity in a specified reference frame. The target's state is provided by the calling program rather than by loaded SPK files. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkcvt_c.html :param trgsta: Target state relative to center of motion. :type trgsta: 6-Element Array of Floats :param trgepc: Epoch of target state. :type trgepc: float :param trgctr: Center of motion of target. :type trgctr: str :param trgref: Frame of target state. :type trgref: str :param et: Observation epoch. :type et: float :param outref: Reference frame of output state. :type outref: str :param refloc: Output reference frame evaluation locus. :type refloc: str :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing ephemeris object. :type obsrvr: str :return: State of target with respect to observer, One way light time between target and observer. :rtype: tuple """ trgpos = stypes.toDoubleVector(trgsta) trgepc = ctypes.c_double(trgepc) trgctr = stypes.stringToCharP(trgctr) trgref = stypes.stringToCharP(trgref) et = ctypes.c_double(et) outref = stypes.stringToCharP(outref) refloc = stypes.stringToCharP(refloc) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) state = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkcvt_c(trgpos, trgepc, trgctr, trgref, et, outref, refloc, abcorr, obsrvr, state, ctypes.byref(lt)) return stypes.vectorToList(state), lt.value @spiceErrorCheck def spkez(targ, et, ref, abcorr, obs): """ Return the state (position and velocity) of a target body relative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkez_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: Reference frame of output state vector. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param obs: Observing body. :type obs: int :return: State of target, One way light time between observer and target. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) obs = ctypes.c_int(obs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkez_c(targ, et, ref, abcorr, obs, starg, ctypes.byref(lt)) return stypes.vectorToList(starg), lt.value @spiceErrorCheck def spkezp(targ, et, ref, abcorr, obs): """ Return the position of a target body relative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkezp_c.html :param targ: Target body NAIF ID code. :type targ: int :param et: Observer epoch. :type et: float :param ref: Reference frame of output position vector. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param obs: Observing body NAIF ID code. :type obs: int :return: Position of target, One way light time between observer and target. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) obs = ctypes.c_int(obs) ptarg = stypes.emptyDoubleVector(3) lt = ctypes.c_double() libspice.spkezp_c(targ, et, ref, abcorr, obs, ptarg, ctypes.byref(lt)) return stypes.vectorToList(ptarg), lt.value @spiceErrorCheck def spkezr(targ, et, ref, abcorr, obs): """ Return the state (position and velocity) of a target body relative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkezr_c.html :param targ: Target body name. :type targ: str :param et: Observer epoch. :type et: float :param ref: Reference frame of output state vector. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param obs: Observing body name. :type obs: str :return: State of target, One way light time between observer and target. :rtype: tuple """ targ = stypes.stringToCharP(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) obs = stypes.stringToCharP(obs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkezr_c(targ, et, ref, abcorr, obs, starg, ctypes.byref(lt)) return stypes.vectorToList(starg), lt.value @spiceErrorCheck def spkgeo(targ, et, ref, obs): """ Compute the geometric state (position and velocity) of a target body relative to an observing body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkgeo_c.html :param targ: Target body. :type targ: int :param et: Target epoch. :type et: float :param ref: Target reference frame. :type ref: str :param obs: Observing body. :type obs: int :return: State of target, Light time. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) obs = ctypes.c_int(obs) state = stypes.emptyDoubleVector(6) lt = ctypes.c_double() libspice.spkgeo_c(targ, et, ref, obs, state, ctypes.byref(lt)) return stypes.vectorToList(state), lt.value @spiceErrorCheck def spkgps(targ, et, ref, obs): """ Compute the geometric position of a target body relative to an observing body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkgps_c.html :param targ: Target body. :type targ: int :param et: Target epoch. :type et: float :param ref: Target reference frame. :type ref: str :param obs: Observing body. :type obs: int :return: Position of target, Light time. :rtype: tuple """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) obs = ctypes.c_int(obs) position = stypes.emptyDoubleVector(3) lt = ctypes.c_double() libspice.spkgps_c(targ, et, ref, obs, position, ctypes.byref(lt)) return stypes.vectorToList(position), lt.value @spiceErrorCheck def spklef(filename): """ Load an ephemeris file for use by the readers. Return that file's handle, to be used by other SPK routines to refer to the file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spklef_c.html :param filename: Name of the file to be loaded. :type filename: str :return: Loaded file's handle. :rtype: int """ filename = stypes.stringToCharP(filename) handle = ctypes.c_int() libspice.spklef_c(filename, ctypes.byref(handle)) return handle.value @spiceErrorCheck def spkltc(targ, et, ref, abcorr, stobs): """ Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time, expressed relative to an inertial reference frame. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkltc_c.html :param targ: Target body. :type targ: int :param et: Observer epoch. :type et: float :param ref: Inertial reference frame of output state. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param stobs: State of the observer relative to the SSB. :type stobs: 6-Element Array of Floats :return: One way light time between observer and target, Derivative of light time with respect to time :rtype: tuple """ assert len(stobs) == 6 targ = stypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) stobs = stypes.toDoubleVector(stobs) starg = stypes.emptyDoubleVector(6) lt = ctypes.c_double() dlt = ctypes.c_double() libspice.spkltc_c(targ, et, ref, abcorr, stobs, starg, ctypes.byref(lt), ctypes.byref(dlt)) return stypes.vectorToList(starg), lt.value, dlt.value @spiceErrorCheck def spkobj(spk, ids): """ Find the set of ID codes of all objects in a specified SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkobj_c.html :param spk: Name of SPK file. :type spk: str :param ids: Empty SpiceCell :type ids: SpiceyPy.support_types.SpiceCell """ spk = stypes.stringToCharP(spk) assert isinstance(ids, stypes.SpiceCell) assert ids.dtype == 2 libspice.spkobj_c(spk, ctypes.byref(ids)) @spiceErrorCheck def spkopa(filename): # Todo: test spkopa """ Open an existing SPK file for subsequent write. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopa_c.html :param filename: The name of an existing SPK file. :type filename: str :return: A handle attached to the SPK file opened to append. :rtype: int """ filename = stypes.stringToCharP(filename) handle = ctypes.c_int() libspice.spkopa_c(filename, ctypes.byref(handle)) return handle.value @spiceErrorCheck def spkopn(filename, ifname, ncomch): """ Create a new SPK file, returning the handle of the opened file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopn_c.html :param filename: The name of the new SPK file to be created. :type filename: str :param ifname: The internal filename for the SPK file. :type ifname: str :param ncomch: The number of characters to reserve for comments. :type ncomch: int :return: The handle of the opened SPK file. :rtype: int """ filename = stypes.stringToCharP(filename) ifname = stypes.stringToCharP(ifname) ncomch = ctypes.c_int(ncomch) handle = ctypes.c_int() libspice.spkopn_c(filename, ifname, ncomch, ctypes.byref(handle)) return handle.value @spiceErrorCheck def spkpds(body, center, framestr, typenum, first, last): # Todo: test spkpds """ Perform routine error checks and if all check pass, pack the descriptor for an SPK segment http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpds_c.html :param body: The NAIF ID code for the body of the segment. :type body: int :param center: The center of motion for body. :type center: int :param framestr: The frame for this segment. :type framestr: str :param typenum: The type of SPK segment to create. :type typenum: int :param first: The first epoch for which the segment is valid. :type first: float :param last: The last epoch for which the segment is valid. :type last: float :return: An SPK segment descriptor. :rtype: 5-Element Array of Floats """ body = ctypes.c_int(body) center = ctypes.c_int(center) framestr = stypes.stringToCharP(framestr) typenum = ctypes.c_int(typenum) first = ctypes.c_double(first) last = ctypes.c_double(last) descr = stypes.emptyDoubleVector(5) libspice.spkpds_c(body, center, framestr, typenum, first, last, descr) return stypes.vectorToList(descr) @spiceErrorCheck def spkpos(targ, et, ref, abcorr, obs): """ Return the position of a target body relative to an observing body, optionally corrected for light time (planetary aberration) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpos_c.html :param targ: Target body name. :type targ: str :param et: Observer epoch. :type et: float or List of Floats :param ref: Reference frame of output position vector. :type ref: str :param abcorr: Aberration correction flag. :type abcorr: str :param obs: Observing body name. :type obs: str :return: Position of target, One way light time between observer and target. :rtype: tuple """ if hasattr(et, "__iter__"): vlen = len(et) positions = numpy.zeros((vlen, 3), dtype=numpy.float) times = numpy.zeros(vlen, dtype=numpy.float) for (index, time) in enumerate(et): positions[index], times[index] = spkpos(targ, time, ref, abcorr, obs) return positions, times targ = stypes.stringToCharP(targ) ref = stypes.stringToCharP(ref) abcorr = stypes.stringToCharP(abcorr) obs = stypes.stringToCharP(obs) ptarg = stypes.emptyDoubleVector(3) lt = ctypes.c_double() libspice.spkpos_c(targ, et, ref, abcorr, obs, ptarg, ctypes.byref(lt)) return stypes.vectorToList(ptarg), lt.value @spiceErrorCheck def spkpvn(handle, descr, et): """ For a specified SPK segment and time, return the state (position and velocity) of the segment's target body relative to its center of motion. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkpvn_c.html :param handle: File handle. :type handle: int :param descr: Segment descriptor. :type descr: 5-Element Array of Floats. :param et: Evaluation epoch. :type et: float :return: Segment reference frame ID code, Output state vector, Center of state. :rtype: tuple """ handle = ctypes.c_int(handle) descr = stypes.toDoubleVector(descr) et = ctypes.c_double(et) ref = ctypes.c_int() state = stypes.emptyDoubleVector(6) center = ctypes.c_int() libspice.spkpvn_c(handle, descr, et, ctypes.byref(ref), state, ctypes.byref(center)) return ref.value, stypes.vectorToList(state), center.value @spiceErrorCheck def spksfs(body, et, idlen): # spksfs has a Parameter SIDLEN, # sounds like an optional but is that possible? """ Search through loaded SPK files to find the highest-priority segment applicable to the body and time specified. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spksfs_c.html :param body: Body ID. :type body: int :param et: Ephemeris time. :type et: float :param idlen: Length of output segment ID string. :type idlen: int :return: Handle of file containing the applicable segment, Descriptor of the applicable segment, Identifier of the applicable segment, Found flag Indicates whether or not a segment was found. :rtype: tuple """ body = ctypes.c_int(body) et = ctypes.c_double(et) idlen = ctypes.c_int(idlen) handle = ctypes.c_int() descr = stypes.emptyDoubleVector(5) identstring = stypes.stringToCharP(idlen) found = ctypes.c_bool() libspice.spksfs_c(body, et, idlen, ctypes.byref(handle), descr, identstring, ctypes.byref(found)) return handle.value, stypes.vectorToList(descr),\ stypes.toPythonString(identstring), found.value @spiceErrorCheck def spkssb(targ, et, ref): # Todo: test spkssb """ Return the state (position and velocity) of a target body relative to the solar system barycenter. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkssb_c.html :param targ: Target body. :type targ: int :param et: Target epoch. :type et: float :param ref: Target reference frame. :type ref: str :return: State of target. :rtype: 6-Element Array of Floats. """ targ = ctypes.c_int(targ) et = ctypes.c_double(et) ref = stypes.stringToCharP(ref) starg = stypes.emptyDoubleVector(6) libspice.spkssb_c(targ, et, ref, starg) return stypes.vectorToList(starg) @spiceErrorCheck def spksub(handle, descr, identin, begin, end, newh): # Todo: test spksub """ Extract a subset of the data in an SPK segment into a separate segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spksub_c.html :param handle: Handle of source segment. :type handle: int :param descr: Descriptor of source segment. :type descr: 5-Element Array of Floats :param identin: Indentifier of source segment. :type identin: str :param begin: Beginning (initial epoch) of subset. :type begin: int :param end: End (fincal epoch) of subset. :type end: int :param newh: Handle of new segment. :type newh: int """ assert len(descr) is 5 handle = ctypes.c_int(handle) descr = stypes.toDoubleVector(descr) identin = stypes.stringToCharP(identin) begin = ctypes.c_int(begin) end = ctypes.c_int(end) newh = ctypes.c_int(newh) libspice.spksub_c(handle, descr, identin, begin, end, newh) pass @spiceErrorCheck def spkuds(descr): # Todo: test spkuds """ Unpack the contents of an SPK segment descriptor. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkuds_c.html :param descr: An SPK segment descriptor. :type descr: 5-Element Array of Floats. :return: The NAIF ID code for the body of the segment, The center of motion for body, The ID code for the frame of this segment, The type of SPK segment, The first epoch for which the segment is valid, The last epoch for which the segment is valid, Beginning DAF address of the segment, Ending DAF address of the segment. :rtype: tuple """ assert len(descr) is 5 descr = stypes.toDoubleVector(descr) body = ctypes.c_int() center = ctypes.c_int() framenum = ctypes.c_int() typenum = ctypes.c_int() first = ctypes.c_double() last = ctypes.c_double() begin = ctypes.c_int() end = ctypes.c_int() libspice.spkuds_c(descr, ctypes.byref(body), ctypes.byref(center), ctypes.byref(framenum), ctypes.byref(typenum), ctypes.byref(first), ctypes.byref(last), ctypes.byref(begin), ctypes.byref(end)) return body.value, center.value, framenum.value, typenum.value,\ first.value, last.value, begin.value, end.value @spiceErrorCheck def spkuef(handle): # Todo: test spkuef """ Unload an ephemeris file so that it will no longer be searched by the readers. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkuef_c.html :param handle: Handle of file to be unloaded :type handle: int """ handle = ctypes.c_int(handle) libspice.spkuef_c(handle) pass @spiceErrorCheck def spkw02(handle, body, center, inframe, first, last, segid, intlen, n, polydg, cdata, btime): """ Write a type 2 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw02_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: Body code for ephemeris object. :type body: int :param center: Body code for the center of motion of the body. :type center: int :param inframe: The reference frame of the states. :type inframe: str :param first: First valid time for which states can be computed. :type first: float :param last: Last valid time for which states can be computed. :type last: float :param segid: Segment identifier. :type segid: str :param intlen: Length of time covered by logical record. :type intlen: float :param n: Number of coefficient sets. :type n: int :param polydg: Chebyshev polynomial degree. :type polydg: int :param cdata: Array of Chebyshev coefficients. :type cdata: N-Element Array of Floats. :param btime: Begin time of first logical record. :type btime: float """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) intlen = ctypes.c_double(intlen) n = ctypes.c_int(n) polydg = ctypes.c_int(polydg) cdata = stypes.toDoubleVector(cdata) btime = ctypes.c_double(btime) libspice.spkw02_c(handle, body, center, inframe, first, last, segid, intlen, n, polydg, cdata, btime) pass @spiceErrorCheck def spkw03(handle, body, center, inframe, first, last, segid, intlen, n, polydg, cdata, btime): """ Write a type 3 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw03_c.html :param handle: Handle of SPK file open for writing. :type handle: int :param body: NAIF code for ephemeris object. :type body: int :param center: NAIF code for the center of motion of the body. :type center: int :param inframe: Reference frame name. :type inframe: str :param first: Start time of interval covered by segment. :type first: float :param last: End time of interval covered by segment. :type last: float :param segid: Segment identifier. :type segid: str :param intlen: Length of time covered by record. :type intlen: float :param n: Number of records in segment. :type n: int :param polydg: Chebyshev polynomial degree. :type polydg: int :param cdata: Array of Chebyshev coefficients. :type cdata: N-Element Array of Floats :param btime: Begin time of first record. :type btime: float """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) intlen = ctypes.c_double(intlen) n = ctypes.c_int(n) polydg = ctypes.c_int(polydg) cdata = stypes.toDoubleVector(cdata) btime = ctypes.c_double(btime) libspice.spkw03_c(handle, body, center, inframe, first, last, segid, intlen, n, polydg, cdata, btime) pass @spiceErrorCheck def spkw05(handle, body, center, inframe, first, last, segid, gm, n, states, epochs): # see libspice args for solution to array[][N] problem """ Write an SPK segment of type 5 given a time-ordered set of discrete states and epochs, and the gravitational parameter of a central body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw05_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: Body code for ephemeris object. :type body: int :param center: Body code for the center of motion of the body. :type center: int :param inframe: The reference frame of the states. :type inframe: str :param first: First valid time for which states can be computed. :type first: float :param last: Last valid time for which states can be computed. :type last: float :param segid: Segment identifier. :type segid: str :param gm: Gravitational parameter of central body. :type gm: float :param n: Number of states and epochs. :type n: int :param states: States. :type states: Nx6-Element Array of Floats. :param epochs: Epochs. :type epochs: N-Element Array of Floats. """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) gm = ctypes.c_double(gm) n = ctypes.c_int(n) states = stypes.toDoubleMatrix(states) epochs = stypes.toDoubleVector(epochs) libspice.spkw05_c(handle, body, center, inframe, first, last, segid, gm, n, states, epochs) pass @spiceErrorCheck def spkw08(handle, body, center, inframe, first, last, segid, degree, n, states, epoch1, step): # see libspice args for solution to array[][N] problem """ Write a type 8 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw08_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: NAIF code for an ephemeris object. :type body: int :param center: NAIF code for center of motion of "body". :type center: int :param inframe: Reference frame name. :type inframe: str :param first: Start time of interval covered by segment. :type first: float :param last: End time of interval covered by segment. :type last: float :param segid: Segment identifier. :type segid: str :param degree: Degree of interpolating polynomials. :type degree: int :param n: Number of states. :type n: int :param states: Array of states. :type states: Nx6-Element Array of Floats. :param epoch1: Epoch of first state in states array. :type epoch1: float :param step: Time step separating epochs of states. :type step: float """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) degree = ctypes.c_int(degree) n = ctypes.c_int(n) states = stypes.toDoubleMatrix(states) # X by 6 array epoch1 = ctypes.c_double(epoch1) step = ctypes.c_double(step) libspice.spkw08_c(handle, body, center, inframe, first, last, segid, degree, n, states, epoch1, step) pass @spiceErrorCheck def spkw09(handle, body, center, inframe, first, last, segid, degree, n, states, epochs): """ Write a type 9 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw09_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: NAIF code for an ephemeris object. :type body: int :param center: NAIF code for center of motion of "body". :type center: int :param inframe: Reference frame name. :type inframe: str :param first: Start time of interval covered by segment. :type first: float :param last: End time of interval covered by segment. :type last: float :param segid: Segment identifier. :type segid: str :param degree: Degree of interpolating polynomials. :type degree: int :param n: Number of states. :type n: int :param states: Array of states. :type states: Nx6-Element Array of Floats. :param epochs: Array of epochs corresponding to states. :type epochs: N-Element Array of Floats. """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) degree = ctypes.c_int(degree) n = ctypes.c_int(n) states = stypes.toDoubleMatrix(states) # X by 6 array epochs = stypes.toDoubleVector(epochs) libspice.spkw09_c(handle, body, center, inframe, first, last, segid, degree, n, states, epochs) pass @spiceErrorCheck def spkw10(handle, body, center, inframe, first, last, segid, consts, n, elems, epochs): """ Write an SPK type 10 segment to the DAF open and attached to the input handle. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw10_c.html :param handle: The handle of a DAF file open for writing. :type handle: int :param body: The NAIF ID code for the body of the segment. :type body: int :param center: The center of motion for body. :type center: int :param inframe: The reference frame for this segment. :type inframe: str :param first: The first epoch for which the segment is valid. :type first: float :param last: The last epoch for which the segment is valid. :type last: float :param segid: The string to use for segment identifier. :type segid: str :param consts: The array of geophysical constants for the segment. :type consts: 8-Element Array of Floats :param n: The number of element/epoch pairs to be stored. :type n: int :param elems: The collection of "two-line" element sets. :type elems: N-Element Array of Floats. :param epochs: The epochs associated with the element sets. :type epochs: N-Element Array of Floats. """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) consts = stypes.toDoubleVector(consts) n = ctypes.c_int(n) elems = stypes.toDoubleVector(elems) epochs = stypes.toDoubleVector(epochs) libspice.spkw10_c(handle, body, center, inframe, first, last, segid, consts, n, elems, epochs) pass @spiceErrorCheck def spkw12(handle, body, center, inframe, first, last, segid, degree, n, states, epoch0, step): """ Write a type 12 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw12_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: NAIF code for an ephemeris object. :type body: int :param center: NAIF code for center of motion of body. :type center: int :param inframe: Reference frame name. :type inframe: str :param first: Start time of interval covered by segment. :type first: float :param last: End time of interval covered by segment. :type last: float :param segid: Segment identifier. :type segid: str :param degree: Degree of interpolating polynomials. :type degree: int :param n: Number of states. :type n: int :param states: Array of states. :type states: Nx6-Element Array of Floats. :param epoch0: Epoch of first state in states array. :type epoch0: float :param step: Time step separating epochs of states. :type step: float """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) degree = ctypes.c_int(degree) n = ctypes.c_int(n) states = stypes.toDoubleMatrix(states) # X by 6 array epoch0 = ctypes.c_double(epoch0) step = ctypes.c_double(step) libspice.spkw12_c(handle, body, center, inframe, first, last, segid, degree, n, states, epoch0, step) pass @spiceErrorCheck def spkw13(handle, body, center, inframe, first, last, segid, degree, n, states, epochs): """ Write a type 13 segment to an SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw13_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: NAIF code for an ephemeris object. :type body: int :param center: NAIF code for center of motion of body. :type center: int :param inframe: Reference frame name. :type inframe: str :param first: Start time of interval covered by segment. :type first: float :param last: End time of interval covered by segment. :type last: float :param segid: Segment identifier. :type segid: str :param degree: Degree of interpolating polynomials. :type degree: int :param n: Number of states. :type n: int :param states: Array of states. :type states: Nx6-Element Array of Floats. :param epochs: Array of epochs corresponding to states. :type epochs: N-Element Array of Floats. """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) degree = ctypes.c_int(degree) n = ctypes.c_int(n) states = stypes.toDoubleMatrix(states) # X by 6 array epochs = stypes.toDoubleVector(epochs) libspice.spkw13_c(handle, body, center, inframe, first, last, segid, degree, n, states, epochs) pass @spiceErrorCheck def spkw15(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p, ecc, j2flg, pv, gm, j2, radius): # Todo: test spkw15 """ Write an SPK segment of type 15 given a type 15 data record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: Body code for ephemeris object. :type body: int :param center: Body code for the center of motion of the body. :type center: int :param inframe: The reference frame of the states. :type inframe: str :param first: First valid time for which states can be computed. :type first: float :param last: Last valid time for which states can be computed. :type last: float :param segid: Segment identifier. :type segid: str :param epoch: Epoch of the periapse. :type epoch: float :param tp: Trajectory pole vector. :type tp: 3-Element Array of Floats. :param pa: Periapsis vector. :type pa: 3-Element Array of Floats :param p: Semi-latus rectum. :type p: float :param ecc: Eccentricity. :type ecc: float :param j2flg: J2 processing flag. :type j2flg: float :param pv: Central body pole vector. :type pv: float :param gm: Central body GM. :type gm: float :param j2: Central body J2. :type j2: float :param radius: Equatorial radius of central body. :type radius: float """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) epoch = ctypes.c_double(epoch) tp = stypes.toDoubleVector(tp) pa = stypes.toDoubleVector(pa) p = ctypes.c_double(p) ecc = ctypes.c_double(ecc) j2flg = ctypes.c_double(j2flg) pv = ctypes.c_double(pv) gm = ctypes.c_double(gm) j2 = ctypes.c_double(j2) radius = ctypes.c_double(radius) libspice.spkw15_c(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p, ecc, j2flg, pv, gm, j2, radius) pass @spiceErrorCheck def spkw17(handle, body, center, inframe, first, last, segid, epoch, eqel, rapol, decpol): # Todo: test spkw17 """ Write an SPK segment of type 17 given a type 17 data record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw17_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: Body code for ephemeris object. :type body: int :param center: Body code for the center of motion of the body. :type center: int :param inframe: The reference frame of the states. :type inframe: str :param first: First valid time for which states can be computed. :type first: float :param last: Last valid time for which states can be computed. :type last: float :param segid: Segment identifier. :type segid: str :param epoch: Epoch of elements in seconds past J2000. :type epoch: float :param eqel: Array of equinoctial elements. :type eqel: 9-Element Array of Floats. :param rapol: Right Ascension of the pole of the reference plane. :type rapol: float :param decpol: Declination of the pole of the reference plane. :type decpol: float """ handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = ctypes.c_double(last) segid = stypes.stringToCharP(segid) epoch = ctypes.c_double(epoch) eqel = stypes.toDoubleVector(eqel) rapol = ctypes.c_double(rapol) decpol = ctypes.c_double(decpol) libspice.spkw17_c(handle, body, center, inframe, first, last, segid, epoch, eqel, rapol, decpol) pass # spkw18 # spkw20 @spiceErrorCheck def srfrec(body, longitude, latitude): """ Convert planetocentric latitude and longitude of a surface point on a specified body to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfrec_c.html :param body: NAIF integer code of an extended body. :type body: int :param longitude: Longitude of point in radians. :type longitude: float :param latitude: Latitude of point in radians. :type latitude: float :return: Rectangular coordinates of the point. :rtype: 3-Element Array of Floats """ if hasattr(longitude, "__iter__") and hasattr(latitude, "__iter__"): return numpy.array( [srfrec(body, lon, lat) for lon, lat in zip(longitude, latitude)]) body = ctypes.c_int(body) longitude = ctypes.c_double(longitude) latitude = ctypes.c_double(latitude) rectan = stypes.emptyDoubleVector(3) libspice.srfrec_c(body, longitude, latitude, rectan) return stypes.vectorToList(rectan) @spiceErrorCheck def srfxpt(method, target, et, abcorr, obsrvr, dref, dvec): """ Deprecated: This routine has been superseded by the CSPICE routine :func:`sincpt`. This routine is supported for purposes of backward compatibility only. Given an observer and a direction vector defining a ray, compute the surface intercept point of the ray on a target body at a specified epoch, optionally corrected for light time and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfxpt_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000 TDB. :type et: float :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :param dref: Reference frame of input direction vector. :type dref: str :param dvec: Ray's direction vector. :type dvec: 3-Element Array of Floats. :return: Surface intercept point on the target body, Distance from the observer to the intercept point, Intercept epoch, Observer position relative to target center, Flag indicating whether intercept was found. :rtype: tuple """ if hasattr(et, "__iter__"): return numpy.array( [srfxpt(method, target, t, abcorr, obsrvr, dref, dvec) for t in et]) method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) dref = stypes.stringToCharP(dref) dvec = stypes.toDoubleVector(dvec) spoint = stypes.emptyDoubleVector(3) trgepc = ctypes.c_double() dist = ctypes.c_double() obspos = stypes.emptyDoubleVector(3) found = ctypes.c_bool() libspice.srfxpt_c(method, target, et, abcorr, obsrvr, dref, dvec, spoint, ctypes.byref(dist), ctypes.byref(trgepc), obspos, ctypes.byref(found)) return stypes.vectorToList( spoint), dist.value, trgepc.value, stypes.vectorToList( obspos), found.value @spiceErrorCheck def ssize(newsize, cell): """ Set the size (maximum cardinality) of a CSPICE cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ssize_c.html :param newsize: Size (maximum cardinality) of the cell. :type newsize: int :param cell: The cell. :type cell: SpiceyPy.support_types.SpiceCell :return: The updated cell. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(cell, stypes.SpiceCell) newsize = ctypes.c_int(newsize) libspice.ssize_c(newsize, ctypes.byref(cell)) return cell @spiceErrorCheck def stelab(pobj, vobs): """ Correct the apparent position of an object for stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stelab_c.html :param pobj: Position of an object with respect to the observer. :type pobj: 3-Element Array of Floats. :param vobs: Velocity of the observer with respect to the Solar System barycenter. :type vobs: 3-Element Array of Floats. :return: Apparent position of the object with respect to the observer, corrected for stellar aberration. :rtype: 3-Element Array of Floats. """ pobj = stypes.toDoubleVector(pobj) vobs = stypes.toDoubleVector(vobs) appobj = stypes.emptyDoubleVector(3) libspice.stelab_c(pobj, vobs, appobj) return stypes.vectorToList(appobj) @spiceErrorCheck def stpool(item, nth, contin, lenout): """ Retrieve the nth string from the kernel pool variable, where the string may be continued across several components of the kernel pool variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stpool_c.html :param item: Name of the kernel pool variable. :type item: str :param nth: Index of the full string to retrieve. :type nth: int :param contin: Character sequence used to indicate continuation. :type contin: str :param lenout: Available space in output string. :type lenout: int :return: A full string concatenated across continuations, The number of characters in the full string value, Flag indicating success or failure of request. :rtype: tuple """ item = stypes.stringToCharP(item) contin = stypes.stringToCharP(contin) nth = ctypes.c_int(nth) strout = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) found = ctypes.c_bool() sizet = ctypes.c_int() libspice.stpool_c(item, nth, contin, lenout, strout, ctypes.byref(sizet), ctypes.byref(found)) return stypes.toPythonString(strout), sizet.value, found.value @spiceErrorCheck def str2et(time): """ Convert a string representing an epoch to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/str2et_c.html :param time: A string representing an epoch. :type time: str :return: The equivalent value in seconds past J2000, TDB. :rtype: float """ if isinstance(time, list): return numpy.array([str2et(t) for t in time]) time = stypes.stringToCharP(time) et = ctypes.c_double() libspice.str2et_c(time, ctypes.byref(et)) return et.value @spiceErrorCheck def subpnt(method, target, et, fixref, abcorr, obsrvr): """ Compute the rectangular coordinates of the sub-observer point on a target body at a specified epoch, optionally corrected for light time and stellar aberration. This routine supersedes :func:`subpt`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/subpnt_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000 TDB. :type et: float :param fixref: Body-fixed, body-centered target body frame. :type fixref: str :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :return: Sub-observer point on the target body, Sub-observer point epoch, Vector from observer to sub-observer point. :rtype: tuple """ method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) fixref = stypes.stringToCharP(fixref) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) spoint = stypes.emptyDoubleVector(3) trgepc = ctypes.c_double(0) srfvec = stypes.emptyDoubleVector(3) libspice.subpnt_c(method, target, et, fixref, abcorr, obsrvr, spoint, ctypes.byref(trgepc), srfvec) return stypes.vectorToList(spoint), trgepc.value, stypes.vectorToList( srfvec) @spiceErrorCheck def subpt(method, target, et, abcorr, obsrvr): """ Deprecated: This routine has been superseded by the CSPICE routine :func:`subpnt`. This routine is supported for purposes of backward compatibility only. Compute the rectangular coordinates of the sub-observer point on a target body at a particular epoch, optionally corrected for planetary (light time) and stellar aberration. Return these coordinates expressed in the body-fixed frame associated with the target body. Also, return the observer's altitude above the target body. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/subpt_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000 TDB. :type et: float or N-Elment Array of Floats. :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :return: Sub-observer point on the target body, Altitude of the observer above the target body. :rtype: tuple """ if hasattr(et, "__iter__"): return numpy.array( [subpt(method, target, t, abcorr, obsrvr) for t in et]) method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) spoint = stypes.emptyDoubleVector(3) alt = ctypes.c_double() libspice.subpt_c(method, target, et, abcorr, obsrvr, spoint, ctypes.byref(alt)) return stypes.vectorToList(spoint), alt.value @spiceErrorCheck def subslr(method, target, et, fixref, abcorr, obsrvr): """ Compute the rectangular coordinates of the sub-solar point on a target body at a specified epoch, optionally corrected for light time and stellar aberration. This routine supersedes subsol_c. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/subslr_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000 TDB. :type et: float :param fixref: Body-fixed, body-centered target body frame. :type fixref: str :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :return: Sub-solar point on the target body, Sub-solar point epoch, Vector from observer to sub-solar point. :rtype: tuple """ method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) fixref = stypes.stringToCharP(fixref) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) spoint = stypes.emptyDoubleVector(3) trgepc = ctypes.c_double(0) srfvec = stypes.emptyDoubleVector(3) libspice.subslr_c(method, target, et, fixref, abcorr, obsrvr, spoint, ctypes.byref(trgepc), srfvec) return stypes.vectorToList(spoint), trgepc.value, stypes.vectorToList( srfvec) @spiceErrorCheck def subsol(method, target, et, abcorr, obsrvr): """ Deprecated: This routine has been superseded by the CSPICE routine :func:`subslr`. This routine is supported for purposes of backward compatibility only. Determine the coordinates of the sub-solar point on a target body as seen by a specified observer at a specified epoch, optionally corrected for planetary (light time) and stellar aberration. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/subsol_c.html :param method: Computation method. :type method: str :param target: Name of target body. :type target: str :param et: Epoch in ephemeris seconds past J2000 TDB. :type et: float :param abcorr: Aberration correction. :type abcorr: str :param obsrvr: Name of observing body. :type obsrvr: str :return: Sub-solar point on the target body. :rtype: 3-Element Array of Floats. """ method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) abcorr = stypes.stringToCharP(abcorr) obsrvr = stypes.stringToCharP(obsrvr) spoint = stypes.emptyDoubleVector(3) libspice.subsol_c(method, target, et, abcorr, obsrvr, spoint) return stypes.vectorToList(spoint) @spiceErrorCheck def sumad(array): """ Return the sum of the elements of a double precision array. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sumad_c.html :param array: Input Array. :type array: N-Element Array of Floats. :return: The sum of the array. :rtype: float """ n = ctypes.c_int(len(array)) array = stypes.toDoubleVector(array) return libspice.sumad_c(array, n) @spiceErrorCheck def sumai(array): """ Return the sum of the elements of an integer array. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sumai_c.html :param array: Input Array. :type array: N-Element Array of Ints. :return: The sum of the array. :rtype: int """ n = ctypes.c_int(len(array)) array = stypes.toIntVector(array) return libspice.sumai_c(array, n) @spiceErrorCheck def surfnm(a, b, c, point): """ This routine computes the outward-pointing, unit normal vector from a point on the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfnm_c.html :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :param b: Length of the ellisoid semi-axis along the y-axis. :type b: float :param c: Length of the ellisoid semi-axis along the z-axis. :type c: float :param point: Body-fixed coordinates of a point on the ellipsoid' :type point: 3-Element Array of Floats. :return: Outward pointing unit normal to ellipsoid at point. :rtype: 3-Element Array of Floats. """ a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) point = stypes.toDoubleVector(point) normal = stypes.emptyDoubleVector(3) libspice.surfnm_c(a, b, c, point, normal) return stypes.vectorToList(normal) @spiceErrorCheck def surfpt(positn, u, a, b, c): """ Determine the intersection of a line-of-sight vector with the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpt_c.html :param positn: Position of the observer in body-fixed frame. :type positn: 3-Element Array of Floats. :param u: Vector from the observer in some direction. :type u: 3-Element Array of Floats. :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :param b: Length of the ellisoid semi-axis along the y-axis. :type b: float :param c: Length of the ellisoid semi-axis along the z-axis. :type c: float :return: Point on the ellipsoid pointed to by u, Found Flag. :rtype: 3-Element Array of Floats """ a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) positn = stypes.toDoubleVector(positn) u = stypes.toDoubleVector(u) point = stypes.emptyDoubleVector(3) found = ctypes.c_bool() libspice.surfpt_c(positn, u, a, b, c, point, ctypes.byref(found)) return stypes.vectorToList(point), found.value @spiceErrorCheck def surfpv(stvrtx, stdir, a, b, c): """ Find the state (position and velocity) of the surface intercept defined by a specified ray, ray velocity, and ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpv_c.html :param stvrtx: State of ray's vertex. :type stvrtx: 6-Element Array of Floats. :param stdir: State of ray's direction vector. :type stdir: 6-Element Array of Floats. :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :param b: Length of the ellisoid semi-axis along the y-axis. :type b: float :param c: Length of the ellisoid semi-axis along the z-axis. :type c: float :return: State of surface intercept, Flag indicating whether intercept state was found. :rtype: tuple """ a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) stvrtx = stypes.toDoubleVector(stvrtx) stdir = stypes.toDoubleVector(stdir) stx = stypes.emptyDoubleVector(6) found = ctypes.c_bool() libspice.surfpv_c(stvrtx, stdir, a, b, c, stx, ctypes.byref(found)) return stypes.vectorToList(stx), found.value @spiceErrorCheck def swpool(agent, nnames, lenvals, names): # Todo: test swpool """ Add a name to the list of agents to notify whenever a member of a list of kernel variables is updated. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/swpool_c.html :param agent: The name of an agent to be notified after updates. :type agent: str :param nnames: The number of variables to associate with agent. :type nnames: int :param lenvals: Length of strings in the names array. :type lenvals: int :param names: Variable names whose update causes the notice. :type names: List of strs. """ agent = stypes.stringToCharP(agent) nnames = ctypes.c_int(nnames) lenvals = ctypes.c_int(lenvals) names = stypes.listtocharvector(names) libspice.swpool_c(agent, nnames, lenvals, names) pass @spiceErrorCheck def sxform(instring, tostring, et): """ Return the state transformation matrix from one frame to another at a specified epoch. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sxform_c.html :param instring: Name of the frame to transform from. :type instring: str :param tostring: Name of the frame to transform to. :type tostring: str :param et: Epoch of the state transformation matrix. :type et: float :return: A state transformation matrix. :rtype: 6x6-Element Array of Floats. """ if hasattr(et, "__iter__"): return numpy.array([sxform(instring, tostring, t) for t in et]) instring = stypes.stringToCharP(instring) tostring = stypes.stringToCharP(tostring) et = ctypes.c_double(et) xform = stypes.emptyDoubleMatrix(x=6, y=6) libspice.sxform_c(instring, tostring, et, xform) return stypes.matrixToList(xform) @spiceErrorCheck def szpool(name): """ Return the kernel pool size limitations. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/szpool_c.html :param name: Name of the parameter to be returned. :type name: str :return: Value of parameter specified by name, Found Flag. :rtype: Int or None """ name = stypes.stringToCharP(name) n = ctypes.c_int() found = ctypes.c_bool(0) libspice.szpool_c(name, ctypes.byref(n), ctypes.byref(found)) return n.value, found.value ################################################################################ # T @spiceErrorCheck def timdef(action, item, lenout, value=None): """ Set and retrieve the defaults associated with calendar input strings. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/timdef_c.html :param action: the kind of action to take "SET" or "GET". :type action: str :param item: the default item of interest. :type item: str :param lenout: the length of list for output. :type lenout: int :param value: the optional string used if action is "SET" :type value: str :return: the value associated with the default item. :rtype: str """ action = stypes.stringToCharP(action) item = stypes.stringToCharP(item) lenout = ctypes.c_int(lenout) if value is None: value = stypes.stringToCharP(lenout) else: value = stypes.stringToCharP(value) libspice.timdef_c(action, item, lenout, value) return stypes.toPythonString(value) @spiceErrorCheck def timout(et, pictur, lenout): """ This vectorized routine converts an input epoch represented in TDB seconds past the TDB epoch of J2000 to a character string formatted to the specifications of a user's format picture. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/timout_c.html :param et: An epoch in seconds past the ephemeris epoch J2000. :type et: N-Element Array of Floats or Float :param pictur: A format specification for the output string. :type pictur: str :param lenout: The length of the output string plus 1. :type lenout: int :return: A string representation of the input epoch. :rtype: str or array of str """ if hasattr(et, "__iter__"): return numpy.array([timout(t, pictur, lenout) for t in et]) pictur = stypes.stringToCharP(pictur) output = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) et = ctypes.c_double(et) libspice.timout_c(et, pictur, lenout, output) return stypes.toPythonString(output) @spiceErrorCheck def tipbod(ref, body, et): """ Return a 3x3 matrix that transforms positions in inertial coordinates to positions in body-equator-and-prime-meridian coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tipbod_c.html :param ref: ID of inertial reference frame to transform from. :type ref: str :param body: ID code of body. :type body: int :param et: Epoch of transformation. :type et: float :return: Transformation (position), inertial to prime meridian. :rtype: 3x3-Element Array of floats. """ ref = stypes.stringToCharP(ref) body = ctypes.c_int(body) et = ctypes.c_double(et) retmatrix = stypes.emptyDoubleMatrix() libspice.tipbod_c(ref, body, et, retmatrix) return stypes.matrixToList(retmatrix) @spiceErrorCheck def tisbod(ref, body, et): """ Return a 6x6 matrix that transforms states in inertial coordinates to states in body-equator-and-prime-meridian coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tisbod_c.html :param ref: ID of inertial reference frame to transform from. :type ref: str :param body: ID code of body. :type body: int :param et: Epoch of transformation. :type et: float :return: Transformation (state), inertial to prime meridian. :rtype: 6x6-Element Array of floats. """ ref = stypes.stringToCharP(ref) body = ctypes.c_int(body) et = ctypes.c_double(et) retmatrix = stypes.emptyDoubleMatrix(x=6, y=6) libspice.tisbod_c(ref, body, et, retmatrix) return stypes.matrixToList(retmatrix) #@spiceErrorCheck def tkvrsn(item): """ Given an item such as the Toolkit or an entry point name, return the latest version string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tkvrsn_c.html :param item: Item for which a version string is desired. :type item: str :return: the latest version string. :rtype: str """ item = stypes.stringToCharP(item) return stypes.toPythonString(libspice.tkvrsn_c(item)) @spiceErrorCheck def tparse(instring, lenout): """ Parse a time string and return seconds past the J2000 epoch on a formal calendar. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tparse_c.html :param instring: Input time string, UTC. :type instring: str :param lenout: Available space in output error message string. :type lenout: int :return: Equivalent UTC seconds past J2000, Descriptive error message. :rtype: tuple """ errmsg = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) instring = stypes.stringToCharP(instring) sp2000 = ctypes.c_double() libspice.tparse_c(instring, lenout, ctypes.byref(sp2000), errmsg) return sp2000.value, stypes.toPythonString(errmsg) @spiceErrorCheck def tpictr(sample, lenout, lenerr): """ Given a sample time string, create a time format picture suitable for use by the routine timout. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tpictr_c.html :param sample: A sample time string. :type sample: str :param lenout: The length for the output picture string. :type lenout: int :param lenerr: The length for the output error string. :type lenerr: int :return: A format picture that describes sample, Flag indicating whether sample parsed successfully, Diagnostic returned if sample cannot be parsed :rtype: tuple """ sample = stypes.stringToCharP(sample) pictur = stypes.stringToCharP(lenout) errmsg = stypes.stringToCharP(lenerr) lenout = ctypes.c_int(lenout) lenerr = ctypes.c_int(lenerr) ok = ctypes.c_bool() libspice.tpictr_c(sample, lenout, lenerr, pictur, ctypes.byref(ok), errmsg) return stypes.toPythonString(pictur), ok.value, stypes.toPythonString( errmsg) @spiceErrorCheck def trace(matrix): """ Return the trace of a 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trace_c.html :param matrix: 3x3 matrix of double precision numbers. :type matrix: 3x3-Element Array of floats. :return: The trace of matrix. :rtype: float """ matrix = stypes.toDoubleMatrix(matrix) return libspice.trace_c(matrix) @spiceErrorCheck def trcdep(): """ Return the number of modules in the traceback representation. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcdep_c.html :return: The number of modules in the traceback. :rtype: int """ depth = ctypes.c_int() libspice.trcdep_c(ctypes.byref(depth)) return depth.value @spiceErrorCheck def trcnam(index, namlen): """ Return the name of the module having the specified position in the trace representation. The first module to check in is at index 0. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcnam_c.html :param index: The position of the requested module name. :type index: int :param namlen: Available space in output name string. :type namlen: int :return: The name at position index in the traceback. :rtype: str """ index = ctypes.c_int(index) name = stypes.stringToCharP(namlen) namlen = ctypes.c_int(namlen) libspice.trcnam_c(index, namlen, name) return stypes.toPythonString(name) @spiceErrorCheck def trcoff(): # Todo: test trcoff """ Disable tracing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcoff_c.html """ libspice.trcoff_c() pass @spiceErrorCheck def tsetyr(year): # Todo: test tsetyr """ Set the lower bound on the 100 year range. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tsetyr_c.html :param year: Lower bound on the 100 year interval of expansion :type year: int """ year = ctypes.c_int(year) libspice.tsetyr_c(year) pass @spiceErrorCheck def twopi(): """ Return twice the value of pi (the ratio of the circumference of a circle to its diameter). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twopi_c.html :return: Twice the value of pi. :rtype: float """ return libspice.twopi_c() @spiceErrorCheck def twovec(axdef, indexa, plndef, indexp): """ Find the transformation to the right-handed frame having a given vector as a specified axis and having a second given vector lying in a specified coordinate plane. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/twovec_c.html :param axdef: Vector defining a principal axis. :type axdef: 3-Element Array of floats. :param indexa: Principal axis number of axdef (X=1, Y=2, Z=3). :type indexa: int :param plndef: Vector defining (with axdef) a principal plane. :type plndef: 3-Element Array of floats. :param indexp: Second axis number (with indexa) of principal plane. :type indexp: int :return: Output rotation matrix. :rtype: 3x3-Element Array of floats. """ axdef = stypes.toDoubleVector(axdef) indexa = ctypes.c_int(indexa) plndef = stypes.toDoubleVector(plndef) indexp = ctypes.c_int(indexp) mout = stypes.emptyDoubleMatrix() libspice.twovec_c(axdef, indexa, plndef, indexp, mout) return stypes.matrixToList(mout) @spiceErrorCheck def tyear(): """ Return the number of seconds in a tropical year. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tyear_c.html :return: The number of seconds in a tropical year. :rtype: float """ return libspice.tyear_c() ################################################################################ # U @spiceErrorCheck def ucase(inchar, lenout=None): """ Convert the characters in a string to uppercase. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ucase_c.html :param inchar: Input string. :type inchar: str :param lenout: Optional Maximum length of output string. :type lenout: int :return: Output string, all uppercase. :rtype: str """ if lenout is None: lenout = len(inchar) + 1 inchar = stypes.stringToCharP(inchar) outchar = stypes.stringToCharP(" " * lenout) lenout = ctypes.c_int(lenout) libspice.ucase_c(inchar, lenout, outchar) return stypes.toPythonString(outchar) @spiceErrorCheck def ucrss(v1, v2): """ Compute the normalized cross product of two 3-vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ucrss_c.html :param v1: Left vector for cross product. :type v1: 3-Element Array of Floats :param v2: Right vector for cross product. :type v2: 3-Element Array of Floats :return: Normalized cross product v1xv2 / abs(v1xv2). :rtype: Array of Floats """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) vout = stypes.emptyDoubleVector(3) libspice.ucrss_c(v1, v2, vout) return stypes.vectorToList(vout) # UDDC # callback? # UDDF # callback? # UDF # callback? @spiceErrorCheck def union(a, b): """ Compute the union of two sets of any data type to form a third set. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/union_c.html :param a: First input set. :type a: SpiceyPy.support_types.SpiceCell :param b: Second input set. :type b: SpiceyPy.support_types.SpiceCell :return: Union of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert isinstance(b, stypes.SpiceCell) assert a.dtype == b.dtype assert a.dtype == 0 or a.dtype == 1 or a.dtype == 2 if a.dtype is 0: c = stypes.SPICECHAR_CELL(max(a.size, b.size), max(a.length, b.length)) elif a.dtype is 1: c = stypes.SPICEDOUBLE_CELL(max(a.size, b.size)) elif a.dtype is 2: c = stypes.SPICEINT_CELL(max(a.size, b.size)) else: raise NotImplementedError libspice.union_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def unitim(epoch, insys, outsys): """ Transform time from one uniform scale to another. The uniform time scales are TAI, TDT, TDB, ET, JED, JDTDB, JDTDT. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unitim_c.html :param epoch: An epoch to be converted. :type epoch: float :param insys: The time scale associated with the input epoch. :type insys: str :param outsys: The time scale associated with the function value. :type outsys: str :return: The float in outsys that is equivalent to the epoch on the insys time scale. :rtype: float """ epoch = ctypes.c_double(epoch) insys = stypes.stringToCharP(insys) outsys = stypes.stringToCharP(outsys) return libspice.unitim_c(epoch, insys, outsys) @spiceErrorCheck def unload(filename): """ Unload a SPICE kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unload_c.html :param filename: The name of a kernel to unload. :type filename: str """ if isinstance(filename, list): for f in filename: libspice.unload_c(stypes.stringToCharP(f)) filename = stypes.stringToCharP(filename) libspice.unload_c(filename) pass @spiceErrorCheck def unorm(v1): """ Normalize a double precision 3-vector and return its magnitude. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unorm_c.html :param v1: Vector to be normalized. :type v1: 3-Element Array of Floats :return: Unit vector of v1, Magnitude of v1. :rtype: tuple """ v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(3) vmag = ctypes.c_double() libspice.unorm_c(v1, vout, ctypes.byref(vmag)) return stypes.vectorToList(vout), vmag.value @spiceErrorCheck def unormg(v1, ndim): """ Normalize a double precision vector of arbitrary dimension and return its magnitude. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/unormg_c.html :param v1: Vector to be normalized. :type v1: N-Element Array of Floats :param ndim: This is the dimension of v1 and vout. :type ndim: int :return: Unit vector of v1, Magnitude of v1. :rtype: tuple """ v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(ndim) vmag = ctypes.c_double() ndim = ctypes.c_int(ndim) libspice.unormg_c(v1, ndim, vout, ctypes.byref(vmag)) return stypes.vectorToList(vout), vmag.value @spiceErrorCheck def utc2et(utcstr): """ Convert an input time from Calendar or Julian Date format, UTC, to ephemeris seconds past J2000. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/utc2et_c.html :param utcstr: Input time string, UTC. :type utcstr: str :return: Output epoch, ephemeris seconds past J2000. :rtype: float """ utcstr = stypes.stringToCharP(utcstr) et = ctypes.c_double() libspice.utc2et_c(utcstr, ctypes.byref(et)) return et.value ################################################################################ # V @spiceErrorCheck def vadd(v1, v2): """ Add two 3 dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vadd_c.html :param v1: First vector to be added. :type v1: 3-Element Array of Floats. :param v2: Second vector to be added. :type v2: 3-Element Array of Floats. :return: v1+v2 :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) vout = stypes.emptyDoubleVector(3) libspice.vadd_c(v1, v2, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vaddg(v1, v2, ndim): """ Add two n-dimensional vectors http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html :param v1: First vector to be added. :type v1: list[ndim] :param v2: Second vector to be added. :type v2: list[ndim] :param ndim: Dimension of v1 and v2. :type ndim: int :return: v1+v2 :rtype: list[ndim] """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) vout = stypes.emptyDoubleVector(ndim) ndim = ctypes.c_int(ndim) libspice.vaddg_c(v1, v2, ndim, vout) return stypes.vectorToList(vout) @spiceErrorCheck def valid(insize, n, inset): """ Create a valid CSPICE set from a CSPICE Cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/valid_c.html :param insize: Size (maximum cardinality) of the set. :type insize: int :param n: Initial no. of (possibly non-distinct) elements. :type n: int :param inset: Set to be validated. :return: validated set :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(inset, stypes.SpiceCell) insize = ctypes.c_int(insize) n = ctypes.c_int(n) libspice.valid_c(insize, n, inset) return inset @spiceErrorCheck def vcrss(v1, v2): """ Compute the cross product of two 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vcrss_c.html :param v1: Left hand vector for cross product. :type v1: 3-Element Array of Floats. :param v2: Right hand vector for cross product. :type v2: 3-Element Array of Floats. :return: Cross product v1 x v2. :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) vout = stypes.emptyDoubleVector(3) libspice.vcrss_c(v1, v2, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vdist(v1, v2): """ Return the distance between two three-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdist_c.html :param v1: First vector in the dot product. :type v1: 3-Element Array of Floats. :param v2: Second vector in the dot product. :type v2: 3-Element Array of Floats. :return: the distance between v1 and v2 :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) return libspice.vdist_c(v1, v2) @spiceErrorCheck def vdistg(v1, v2, ndim): """ Return the distance between two vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdistg_c.html :param v1: ndim-dimensional double precision vector. :type v1: list[ndim] :param v2: ndim-dimensional double precision vector. :type v2: list[ndim] :param ndim: Dimension of v1 and v2. :type ndim: int :return: the distance between v1 and v2 :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) ndim = ctypes.c_int(ndim) return libspice.vdistg_c(v1, v2, ndim) @spiceErrorCheck def vdot(v1, v2): """ Compute the dot product of two double precision, 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdot_c.html :param v1: First vector in the dot product. :type v1: 3-Element Array of Floats. :param v2: Second vector in the dot product. :type v2: 3-Element Array of Floats. :return: dot product of v1 and v2. :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) return libspice.vdot_c(v1, v2) @spiceErrorCheck def vdotg(v1, v2, ndim): """ Compute the dot product of two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vdotg_c.html :param v1: First vector in the dot product. :type v1: list[ndim] :param v2: Second vector in the dot product. :type v2: list[ndim] :param ndim: Dimension of v1 and v2. :type ndim: int :return: dot product of v1 and v2. :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) ndim = ctypes.c_int(ndim) return libspice.vdotg_c(v1, v2, ndim) @spiceErrorCheck def vequ(v1): """ Make one double precision 3-dimensional vector equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vequ_c.html :param v1: 3-dimensional double precision vector. :type v1: 3-Element Array of Floats. :return: 3-dimensional double precision vector set equal to vin. :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(3) libspice.vequ_c(v1, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vequg(v1, ndim): """ Make one double precision vector of arbitrary dimension equal to another. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vequg_c.html :param v1: ndim-dimensional double precision vector. :type v1: list[ndim] :param ndim: Dimension of vin (and also vout). :type ndim: int :return: ndim-dimensional double precision vector set equal to vin. :rtype: list[ndim] """ v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(ndim) ndim = ctypes.c_int(ndim) libspice.vequg_c(v1, ndim, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vhat(v1): """ Find the unit vector along a double precision 3-dimensional vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vhat_c.html :param v1: Vector to be unitized. :type v1: 3-Element Array of Floats. :return: Unit vector v / abs(v). :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(3) libspice.vhat_c(v1, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vhatg(v1, ndim): """ Find the unit vector along a double precision vector of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vhatg_c.html :param v1: Vector to be normalized. :type v1: list[ndim] :param ndim: Dimension of v1 (and also vout). :type ndim: int :return: Unit vector v / abs(v). :rtype: list[ndim] """ v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(ndim) ndim = ctypes.c_int(ndim) libspice.vhatg_c(v1, ndim, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vlcom(a, v1, b, v2): """ Compute a vector linear combination of two double precision, 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vlcom_c.html :param a: Coefficient of v1 :type a: float :param v1: Vector in 3-space :type v1: 3-Element Array of Floats. :param b: Coefficient of v2 :type b: float :param v2: Vector in 3-space :type v2: 3-Element Array of Floats. :return: Linear Vector Combination a*v1 + b*v2. :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) sumv = stypes.emptyDoubleVector(3) a = ctypes.c_double(a) b = ctypes.c_double(b) libspice.vlcom_c(a, v1, b, v2, sumv) return stypes.vectorToList(sumv) @spiceErrorCheck def vlcom3(a, v1, b, v2, c, v3): """ This subroutine computes the vector linear combination a*v1 + b*v2 + c*v3 of double precision, 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vlcom3_c.html :param a: Coefficient of v1 :type a: float :param v1: Vector in 3-space :type v1: 3-Element Array of Floats. :param b: Coefficient of v2 :type b: float :param v2: Vector in 3-space :type v2: 3-Element Array of Floats. :param c: Coefficient of v3 :type c: float :param v3: Vector in 3-space :type v3: 3-Element Array of Floats. :return: Linear Vector Combination a*v1 + b*v2 + c*v3 :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) v3 = stypes.toDoubleVector(v3) sumv = stypes.emptyDoubleVector(3) a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) libspice.vlcom3_c(a, v1, b, v2, c, v3, sumv) return stypes.vectorToList(sumv) @spiceErrorCheck def vlcomg(n, a, v1, b, v2): """ Compute a vector linear combination of two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vlcomg_c.html :param n: Dimension of vector space :type n: int :param a: Coefficient of v1 :type a: float :param v1: Vector in n-space :type v1: list[n] :param b: Coefficient of v2 :type b: float :param v2: Vector in n-space :type v2: list[n] :return: Linear Vector Combination a*v1 + b*v2 :rtype: list[n] """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) sumv = stypes.emptyDoubleVector(n) a = ctypes.c_double(a) b = ctypes.c_double(b) n = ctypes.c_int(n) libspice.vlcomg_c(n, a, v1, b, v2, sumv) return stypes.vectorToList(sumv) @spiceErrorCheck def vminug(vin, ndim): """ Negate a double precision vector of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vminug_c.html :param vin: ndim-dimensional double precision vector to be negated. :type vin: N-Element Array of Floats. :param ndim: Dimension of vin. :type ndim: int :return: ndim-dimensional double precision vector equal to -vin. :rtype: list[ndim] """ vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(ndim) ndim = ctypes.c_int(ndim) libspice.vminug_c(vin, ndim, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vminus(vin): """ Negate a double precision 3-dimensional vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vminus_c.html :param vin: Vector to be negated. :type vin: 3-Element Array of Floats. :return: Negated vector -v1. :rtype: 3-Element Array of Floats. """ vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(3) libspice.vminus_c(vin, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vnorm(v): """ Compute the magnitude of a double precision, 3-dimensional vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vnorm_c.html :param v: Vector whose magnitude is to be found. :type v: 3-Element Array of Floats. :return: magnitude of v calculated in a numerically stable way :rtype: float """ v = stypes.toDoubleVector(v) return libspice.vnorm_c(v) @spiceErrorCheck def vnormg(v, ndim): """ Compute the magnitude of a double precision vector of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vnormg_c.html :param v: Vector whose magnitude is to be found. :type v: N-Element Array of Floats. :param ndim: Dimension of v :type ndim: int :return: magnitude of v calculated in a numerically stable way :rtype: float """ v = stypes.toDoubleVector(v) ndim = ctypes.c_int(ndim) return libspice.vnormg_c(v, ndim) @spiceErrorCheck def vpack(x, y, z): """ Pack three scalar components into a vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vpack_c.html :param x: first scalar component :type x: float :param y: second scalar component :type y: float :param z: third scalar component :type z: float :return: Equivalent 3-vector. :rtype: 3-Element Array of Floats. """ x = ctypes.c_double(x) y = ctypes.c_double(y) z = ctypes.c_double(z) vout = stypes.emptyDoubleVector(3) libspice.vpack_c(x, y, z, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vperp(a, b): """ Find the component of a vector that is perpendicular to a second vector. All vectors are 3-dimensional. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vperp_c.html :param a: The vector whose orthogonal component is sought. :type a: 3-Element Array of Floats. :param b: The vector used as the orthogonal reference. :type b: 3-Element Array of Floats. :return: The component of a orthogonal to b. :rtype: 3-Element Array of Floats. """ a = stypes.toDoubleVector(a) b = stypes.toDoubleVector(b) vout = stypes.emptyDoubleVector(3) libspice.vperp_c(a, b, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vprjp(vin, plane): """ Project a vector onto a specified plane, orthogonally. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vprjp_c.html :param vin: The projected vector. :type vin: 3-Element Array of Floats. :param plane: Plane containing vin. :type plane: SpiceyPy.support_types.Plane :return: Vector resulting from projection. :rtype: 3-Element Array of Floats. """ vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(3) libspice.vprjp_c(vin, ctypes.byref(plane), vout) return stypes.vectorToList(vout) @spiceErrorCheck def vprjpi(vin, projpl, invpl): """ Find the vector in a specified plane that maps to a specified vector in another plane under orthogonal projection. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vprjpi_c.html :param vin: The projected vector. :type vin: 3-Element Array of Floats. :param projpl: Plane containing vin. :type projpl: SpiceyPy.support_types.Plane :param invpl: Plane containing inverse image of vin. :type invpl: SpiceyPy.support_types.Plane :return: (Inverse projection of vin, success) :rtype: tuple """ vin = stypes.toDoubleVector(vin) vout = stypes.emptyDoubleVector(3) found = ctypes.c_bool() libspice.vprjpi_c(vin, ctypes.byref(projpl), ctypes.byref(invpl), vout, ctypes.byref(found)) return stypes.vectorToList(vout), found.value @spiceErrorCheck def vproj(a, b): """ Find the projection of one vector onto another vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vproj_c.html :param a: The vector to be projected. :type a: 3-Element Array of Floats. :param b: The vector onto which a is to be projected. :type b: 3-Element Array of Floats. :return: The projection of a onto b. :rtype: 3-Element Array of Floats. """ a = stypes.toDoubleVector(a) b = stypes.toDoubleVector(b) vout = stypes.emptyDoubleVector(3) libspice.vproj_c(a, b, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vrel(v1, v2): """ Return the relative difference between two 3-dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrel_c.html :param v1: First vector :type v1: 3-Element Array of Floats. :param v2: Second vector :type v2: 3-Element Array of Floats. :return: the relative difference between v1 and v2. :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) return libspice.vrel_c(v1, v2) @spiceErrorCheck def vrelg(v1, v2, ndim): """ Return the relative difference between two vectors of general dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrelg_c.html :param v1: First vector :type v1: N-Element Array of Floats. :param v2: Second vector :type v2: N-Element Array of Floats. :param ndim: Dimension of v1 and v2. :type ndim: int :return: the relative difference between v1 and v2. :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) ndim = ctypes.c_int(ndim) return libspice.vrelg_c(v1, v2, ndim) @spiceErrorCheck def vrotv(v, axis, theta): """ Rotate a vector about a specified axis vector by a specified angle and return the rotated vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vrotv_c.html :param v: Vector to be rotated. :type v: 3-Element Array of Floats. :param axis: Axis of the rotation. :type axis: 3-Element Array of Floats. :param theta: Angle of rotation (radians). :type theta: float :return: Result of rotating v about axis by theta :rtype: 3-Element Array of Floats. """ v = stypes.toDoubleVector(v) axis = stypes.toDoubleVector(axis) theta = ctypes.c_double(theta) r = stypes.emptyDoubleVector(3) libspice.vrotv_c(v, axis, theta, r) return stypes.vectorToList(r) @spiceErrorCheck def vscl(s, v1): """ Multiply a scalar and a 3-dimensional double precision vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vscl_c.html :param s: Scalar to multiply a vector :type s: float :param v1: Vector to be multiplied :type v1: 3-Element Array of Floats. :return: Product vector, s*v1. :rtype: 3-Element Array of Floats. """ s = ctypes.c_double(s) v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(3) libspice.vscl_c(s, v1, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vsclg(s, v1, ndim): """ Multiply a scalar and a double precision vector of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsclg_c.html :param s: Scalar to multiply a vector :type s: float :param v1: Vector to be multiplied :type v1: N-Element Array of Floats. :param ndim: Dimension of v1 :type ndim: int :return: Product vector, s*v1. :rtype: N-Element Array of Floats. """ s = ctypes.c_double(s) v1 = stypes.toDoubleVector(v1) vout = stypes.emptyDoubleVector(ndim) ndim = ctypes.c_int(ndim) libspice.vsclg_c(s, v1, ndim, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vsep(v1, v2): """ Find the separation angle in radians between two double precision, 3-dimensional vectors. This angle is defined as zero if either vector is zero. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsep_c.html :param v1: First vector :type v1: 3-Element Array of Floats. :param v2: Second vector :type v2: 3-Element Array of Floats. :return: separation angle in radians :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) return libspice.vsep_c(v1, v2) @spiceErrorCheck def vsepg(v1, v2, ndim): """ Find the separation angle in radians between two double precision vectors of arbitrary dimension. This angle is defined as zero if either vector is zero. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsepg_c.html :param v1: First vector :type v1: N-Element Array of Floats. :param v2: Second vector :type v2: N-Element Array of Floats. :param ndim: The number of elements in v1 and v2. :type ndim: int :return: separation angle in radians :rtype: float """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) ndim = ctypes.c_int(ndim) return libspice.vsepg_c(v1, v2, ndim) @spiceErrorCheck def vsub(v1, v2): """ Compute the difference between two 3-dimensional, double precision vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsub_c.html :param v1: First vector (minuend). :type v1: 3-Element Array of Floats. :param v2: Second vector (subtrahend). :type v2: 3-Element Array of Floats. :return: Difference vector, v1 - v2. :rtype: 3-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) vout = stypes.emptyDoubleVector(3) libspice.vsub_c(v1, v2, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vsubg(v1, v2, ndim): """ Compute the difference between two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html :param v1: First vector (minuend). :type v1: N-Element Array of Floats. :param v2: Second vector (subtrahend). :type v2: N-Element Array of Floats. :param ndim: Dimension of v1, v2, and vout. :type ndim: int :return: Difference vector, v1 - v2. :rtype: N-Element Array of Floats. """ v1 = stypes.toDoubleVector(v1) v2 = stypes.toDoubleVector(v2) vout = stypes.emptyDoubleVector(ndim) ndim = ctypes.c_int(ndim) libspice.vsubg_c(v1, v2, ndim, vout) return stypes.vectorToList(vout) @spiceErrorCheck def vtmv(v1, matrix, v2): """ Multiply the transpose of a 3-dimensional column vector a 3x3 matrix, and a 3-dimensional column vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vtmv_c.html :param v1: 3 dimensional double precision column vector. :type v1: 3-Element Array of Floats. :param matrix: 3x3 double precision matrix. :type matrix: 3x3-Element Array of Floats. :param v2: 3 dimensional double precision column vector. :type v2: 3-Element Array of Floats. :return: the result of (v1**t * matrix * v2 ). :rtype: float """ v1 = stypes.toDoubleVector(v1) matrix = stypes.listtodoublematrix(matrix) v2 = stypes.toDoubleVector(v2) return libspice.vtmv_c(v1, matrix, v2) @spiceErrorCheck def vtmvg(v1, matrix, v2, nrow, ncol): """ Multiply the transpose of a n-dimensional column vector a nxm matrix, and a m-dimensional column vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vtmvg_c.html :param v1: n-dimensional double precision column vector. :type v1: N-Element Array of Floats. :param matrix: nxm double precision matrix. :type matrix: NxM-Element Array of Floats. :param v2: m-dimensional double porecision column vector. :type v2: N-Element Array of Floats. :param nrow: Number of rows in matrix (number of rows in v1.) :type nrow: int :param ncol: Number of columns in matrix (number of rows in v2.) :type ncol: int :return: the result of (v1**t * matrix * v2 ) :rtype: float """ v1 = stypes.toDoubleVector(v1) matrix = stypes.listtodoublematrix(matrix, x=ncol, y=nrow) v2 = stypes.toDoubleVector(v2) nrow = ctypes.c_int(nrow) ncol = ctypes.c_int(ncol) return libspice.vtmvg_c(v1, matrix, v2, nrow, ncol) @spiceErrorCheck def vupack(v): """ Unpack three scalar components from a vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vupack_c.html :param v: Vector :type v: 3-Element Array of Floats. :return: (x, y, z) :rtype: tuple """ v1 = stypes.toDoubleVector(v) x = ctypes.c_double() y = ctypes.c_double() z = ctypes.c_double() libspice.vupack_c(v1, ctypes.byref(x), ctypes.byref(y), ctypes.byref(z)) return x.value, y.value, z.value @spiceErrorCheck def vzero(v): """ Indicate whether a 3-vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzero_c.html :param v: Vector to be tested :type v: 3-Element Array of Floats. :return: true if and only if v is the zero vector :rtype: bool """ v = stypes.toDoubleVector(v) return libspice.vzero_c(v) @spiceErrorCheck def vzerog(v, ndim): """ Indicate whether a general-dimensional vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzerog_c.html :param v: Vector to be tested :type v: N-Element Array of Floats. :param ndim: Dimension of v :type ndim: int :return: true if and only if v is the zero vector :rtype: bool """ v = stypes.toDoubleVector(v) ndim = ctypes.c_int(ndim) return libspice.vzerog_c(v, ndim) ################################################################################ # W @spiceErrorCheck def wncard(window): """ Return the cardinality (number of intervals) of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncard_c.html :param window: Input window :type window: SpiceyPy.support_types.SpiceCell :return: the cardinality of the input window. :rtype: int """ assert isinstance(window, stypes.SpiceCell) return libspice.wncard_c(window) @spiceErrorCheck def wncomd(left, right, window): """ Determine the complement of a double precision window with respect to a specified interval. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncomd_c.html :param left: left endpoints of complement interval. :type left: float :param right: right endpoints of complement interval. :type right: float :param window: Input window :type window: SpiceyPy.support_types.SpiceCell :return: Complement of window with respect to left and right. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 left = ctypes.c_double(left) right = ctypes.c_double(right) result = stypes.SpiceCell.double(window.size) libspice.wncomd_c(left, right, ctypes.byref(window), result) return result @spiceErrorCheck def wncond(left, right, window): """ Contract each of the intervals of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wncond_c.html :param left: Amount added to each left endpoint. :type left: float :param right: Amount subtracted from each right endpoint. :type right: float :param window: Window to be contracted :type window: SpiceyPy.support_types.SpiceCell :return: Contracted Window. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 left = ctypes.c_double(left) right = ctypes.c_double(right) libspice.wncond_c(left, right, ctypes.byref(window)) return window @spiceErrorCheck def wndifd(a, b): """ Place the difference of two double precision windows into a third window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wndifd_c.html :param a: Input window A. :type a: SpiceyPy.support_types.SpiceCell :param b: Input window B. :type b: SpiceyPy.support_types.SpiceCell :return: Difference of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert isinstance(b, stypes.SpiceCell) assert a.dtype == 1 assert b.dtype == 1 c = stypes.SpiceCell.double(a.size + b.size) libspice.wndifd_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def wnelmd(point, window): """ Determine whether a point is an element of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnelmd_c.html :param point: Input point. :type point: float :param window: Input window :type window: SpiceyPy.support_types.SpiceCell :return: returns True if point is an element of window. :rtype: bool """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 point = ctypes.c_double(point) return libspice.wnelmd_c(point, ctypes.byref(window)) @spiceErrorCheck def wnexpd(left, right, window): """ Expand each of the intervals of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnexpd_c.html :param left: Amount subtracted from each left endpoint. :type left: float :param right: Amount added to each right endpoint. :type right: float :param window: Window to be expanded. :type window: SpiceyPy.support_types.SpiceCell :return: Expanded Window. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 left = ctypes.c_double(left) right = ctypes.c_double(right) libspice.wnexpd_c(left, right, ctypes.byref(window)) return window @spiceErrorCheck def wnextd(side, window): """ Extract the left or right endpoints from a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnextd_c.html :param side: Extract left "L" or right "R" endpoints. :type side: str :param window: Window to be extracted. :type window: SpiceyPy.support_types.SpiceCell :return: Extracted Window. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 assert side == 'L' or side == 'R' side = ctypes.c_char(side.encode(encoding='UTF-8')) libspice.wnextd_c(side, ctypes.byref(window)) return window @spiceErrorCheck def wnfetd(window, n): """ Fetch a particular interval from a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfetd_c.html :param window: Input window :type window: SpiceyPy.support_types.SpiceCell :param n: Index of interval to be fetched. :type n: int :return: Left, right endpoints of the nth interval. :rtype: tuple """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 n = ctypes.c_int(n) left = ctypes.c_double() right = ctypes.c_double() libspice.wnfetd_c(ctypes.byref(window), n, ctypes.byref(left), ctypes.byref(right)) return left.value, right.value @spiceErrorCheck def wnfild(small, window): """ Fill small gaps between adjacent intervals of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfild_c.html :param small: Limiting measure of small gaps. :type small: float :param window: Window to be filled :type window: SpiceyPy.support_types.SpiceCell :return: Filled Window. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 small = ctypes.c_double(small) libspice.wnfild_c(small, ctypes.byref(window)) return window @spiceErrorCheck def wnfltd(small, window): """ Filter (remove) small intervals from a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfltd_c.html :param small: Limiting measure of small intervals. :type small: float :param window: Window to be filtered. :type window: SpiceyPy.support_types.SpiceCell :return: Filtered Window. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 small = ctypes.c_double(small) libspice.wnfltd_c(small, ctypes.byref(window)) return window @spiceErrorCheck def wnincd(left, right, window): """ Determine whether an interval is included in a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnincd_c.html :param left: Left interval :type left: float :param right: Right interval :type right: float :param window: Input window :type window: SpiceyPy.support_types.SpiceCell :return: Returns True if the input interval is included in window. :rtype: bool """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 left = ctypes.c_double(left) right = ctypes.c_double(right) return libspice.wnincd_c(left, right, ctypes.byref(window)) @spiceErrorCheck def wninsd(left, right, window): """ Insert an interval into a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wninsd_c.html :param left: Left endpoints of new interval. :type left: float :param right: Right endpoints of new interval. :type right: float :param window: Input window. :type window: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 left = ctypes.c_double(left) right = ctypes.c_double(right) libspice.wninsd_c(left, right, ctypes.byref(window)) @spiceErrorCheck def wnintd(a, b): """ Place the intersection of two double precision windows into a third window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnintd_c.html :param a: Input window A. :type a: SpiceyPy.support_types.SpiceCell :param b: Input window B. :type b: SpiceyPy.support_types.SpiceCell :return: Intersection of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert b.dtype == 1 assert isinstance(b, stypes.SpiceCell) assert a.dtype == 1 c = stypes.SpiceCell.double(b.size + a.size) libspice.wnintd_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def wnreld(a, op, b): """ Compare two double precision windows. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnreld_c.html :param a: First window. :type a: SpiceyPy.support_types.SpiceCell :param op: Comparison operator. :type op: str :param b: Second window. :type b: SpiceyPy.support_types.SpiceCell :return: The result of comparison: a (op) b. :rtype: bool """ assert isinstance(a, stypes.SpiceCell) assert b.dtype == 1 assert isinstance(b, stypes.SpiceCell) assert a.dtype == 1 assert isinstance(op, str) op = stypes.stringToCharP(op.encode(encoding='UTF-8')) return libspice.wnreld_c(ctypes.byref(a), op, ctypes.byref(b)) @spiceErrorCheck def wnsumd(window): """ Summarize the contents of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnsumd_c.html :param window: Window to be summarized. :type window: SpiceyPy.support_types.SpiceCell :return: Total measure of intervals in window, Average measure, Standard deviation, Location of shortest interval, Location of longest interval. :rtype: tuple """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 meas = ctypes.c_double() avg = ctypes.c_double() stddev = ctypes.c_double() shortest = ctypes.c_int() longest = ctypes.c_int() libspice.wnsumd_c(ctypes.byref(window), ctypes.byref(meas), ctypes.byref(avg), ctypes.byref(stddev), ctypes.byref(shortest), ctypes.byref(longest)) return meas.value, avg.value, stddev.value, shortest.value, longest.value @spiceErrorCheck def wnunid(a, b): """ Place the union of two double precision windows into a third window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnunid_c.html :param a: Input window A. :type a: SpiceyPy.support_types.SpiceCell :param b: Input window B. :type b: SpiceyPy.support_types.SpiceCell :return: Union of a and b. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(a, stypes.SpiceCell) assert b.dtype == 1 assert isinstance(b, stypes.SpiceCell) assert a.dtype == 1 c = stypes.SpiceCell.double(b.size + a.size) libspice.wnunid_c(ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)) return c @spiceErrorCheck def wnvald(insize, n, window): """ Form a valid double precision window from the contents of a window array. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnvald_c.html :param insize: Size of window. :type insize: int :param n: Original number of endpoints. :type n: int :param window: Input window. :type window: SpiceyPy.support_types.SpiceCell :return: The union of the intervals in the input cell. :rtype: SpiceyPy.support_types.SpiceCell """ assert isinstance(window, stypes.SpiceCell) assert window.dtype == 1 insize = ctypes.c_int(insize) n = ctypes.c_int(n) libspice.wnvald_c(insize, n, ctypes.byref(window)) return window ################################################################################ # X @spiceErrorCheck def xf2eul(xform, axisa, axisb, axisc): """ http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xf2eul_c.html :param xform: state transformation matrix :type xform: list[6][6] :param axisa: Axis A of the Euler angle factorization. :type axisa: int :param axisb: Axis B of the Euler angle factorization. :type axisb: int :param axisc: Axis C of the Euler angle factorization. :type axisc: int :return: (eulang, unique) :rtype: tuple """ xform = stypes.listtodoublematrix(xform, x=6, y=6) axisa = ctypes.c_int(axisa) axisb = ctypes.c_int(axisb) axisc = ctypes.c_int(axisc) eulang = stypes.emptyDoubleVector(6) unique = ctypes.c_bool() libspice.xf2eul_c(xform, axisa, axisb, axisc, eulang, unique) return stypes.vectorToList(eulang), unique.value @spiceErrorCheck def xf2rav(xform): """ This routine determines the rotation matrix and angular velocity of the rotation from a state transformation matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xf2rav_c.html :param xform: state transformation matrix :type xform: list[6][6] :return: rotation associated with xform, angular velocity associated with xform. :rtype: tuple """ xform = stypes.listtodoublematrix(xform, x=6, y=6) rot = stypes.emptyDoubleMatrix() av = stypes.emptyDoubleVector(3) libspice.xf2rav_c(xform, rot, av) return stypes.matrixToList(rot), stypes.vectorToList(av) @spiceErrorCheck def xfmsta(input_state, input_coord_sys, output_coord_sys, body): """ Transform a state between coordinate systems. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xfmsta_c.html :param input_state: Input state. :type input_state: 6-Element Array of Floats. :param input_coord_sys: Current (input) coordinate system. :type input_coord_sys: str :param output_coord_sys: Desired (output) coordinate system. :type output_coord_sys: str :param body: Name or NAIF ID of body with which coordinates are associated (if applicable). :type body: str :return: Converted output state :rtype: 6-Element Array of Floats. """ input_state = stypes.toDoubleVector(input_state) input_coord_sys = stypes.stringToCharP(input_coord_sys) output_coord_sys = stypes.stringToCharP(output_coord_sys) body = stypes.stringToCharP(body) output_state = stypes.emptyDoubleVector(6) libspice.xfmsta_c(input_state, input_coord_sys, output_coord_sys, body, output_state) return stypes.vectorToList(output_state) @spiceErrorCheck def xpose(m): """ Transpose a 3x3 matrix http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose_c.html :param m: Matrix to be transposed :type m: 3x3-Element Array of Floats. :return: Transposed matrix :rtype: 3x3-Element Array of Floats. """ m = stypes.toDoubleMatrix(m) mout = stypes.emptyDoubleMatrix(x=3, y=3) libspice.xpose_c(m, mout) return stypes.matrixToList(mout) @spiceErrorCheck def xpose6(m): """ Transpose a 6x6 matrix http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xpose6_c.html :param m: Matrix to be transposed :type m: list[6][6] :return: Transposed matrix :rtype: list[6][6] """ m = stypes.toDoubleMatrix(m) mout = stypes.emptyDoubleMatrix(x=6, y=6) libspice.xpose6_c(m, mout) return stypes.matrixToList(mout) @spiceErrorCheck def xposeg(matrix, nrow, ncol): """ Transpose a matrix of arbitrary size in place, the matrix need not be square. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/xposeg_c.html :param matrix: Matrix to be transposed :type matrix: NxM-Element Array of Floats. :param nrow: Number of rows of input matrix. :type nrow: int :param ncol: Number of columns of input matrix :type ncol: int :return: Transposed matrix :rtype: NxM-Element Array of Floats. """ matrix = stypes.listtodoublematrix(matrix, x=ncol, y=nrow) mout = stypes.emptyDoubleMatrix(x=ncol, y=nrow) ncol = ctypes.c_int(ncol) nrow = ctypes.c_int(nrow) libspice.xposeg_c(matrix, nrow, ncol, mout) return stypes.matrixToList(mout)
{ "repo_name": "johnnycakes79/SpiceyPy", "path": "SpiceyPy/wrapper.py", "copies": "1", "size": "421663", "license": "mit", "hash": 561253660711987600, "line_mean": 30.3644748587, "line_max": 82, "alpha_frac": 0.6689678724, "autogenerated": false, "ratio": 3.185247016165584, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4354214888565584, "avg_score": null, "num_lines": null }
__author__ = 'Andrew Ben' class Message(): __messageId = -1 __subject = '' __body = '' __sender = '' __recipients = [] __replyOptions = [] __callbackUrl = '' def __init__(self): pass @property def messageId(self): return self.__messageId @messageId.setter def messageId(self, value): self.__messageId = value @property def messageId(self): return self.__messageId @messageId.setter def messageId(self, value): self.__messageId = value @property def subject(self): return self.__subject @subject.setter def subject(self, value): self.__subject = value @property def body(self): return self.__body @body.setter def body(self, value): self.__body = value @property def sender(self): return self.__sender @sender.setter def sender(self, value): self.__sender = value @property def recipients(self): return self.__recipients @recipients.setter def recipients(self, value): self.__recipients = value @property def replyOptions(self): return self.__replyOptions @replyOptions.setter def replyOptions(self, value): self.__replyOptions = value @property def callBackUrl(self): return self.__callbackUrl @callBackUrl.setter def callBackUrl(self, value): self.__callbackUrl = value
{ "repo_name": "onsetinc/onpage_hub_api_client_py", "path": "onpage_hub_api_client/Message.py", "copies": "1", "size": "1490", "license": "mit", "hash": -6011084843042528000, "line_mean": 17.1707317073, "line_max": 35, "alpha_frac": 0.5758389262, "autogenerated": false, "ratio": 4.257142857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.015525722484115597, "num_lines": 82 }
__author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)" __version__ = "1.5" __date__ = "2011" __copyright__ = "Creative Commons Attribution" __license__ = """The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" """ Exceptions for PyBagIt """ class BagError(Exception): """ BagIt Errors """ def __init__(self, message): self.message = message def __str__(self): return repr(self.message) class BagDoesNotExistError(BagError): pass class BagIsNotValidError(BagError): pass class BagCouldNotBeCreatedError(BagError): pass class BagFormatNotRecognized(BagError): pass class BagCheckSumNotValid(BagError): pass class BagFileDownloadError(BagError): pass
{ "repo_name": "WoLpH/pybagit", "path": "pybagit/exceptions.py", "copies": "1", "size": "1960", "license": "mit", "hash": 7487800217309598000, "line_mean": 31.131147541, "line_max": 93, "alpha_frac": 0.6591836735, "autogenerated": false, "ratio": 4.666666666666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5825850340166667, "avg_score": null, "num_lines": null }
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' import calendar import collections import datetime import functools import logging import re import threading import time LOG = logging.getLogger(__name__) DAY_NAME = dict((v.lower(),k) for k,v in enumerate(calendar.day_name)) #(ex: Monday, Tuesday, etc) DAY_ABBR = dict((v.lower(),k) for k,v in enumerate(calendar.day_abbr)) #(ex: Mon, Tue, etc) MON_NAME = dict((v.lower(),k) for k,v in enumerate(calendar.month_name)) #(ex: January, February, etc) MON_ABBR = dict((v.lower(),k) for k,v in enumerate(calendar.month_abbr)) #(ex: Jan, Feb, etc) PHRASES = dict(DAY_NAME.items() + DAY_ABBR.items() + MON_NAME.items() + MON_ABBR.items()) PHRASES_REGEX = re.compile('|'.join(PHRASES.keys()).lstrip('|'), flags=re.IGNORECASE) class CronField(object): SPECIALS = set(['*', '/', '%', ',', '-', 'L', 'W', '#', '?']) def __init__(self, *args): self.value, self.min, self.max, self.specials = args if isinstance(self.value, (int, long)): #numbers must be within bounds if not self.min <= self.value <= self.max: raise ValueError('Value must be between {0} and {1}'.format(self.min, self.max)) if isinstance(self.value, basestring): #sub name/abbr for month/dayofweek self.value = CronField.sub_english_phrases(self.value) invalid_chars = self.SPECIALS.difference(self.specials).intersection(set(self.value)) if invalid_chars: raise ValueError('Field contains invalid special characters: {0}'.format(','.join(invalid_chars))) elif isinstance(self.value, collections.Iterable): #sort iterables self.value = sorted(self.value) def __repr__(self): return '<CronField: {0}>'.format(self) def __str__(self): if isinstance(self.value, collections.Iterable) and len(self.value) >= 5: return '[{0}...{1}]'.format(self.value[0], self.value[-1]) return str(self.value) def __contains__(self, item): """ Determines if the given time is 'within' the time denoted by this individual field. """ value = self.value if isinstance(value, (int, long)): #standard numeric (python obj) return value == item if isinstance(value, basestring): result = False for value in value.split(','): #comma separated values (ex: 1,4,10) value = re.split(r'[-/]', value) #separate range and step characters if len(value) == 1: if value[0] == '*': #single wildcard (ex: *) return self.min <= item <= self.max result |= int(value[0]) == item #single digit (ex: 10) continue if value[0] == '*': #wildcard w/ step (ex: */2 ==> 0-59/2) value = [self.min, self.max, value[1]] start, stop = sorted(map(int, value[:2])) #range (ex: 0-10) step = int(value[2]) if len(value) > 2 else None #range w/ step (ex: 0-10/2) result |= start <= item <= stop and (not step or (item + start) % step == 0) return result if isinstance(value, collections.Iterable): #iterable (assumed range() python obj) return item in value @staticmethod def sub_english_phrases(value): """ Replace any full or abbreviated english dow/mon phrases (Jan, Monday, etc) from the field value with its respective integer representation. """ def _repl(match): return str(PHRASES[match.group(0).lower()]) return PHRASES_REGEX.sub(_repl, str(value)) #funcs for field creation so we don't need to subclass CronField with min/max/specials sec = lambda v: CronField(v, 0, 59, set(['*', '/', ',', '-'])) minu = lambda v: CronField(v, 0, 59, set(['*', '/', ',', '-'])) hr = lambda v: CronField(v, 0, 23, set(['*', '/', ',', '-'])) dom = lambda v: CronField(v, 1, 31, set(['*', '/', ',', '-', '?', 'L', 'W'])) mon = lambda v: CronField(v, 1, 12, set(['*', '/', ',', '-'])) dow = lambda v: CronField(v, 0, 6, set(['*', '/', ',', '-', '?', 'L', '#'])) yr = lambda v: CronField(v, 1970, 2099, set(['*', '/', ',', '-'])) class CronExpression(object): STRUCT_TIME = ('year', 'month', 'day', 'hour', 'minute', 'second', 'weekday') #time.struct_time fields FIELD_NAMES = ('second', 'minute', 'hour', 'day', 'month', 'weekday', 'year', 'expr') #supported kwargs FIELDS = dict(zip(FIELD_NAMES, (sec, minu, hr, dom, mon, dow, yr))) #field name->init func KEYWORDS = {'@yearly': '0 0 0 1 1 *', '@annually': '0 0 0 1 1 *', '@monthly': '0 0 0 1 * *', '@weekly': '0 0 0 * * 0', '@daily': '0 0 0 * * *', '@hourly': '0 0 * * * *', '@minutely': '0 * * * * *', '@reboot': None} #TODO def __init__(self, **kwargs): #this line is bugged #expression = self.KEYWORDS.get(kwargs.get('expr'), '* * * * * * *') #correction @Simon Gwerder expr = kwargs.get('expr') if expr in self.KEYWORDS: expression = self.KEYWORDS[expr] else: # actually would have to valid check pattern here. expression = expr expression = dict(zip(self.FIELD_NAMES, expression.split())) for field, ctor in self.FIELDS.items(): setattr(self, field, ctor(kwargs.get(field, expression.get(field, '*')))) def __repr__(self): return '<CronExpression: {0}>'.format(self) def __str__(self): return '{second} {minute} {hour} {day} {month} {weekday} {year}'.format(**self.__dict__) def __contains__(self, item): #item should always be a datetime #XXX confirm and revise if not isinstance(item, datetime.datetime): #hrm return False item = dict(zip(self.STRUCT_TIME, item.timetuple()[:7])) return all(item[k] in v for k,v in self.__dict__.items()) class CronTab(threading.Thread): def __init__(self, *args, **kwargs): super(CronTab, self).__init__(*args, **kwargs) self.name = kwargs.get('name', 'CronTab ({0})'.format(id(self))) self.daemon = True self.jobs = {} self.proc_event = threading.Event() self.stop_event = threading.Event() def register(self, name, job): self.jobs[name] = job self.proc_event.set() def deregister(self, name): if name in self.jobs: del self.jobs[name] if len(self.jobs) == 0: self.proc_event.clear() def stop(self): self.stop_event.set() self.proc_event.clear() def run(self): LOG.debug('{0} started.'.format(self.name)) try: while True: self.proc_event.wait() if self.stop_event.is_set(): LOG.info('{0} stopped.'.format(self.name)) return now = datetime.datetime.now() for _, job in self.jobs.items(): if now in job.cron: threading.Thread(target=job).start() time.sleep(1) except Exception: LOG.exception('{0} encountered unhandled exception. '.format(self.name)) tab = CronTab() def job(*args, **kwargs): ctab = kwargs.pop('tab', tab) on_success = kwargs.pop('on_success', lambda ctx: None) on_failure = kwargs.pop('on_failure', lambda ctx: None) cron = CronExpression(**kwargs) fargs = dict((k, kwargs[k]) for k in kwargs.keys() if k not in CronExpression.FIELD_NAMES) #func specific kwargs def decorator(func): @functools.wraps(func) def f(): try: return on_success(func(*args, **fargs)) except Exception as e: return on_failure(e) f.cron = cron f.name = func.name = '.'.join((func.__module__ or '__main__', func.__name__)) ctab.register(f.name, f) return f return decorator
{ "repo_name": "geometalab/OSMTagFinder", "path": "OSMTagFinder/utilities/crython.py", "copies": "1", "size": "8408", "license": "mit", "hash": -7479666036155662000, "line_mean": 43.2526315789, "line_max": 116, "alpha_frac": 0.5309229305, "autogenerated": false, "ratio": 3.681260945709282, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4712183876209282, "avg_score": null, "num_lines": null }
__author__ = 'Andrew Hawker <andrew.r.hawker@gmail.com>' import calendar import functools import logging import re import datetime import threading import collections import multiprocessing import time LOG = logging.getLogger(__name__) DAY_NAME = dict((v.lower(),k) for k,v in enumerate(calendar.day_name)) #(ex: Monday, Tuesday, etc) DAY_ABBR = dict((v.lower(),k) for k,v in enumerate(calendar.day_abbr)) #(ex: Mon, Tue, etc) MON_NAME = dict((v.lower(),k) for k,v in enumerate(calendar.month_name)) #(ex: January, February, etc) MON_ABBR = dict((v.lower(),k) for k,v in enumerate(calendar.month_abbr)) #(ex: Jan, Feb, etc) PHRASES = dict(list(DAY_NAME.items()) + list(DAY_ABBR.items()) + list(MON_NAME.items()) + list(MON_ABBR.items())) # MON_NAME and MON_ABBR contains ('', 0) # it will cause random behavior in sub_english_phrases if '' in PHRASES: del PHRASES[''] PHRASES_REGEX = re.compile('|'.join(list(PHRASES.keys())).lstrip('|'), flags=re.IGNORECASE) class CronField(object): SPECIALS = set(['*', '/', '%', ',', '-', 'L', 'W', '#', '?']) def __init__(self, *args): self.value, self.min, self.max, self.specials = args if isinstance(self.value, int): #numbers must be within bounds if not self.min <= self.value <= self.max: raise ValueError('Value must be between {0} and {1}'.format(self.min, self.max)) if isinstance(self.value, str): #sub name/abbr for month/dayofweek self.value = CronField.sub_english_phrases(self.value) invalid_chars = self.SPECIALS.difference(self.specials).intersection(set(self.value)) if invalid_chars: raise ValueError('Field contains invalid special characters: {0}'.format(','.join(invalid_chars))) elif isinstance(self.value, collections.Iterable): #sort iterables self.value = sorted(self.value) def __repr__(self): return '<CronField: {0}>'.format(self) def __str__(self): return str(self.value) def __contains__(self, item): """ Determines if the given time is 'within' the time denoted by this individual field. """ year,month = None,None value = self.value if isinstance(value, int): #standard numeric (python obj) return value == item if isinstance(value, str): result = False for value in value.split(','): #comma separated values (ex: 1,4,10) value = re.split(r'[-/]', value) #separate range and step characters if len(value) == 1: value = value[0] if value == '*': #single wildcard (ex: *) return self.min <= item <= self.max if value == 'L': #last day of month (ex: L ==> 31) return self.max == item #TODO: last_dom not necessary to be max (feb) result |= int(value) == item #single digit (ex: 10) continue if value[0] == '*': #wildcard w/ step (ex: */2 ==> 0-59/2) value = [self.min, self.max, value[1]] if value[1] == 'L': #last weekday of month (ex: 5L ==> last fri) last_dom = calendar.monthrange(year, month)[-1] start, stop = sorted(map(int, value[:2])) #range (ex: 0-10) step = int(value[2]) if len(value) > 2 else None #range w/ step (ex: 0-10/2) result |= start <= item <= stop and (not step or (item + start) % step == 0) return result if isinstance(value, collections.Iterable): #iterable (assumed range() python obj) return item in value def __eq__(self, other): return self.value == other @staticmethod def sub_english_phrases(value): """ Replace any full or abbreviated english dow/mon phrases (Jan, Monday, etc) from the field value with its respective integer representation. """ def _repl(match): return str(PHRASES[match.group(0).lower()]) return PHRASES_REGEX.sub(_repl, str(value)) #funcs for field creation so we don't need to subclass CronField with min/max/specials sec = lambda v: CronField(v, 0, 59, set(['*', '/', ',', '-'])) min = lambda v: CronField(v, 0, 59, set(['*', '/', ',', '-'])) hr = lambda v: CronField(v, 0, 23, set(['*', '/', ',', '-'])) dom = lambda v: CronField(v, 1, 31, set(['*', '/', ',', '-', '?', 'L', 'W'])) mon = lambda v: CronField(v, 1, 12, set(['*', '/', ',', '-'])) dow = lambda v: CronField(v, 0, 6, set(['*', '/', ',', '-', '?', 'L', '#'])) yr = lambda v: CronField(v, 1970, 2099, set(['*', '/', ',', '-'])) class CronExpression(object): STRUCT_TIME = ('year', 'month', 'day', 'hour', 'minute', 'second', 'weekday') #time.struct_time fields FIELD_NAMES = ('second', 'minute', 'hour', 'day', 'month', 'weekday', 'year', 'expr') #supported kwargs FIELDS = dict(list(zip(FIELD_NAMES, (sec, min, hr, dom, mon, dow, yr)))) #field name->init func KEYWORDS = {'@yearly': '0 0 0 0 1 1 *', '@annually': '0 0 0 0 1 1 *', '@monthly': '0 0 0 0 1 * *', '@weekly': '0 0 0 0 * 0 *', '@daily': '0 0 0 * * * *', '@hourly': '0 0 * * * * *', '@minutely': '0 * * * * * *'} def __init__(self, **kwargs): expression = kwargs.get('expr', '* * * * * * *') expression = self.KEYWORDS.get(expression, expression) expression = dict(list(zip(self.FIELD_NAMES, expression.split()))) for field, ctor in list(self.FIELDS.items()): setattr(self, field, ctor(kwargs.get(field, expression.get(field, '*')))) def __repr__(self): return '<CronExpression: {0}>'.format(self) def __str__(self): return '{second} {minute} {hour} {day} {month} {weekday} {year}'.format(**self.__dict__) def __contains__(self, item): #item should always be a datetime #XXX confirm and revise if not isinstance(item, datetime.datetime): #hrm return False item = dict(list(zip(self.STRUCT_TIME, item.timetuple()[:7]))) return all(item[k] in v for k,v in list(self.__dict__.items())) def __eq__(self, other): if isinstance(other, str): other = CronExpression(expr=other) if not isinstance(other, CronExpression): return False return all(getattr(other, k) == v for (k,v) in list(self.__dict__.items())) class CronTab(threading.Thread): CONTEXTS = {'thread': lambda job: threading.Thread(target=job).start(), 'process': lambda job: multiprocessing.Process(target=job).start()} def __init__(self, *args, **kwargs): super(CronTab, self).__init__(*args, **kwargs) self.name = kwargs.get('name', 'CronTab ({0})'.format(id(self))) self.daemon = True self.jobs = {} self.proc_event = threading.Event() self.stop_event = threading.Event() def register(self, name, job): self.jobs[name] = job self.proc_event.set() def deregister(self, name): if name in self.jobs: del self.jobs[name] if not len(self.jobs): self.proc_event.clear() def stop(self): self.stop_event.set() self.proc_event.clear() def run(self): LOG.info('{0} started.'.format(self.name)) try: self.proc_event.wait() for job in (self.jobs.pop(k) for (k,v) in list(self.jobs.items()) if v.reboot): self.CONTEXTS[job.ctx](job) while True: self.proc_event.wait() if self.stop_event.is_set(): LOG.info('{0} stopped.'.format(self.name)) break now = datetime.datetime.now() for _, job in list(self.jobs.items()): if now in job.cron: self.CONTEXTS[job.ctx](job) time.sleep(1) except Exception: LOG.exception('{0} encountered unhandled exception. '.format(self.name)) tab = CronTab(name='global') def job(*args, **kwargs): crontab = kwargs.pop('tab', tab) ctx = kwargs.pop('ctx', 'thread') on_success = kwargs.pop('on_success', lambda ctx: None) on_failure = kwargs.pop('on_failure', lambda ctx: None) fkwargs = dict((k, kwargs[k]) for k in list(kwargs.keys()) if k not in CronExpression.FIELD_NAMES) #func specific kwargs def decorator(func): @functools.wraps(func) def f(): try: return on_success(func(*args, **fkwargs)) except Exception as e: return on_failure(e) f.cron = CronExpression(**kwargs) f.ctx = ctx f.name = func.name = '.'.join((func.__module__ or '__main__', func.__name__)) f.reboot = kwargs.get('expr', '') == '@reboot' crontab.register(f.name, f) return f return decorator
{ "repo_name": "Answeror/yacron", "path": "yacron/crython/crython.py", "copies": "1", "size": "9429", "license": "mit", "hash": -4224911497168276500, "line_mean": 44.3317307692, "line_max": 124, "alpha_frac": 0.5290062573, "autogenerated": false, "ratio": 3.706367924528302, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4735374181828302, "avg_score": null, "num_lines": null }
#__all__ = ['Ugraph', 'GraphMatcher', 'DFS', 'GenError', 'GraphError', 'Disconnected', 'NotUndirected'] import sys import copy from operator import itemgetter class GenError(Exception): """ An exception class containing string for error reporting. """ def __init__(self, err_msg): self.err_msg = err_msg def __str__(self): return self.err_msg def __repr__(self): return str(self) class GraphError(GenError): """ An exception class containing a graph and a string for error reporting. """ def __init__(self, g, err_msg): GenError.__init__(self, err_msg) self.g = g def __str__(self): g_str = str(g) # If the string representation of the graph is too # large to fit in one screen, truncate it g_str_lines = g_str.split('\n') if (len(g_str_lines) > 12): g_str_lines = g_str_lines[0:12] + \ [' ...(additional lines not shown)]'] g_str = '\n'.join(g_str_lines) return 'Problem with graph:\n' + g_str + '\n' + self.err_msg def __repr__(self): return str(self) class Disconnected(GraphError): def __init__(self, g, err_msg): GraphError.__init__(self, g, err_msg) class NotUndirected(GraphError): def __init__(self, g, err_msg): GraphError.__init__(self, g, err_msg) class Edge(object): __slots__ = ["start", "stop", "attr"] def __init__(self, iv_start, # edge starts here (index into vertex list) iv_stop, # edge ends here (index into vertex list) attr=None): # edges have an optional type attribute self.start = iv_start self.stop = iv_stop self.attr = attr def __str__(self): return '(' + str(self.start) + ',' + str(self.stop) + ')' def __repr__(self): return str(self) class Vertex(object): __slots__ = ["attr"] def __init__(self, attr=None): self.attr = attr class Dgraph(object): """ This class is a minimal implementation of a directed graph. Vertices and edges are accessed by integer index only (beginning at 0). Multiple edges connecting the same pair of vertices are allowed. (One would use the AddEdge() member function to accomplish this.) Both vertices and edges have an optional "attr" attribute. """ NULL = -1 # forbidden vertex id number (used several places) def __init__(self, edgelist=None): """ The constructor accepts an optional neighborlist argument. This is a simple list of neighbors for every vertex in the graph and it completely defines the topology of the graph. (Vertex and edge attributes can be specified later.) Alternatley, you can leave the neighborlist argument blank, and build the graph one vertex at a time later using the "AddVertex()" and "AddEdge()" commands. (AddEdge() commands must be issued strictly after all vertices have been defined.) """ if edgelist == None: self.verts = [] self.edges = [] # integer keeps track of # of vertices = len(self.verts) self.nv = 0 # integer keeps track of # of edges = len(self.edges) self.ne = 0 self.neighbors = [] # The adjacency list. else: # Parse the edge-list format: iv_max = 0 # <-- what's the vertex with the maximum id number? for i in range(0, len(edgelist)): iv = edgelist[i][0] jv = edgelist[i][1] if ((iv < 0) or (jv < 0)): raise(GenError( 'Error in Dgraph.__init__: Negative vertex number pair encountered: (' + str(iv) + ',' + str(jv) + ')')) if iv > iv_max: iv_max = iv if jv > iv_max: iv_max = jv self.nv = iv_max + 1 self.verts = [Vertex() for iv in range(0, self.nv)] self.edges = [] self.ne = 0 self.neighbors = [[] for iv in range(0, self.nv)] for i in range(0, len(edgelist)): iv = edgelist[i][0] jv = edgelist[i][1] self.neighbors[iv].append(self.ne) self.edges.append(Edge(iv, jv)) self.ne += 1 assert(self.ne == len(self.edges)) self.SortNeighborLists() def AddVertex(self, iv=-1, attr=None): """ Add a vertex to the graph. (Edges connected to this vertex must be added later using "AddEdge()" All vertices should be added before "AddEdge()" is ever invoked.) Optional "attr" argument allows you to set the attribute of this vertex. (for example, in a molecule this might correspond to the type of atom in the molecule). Optional "iv" argument allows you to specify the index of that vertex. Vertices can be added in any order, but thei vertex id numbers should eventually fill the range from 0 to self.nv-1. """ if iv == -1: # if iv unspecified, put the vertex at the end of the list iv = self.nv if iv < self.nv: self.verts[iv].attr = attr else: # In case there is a gap between iv and nv, fill it with blanks self.verts += ([Vertex()] * ((1 + iv) - self.nv)) self.neighbors += ([[]] * ((1 + iv) - self.nv)) self.verts[iv].attr = attr self.nv = iv + 1 assert(self.nv == len(self.verts)) assert(self.nv == len(self.neighbors)) def AddEdge(self, iv, jv, attr=None, remove_duplicates=False): """ Add an edge to graph connecting vertex iv to jv. (both are integers from 0 to self.nv-1) This function must not be called until all vertices have been added. If the edge is already present (and remove_duplicates==True), no new edge will be added. """ if remove_duplicates: for je in self.neighbors[iv]: if jv == self.edges[je].stop: return # In that case, do nothing, the edge is already present self.edges.append(Edge(iv, jv, attr)) self.neighbors[iv].append(self.ne) self.ne += 1 assert(self.ne == len(self.edges)) def ReorderVerts(self, vpermutation, invert=False): """ This function allows the user to re-order (relabel) the vertices in a graph, making the necessary changes to the self.verts, self.edges, and self.neighbors lists. By default (invert=False). The vpermutation is a list from 1 to self.nv which is interpreted this way: iv = vpermutation[iv_orig] where "iv" and "iv_orig" are the vertex id numbers before and after the mapping (which also corresponds to its position in the self.verts and self.neighbors arrays). """ assert(len(self.verts) == self.nv) assert(len(self.edges) == self.ne) assert(len(vpermutation) == self.nv) if (invert): vperm = [-1 for iv in vpermutation] for iv in range(0, self.nv): vperm[vpermutation[iv]] = iv else: vperm = vpermutation orig_verts = [vert for vert in self.verts] for iv_old in range(0, self.nv): iv = vperm[iv_old] self.verts[iv] = orig_verts[iv_old] for ie in range(0, self.ne): self.edges[ie].start = vperm[self.edges[ie].start] self.edges[ie].stop = vperm[self.edges[ie].stop] orig_neighbors = [nlist for nlist in self.neighbors] # self.neighbors is a 2-d array. # We need to re-sort "self.neighbors" because the first index is # a vertex id number, and these id numbers have been permuted. # However, there's no need to sort the contents of each sub-array # (self.neighbors[iv]), because these are edge id numbers (indices into # the self.edges[] array). These edge index numbers are never altered. # (However the entries stored in self.edges were modified earlier.) for iv_old in range(0, self.nv): iv = vperm[iv_old] self.neighbors[iv] = orig_neighbors[iv_old] # Optional: self.SortNeighborLists() def ReorderEdges(self, epermutation, invert=False): """ This function allows the user to re-order (relabel) the edges in a graph, making the necessary changes to the self.edges and self.neighbors lists. By default (invert=False). The epermutation is a list from 1 to self.ne which is interpreted this way: ie = epermutation[ie_orig] where "ie" and "ie_orig" are the edge id numbers before and after the mapping (which also corresponds to that edge's position in the self.edges array). (Minor detail: Recall that in this code, Ugraphs are implemented by placing two (directed) edges between each pair of connected, adjacent vertices, which point back-and-forth between them. Consequently the list of edges in self.edges is often typically twice as large you might expect.) """ assert(len(self.verts) == self.nv) assert(len(self.edges) == self.ne) assert(len(epermutation) == self.ne) if (invert): eperm = [-1 for ie in epermutation] for ie in range(0, self.ne): eperm[epermutation[ie]] = ie else: eperm = epermutation orig_edges = [edge for edge in self.edges] for ie_old in range(0, self.ne): ie = eperm[ie_old] self.edges[ie] = orig_edges[ie_old] for iv in range(0, self.nv): for j in range(0, len(self.neighbors[iv])): je_old = self.neighbors[iv][j] self.neighbors[iv][j] = eperm[je_old] def SortNeighborLists(self): assert(self.nv == len(self.neighbors)) for iv in range(0, self.nv): # Back when self.neighbors was just a 2-dimensional list of # vertex id numbers, then the following line would have worked: # self.neighbors[iv].sort() # ugly python code alert: # Unfortunately, we had to change the format of self.neighbors. Now # it is a list of indices into the self.edges array ("ie" numbers). # We want to sort the "ie" numbers by the vertices they point to. # self.edge[ie].start should point to the current vertex (hopefully). # self.edge[ie].stop should point to the vertex it's attached to. # So we want to sort the ie's in self.neighbors by self.edge[ie].stop # Create a temporary array of 2-tuples (ie, jv) nlist = [(ie, self.edges[ie].stop) for ie in self.neighbors[iv]] self.neighbors[iv] = [ie for ie, jv in sorted(nlist, key=itemgetter(1))] def FindEdge(self, istart, istop): """ A simple function looks up the edge id number corresponding to an edge connecting vertex istart to istop. If not present returns Dgraph.NULL. """ iv = istart for je in self.neighbors[iv]: jv = self.edges[je].stop if jv == istop: return je return Dgraph.NULL def GetVert(self, iv): return self.verts[iv] def GetEdge(self, ie): return self.edges[ie] def GetNumVerts(self): return self.nv def GetNumEdges(self): return self.ne # Commenting out. I think it's clearer to use python's deepcopy instead # def makecopy(self): # new_copy = Ugraph() # new_copy.verts = [vertex for vertex in self.verts] # new_copy.edges = [ edge for edge in self.edges] # new_copy.neighbors = [nlist for nlist in self.neighbors] # new_copy.nv = self.nv # new_copy.ne = self.ne # return new_copy def __str__(self): # Print the graph as a list of neighbor-lists. # (Note: This is the same format as the first argument to __init__(). # The Vertex.attr and Edge.attr attributes are not printed.) l = ['(['] for iv in range(0, self.nv): l.append('[') for j in range(0, len(self.neighbors[iv])): je = self.neighbors[iv][j] jv = self.edges[je].stop l.append(str(jv)) if j < len(self.neighbors[iv]) - 1: l.append(', ') else: l.append(']') if iv < self.nv - 1: l.append(',\n ') else: l.append(']') l.append(',\n [') for ie in range(0, self.ne): l.append(str(self.edges[ie])) if ie < self.ne - 1: l.append(', ') else: l.append('])\n') return ''.join(l) def __repr__(self): return str(self) class Ugraph(Dgraph): """ This class is a minimal implementation of an undirected graph. Vertices and edges are accessed by integer index only (beginning at 0). Multiple edges connecting the same pair of vertices are allowed. (One would use the AddEdge() member function to accomplish this.) Both vertices and edges have an optional "attr" attribute. Undirected graphs (Ugraphs) are represented internally as directed graphs. This means that for every edge in the Ugraph, connecting vertex 2 to 3, for example, two edges are stored internally, (2 -> 3, and 3 -> 2), Edges which begin and end at the same vertex are stored only once.) """ def __init__(self, edgelist=None): Dgraph.__init__(self, edgelist) # Now add the extra edges which point in the reverse direction. neu = self.ne ned = self.ne for ieu in range(0, self.ne): iv = self.edges[ieu].start jv = self.edges[ieu].stop if iv != jv: ned += 1 self.ieu_to_ied = [Dgraph.NULL for ieu in range(0, neu)] self.ied_to_ieu = [Dgraph.NULL for ied in range(0, ned)] ied_redundant = neu for ie in range(0, neu): iv = self.edges[ie].start jv = self.edges[ie].stop attr = self.edges[ie].attr self.ieu_to_ied[ie] = ie self.ied_to_ieu[ie] = ie if iv != jv: # Then create another edge which points in the reverse direction # <--this increments self.ne Dgraph.AddEdge(self, jv, iv, attr) self.ied_to_ieu[ied_redundant] = ie ied_redundant += 1 self.neu = neu assert(self.ne == ned) def AddEdge(self, iv, jv, attr=None, remove_duplicates=False): """ Add an edge to an undirected graph connecting vertices iv and jv. If the edge is already present (and remove_duplicates==True), no new edge will be added. Note: Undirected Ugraphs are implemented by creating two separate digraph edges that conect iv->jv and jv->iv. """ self.ieu_to_ied.append(len(self.edges)) Dgraph.AddEdge(self, iv, jv, attr, remove_duplicates) self.ied_to_ieu.append(self.neu) if jv != iv: Dgraph.AddEdge(self, jv, iv, attr, remove_duplicates) self.ied_to_ieu.append(self.neu) self.neu += 1 assert(len(self.ieu_to_ied) == self.neu) assert(len(self.ied_to_ieu) == len(self.edges)) def ReorderEdges(self, epermutation, invert=False): Dgraph.ReorderEdges(self, epermutation, invert) # Now update the # self.ieu_to_ied and # self.ied_to_ieu lookup tables: if (invert): # (first invert the permutation if necessary) eperm = [-1 for ie in epermutation] for ie in range(0, self.ne): eperm[epermutation[ie]] = ie else: eperm = epermutation # epermutation.reverse() ieu_to_ied_orig = [ied for ied in self.ieu_to_ied] ied_to_ieu_orig = [ieu for ieu in self.ied_to_ieu] for ieu in range(0, self.neu): ied_old = ieu_to_ied_orig[ieu] ied = eperm[ied_old] self.ieu_to_ied[ieu] = ied for ied_old in range(0, self.ne): ieu = ied_to_ieu_orig[ied_old] ied = eperm[ied_old] self.ied_to_ieu[ied] = ieu eperm = epermutation def LookupDirectedEdgeIdx(self, ieu): return self.ieu_to_ied[ieu] def LookupUndirectedEdgeIdx(self, ied): return self.ied_to_ieu[ied] # def GetVert(self, iv): <-- (inherited from parent) # return self.verts[iv] def GetEdge(self, ieu): ied = self.ieu_to_ied[ieu] return self.edges[ied] # def GetNumVerts(self): <-- (inherited from parent) # return self.nv def GetNumEdges(self): return self.neu def FindEdge(self, istart, istop): """ A simple function looks up the (undirected) edge id number corresponding to an edge connecting vertices istart and istop. If not present returns Dgraph.NULL. To find the corresponding entry in the self.edges[] list, you can either: use the LookupDirectedEdge() lookup function or you can use the parent-class' version of this function Dgraph.FindEdge(self, istart, istop) which returns this number by default. """ ied = Dgraph.FindEdge(self, istart, istop) ieu = self.LookupUndirectedEdgeIdx(ied) return ieu def CalcEdgeLookupTable(self): """ COMMENT: THIS NEXT FUNCTION IS PROBABLY NOT NECESSARY AND MIGHT BE REMOVED AT A LATER TIME WHEN I FIGURE OUT A BETTER WAY. Because undirected graphs (Ugraphs) are implemented as directed graphs (Dgraphs) with redundant edges, they may have some extra edges which the user never explicitly asked for. There is some confusion about whether the i'th edge refers to the i'th undirected edge that the user explicitly added, or the i'th directed edge which is stored internally. (The number of directed edges is usually twice the number of edges that the user asked for. But not always, because edges wich start and end at the same vertex are only represented once.) This function calculates lookup tables to translate between the two edge numbering systems: self.ieu_to_ied[ieu] returns a directed edge id number, (which is an index into the self.edges list) corresponding to the ieu'th undirected edge which was explicitly added by the caller. self.ied_to_ieu[ied] takes a directed edge id number (ied, an index into the self.edges list) and returns the undirected edge number, which is allways <= ied """ self.ieu_to_ied = [] self.ied_to_ieu = [Ugraph.NULL for ied in range(0, self.ne)] for ied in range(0, self.ne): iv = self.edges[ied].start jv = self.edges[ied].stop ieu = len(self.ieu_to_ied) self.ied_to_ieu[ied] = ieu if iv <= jv: self.ieu_to_ied.append(ied) def SortVertsByDegree(g): vert_numneighbors = [(iv, len(g.neighbors[iv])) for iv in range(0, g.nv)] vert_numneighbors.sort(key=itemgetter(1)) order = [vert_numneighbors[iv][0] for iv in range(0, g.nv)] g.ReorderVerts(order, invert=True) class DFS(object): """ This class contains a member function (Order()) calculates the order of vertices visited in a depth-first-search over a connected graph. """ def __init__(self, g): self.g = g self.sv = 0 # integer sv keeps track of how many vertices visited so far self.se = 0 # integer se keeps track of how many edges visited so far self.vvisited = [False for iv in range(0, self.g.nv)] # verts visited self.vorder = [Dgraph.NULL for iv in range( 0, self.g.nv)] # search order self.evisited = [False for ie in range(0, self.g.ne)] # edges visited self.eorder = [Dgraph.NULL for ie in range( 0, self.g.ne)] # search order def Reset(self): self.sv = 0 self.se = 0 for iv in range(0, self.g.nv): self.vvisited[iv] = False self.vorder[iv] = Dgraph.NULL for ie in range(0, self.g.ne): self.evisited[ie] = False self.eorder[ie] = Dgraph.NULL def Order(self, starting_node=0): """ VisitOrder(starting_node) generates a list of integers from 0 to self.g.nv-1 (=#vertices minus 1) which represents the order in which the vertices would be visited during a Depth-First-Search. The first vertex visited is specified by the "starting_node" argument (an integer (from 0 to g.nv-1)). """ self.Reset() # The first vertex to be visited should be the starting_node self.vorder[0] = starting_node self.vvisited[starting_node] = True self.sv = 1 self._Order(starting_node) if self.sv != self.g.nv: raise(Disconnected(self.g, "Error(Order): " + "The input graph is not connected.")) assert(self.se == self.g.ne) return ([iv for iv in self.vorder], [ie for ie in self.eorder]) # return self.order def _Order(self, iv): """ _Order() is a recursive function which carries out a Depth-First-Search over the graph "self.g", starting with vertex iv. """ for je in self.g.neighbors[iv]: jv = self.g.edges[je].stop if not self.evisited[je]: self.eorder[self.se] = je self.se += 1 self.evisited[je] = True if not self.vvisited[jv]: self.vorder[self.sv] = jv self.sv += 1 self.vvisited[jv] = True self._Order(jv) def IsConnected(self): self.Reset() self._Order(0) return (self.sv == self.g.nv) def IsCyclic(self): """ IsCyclic() returns True if the graph is cyclic (and connected). (An exception is raised on disconnected graphs.) This function quits early as soon as a cycle is found. """ self.Reset() if (type(self.g) is Ugraph): is_cyclic = self._IsCyclicUgraph(0, Dgraph.NULL) else: is_cyclic = self._IsCyclic(0) if ((self.sv != self.g.nv) and (not is_cyclic)): raise(Disconnected(self.g, "Error(IsCyclic): " + "The input graph is not connected.")) return is_cyclic def _IsCyclicUgraph(self, iv, ivprev): """ _IsCyclicUgraph() is a recursive function which carries out a Depth-First-Search over the graph "self.g" to determine whether the graph is cyclic. This function works on undirected graphs (Ugraphs). Indirected graphs (Ugraphs) are a special case. Ugraphs are implemented by using two (redundant) forward/backward edges connecting each pair of adjacent vertices. This creates trivial loops. This version of _IsCyclicUgraph() only counts loops between more distantly connected vertices. """ self.sv += 1 self.vvisited[iv] = True for je in self.g.neighbors[iv]: jv = self.g.edges[je].stop if self.vvisited[jv]: if jv != ivprev: return True elif self._IsCyclicUgraph(jv, iv): return True return False def _IsCyclic(self, iv): """ _IsCyclic() is a recursive function which carries out a Depth-First-Search over the graph "self.g" to determine whether the graph is cyclic. This function works on directed graphs. """ self.sv += 1 self.vvisited[iv] = True for je in self.g.neighbors[iv]: jv = self.g.edges[je].stop if self.vvisited[jv]: return True elif self._IsCyclic(jv): return True return False class GraphMatcher(object): """ This class is a variant of the VF2 algorithm for searching for small connected subgraphs (g) within a larger graph (G). GraphMatcher works on directed or underected graphs (Dgraph or Ugraph). This particular version is better optimized for detecting subgraph isomorphisms between two graphs of highly unequal size. It should be faster in these situations because, the computation required for each step is independent of the number of vertices in the larger graph In the original VF2 algorithm, the computation time for each step is proportional to the number of vertices in the larger graph. (The distinction matters when one graph is much smaller than the other.) Limitations: At the moment, the matching process uses a simple depth-first-search to search the vertices of the small graph "g". Hence this approach fails when the smaller graph g is disconnected. (but it can probably be fixed by picking a different algorithm to search the small graph). """ def __init__(self, G, # The "big" graph g): # The little graph (number of vertices in g must be <= G) self.G = G self.g = copy.deepcopy(g) if (type(self.G) is Ugraph): assert(type(self.g) is Ugraph) # self.G.CalcEdgeLookupTable() <-- not needed anymore self.sv = 0 self.se = 0 self.voccupiedG = [False for iv in range(0, G.nv)] self.eoccupiedG = [False for ie in range(0, G.ne)] self.G_is_too_small = False if ((g.nv > G.nv) or (g.ne > G.ne)): self.G_is_too_small = True # raise GenErr('Error: The first argument of GraphMatcher(G,g),\n'+ # ' must be at least as large as the second.') # The list self.iv_to_Iv is the mapping between the graph vertices. # Iv is an index into the large graph's list of vertices. # iv is an index into the small graph's list of vertices. # The mapping is stored in the iv_to_Iv list. self.iv_to_Iv = [Dgraph.NULL for Iv in range(0, self.g.nv)] self.ie_to_Ie = [Dgraph.NULL for Ie in range(0, self.g.ne)] # (This used to be called "core_2" in the VF2 algorithm) # Due to the large number of recursion limit self.old_recursion_limit = sys.getrecursionlimit() expected_max_recursion = self.g.nv if self.old_recursion_limit < 1.5 * expected_max_recursion: # Give some breathing room. sys.setrecursionlimit(int(1.5 * expected_max_recursion)) subgraph_searcher = DFS(self.g) # Perform a Depth-First-Search on the small graph. self.vorder_g, self.eorder_g = subgraph_searcher.Order() # Then re-order the vertices and edgers to # match the order they were visited. # Note on permutation order: # (The DFS.Order() function returns the permutation in this format # old_index[ new_index ] # where new_index is the DFS iteration when the vertex/edge was visited # and old_index is the original vertex/edge order. # However the ReorderVerts() and ReorderEdges() functions expect # the permutation to have the opposite order: new_index[ old_index ] # Hence we set "invert=True", when we invoke these functions.) self.g.ReorderVerts(self.vorder_g, invert=True) self.g.ReorderEdges(self.eorder_g, invert=True) # Initialize state self.Reset() def Reset(self): """Reinitializes the state of the match-search algorithm. """ for iv in range(0, self.g.nv): self.iv_to_Iv[iv] = Dgraph.NULL for ie in range(0, self.g.ne): self.ie_to_Ie[ie] = Dgraph.NULL for Iv in range(0, self.G.nv): self.voccupiedG[Iv] = False for Ie in range(0, self.G.ne): self.eoccupiedG[Ie] = False self.se = 0 self.sv = 0 # OPTIONAL: First, do a partial sort for the vertices in the graphs # based on number of edges emanating from each vertex. # (This is probably unnecessary for small subgraphs.) # SortVertsByDegree(self.g) def Matches(self): """ Iterator over all matches between G and g. Each "match" corresponds to a subgraph of G which is isomorphic to g. Matches is formatted as a 2-tuple of lists: (list of vertex ids from G, list of edge ids from G) The vertex ids in the list are a subset of the integers from 0 to G.nv. The edge ids in the list are a subset of the integers from 0 to G.ne. (The corresponding vertices and edges from g are indicated by the order) """ self.Reset() if self.G_is_too_small: # Then there are fewer verts and edges in G than in g. # Thus it is impossible for a subgraph of G to be isomorphic to g. return # return no matches for Iv in range(0, self.G.nv): # match vertex Iv from G with vertex 0 from graph g self.iv_to_Iv[0] = Iv self.voccupiedG[Iv] = True # Implementation: # In this loop we begin the search process # starting with a different vertex (Iv) from big graph G, # and matching it with the first vertex (iv=0) from small graph g. # In this way the match "begins" from vertex Iv in G. # # Any matches found which begin from vertex Iv are distinct # from matches beginning from any other vertex in G. # Looping over all Iv in G is necessary and sufficient # to insure that all possible subgraphs of G # (which are isomorphic to g) are considered. self.sv = 1 # we have matched one vertex already self.se = 0 # we haven't matched any edges yet for match in self.Match(): yield match self.voccupiedG[Iv] = False def Match(self): # self.se represents how many vertices have been matched so far. # We are done searching if all of the edges from 0 to self.se-1 # from graph g have been selected (matched with edges from graph G). if self.se == self.g.ne: # Note: This also gaurantees that all vertices have been visited. assert(self.sv == self.g.nv) yield self.ReformatMatch() else: # VF2-style recursive loop: # We know the next edge to be matched is connected to at least # one previously visited vertex from g which has already been # been added to the the current match-in-progress. iv = self.g.edges[self.se].start Iv = self.iv_to_Iv[iv] assert(iv < self.sv) # <-- check to verify this is so # The other vertex may or may not have been visited (matched) yet. iv_neighbor = self.g.edges[self.se].stop # Two cases: # Case 1: edge self.se points to a previously visited vertex from g # This means we have a loop. if iv_neighbor < self.sv: # In that case, then the corresponding edge in G must # connect the corresponding pair of vertices from G. # (Which we know have already been assigned to vertices in g # because both iv and iv_neighbor are < self.sv) Iv_neighbor = self.iv_to_Iv[iv_neighbor] # Loop over all of the edges in G which connect this pair # of vertices (Iv --> Iv_neighbor) for Je in self.G.neighbors[Iv]: Jv = self.G.edges[Je].stop if ((Jv == Iv_neighbor) and (not self.eoccupiedG[Je])): # Match edge Je from big graph G with # edge self.se from small graph g self.ie_to_Ie[self.se] = Je self.se += 1 self.eoccupiedG[Je] = True for match in self.Match(): yield match self.eoccupiedG[Je] = False self.se -= 1 self.ie_to_Ie[self.se] = Dgraph.NULL # Case 2: else: # this would mean that iv_neighbor >= self.sv # If iv_neighbor>=self.sv, then this edge points to to a vertex # in g which has not yet been paired with a vertex from G. # Loop over all of the edges in G which connect vertex # Iv from G to new (unvisited) vertices in G for Je in self.G.neighbors[Iv]: Jv = self.G.edges[Je].stop if (not self.voccupiedG[Jv]): assert(not self.eoccupiedG[Je]) # Match both edge Je with je # AND vertex Jv with jv self.ie_to_Ie[self.se] = Je self.se += 1 self.eoccupiedG[Je] = True self.iv_to_Iv[self.sv] = Jv self.sv += 1 self.voccupiedG[Jv] = True # Then continue the recursion for match in self.Match(): yield match self.voccupiedG[Jv] = False self.sv -= 1 self.iv_to_Iv[self.sv] = Dgraph.NULL self.eoccupiedG[Je] = False self.se -= 1 self.ie_to_Ie[self.se] = Dgraph.NULL def ReformatMatch(self): # (This is because we are assuming g is connected. # IT should not have any orphanned vertices.) # Now return the match: # # There are different ways of doing this # version 1: # match = (self.iv_to_Iv, self.ie_to_Ie) <-return a pointer to array # version 2: # match = ([Iv for Iv in self.iv_to_Iv], <-return a copy of the array # [Ie for Ie in self.ie_to_Ie]) # version 3: # Recall that the vertices and edges and g have been re-ordered, # so sort the list of Iv indices in the order they would be # matched with the original vertices from the original graph g: # match = ([self.iv_to_Iv[self.vorder_g[iv]] # for iv in range(0,self.g.nv)], # [self.ie_to_Ie[self.eorder_g[ie]] # for ie in range(0,self.g.ne)]) # version 4: Similar to version 3 above, but we also translate # the directed edge id list into a shorter undirected # edge id list. match_verts = [self.iv_to_Iv[self.vorder_g[iv]] for iv in range(0, self.g.nv)] if type(self.g) is Dgraph: match_edges = [self.ie_to_Ie[self.eorder_g[ie]] for ie in range(0, self.g.ne)] else: #assert(atype(self.g) is Ugraph) match_edges = [Dgraph.NULL for ieu in range(0, self.g.neu)] for ie in range(0, self.g.ne): iv = self.g.edges[ie].start jv = self.g.edges[ie].stop if iv <= jv: # <-- avoid duplicating edges (iv,jv) and (jv,iv) ieu = self.g.LookupUndirectedEdgeIdx(ie) Ie = self.ie_to_Ie[ie] Ieu = self.G.LookupUndirectedEdgeIdx(Ie) match_edges[ieu] = Ieu return (tuple(match_verts), tuple(match_edges))
{ "repo_name": "smsaladi/moltemplate", "path": "moltemplate/nbody_graph_search.py", "copies": "2", "size": "36992", "license": "bsd-3-clause", "hash": 4530047178893124600, "line_mean": 37.1360824742, "line_max": 128, "alpha_frac": 0.5618512111, "autogenerated": false, "ratio": 3.9207207207207206, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.548257193182072, "avg_score": null, "num_lines": null }
espt_delim_atom_fields = set(["pos", "type", "v", "f", "bond", "temp", "gamma", "q", "quat", "omega", "torque", "rinertia", "fix", "unfix", "ext_force", "exclude", "delete", "mass", "dipm", "dip", "virtual", "vs_relative", "distance", "vs_auto_relate_to"]) def LinesWSlashes(text): """ Iterate over the lines contained in a string of text. Merge lines ending in backslashes. """ current_line = '' for line in text.split('\n'): current_line += line if (len(line) > 0) and (line[-1] != '\\'): yield current_line current_line = '' if len(current_line) > 0: yield current_line def SplitMultiDelims(line, delimiters): """ Split a string into tokens using one or more (multi-character) delimiters. (Bug: The current version of this function does not preserve white space, but this should not matter.) """ token = '' for sub_token in line.strip().split(): if sub_token in delimiters: yield token yield sub_token token = '' elif len(token) > 0: token += ' ' + sub_token else: token += sub_token if len(token) > 0: yield token def SplitAtomLine(line): l = [] for token in SplitMultiDelims(line, espt_delim_atom_fields): l.append(token) return l # In this type of TCL command, all of the delimiters # (like 'pos', 'type', 'q', ...) # are supposed to be followed by an argument. If the last # token on this line IS a delimiter, then this is a syntax error. if token in espt_delim_atom_fields: raise InputError("Error: Incomplete line:\n" "\""+line+"\"\n") def iEsptAtomCoords(tokens): #tokens = SplitMultiDelims(line) i = 0 while i < len(tokens): if tokens[i] in set(['pos', 'fix', 'unfix']): assert(i+1 < len(tokens)) yield i+1 i += 1 i += 1 def iEsptAtomVects(tokens): #tokens = SplitMultiDelims(line) i = 0 while i < len(tokens): if tokens[i] in set(['dip', 'rinertia', 'v', 'f', 'omega', 'torque']): assert(i+1 < len(tokens)) yield i+1 i += 1 i += 1 def iEsptAtomType(tokens): #tokens = SplitMultiDelims(line) i = 0 while i < len(tokens): if tokens[i] == 'type': assert(i+1 < len(tokens)) yield i+1 i += 1 i += 1 def iEsptAtomID(tokens): if len(tokens) > 1: return 1 else: raise InputError("Error: Incomplete line:\n" "\""+line+"\"\n")
{ "repo_name": "smsaladi/moltemplate", "path": "moltemplate/ettree_styles.py", "copies": "2", "size": "3070", "license": "bsd-3-clause", "hash": 8515121000895741000, "line_mean": 25.2393162393, "line_max": 78, "alpha_frac": 0.4892508143, "autogenerated": false, "ratio": 3.7995049504950495, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5288755764795049, "avg_score": null, "num_lines": null }
try: from .nbody_graph_search import Ugraph except (ImportError, SystemError, ValueError): # not installed as a package from nbody_graph_search import Ugraph # This file defines how 3-body angle interactions are generated by moltemplate # by default. It can be overridden by supplying your own custom file. # To find 3-body "angle" interactions, we would use this subgraph: # # # *---*---* => 1st bond connects atoms 0 and 1 # 0 1 2 2nd bond connects atoms 1 and 2 # bond_pattern = Ugraph([(0, 1), (1, 2)]) # (Ugraph atom indices begin at 0, not 1) # The next function eliminates the redundancy between 0-1-2 and 2-1-0: def canonical_order(match): """ Before defining a new interaction, we must check to see if an interaction between these same 3 atoms has already been created (perhaps listed in a different, but equivalent order). If we don't check for this this, we will create many unnecessary redundant interactions (which can slow down he simulation). To avoid this, I define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the symmetry of the interaction being generated... Later the re-ordered list of atom and bond ids will be tested against the list of atom/bond ids in the matches-found-so-far, before it is added to the list of interactions found so far. Note that the energy of an angle interaction is a function of the angle between. three consecutively bonded atoms (referred to here as: 0,1,2). This angle does not change when swapping the atoms at either end (0 and 2). So it does not make sense to define a separate 3-body angle interaction between atoms 0,1,2 AS WELL AS an interaction between 2,1,0. So we sort the atoms and bonds so that the first atom has a always has a lower atomID than the third atom. (Later we will check to see if we have already defined an interaction between these 3 atoms. If not then we create a new one.) """ # match[0][0:2] contains the ID numbers for the 3 atoms in the match atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] # match[1][0:1] contains the ID numbers for the 2 bonds bond0 = match[1][0] bond1 = match[1][1] if atom0 < atom2: # return ((atom0, atom1, atom2), (bond0, bond1)) same thing as: return match else: return ((atom2, atom1, atom0), (bond1, bond0))
{ "repo_name": "smsaladi/moltemplate", "path": "moltemplate/nbody_Angles.py", "copies": "2", "size": "2608", "license": "bsd-3-clause", "hash": -375113655826202900, "line_mean": 41.064516129, "line_max": 79, "alpha_frac": 0.6844325153, "autogenerated": false, "ratio": 3.6475524475524477, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5331984962852447, "avg_score": null, "num_lines": null }
try: from .nbody_graph_search import Ugraph except (ImportError, SystemError, ValueError): # not installed as a package from nbody_graph_search import Ugraph # This file defines how dihedral interactions are generated by moltemplate.sh # by default. It can be overridden by supplying your own custom file. # To find 4-body "dihedral" interactions, we would use this subgraph: # # 1st bond connects atoms 0 and 1 # *---*---*---* => 2nd bond connects atoms 1 and 2 # 0 1 2 3 3rd bond connects atoms 2 and 3 # bond_pattern = Ugraph([(0, 1), (1, 2), (2, 3)]) # (Ugraph atom indices begin at 0, not 1) def canonical_order(match): """ Before defining a new interaction, we must check to see if an interaction between these same 4 atoms has already been created (perhaps listed in a different, but equivalent order). If we don't check for this this, we will create many unnecessary redundant interactions (which can slow down he simulation). To avoid this, I define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the symmetry of the interaction being generated... Later the re-ordered list of atom and bond ids will be tested against the list of atom/bond ids in the matches-found-so-far, before it is added to the list of interactions found so far. Note that the energy of a dihedral interaction is a function of the dihedral-angle. The dihedral-angle is usually defined as the angle between planes formed by atoms 0,1,2 & 1,2,3. This angle does not change when reversing the order of the atoms. So it does not make sense to define a separate dihedral interaction between atoms 0,1,2,3 AS WELL AS between 3,2,1,0. So we sort the atoms so that the first atom has a lower atomID than the last atom. (Later we will check to see if we have already defined an interaction between these 4 atoms. If not then we create a new one.) """ # match[0][0:3] contains the ID numbers of the 4 atoms in the match atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] atom3 = match[0][3] # match[1][0:2] contains the ID numbers of the the 3 bonds bond0 = match[1][0] bond1 = match[1][1] bond2 = match[1][2] if atom0 < atom3: # return ((atom0, atom1, atom2, atom3), (bond0, bond1, bond2)) same # as: return match else: return ((atom3, atom2, atom1, atom0), (bond2, bond1, bond0))
{ "repo_name": "smsaladi/moltemplate", "path": "moltemplate/nbody_Dihedrals.py", "copies": "2", "size": "2673", "license": "bsd-3-clause", "hash": 8700546616481787000, "line_mean": 41.4285714286, "line_max": 79, "alpha_frac": 0.6711560045, "autogenerated": false, "ratio": 3.5783132530120483, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5249469257512048, "avg_score": null, "num_lines": null }
try: from .nbody_graph_search import Ugraph except (ImportError, SystemError, ValueError): # not installed as a package from nbody_graph_search import Ugraph # This file defines how improper interactions are generated by moltemplate.sh # by default. It can be overridden by supplying your own custom file # (for example, see "opls_imp.py") # To find 4-body "improper" interactions, # (by default, most of the time), we would use this subgraph: # 3 # * 1st bond connects atoms 0 and 1 # | => 2nd bond connects atoms 0 and 2 # _.*._ 3rd bond connects atoms 0 and 3 # *' 0 `* # 1 2 # bond_pattern = Ugraph([(0, 1), (0, 2), (0, 3)]) # (Ugraph atom indices begin at 0, not 1) def canonical_order(match): """ Before defining a new interaction, we must check to see if an interaction between these same 4 atoms has already been created (perhaps listed in a different, but equivalent order). If we don't check for this this, we will create many unnecessary redundant interactions (which can slow down he simulation). To avoid this, I define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the symmetry of the interaction being generated... Later the re-ordered list of atom and bond ids will be tested against the list of atom/bond ids in the matches-found-so-far, before it is added to the list of interactions found so far. Note that the energy of an improper interactions is a function of the improper angle. The improper-angle is usually defined as the angle between planes formed by atoms 0,1,2 & 1,2,3. (Alternately, it is sometimes defined as the angle between the 0,1,2 plane and atom 3.) This angle does not change when swapping the MIDDLE pair of atoms (1 and 2) (except for a change of sign, which does not matter since the energy functions used are typically sign invariant. Furthermore, neither of MIDDLE pair of atoms are the central atom, and there are 3!=6 ways of ordering the remaining 3 atoms.) Consequently it does not make sense to define a separate 4-body improper interaction between atoms 0,1,2,3 AS WELL AS between 0,2,1,3. So we sort the atoms and bonds so that the second atom has a always has a lower atomID than the third atom. (Later we will check to see if we have already defined an interaction between these 4 atoms. If not then we create a new one.) """ atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] atom3 = match[0][3] # match[1][0:2] contains the ID numbers for the 3 bonds bond0 = match[1][0] bond1 = match[1][1] bond2 = match[1][2] if atom1 <= atom2: # return ((atom0,atom1,atom2,atom3), (bond0,bond1,bond2)) # But this is the same thing as: return match else: return ((atom0, atom2, atom1, atom3), (bond1, bond0, bond2))
{ "repo_name": "smsaladi/moltemplate", "path": "moltemplate/nbody_Impropers.py", "copies": "2", "size": "3141", "license": "bsd-3-clause", "hash": 1330578588708679700, "line_mean": 43.8714285714, "line_max": 86, "alpha_frac": 0.6701687361, "autogenerated": false, "ratio": 3.6565774155995343, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005024336088770249, "num_lines": 70 }
import random, math from collections import deque from array import array #try: # from StringIO import StringIO #except ImportError: # from io import StringIO try: from .ttree_lex import InputError, ErrorLeader, OSrcLoc except (ImportError, SystemError, ValueError): # not installed as a package from ttree_lex import InputError, ErrorLeader, OSrcLoc def MultMat(dest, A, B): """ Multiply two matrices together. Store result in "dest". """ I = len(A) J = len(B[0]) K = len(B) # or len(A[0]) for i in range(0, I): for j in range(0, J): dest[i][j] = 0.0 for k in range(0, K): dest[i][j] += A[i][k] * B[k][j] def Transpose(M): return [ [M[j][i] for j in range(0, len(M))] for i in range(0, len(M[0])) ] def TransposeInPlace(M): N = len(M) for i in range(0, N): for j in range(0, i): M_ij = M[i][j] M_ji = M[j][i] M[i][j] = M_ji M[j][i] = M_ij def MatToStr(M): strs = [] for i in range(0, len(M)): for j in range(0, len(M[i])): strs.append(str(M[i][j]) + ' ') strs.append('\n') return(''.join(strs)) def LinTransform(dest, M, x): """ Multiply matrix M by 1-dimensioal array (vector) "x" (from the right). Store result in 1-dimensional array "dest". In this function, wetreat "x" and "dest" as a column vectors. (Not row vectors.) """ I = len(M) J = len(x) for i in range(0, I): dest[i] = 0.0 for j in range(0, J): dest[i] += M[i][j] * x[j] def AffineTransform(dest, M, x): """ This function performs an affine transformation on vector "x". Multiply 3-dimensional vector "x" by first three columns of 3x4 matrix M. Add to this the final column of M. Store result in "dest": dest[0] = M[0][0]*x[0] + M[0][1]*x[1] + M[0][2]*x[2] + M[0][3] dest[1] = M[1][0]*x[0] + M[1][1]*x[1] + M[1][2]*x[2] + M[1][3] dest[2] = M[2][0]*x[0] + M[2][1]*x[1] + M[2][2]*x[2] + M[2][3] """ D = len(M) #assert(len(M[0]) == D+1) for i in range(0, D): dest[i] = 0.0 for j in range(0, D): dest[i] += M[i][j] * x[j] dest[i] += M[i][D] # (translation offset stored in final column) def AffineCompose(dest, M2, M1): """ Multiplication for pairs of 3x4 matrices is technically undefined. However what we want to do is compose two affine transformations: M1 and M2 3x4 matrices are used to define rotations/translations x' = M[0][0]*x + M[0][1]*y + M[0][2]*z + M[0][3] y' = M[1][0]*x + M[1][1]*y + M[1][2]*z + M[1][3] z' = M[2][0]*x + M[2][1]*y + M[2][2]*z + M[2][3] We want to create a new 3x4 matrix representing an affine transformation (M2 M1), defined so that when (M2 M1) is applied to vector x, the result is M2 (M1 x). In other words: first, affine transformation M1 is applied to to x then, affine transformation M2 is applied to (M1 x) """ D = len(M1) #assert(len(M1[0]) == D+1) #assert(len(M2[0]) == D+1) for i in range(0, D): dest[i][D] = 0.0 for j in range(0, D + 1): dest[i][j] = 0.0 for k in range(0, D): dest[i][j] += M2[i][k] * M1[k][j] dest[i][D] += M2[i][D] def CopyMat(dest, source): for i in range(0, len(source)): for j in range(0, len(source[i])): dest[i][j] = source[i][j] class AffineStack(object): """ This class defines a matrix stack used to define compositions of affine transformations of 3 dimensional coordinates (rotation and translation). Affine transformations are represented using 3x4 matrices. (Coordinates of atoms are thought of as column vectors: [[x],[y],[z]], although they are represented internally in the more ordinary way [x,y,z]. To aplly an affine transformation to a vector, multiply the vector by the matrix, from the left-hand side, as explained in the comments for: AffineTransform(dest, M, x) Note: The last column of the 3x4 matrix stores a translational offset. This bears similarity with the original OpenGL matrix stack http://content.gpwiki.org/index.php/OpenGL:Tutorials:Theory (OpenGL uses 4x4 matrices. We don't need the final row of these matrices, because in OpenGL, these rows are used for perspective transformations.) http://en.wikipedia.org/wiki/Homogeneous_coordinates#Use_in_computer_graphics """ def __init__(self): self.stack = None self.M = None self._tmp = None self.Clear() def Clear(self): self.stack = deque([]) self.M = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] # (identity, initially) self._tmp = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] def PushRight(self, M): # Push a copy of matrix self.M onto the stack # We make no distinction between "right" and "left" here. # All transformations are pushed onto the stack in the same way. # (The "right" and "left" refer to whether the matrix is multiplied # on the right of left hand side. Because not all matrices need be # invertible, we require that matrices be popped from the stack # in the reverse order they were pushed. This prevents the ability # to push and pop matrices to either end of the stack in an arbitrary # order (like append(), appendleft(), pop(), popleft()).) self.stack.append([[self.M[i][j] for j in range(0, len(self.M[i]))] for i in range(0, len(self.M))]) # The "Right" and "Left" refer to whether the new matrix is multiplied # on the right or left side of the culmulatie matrix product. # Afterwards, self._tmp = self.M * M AffineCompose(self._tmp, self.M, M) # sys.stderr.write('DEBUG: PushLeft()\n' + # MatToStr(self._tmp) + '\n = \n' + # MatToStr(M) + '\n * \n' + # MatToStr(self.M) + '\n') CopyMat(self.M, self._tmp) # Copy self._tmp into self.M def PushLeft(self, M): # Push a copy of matrix self.M onto the stack # We make no distinction between right and left here. # All transformations are pushed onto the stack in the same way. # (The "right" and "left" refer to whether the matrix is multiplied # on the right of left hand side. Because not all matrices need be # invertible, we require that matrices be popped from the stack # in the reverse order they were pushed. This prevents the ability # to push and pop matrices to either end of the stack in an arbitrary # order (like append(), appendleft(), pop(), popleft()).) self.stack.append([[self.M[i][j] for j in range(0, len(self.M[i]))] for i in range(0, len(self.M))]) # The "Right" and "Left" refer to whether the new matrix is multiplied # on the right or left side of the culmulatie matrix product. # Afterwards, self._tmp = M * self.M AffineCompose(self._tmp, M, self.M) # sys.stderr.write('DEBUG: PushLeft()\n' + # MatToStr(self._tmp) + '\n = \n' + # MatToStr(M) + '\n * \n' + # MatToStr(self.M) + '\n') CopyMat(self.M, self._tmp) # Copy self.tmp into self.M def Pop(self): CopyMat(self.M, self.stack.pop()) # (No need to return a matrix,"self.M",after popping. # The caller can directly access self.M later.) # return self.M def PopRight(self): self.Pop() def PopLeft(self): self.Pop() def PushCommandsRight(self, text, # text containing affine transformation commands # The next two arguments are optional: src_loc=OSrcLoc(), # for debugging xcm=None): # position of center of object """Generate affine transformation matrices from simple text commands (such as \"rotcm(90,0,0,1)\" and \"move(0,5.0,0)". Chains of "rotcm", "movecm", "rot", and "move" commands can also be strung together: \"rotcm(90,0,0,1).move(0,5.0,0)\" Commands ending in \"cm\" are carried out relative to center-of-mass (average position) of the object, and consequently require an additional argument (\"xcm\"). """ self.PushRight(AffineStack.CommandsToMatrix(text, src_loc, xcm)) def PushCommandsLeft(self, text, # text containing affine transformation commands # The next two arguments are optional: src_loc=OSrcLoc(), # for debugging xcm=None): # position of center of object self.PushLeft(AffineStack.CommandsToMatrix(text, src_loc, xcm)) def __len__(self): return 1 + len(self.stack) @staticmethod def CommandsToMatrix(text, # text containing affine transformation commands src_loc=OSrcLoc(), # for debugging xcm=None): # position of center of object Mdest = [[1.0, 0.0, 0.0, 0.0], [ 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] M = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] Mtmp = [[1.0, 0.0, 0.0, 0.0], [ 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]] transform_commands = text.split(').') for transform_str in transform_commands: if transform_str.find('move(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') if (len(args) != 3): raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires 3 numerical arguments.') M = [[1.0, 0.0, 0.0, float(args[0])], [0.0, 1.0, 0.0, float(args[1])], [0.0, 0.0, 1.0, float(args[2])]] AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) # # if transform_str.find('movecm(') == 0: # # assert(xcm != None) # # i_paren_open = transform_str.find('(') # # i_paren_close = transform_str.find(')') # # if i_paren_close == -1: # # i_paren_close = len(transform_str) # # args =transform_str[i_paren_open+1:i_paren_close].split(',') # # if (len(args) != 3): # # raise InputError('Error near '+ErrorLeader(src_loc.infile, src_loc.lineno)+':\n' # # ' Invalid command: \"'+transform_str+'\"\n' # # ' This command requires 3 numerical arguments.') # # M = [[1.0, 0.0, 0.0, float(args[0])-(xcm[0])], # # [0.0, 1.0, 0.0, float(args[1])-(xcm[1])], # # [0.0, 0.0, 1.0, float(args[2])-(xcm[2])]] # # AffineCompose(Mtmp, M, Mdest) # # CopyMat(Mdest, Mtmp) elif transform_str.find('move_rand(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') seed = 1 if len(args) in (2,4,7): seed = int(args[0]) random.seed(seed) if len(args) == 1: sigma = float(args[1]) x = random.gauss(0.0, sigma) y = random.gauss(0.0, sigma) z = random.gauss(0.0, sigma) elif len(args) == 2: # seed = int(args[0]) this was already handled above sigma = float(args[1]) x = random.gauss(0.0, sigma) y = random.gauss(0.0, sigma) z = random.gauss(0.0, sigma) elif len(args) == 3: x = random.gauss(0.0, float(args[0])) y = random.gauss(0.0, float(args[1])) z = random.gauss(0.0, float(args[2])) elif len(args) == 4: # seed = int(args[0]) this was already handled above x = random.gauss(0.0, float(args[1])) y = random.gauss(0.0, float(args[2])) z = random.gauss(0.0, float(args[3])) elif len(args) == 6: x_min = float(args[0]) x_max = float(args[1]) y_min = float(args[2]) y_max = float(args[3]) z_min = float(args[4]) z_max = float(args[5]) x = x_min + (x_max - x_min)*(random.random()-0.5) y = y_min + (y_max - y_min)*(random.random()-0.5) z = z_min + (z_max - z_min)*(random.random()-0.5) elif len(args) == 7: # seed = int(args[0]) this was already handled above x_min = float(args[1]) x_max = float(args[2]) y_min = float(args[3]) y_max = float(args[4]) z_min = float(args[5]) z_max = float(args[6]) x = x_min + (x_max - x_min)*(random.random()-0.5) y = y_min + (y_max - y_min)*(random.random()-0.5) z = z_min + (z_max - z_min)*(random.random()-0.5) else: raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires either 1, 2, 3, 4, 6 or 7 numerical arguments. Either:\n' ' move_rand(gauss_sigma) or\n' ' move_rand(seed, gauss_sigma) or\n' ' move_rand(gauss_sigma_x, gauss_sigma_y, gauss_sigma_z) or\n' ' move_rand(seed, gauss_sigma_x, gauss_sigma_y, gauss_sigma_z) or\n' ' move_rand(x_min, x_max, y_min, y_max, z_min, z_max) or\n' ' move_rand(seed, x_min, x_max, y_min, y_max, z_min, z_max)\n') M = [[1.0, 0.0, 0.0, x], [0.0, 1.0, 0.0, y], [0.0, 0.0, 1.0, z]] AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) elif transform_str.find('rot(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') center_v = None if (len(args) == 7): center_v = [float(args[4]), float(args[5]), float(args[6])] elif (len(args) != 4): raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires either 4 or 7 numerical arguments. Either:\n' ' rot(angle, axisX, axisY, axiZ) or \n' ' rot(angle, axisX, axisY, axiZ, centerX, centerY, centerZ)') M[0][3] = 0.0 # RotMatAXYZ() only modifies 3x3 submatrix of M M[1][3] = 0.0 # The remaining final column must be zeroed by hand M[2][3] = 0.0 RotMatAXYZ(M, float(args[0]) * math.pi / 180.0, float(args[1]), float(args[2]), float(args[3])) if (center_v == None): AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) else: # Move "center_v" to the origin moveCentToOrig = [[1.0, 0.0, 0.0, -center_v[0]], [0.0, 1.0, 0.0, -center_v[1]], [0.0, 0.0, 1.0, -center_v[2]]] AffineCompose(Mtmp, moveCentToOrig, Mdest) CopyMat(Mdest, Mtmp) # Rotate the coordinates (relative to the origin) AffineCompose(Mtmp, M, Mdest) # M is the rotation matrix CopyMat(Mdest, Mtmp) # Move the origin back to center_v moveCentBack = [[1.0, 0.0, 0.0, center_v[0]], [0.0, 1.0, 0.0, center_v[1]], [0.0, 0.0, 1.0, center_v[2]]] AffineCompose(Mtmp, moveCentBack, Mdest) CopyMat(Mdest, Mtmp) elif transform_str.find('matrix(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') if (len(args) != 9): raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires 9 numerical arguments.') M = [[float(args[0]), float(args[1]), float(args[2]), 0.0], [float(args[3]), float(args[4]), float(args[5]), 0.0], [float(args[6]), float(args[7]), float(args[8]), 0.0]] AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) elif ((transform_str.find('quat(') == 0) or (transform_str.find('quatT(') == 0)): i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') center_v = None if (len(args) == 7): center_v = [float(args[4]), float(args[5]), float(args[6])] elif (len(args) != 4): raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires either 4 or 7 numerical arguments. Either:\n' ' rot(angle, axisX, axisY, axiZ) or \n' ' rot(angle, axisX, axisY, axiZ, centerX, centerY, centerZ)') M[0][3] = 0.0 # RotMatAXYZ() only modifies 3x3 submatrix of M M[1][3] = 0.0 # The remaining final column must be zeroed by hand M[2][3] = 0.0 q = (float(args[0]), float(args[1]), float(args[2]), float(args[3])) Quaternion2Matrix(q, M) if (transform_str.find('quatT(') == 0): TransposeInPlace(M) if (center_v == None): AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) else: # Move "center_v" to the origin moveCentToOrig = [[1.0, 0.0, 0.0, -center_v[0]], [0.0, 1.0, 0.0, -center_v[1]], [0.0, 0.0, 1.0, -center_v[2]]] AffineCompose(Mtmp, moveCentToOrig, Mdest) CopyMat(Mdest, Mtmp) # Rotate the coordinates (relative to the origin) AffineCompose(Mtmp, M, Mdest) # M is the rotation matrix CopyMat(Mdest, Mtmp) # Move the origin back to center_v moveCentBack = [[1.0, 0.0, 0.0, center_v[0]], [0.0, 1.0, 0.0, center_v[1]], [0.0, 0.0, 1.0, center_v[2]]] AffineCompose(Mtmp, moveCentBack, Mdest) CopyMat(Mdest, Mtmp) # # elif transform_str.find('rotcm(') == 0: # # i_paren_open = transform_str.find('(') # # i_paren_close = transform_str.find(')') # # if i_paren_close == -1: # # i_paren_close = len(transform_str) # # args =transform_str[i_paren_open+1:i_paren_close].split(',') # # if (len(args) != 4): # # raise InputError('Error near '+ErrorLeader(src_loc.infile, src_loc.lineno)+':\n' # # ' Invalid command: \"'+transform_str+'\"\n' # # ' This command requires 4 numerical arguments.') # # # # moveCMtoOrig = [[1.0, 0.0, 0.0, -xcm[0]], # # [0.0, 1.0, 0.0, -xcm[1]], # # [0.0, 0.0, 1.0, -xcm[2]]] # # AffineCompose(Mtmp, moveCMtoOrig, Mdest) # # CopyMat(Mdest, Mtmp) # # M[0][3] = 0.0#RotMatAXYZ() only modifies 3x3 submatrix of M # # M[1][3] = 0.0#The remaining final column must be zeroed by hand # # M[2][3] = 0.0 # # RotMatAXYZ(M, # # float(args[0])*math.pi/180.0, # # float(args[1]), # # float(args[2]), # # float(args[3])) # # AffineCompose(Mtmp, M, Mdest) # # CopyMat(Mdest, Mtmp) # # moveCmBack = [[1.0, 0.0, 0.0, xcm[0]], # # [0.0, 1.0, 0.0, xcm[1]], # # [0.0, 0.0, 1.0, xcm[2]]] # # AffineCompose(Mtmp, moveCmBack, Mdest) # # CopyMat(Mdest, Mtmp) elif transform_str.find('rot_rand(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') seed = 1 if len(args) in (2,6): seed = int(args[0]) random.seed(seed) raxis = [0.0, 0.0, 0.0] if len(args) < 5: # choose a random rotation axis raxis_len = 0.0 while (not ((0.01<raxis_len) and (raxis_len <= 1.0))): raxis = [-1+2.0*(random.random()-0.5) for d in range(0,3)] raxis_len = math.sqrt(raxis[0]**2 + raxis[1]**2 + raxis[2]**2) for d in range(0,3): raxis[d] /= raxis_len if len(args) == 0: angle_min = angle_max = 2*math.pi elif len(args) == 1: angle_min = 0.0 angle_max = float(args[0]) * math.pi / 180.0, elif len(args) == 5: angle_min = float(args[0]) angle_max = float(args[1]) raxis[0] = float(args[2]) raxis[1] = float(args[3]) raxis[2] = float(args[4]) elif len(args) == 6: seed = int(args[0]) angle_min = float(args[1]) angle_max = float(args[2]) raxis[0] = float(args[3]) raxis[1] = float(args[4]) raxis[2] = float(args[5]) else: raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires either 0, 1, 2, 5 or 6 numerical arguments. Either:\n' ' rot_rand() or \n' ' rot_rand(delta_angle) or \n' ' rot_rand(seed, delta_angle) or \n' ' rot_rand(angle_min, angle_max, axisX, axisY, axiZ) or\n' ' rot_rand(seed, angle_min, angle_max, axisX, axisY, axiZ)') angle = angle_min + (angle_max - angle_min)*(random.random() - 0.5) M[0][3] = 0.0 # RotMatAXYZ() only modifies 3x3 submatrix of M M[1][3] = 0.0 # The remaining final column must be zeroed by hand M[2][3] = 0.0 RotMatAXYZ(M, angle, raxis[0], raxis[1], raxis[2]) AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) elif transform_str.find('rotvv(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') center_v = None if (len(args) == 9): center_v = [float(args[6]), float(args[7]), float(args[8])] elif (len(args) != 6): raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires either 6 or 9 numerical arguments. Either:\n' ' rotvv(Xold,Yold,Zold,Xnew,Ynew,Znew) or \n' ' rotvv(Xold,Yold,Zold,Xnew,Ynew,Znew,centerX,centerY,centerZ)') M[0][3] = 0.0 # RotMatXYZXYZ() only modifies 3x3 submatrix of M M[1][3] = 0.0 # The remaining final column must be zeroed by hand M[2][3] = 0.0 RotMatXYZXYZ(M, float(args[0]), float(args[1]), float(args[2]), float(args[3]), float(args[4]), float(args[5])) if (center_v == None): AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) else: # Move "center_v" to the origin moveCentToOrig = [[1.0, 0.0, 0.0, -center_v[0]], [0.0, 1.0, 0.0, -center_v[1]], [0.0, 0.0, 1.0, -center_v[2]]] AffineCompose(Mtmp, moveCentToOrig, Mdest) CopyMat(Mdest, Mtmp) # Rotate the coordinates (relative to the origin) AffineCompose(Mtmp, M, Mdest) # M is the rotation matrix CopyMat(Mdest, Mtmp) # Move the origin back to center_v moveCentBack = [[1.0, 0.0, 0.0, center_v[0]], [0.0, 1.0, 0.0, center_v[1]], [0.0, 0.0, 1.0, center_v[2]]] AffineCompose(Mtmp, moveCentBack, Mdest) CopyMat(Mdest, Mtmp) elif transform_str.find('scale(') == 0: i_paren_open = transform_str.find('(') i_paren_close = transform_str.find(')') if i_paren_close == -1: i_paren_close = len(transform_str) args = transform_str[i_paren_open+1:i_paren_close].split(',') if (len(args) == 1): scale_v = [float(args[0]), float(args[0]), float(args[0])] center_v = [0.0, 0.0, 0.0] elif (len(args) == 3): scale_v = [float(args[0]), float(args[1]), float(args[2])] center_v = [0.0, 0.0, 0.0] elif (len(args) == 4): scale_v = [float(args[0]), float(args[0]), float(args[0])] center_v = [float(args[1]), float(args[2]), float(args[3])] elif (len(args) == 6): scale_v = [float(args[0]), float(args[1]), float(args[2])] center_v = [float(args[3]), float(args[4]), float(args[5])] else: raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Invalid command: \"' + transform_str + '\"\n' ' This command requires either 1, 3, 4, or 6 numerical arguments. Either:\n' ' scale(ratio), or \n' ' scale(ratioX, ratioY, ratioZ),\n' ' scale(ratio, centerX, centerY, centerZ), or\n' ' scale(ratioX, ratioY, ratioZ, centerX, centerY, centerZ)') ScaleMat(M, scale_v) # Now worry about translation: for d in range(0, 3): M[d][3] = center_v[d] * (1.0 - scale_v[d]) AffineCompose(Mtmp, M, Mdest) CopyMat(Mdest, Mtmp) # # elif transform_str.find('scalecm(') == 0: # # assert(xcm != None) # # i_paren_open = transform_str.find('(') # # i_paren_close = transform_str.find(')') # # if i_paren_close == -1: # # i_paren_close = len(transform_str) # # args =transform_str[i_paren_open+1:i_paren_close].split(',') # # # # moveCMtoOrig = [[1.0, 0.0, 0.0, -xcm[0]], # # [0.0, 1.0, 0.0, -xcm[1]], # # [0.0, 0.0, 1.0, -xcm[2]]] # # AffineCompose(Mtmp, moveCMtoOrig, Mdest) # # CopyMat(Mdest, Mtmp) # # # # M[0][3] = 0.0 #ScaleMat() only modifies 3x3 submatrix of M # # M[1][3] = 0.0 #The remaining final column must be zeroed by hand # # M[2][3] = 0.0 # # if (len(args) == 1): # # ScaleMat(M, args[0]) # # elif (len(args) == 3): # # ScaleMat(M, args) # # else: # # raise InputError('Error near '+ErrorLeader(src_loc.infile, src_loc.lineno)+':\n' # # ' Invalid command: \"'+transform_str+'\"\n' # # ' This command requires either 1 or 3 numerical arguments.') # # # # AffineCompose(Mtmp, M, Mdest) # # CopyMat(Mdest, Mtmp) # # moveCmBack = [[1.0, 0.0, 0.0, xcm[0]], # # [0.0, 1.0, 0.0, xcm[1]], # # [0.0, 0.0, 1.0, xcm[2]]] # # AffineCompose(Mtmp, moveCmBack, Mdest) # # CopyMat(Mdest, Mtmp) #elif transform_str.find('read_xyz(') == 0: # i_paren_open = transform_str.find('(') # i_paren_close = transform_str.find(')') # if i_paren_close == -1: # i_paren_close = len(transform_str) # args = transform_str[i_paren_open+1:i_paren_close].split(',') # if (len(args) != 1): # raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' # ' Invalid command: \"' + transform_str + '\"\n' # ' This command expects the name of a file in XYZ format.\n') # file_name = args[0] # if (not file_name in coord_files): # f = open(file_name, 'r') # f.close() # f.readline() # skip the first 2 lines # f.readline() # of an .xyz file (header) # for line in f: # tokens = line.split() # if (len(tokens) != 3) and (len(tokens) != 0): # raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' # ' Invalid command: \"' + transform_str + '\"\n' # ' This command expects the name of a file in XYZ format.\n') # crds.append((float(tokens[0]), # float(tokens[1]), # float(tokens[2])) # self.coord_files[file_name] = crds # else: # crds = self.coord_files[file_name] else: raise InputError('Error near ' + ErrorLeader(src_loc.infile, src_loc.lineno) + ':\n' ' Unknown transformation command: \"' + transform_str + '\"\n') return Mdest class MultiAffineStack(object): def __init__(self, which_stack=None): self.tot_stack = None self.stack_lookup = None self.stack_keys = None self.stacks = None self.M = None self.error_if_substack_empty = False self.coord_files = {} self.Clear() def Clear(self): self.tot_stack = AffineStack() self.stack_lookup = {} self.stack_keys = deque([]) self.stacks = deque([]) self.M = self.tot_stack.M self.error_if_substack_empty = False self.coord_files = {} def _Update(self): self.tot_stack.Clear() self.M = self.tot_stack.M assert(len(self.stacks) > 0) for stack in self.stacks: self.tot_stack.PushRight(stack.M) def PushStack(self, which_stack): stack = AffineStack() self.stack_keys.append(which_stack) self.stack_lookup[which_stack] = stack self.stacks.append(stack) self.tot_stack.PushRight(stack.M) def PopStack(self): assert(len(self.stacks) > 0) self.tot_stack.PopRight() which_stack = self.stack_keys.pop() del self.stack_lookup[which_stack] self.stacks.pop() def Push(self, M, which_stack=None, right_not_left=True): if len(self.stacks) == 0: self.PushStack(which_stack) if which_stack == None: stack = self.stacks[-1] if right_not_left: # This should copy the matrix M into stack.M stack.PushRight(M) else: stack.PushLeft(M) else: stack = self.stack_lookup[which_stack] if right_not_left: stack.PushRight(M) else: stack.PushLeft(M) if stack == self.stacks[-1]: self.tot_stack.PopRight() # Replace the last matrix on self.tot_stack # Note: Always use tot_stack.PopRight (even if # right_not_left=False) self.tot_stack.PushRight(stack.M) # with the the updated version. # Note: We could call self._Update(M) here, but that is slower. else: self._Update() def PushRight(self, M, which_stack=None): self.Push(M, which_stack, right_not_left=True) def PushLeft(self, M, which_stack=None): self.Push(M, which_stack, right_not_left=False) def PushCommandsRight(self, text, # text containing affine transformation commands # The next two arguments are optional: src_loc=OSrcLoc(), # for debugging xcm=None, which_stack=None): # position of center of object """Generate affine transformation matrices from simple text commands (such as \"rotcm(90,0,0,1)\" and \"move(0,5.0,0)". Chains of "rotcm", "movecm", "rot", and "move" commands can also be strung together: \"rotcm(90,0,0,1).move(0,5.0,0)\" Commands ending in \"cm\" are carried out relative to center-of-mass (average position) of the object, and consequently require an additional argument (\"xcm\"). """ self.PushRight(AffineStack.CommandsToMatrix(text, src_loc, xcm), which_stack) def PushCommandsLeft(self, text, # text containing affine transformation commands # The next two arguments are optional: src_loc=OSrcLoc(), # for debugging xcm=None, # position of center of object which_stack=None): self.PushLeft(AffineStack.CommandsToMatrix(text, src_loc, xcm), which_stack) def Pop(self, which_stack=None, right_not_left=True): #empty_stack_error = False if which_stack == None: stack = self.stacks[-1] if len(stack) >= 1: if right_not_left: stack.PopRight() else: stack.PopLeft() # Note: We could call self._Update(M) here, but that is slower self.tot_stack.PopRight() # Replace the last matrix on self.tot_stack # Note: Always use tot_stack.PopRight (even if # right_not_left=False) # with the the updated version. self.tot_stack.PushRight(stack.M) else: assert(False) # OPTIONAL CODE BELOW AUTOMATICALLY INVOKES self.PopStack() WHEN # THE stacks[-1].stack IS EMPTY. PROBABLY DOES NOT WORK. IGNORE # if (not self.error_if_substack_empty): # if right_not_left: # assert(len(self.stacks) > 0) # self.PopStack() # else: # assert(False) # else: # empty_stack_error = True else: stack = self.stack_lookup[which_stack] if len(stack) > 1: if right_not_left: stack.PopRight() else: stack.PopLeft() self._Update() else: assert(False) #empty_stack_error = True def PopRight(self, which_stack=None): self.Pop(which_stack, right_not_left=True) def PopLeft(self, which_stack=None): self.Pop(which_stack, right_not_left=True) def ScaleMat(dest, scale): for i in range(0, len(dest)): for j in range(0, len(dest[i])): dest[i][j] = 0.0 if ((type(scale) is float) or (type(scale) is int)): for i in range(0, len(dest)): dest[i][i] = scale else: for i in range(0, len(dest)): dest[i][i] = scale[i] def RotMatAXYZ(dest, angle, axis_x, axis_y, axis_z): r = math.sqrt(axis_x * axis_x + axis_y * axis_y + axis_z * axis_z) X = 1.0 Y = 0.0 Z = 0.0 if r > 0.0: # check for non-sensical input X = axis_x / r Y = axis_y / r Z = axis_z / r else: angle = 0.0 # angle *= math.pi/180.0 # "angle" is assumed to be in degrees # on second thought, let the caller worry about angle units. c = math.cos(angle) s = math.sin(angle) dest[0][0] = X * X * (1 - c) + c dest[1][1] = Y * Y * (1 - c) + c dest[2][2] = Z * Z * (1 - c) + c dest[0][1] = X * Y * (1 - c) - Z * s dest[0][2] = X * Z * (1 - c) + Y * s dest[1][0] = Y * X * (1 - c) + Z * s dest[2][0] = Z * X * (1 - c) - Y * s dest[1][2] = Y * Z * (1 - c) - X * s dest[2][1] = Z * Y * (1 - c) + X * s # formula from these sources: # http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ # also check # http://www.manpagez.com/man/3/glRotate/ # some pdb test commands: # from lttree_matrixstack import * # r = [[1.0,0.0,0.0], [0.0,1.0,0.0], [0.0,0.0,1.0]] # RotMatAXYZ(r, 90.0, 0.0, 0.0, 1.0) def Quaternion2Matrix(q, M): """convert a quaternion (q) to a 3x3 rotation matrix (M)""" s = 1.0 / (q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]) s *= s # (s = 1 if q is normalized) M[0][0] = 1 - 2*s*((q[2]*q[2])+(q[3]*q[3])) M[1][1] = 1 - 2*s*((q[1]*q[1])+(q[3]*q[3])) M[2][2] = 1 - 2*s*((q[1]*q[1])+(q[2]*q[2])) M[0][1] = 2*s*(q[1]*q[2] - q[3]*q[0]) M[1][0] = 2*s*(q[1]*q[2] + q[3]*q[0]) M[1][2] = 2*s*(q[2]*q[3] - q[1]*q[0]) M[2][1] = 2*s*(q[2]*q[3] + q[1]*q[0]) M[0][2] = 2*s*(q[1]*q[3] + q[2]*q[0]) M[2][0] = 2*s*(q[1]*q[3] - q[2]*q[0]) def Matrix2Quaternion(M, q): """convert a 3x3 rotation matrix (M) to a quaternion (q) http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ """ tr = M[0][0] + M[1][1] + M[2][2] if tr > 0: S = math.sqrt(tr+1.0) * 2 # S=4*qw qw = 0.25 * S qx = (M[2][1] - M[1][2]) / S qy = (M[0][2] - M[2][0]) / S qz = (M[1][0] - M[0][1]) / S elif (M[0][0] > M[1][1]) and (M[0][0] > M[2][2]): S = math.sqrt(1.0 + M[0][0] - M[1][1] - M[2][2]) * 2 # S=4*qx qw = (M[2][1] - M[1][2]) / S qx = 0.25 * S qy = (M[0][1] + M[1][0]) / S qz = (M[0][2] + M[2][0]) / S elif (M[1][1] > M[2][2]): S = math.sqrt(1.0 + M[1][1] - M[0][0] - M[2][2]) * 2 # S=4*qy qw = (M[0][2] - M[2][0]) / S qx = (M[0][1] + M[1][0]) / S qy = 0.25 * S qz = (M[1][2] + M[2][1]) / S else: S = math.sqrt(1.0 + M[2][2] - M[0][0] - M[1][1]) * 2 # S=4*qz qw = (M[1][0] - M[0][1]) / S qx = (M[0][2] + M[2][0]) / S qy = (M[1][2] + M[2][1]) / S qz = 0.25 * S q[0] = qw q[1] = qx q[2] = qy q[3] = qz # normalize q (necessary when M is not orthonormal) qnorm = math.sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]) for d in range(0,4): q[d] /= qnorm def MultQuat(dest, q1, q2): """ multiply 2 quaternions and store the result in "qdest" (q1[0] + i*q1[1] + j*q1[2] + k*q1[3]) * (q2[0] + i*q2[1] + j*q3[2] + k*q3[3]) https://en.wikipedia.org/wiki/Quaternion#Hamilton_product """ dest[0] = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3] dest[1] = q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2] dest[2] = q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1] dest[3] = q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0] def CrossProd(dest, A, B): dest[0] = (A[1] * B[2] - B[1] * A[2]) dest[1] = (A[2] * B[0] - B[2] * A[0]) dest[2] = (A[0] * B[1] - B[0] * A[1]) def DotProd(A, B): c = 0.0 for d in range(0, len(A)): c += A[d] * B[d] return c def Length(A): L = 0.0 for x in A: L += x * x return math.sqrt(L) def Normalize(dest, source): assert(len(dest) == len(source)) L = Length(source) for d in range(0, len(source)): dest[d] = source[d] / L def RotMatXYZXYZ(dest, xold, yold, zold, xnew, ynew, znew): A = [xold, yold, zold] B = [xnew, ynew, znew] axis = [0.0, 0.0, 0.0] CrossProd(axis, A, B) La = Length(A) Lb = Length(B) Lc = Length(axis) sinAng = Lc / (La * Lb) cosAng = DotProd(A, B) / (La * Lb) if Lc > 0.0: Normalize(axis, axis) angle = math.atan2(sinAng, cosAng) else: axis = [1.0, 0.0, 0.0] angle = 0.0 RotMatAXYZ(dest, angle, axis[0], axis[1], axis[2])
{ "repo_name": "jewettaij/moltemplate", "path": "moltemplate/ttree_matrix_stack.py", "copies": "2", "size": "45848", "license": "mit", "hash": -8679125560011440000, "line_mean": 43.5126213592, "line_max": 125, "alpha_frac": 0.4497251789, "autogenerated": false, "ratio": 3.3677097105920377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9805434792533034, "avg_score": 0.0024000193918006798, "num_lines": 1030 }
__author__ = "andrew.kelleher@buzzfeed.com (Andrew Kelleher)" try: from setuptools import setup, find_packages except ImportError: import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages setup( name='caliendo', version='2.1.10', packages=find_packages(), author='Andrew Kelleher', author_email='andrew.kelleher@buzzfeed.com', description='Makes mocking services for tests simpler by caching calls to services and loading those responses as fixtures.', long_description='Makes mocking services for tests simpler by caching calls to services and loading those responses as fixtures.', test_suite='test.all_tests', install_requires=[ 'mock==1.0.0', 'dill==0.2b1' ], url='http://www.github.com/buzzfeed/caliendo', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', ], keywords="test testing mock mocking api service cache caching integration unit", )
{ "repo_name": "buzzfeed/caliendo", "path": "setup.py", "copies": "1", "size": "1090", "license": "mit", "hash": 518202945162082050, "line_mean": 35.3333333333, "line_max": 134, "alpha_frac": 0.7009174312, "autogenerated": false, "ratio": 3.892857142857143, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004552733269698317, "num_lines": 30 }
__author__ = "andrew.kelleher@buzzfeed.com (Andrew Kelleher)" try: from setuptools import setup, find_packages except ImportError: import distribute_setup distribute_setup.use_setuptools() from setuptools import setup, find_packages setup( name='phonon', version='2.0', packages=find_packages(), author='Andrew Kelleher, Matthew Semanyshyn', author_email='andrew.kelleher@buzzfeed.com, matthew.semanyshyn@buzzfeed.com', description='Provides easy, fault tolerant, distributed references with redis as a backend.', test_suite='test', install_requires=[ 'redis==2.10.5', 'pytz==2014.10', 'tornado==4.3', ], tests_require=[ 'funcsigs==0.4', 'mock==1.3.0', 'pbr==1.8.1', ], url='http://www.github.com/buzzfeed/phonon', classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Development Status :: 4 - Beta', ], keywords="distributed reference references aggregation pipeline big data online algorithm" )
{ "repo_name": "buzzfeed/phonon", "path": "setup.py", "copies": "1", "size": "1090", "license": "mit", "hash": 8174148387518866000, "line_mean": 30.1428571429, "line_max": 97, "alpha_frac": 0.6486238532, "autogenerated": false, "ratio": 3.5737704918032787, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.47223943450032785, "avg_score": null, "num_lines": null }
from __future__ import print_function, division from decimal import Decimal import numpy as np from obspy import UTCDateTime from PyQt5 import QtWidgets, QtGui, QtCore import pyqtgraph as pg from CustomFunctions import getTimeFromFileName # Custom axis labels for the archive widget class TimeAxisItemArchive(pg.AxisItem): def __init__(self, *args, **kwargs): super(TimeAxisItemArchive, self).__init__(*args, **kwargs) # Some nice units with respect to time self.units=np.array([60, 120,300,600,1800,3600,7200, 3600*6,3600*24,3600*48,3600*24*5,3600*24*31,3600*24*180],dtype=float) self.unitIdxs=np.arange(len(self.units)) # What the above units should be displayed as self.unitStrs=['%Hh%Mm', '%Hh%Mm','%Hh%Mm','%Hh%Mm','%Hh%Mm','%Y-%m-%d %Hh','%Y-%m-%d %Hh', '%Y-%m-%d %Hh','%Y-%m-%d','%Y-%m-%d','%Y-%m-%d','%Y-%m-%d','%Y-%m-%d'] self.unitIdx=0 # Customize the locations of the ticks def tickValues(self, minVal, maxVal, size): # How many ticks are wanted on the page numTicks=float(max([int(size/225),2])) # Given how big the page is, see which units to apply diff=maxVal-minVal self.unitIdx=int(np.interp((diff)/numTicks,self.units,self.unitIdxs)) unit=self.units[self.unitIdx] # In the case where zoomed in way to close if unit>diff: return [(0.5*diff,[minVal+0.20*diff,maxVal-0.20*diff])] # In the case where zoomed out very far if diff/(unit*numTicks)>2: unit*=int(diff/(unit*numTicks)) # Start at the nearest whole unit val=minVal-minVal%unit+unit ticks=[] while val<maxVal: ticks.append(val) val+=unit return [(unit,ticks)] # Customize what string are being shown def tickStrings(self, values, scale, spacing): return [UTCDateTime(value).strftime(self.unitStrs[self.unitIdx]) for value in values] # Function called to display date time text on widget def showHoverText(self,pixPoint): mousePoint=self.pltItem.vb.mapSceneToView(pixPoint) if np.isnan(mousePoint.x()): return self.hoverTimeItem.setText(str(UTCDateTime(Decimal(mousePoint.x())))) t1,t2=self.getPlotItem().vb.viewRange()[0] if t2<=1: return self.hoverTimeItem.setPos(t1+(t2-t1)*0.5,0) self.hoverTimeItem.show() # Hide the date time text when not hovering over widget def hideHoverText(self,ev): super(pg.PlotWidget, self).leaveEvent(ev) self.hoverTimeItem.hide() # Add a new pick file with the center mouse button def addNewPickFile(self, ev): super(pg.PlotWidget, self).mouseDoubleClickEvent(ev) self.newEveTime=self.pltItem.vb.mapSceneToView(ev.pos()).x() self.addNewEventSignal.emit() # Initiate common functions between the archiveEvent and archiveSpan widgets def addArchiveWidgetElements(self): # Create text item self.hoverTimeItem=pg.TextItem(text='',anchor=(0.5,1)) self.hoverTimeItem.setZValue(5) self.hoverTimeItem.hide() self.addItem(self.hoverTimeItem) # Add the show text function self.scene().sigMouseMoved.connect(lambda pixPoint:showHoverText(self,pixPoint)) # Add the hide text function self.leaveEvent=lambda ev:hideHoverText(self,ev) # Add ability to add empty pick files if double clicked self.mouseDoubleClickEvent=lambda ev:addNewPickFile(self,ev) # Widget for seeing what data times are available, and sub-selecting pick files class ArchiveSpanWidget(pg.PlotWidget): addNewEventSignal=QtCore.pyqtSignal() def __init__(self, parent=None): super(ArchiveSpanWidget, self).__init__(parent,axisItems={'bottom': TimeAxisItemArchive(orientation='bottom')}) self.pltItem=self.getPlotItem() self.pltItem.setMenuEnabled(enableMenu=False) # Turn off the auto ranging self.pltItem.vb.disableAutoRange() # Don't plot anything outside of the plot limits self.pltItem.setClipToView(True) # Only show the bottom axis self.pltItem.hideAxis('left') self.pltItem.hideButtons() # Give this widget a span select, for zooming self.span = pg.LinearRegionItem([500,1000]) self.addItem(self.span) # Give a name to the data availability regions self.boxes=[] # Give some x-limits (do not go prior/after to 1970/2200) self.getPlotItem().setLimits(xMin=0,xMax=UTCDateTime('2200-01-01').timestamp) # No y-axis panning or zooming allowed self.pltItem.vb.setMouseEnabled(y=False) self.pltItem.setYRange(0,1) # Give some text upon hovering, and allow events to be added on double clicking addArchiveWidgetElements(self) # Return the span bounds def getSpanBounds(self): t1,t2=self.span.getRegion() return UTCDateTime(t1),UTCDateTime(t2) # Disable any scroll in/scroll out motions def wheelEvent(self,ev): return # Update the boxes representing the times def updateBoxes(self,ranges,penInt): # Remove the previous boxes for item in self.boxes: self.removeItem(item) self.boxes=[] # Skip, if no ranges to add if len(ranges)==0: return # Try to merge these ranges (less lines)... # ...sort first by range start values ranges=np.array(ranges) ranges=ranges[np.argsort(ranges[:,0])] merge=[ranges[0]] for rng in ranges: # In the case they do not overlap if rng[0]>merge[-1][1]: merge.append(rng) # If overlaping, and the new range extends further, push it elif rng[1]>merge[-1][1]: merge[-1][1]=rng[1] merge=np.array(merge) # Plot these efficiently (one disconnected line, rather than many lines) connect = np.ones((len(merge), 2), dtype=np.ubyte) connect[:,-1] = 0 # disconnect segment between lines path = pg.arrayToQPath(merge.reshape(len(merge)*2), np.ones((len(merge)*2))*0.5, connect.reshape(len(merge)*2)) item = pg.QtGui.QGraphicsPathItem(path) item.setPen(pg.mkPen(QtGui.QColor(penInt))) # Add in the new box self.boxes.append(item) self.addItem(item) # Graphview widget which holds all current pick files class ArchiveEventWidget(pg.PlotWidget): addNewEventSignal=QtCore.pyqtSignal() def __init__(self, parent=None): super(ArchiveEventWidget, self).__init__(parent) self.pltItem=self.getPlotItem() self.pltItem.setMenuEnabled(enableMenu=False) # Don't plot anything outside of the plot limits self.pltItem.setClipToView(True) # Do not show any axes self.pltItem.hideAxis('left') self.pltItem.hideAxis('bottom') self.pltItem.hideButtons() # Give some x-limits (do not go prior/after to 1970/2200) self.getPlotItem().setLimits(xMin=0,xMax=UTCDateTime('2200-01-01').timestamp,yMin=-0.3,yMax=1.3) # Disable all panning and zooming self.pltItem.vb.setMouseEnabled(x=False,y=False) self.curEveLine=None # For the highlighted event self.otherEveLine=None # For all other events # Give some text upon hovering, and allow events to be added on double clicking addArchiveWidgetElements(self) # Scale to where ever the archiveSpan has selected def updateXRange(self,linkWidget): self.setXRange(*linkWidget.getRegion(), padding=0) # Disable any scroll in/scroll out motions def wheelEvent(self,ev): return # Reset the event lines, given a new set of event times def updateEveLines(self,fileTimes,curFile): # Remove the not-current event lines if self.otherEveLine!=None: self.removeItem(self.otherEveLine) self.otherEveLine=None # Generate the many pick lines as one disconnected line if len(fileTimes)!=0: fileTimes=np.reshape(fileTimes,(len(fileTimes),1)) times=np.hstack((fileTimes,fileTimes)) connect = np.ones((len(times), 2), dtype=np.ubyte) connect[:,-1] = 0 # disconnect segment between lines connect=connect.reshape(len(times)*2) path = pg.arrayToQPath(times.reshape(len(times)*2),connect,connect) item = pg.QtGui.QGraphicsPathItem(path) # Reference and plot the line self.otherEveLine=item self.addItem(item) # Generate and plot the current pick file (if present) self.updateEveLineSelect(curFile) # Update the current event line to proper position, and appropriate color def updateEveLineSelect(self,curFile): # Remove this line if no current file if self.curEveLine!=None: self.removeItem(self.curEveLine) self.curEveLine=None # Add the line if a pick file is selected if curFile!='': t=getTimeFromFileName(curFile) line=pg.InfiniteLine(pos=t,pen=pg.mkPen(QtGui.QColor(0))) # Reference and plot the line self.curEveLine=line self.addItem(line) # Update the color, width and depth of an event line def updateEvePens(self,evePen,eveType): col,width,dep=evePen col=QtGui.QColor(QtGui.QColor(col)) if eveType=='cur': item=self.curEveLine else: item=self.otherEveLine if item!=None: item.setPen(pg.mkPen(col,width=width)) item.setZValue(dep) # List widget which holds all current pick files class ArchiveListWidget(QtWidgets.QListWidget): def __init__(self, parent=None): super(ArchiveListWidget, self).__init__(parent) # Return the list entries in the order which it appears def visualListOrder(self): aList=np.array([self.item(i).text() for i in range(self.count())]) args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())]) return [str(aFile) for aFile in aList[np.argsort(args)]] # Ensure that key presses are sent to the widget which the mouse is hovering over def enterEvent(self,ev): super(ArchiveListWidget, self).enterEvent(ev) self.setFocus() # Exit focus when the list widget is left def leaveEvent(self,ev): super(ArchiveListWidget, self).leaveEvent(ev) self.clearFocus() # Custom axis labels for the time widget class TimeAxisItem(pg.AxisItem): def __init__(self, *args, **kwargs): super(TimeAxisItem, self).__init__(*args, **kwargs) # Some nice units with respect to time self.units=np.array([10**-4,10**-3,10**-2,10**-1, 1,2,5,10,30,60, 120,300,600,1800,3600,7200, 3600*6,3600*24,3600*48,3600*24*5,3600*24*31,3600*24*180],dtype=float) self.unitIdxs=np.arange(len(self.units)) # What the above units should be displayed as self.unitStrs=['%S.%fs','%S.%fs','%S.%fs','%S.%fs', '%Mm%Ss','%Mm%Ss','%Mm%Ss','%Mm%Ss','%Mm%Ss','%Mm%Ss', '%Mm%Ss','%Hh%Mm','%Hh%Mm','%dd %Hh%Mm','%dd %Hh%Mm','%dd %Hh%Mm', '%m-%d %Hh','%m-%d %Hh','%m-%d %Hh','%Y-%m-%d','%Y-%m-%d','%Y-%m-%d'] self.unitIdx=0 # Customize the locations of the ticks def tickValues(self, minVal, maxVal, size): # How many ticks are wanted on the page numTicks=float(max([int(size/160),2])) # Given how big the page is, see which units to apply diff=maxVal-minVal self.unitIdx=int(np.interp((diff)/numTicks,self.units,self.unitIdxs)) unit=self.units[self.unitIdx] # In the case where zoomed in way to close if unit>diff: return [(0.5*diff,[minVal+0.20*diff,maxVal-0.20*diff])] # In the case where zoomed out very far if diff/(unit*numTicks)>2: unit*=int(diff/(unit*numTicks)) # Start at the nearest whole unit val=minVal-minVal%unit+unit ticks=[] while val<maxVal: ticks.append(val) val+=unit return [(unit,ticks)] # Round the time to the nearest ten-thousandth (minimum unit) def formatTime(self,val,fmt): string=UTCDateTime(val).strftime(fmt) if '%fs' in fmt: temp='{:.4f}'.format(round(float(string[-8:-1]),4)) string=string[:-8]+temp[1:]+'s' return string # Customize what string are being shown def tickStrings(self, values, scale, spacing): fmt=self.unitStrs[self.unitIdx] return [self.formatTime(val,fmt) for val in values] # Widget to nicely show the time axis, which is in sync with the trace data class TimeWidget(pg.PlotWidget): def __init__(self, parent=None): super(TimeWidget, self).__init__(parent,name='timeAxis',axisItems={'bottom': TimeAxisItem(orientation='bottom'), 'left':pg.AxisItem(orientation='left',showValues=False)}) self.getPlotItem().getAxis('left').setWidth(70) self.getPlotItem().setMenuEnabled(enableMenu=False) self.getPlotItem().hideButtons() # Give some x-limits (do not go prior/after to 1970/2200) self.getPlotItem().setLimits(xMin=0,xMax=UTCDateTime('2200-01-01').timestamp) self.getPlotItem().vb.setMouseEnabled(y=False,x=False) # Turn off all interaction self.setEnabled(False) # Give a blank title (gets rid of the y-axis) self.getPlotItem().setLabels(title='') # Null any built in hover actions def enterEvent(self,event): return def leaveEvent(self,event): return # Return the xmin,xmax (times) of the plot def getTimeRange(self): return self.getPlotItem().vb.viewRange()[0] # Infinite line, but now with reference to the pick type class PickLine(pg.InfiniteLine): def __init__(self, aTime,aType,pen,parent=None): super(PickLine, self).__init__(parent) col,width,depth=pen self.pickType=aType self.setValue(aTime) self.setZValue(depth) self.setPen(col,width=width) self.setVisible(width!=0) # Plot curve item, but now with reference to the channel class TraceCurve(pg.PlotCurveItem): def __init__(self,x,y,cha,pen,dep,parent=None): super(TraceCurve,self).__init__(parent) self.setData(x=x,y=y,pen=pen) self.cha=cha self.setZValue(dep) # If width of zero, do not show the curve if pen.widthF()==0: self.setVisible(False) # Widget which will hold the trace data, and respond to picking keybinds class TraceWidget(pg.PlotWidget): doubleClickSignal=QtCore.pyqtSignal() def __init__(self, parent=None,sta='',hoverPos=None): super(TraceWidget, self).__init__(parent) self.pltItem=self.getPlotItem() self.pltItem.setMenuEnabled(enableMenu=False) # Speed up the panning and zooming self.pltItem.setClipToView(True) self.pltItem.setDownsampling(True, True, 'peak') # Turn off the auto ranging self.pltItem.vb.disableAutoRange() # Only show the left axis self.pltItem.hideAxis('bottom') self.pltItem.hideButtons() self.pltItem.getAxis('left').setWidth(70) # Give some x-limits (do not go prior/after to 1970/2200) self.getPlotItem().setLimits(xMin=0,xMax=UTCDateTime('2200-01-01').timestamp) # Assign this widget a station self.sta=sta # Allow the widget to hold memory of pick lines, and traces self.pickLines=[] self.traceCurves=[] # Set the hover position, upon hovering self.scene().sigMouseMoved.connect(self.onHover) self.hoverPos=hoverPos # Allow this widget to be fairly small sizePolicy = QtGui.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.MinimumExpanding) self.setSizePolicy(sizePolicy) self.setMinimumSize(QtCore.QSize(0, 15)) # Update the mouse position def onHover(self,pixPoint): mousePoint=self.pltItem.vb.mapSceneToView(pixPoint) self.hoverPos=Decimal(mousePoint.x()),Decimal(mousePoint.y()) # Add a trace to the widget def addTrace(self,x,y,cha,pen,dep): curve=TraceCurve(x,y,cha,pen,dep) self.addItem(curve) self.traceCurves.append(curve) # Add a single pick line to this station def addPick(self,aTime,aType,pen): aLine=PickLine(aTime,aType,pen) # Add the line to the plot, and its own pick lines self.pltItem.addItem(aLine) self.pickLines.append(aLine) # Remove a specific number of picks from the pick lines (with a given pick type) def removePicks(self,aType,delTimes): # Count forwards to select picks for deletion delIdxs=[] for i,aLine in enumerate(self.pickLines): # If picks overlap, do not delete more than necessary if len(delIdxs)==len(delTimes): break if aLine.pickType==aType and aLine.value() in delTimes: delIdxs.append(i) # Check to make sure all were deleted if len(delIdxs)!=len(delTimes): print('Missed deleting some plotted pick lines') # Loop backwards and pop these picks off the widget for idx in delIdxs[::-1]: aLine=self.pickLines.pop(idx) self.pltItem.removeItem(aLine) # Emit signal for picking def mouseDoubleClickEvent(self, ev): super(TraceWidget, self).mouseDoubleClickEvent(ev) # If this widget is assigned a station, return signal if self.sta!=None: self.doubleClickSignal.emit() # Ensure that key presses are sent to the widget which the mouse is hovering over def enterEvent(self,ev): super(TraceWidget, self).enterEvent(ev) self.setFocus() # Exit focus when the trace is left def leaveEvent(self,ev): super(TraceWidget, self).leaveEvent(ev) self.clearFocus() self.hoverPos=None # Return the ymin,ymax of the plot def getRangeY(self): return self.getPlotItem().vb.viewRange()[1] # Widget to hold raster information for plotting class ImageWidget(pg.PlotWidget): def __init__(self, parent=None): super(ImageWidget, self).__init__(parent) self.pltItem=self.getPlotItem() self.pltItem.setMenuEnabled(enableMenu=False) # Speed up the panning and zooming self.pltItem.setClipToView(True) # Turn off the auto ranging self.pltItem.vb.disableAutoRange() # Only show the left axis self.pltItem.hideAxis('bottom') self.pltItem.hideButtons() self.pltItem.getAxis('left').setWidth(70) self.pltItem.getAxis('left').setZValue(1) # Give some x-limits (do not go prior/after to 1970/2200) self.getPlotItem().setLimits(xMin=0,xMax=UTCDateTime('2200-01-01').timestamp) # Create a blank image item self.imageItem=pg.ImageItem() self.addItem(self.imageItem) self.prevPosX,self.prevScaleX=0,1 self.prevPosY,self.prevScaleY=0,1 # Give the image a border self.imageBorder=pg.QtGui.QGraphicsRectItem(-1,-1,0.1,0.1) self.addItem(self.imageBorder) # Update the image on this widget def loadImage(self,imgDict): # Load in the defaults if some optional keys are not present imgDict=self.loadDefaultKeys(imgDict) # Set the image data self.imageItem.setImage(imgDict['data'].T) # Set position and scale of image... diffX=imgDict['t0']-self.prevPosX diffY=imgDict['y0']-self.prevPosY self.imageItem.scale(imgDict['tDelta']/self.prevScaleX,imgDict['yDelta']/self.prevScaleY) self.imageItem.translate(diffX/imgDict['tDelta'], diffY/imgDict['yDelta']) self.prevPosX+=diffX self.prevPosY+=diffY self.prevScaleX,self.prevScaleY=imgDict['tDelta'],imgDict['yDelta'] # Set the coloring lut=self.getLUT(imgDict['data'],imgDict['cmapPos'],imgDict['cmapRGBA']) self.imageItem.setLookupTable(lut) # Update image boundary xSize,ySize=np.array([imgDict['tDelta'],imgDict['yDelta']])*imgDict['data'].T.shape self.imageBorder.setRect(imgDict['t0'],imgDict['y0'],xSize,ySize) # Set default Y-limit to zoom to the image self.setYRange(imgDict['y0'],ySize,padding=0.0) # Apply the label self.pltItem.setLabel(axis='left',text=imgDict['label']) # Give default values to keys which are not present in the image dictionary def loadDefaultKeys(self,imgDict): for key,val in [['y0',0],['yDelta',1],['label',''], ['cmapPos',np.array([np.min(imgDict['data']),np.max(imgDict['data'])])], ['cmapRGBA',np.array([[0,0,0,255],[255,255,255,255]])] ]: if key not in imgDict.keys(): # In the case where the colors are given, but the positions are not, give evenly spaced positions if key=='cmapPos' and 'cmapRGBA' in imgDict.keys(): imgDict[key]=np.linspace(np.min(imgDict['data']),np.max(imgDict['data']),len(imgDict['cmapRGBA'])) else: imgDict[key]=val # In the case where the positions are given, but not the colors - just use first and last position if len(imgDict['cmapPos'])!=len(imgDict['cmapRGBA']): imgDict['cmapPos']=np.array([imgDict['cmapPos'][0],imgDict['cmapPos'][-1]]) return imgDict # Get the look-up-table (color map) def getLUT(self,data,pos,col): aMap = pg.ColorMap(np.array(pos), np.array(col,dtype=np.ubyte)) lut = aMap.getLookupTable(np.min(data),np.max(data),256) return lut
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/TemporalWidgets.py", "copies": "1", "size": "22412", "license": "mit", "hash": -9117689433098825000, "line_mean": 42.019193858, "line_max": 132, "alpha_frac": 0.6252900232, "autogenerated": false, "ratio": 3.6206785137318254, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47459685369318255, "avg_score": null, "num_lines": null }
from __future__ import print_function, division import time import numpy as np from PyQt5 import QtGui,QtCore,QtWidgets import pyqtgraph as pg # Scatter Item class, but allow double click signal class CustScatter(pg.ScatterPlotItem): doubleClicked=QtCore.Signal(object) def __init__(self, *args, **kwargs): super(CustScatter, self).__init__(*args, **kwargs) # Set the clicked points upon double clicking def mouseDoubleClickEvent(self,ev): if ev.button() == QtCore.Qt.LeftButton: # Set the clicked position self.clickPos=np.array([ev.pos().x(),ev.pos().y()]) # See which points were near the click position self.ptsClicked=self.pointsAt(ev.pos()) # Emit the scatter plot self.doubleClicked.emit(self) ev.accept() # Verticies on the polygon for the map polygon class RoiHandle(pg.graphicsItems.ROI.Handle): handleMenuSignal=QtCore.Signal(float) def __init__(self, *args, **kwargs): super(RoiHandle, self).__init__(*args, **kwargs) def mouseClickEvent(self, ev): # Right-click cancels drag if ev.button() == QtCore.Qt.RightButton and self.isMoving: self.isMoving = False # Prevent any further motion self.movePoint(self.startPos, finish=True) ev.accept() elif int(ev.button() & self.acceptedMouseButtons()) > 0: ev.accept() if ev.button() == QtCore.Qt.RightButton and self.deletable: self.raiseContextMenu(ev) self.sigClicked.emit(self, ev) else: ev.ignore() # Make some edits to default pg Handle def raiseContextMenu(self, ev): menu = self.scene().addParentContextMenus(self, self.getMenu(), ev) # Remove the unwanted actions for action in menu.actions(): if str(action.text())!='Remove handle': menu.removeAction(action) # Make sure it is still ok to remove this handle removeAllowed = all([r.checkRemoveHandle(self) for r in self.rois]) self.removeAction.setEnabled(removeAllowed) pos = ev.screenPos() # Note when the menu was added self.handleMenuSignal.emit(time.time()) menu.popup(QtCore.QPoint(pos.x(), pos.y())) # Editable polygon class RoiPolyLine(pg.PolyLineROI): handleMenuSignal=QtCore.Signal(float) def __init__(self, *args, **kwargs): super(RoiPolyLine, self).__init__(*args, **kwargs) # Make use of the edited pg Handle "RoiHandle" def addHandle(self, info, index=None): # If a Handle was not supplied, create it now if 'item' not in info or info['item'] is None: h = RoiHandle(self.handleSize, typ=info['type'], pen=self.handlePen, parent=self) h.setPos(info['pos'] * self.state['size']) info['item'] = h else: h = info['item'] if info['pos'] is None: info['pos'] = h.pos() # Connect the handle to this ROI h.connectROI(self) if index is None: self.handles.append(info) else: self.handles.insert(index, info) h.setZValue(self.zValue()+1) h.sigRemoveRequested.connect(self.removeHandle) h.handleMenuSignal.connect(self.relayMenuTime) self.stateChanged(finish=True) return h # Relay the time of a menu pop up on a handle def relayMenuTime(self,aTime): self.handleMenuSignal.emit(aTime) # Widget for seeing what data times are available, and sub-selecting pick files class MapWidget(pg.GraphicsLayoutWidget): doubleClicked=QtCore.Signal() updatePolygonPenSignal=QtCore.Signal() def __init__(self, parent=None): super(MapWidget, self).__init__(parent) # Add the map to the view, and turn off some of the automatic interactive properties self.map=self.addPlot() self.map.setMenuEnabled(enableMenu=False) self.map.hideButtons() # Disable any resizing self.map.vb.disableAutoRange() # Initialize extra variables self.stas=[] # The station names for the station spot items self.staItem=None # The station scatter item self.selectSta=None # Which station is currently selected self.curEveItem=None # The current event scatter item self.prevEveItem=None # The previous event scatter item self.clickPos=[0,0] # Last double clicked position self.clickDownPos=False # Mouse position upon clicking down # Add in the hovered over station label self.hoverStaItem=pg.TextItem(text='',anchor=(0.5,1)) self.hoverStaItem.hide() self.map.addItem(self.hoverStaItem) # Show station text when hovering over the station symbol self.scene().sigMouseMoved.connect(self.onHover) # Holder for editable polygon self.polygon=None self.handleMenuTime=0 # Projection functions for converting Lon/Lat to X,Y and back self.projFunc=None self.projFuncInv=None # Track where the mouse was pressed down def mousePressEvent(self, event): pg.GraphicsLayoutWidget.mousePressEvent(self,event) self.clickDownPos=event.pos() # If no dragging occcured and handle menu was not created, create menu to add polygon def mouseReleaseEvent(self,event): pg.GraphicsLayoutWidget.mouseReleaseEvent(self,event) if (event.pos()==self.clickDownPos and event.button() == QtCore.Qt.RightButton and time.time()-self.handleMenuTime>0.05): self.createMenu(event) # Add some functionality to default hover events... # ...see which station is being hovered over def onHover(self,pixPoint): if len(self.stas)==0: return # Get the nearby points mousePoint=self.staItem.mapFromScene(pixPoint) nearPoints = self.staItem.pointsAt(mousePoint) # Grab the nearest ones station code and update the if len(nearPoints)==0: self.hoverStaItem.hide() else: mousePos=np.array([mousePoint.x(),mousePoint.y()]) sta=self.getSelectSta(mousePos,nearPoints) self.hoverStaItem.setText(sta) self.hoverStaItem.setPos(mousePoint) self.hoverStaItem.show() # Handle double click events to the station scatter item def dblClicked(self,staScat): self.clickPos=list(staScat.clickPos) # Update the nearby station which was clicked self.selectSta=self.getSelectSta(staScat.clickPos,staScat.ptsClicked) # Forward the double clicked signal to main window self.doubleClicked.emit() # Create pop up menu to add/remove groups/variables def createMenu(self,event, parent=None): pixelPos=event.pos() self.menu=QtWidgets.QMenu(parent) if self.polygon is None: self.menu.addAction('Add polygon', lambda:self.addDefaultPolygon(pixelPos)) else: self.menu.addAction('Remove polygon',self.removePolygon) self.menu.move(self.mapToGlobal(QtCore.QPoint(0,0))+pixelPos) self.menu.show() # Load the polygon onto the map def loadPolygon(self,vertices,alreadyProj=False): # If already projected, do nothing if alreadyProj: verticesProj=vertices # Project Lon,Lat to X,Y else: verticesProj=self.projFunc(vertices) self.polygon=RoiPolyLine(verticesProj, closed=True) self.polygon.handleMenuSignal.connect(self.setHandleMenuTime) self.map.addItem(self.polygon) # If polygon created via GUI, make a box near clicked position def addDefaultPolygon(self,pixelPos): viewBox=self.map.getViewBox() # Convert from pixel position clickPos=viewBox.mapSceneToView(pixelPos) clickPos=np.array([clickPos.x(),clickPos.y()]) # Get the map axis lengths xLen,yLen=np.diff(np.array(viewBox.viewRange(),dtype=float),axis=1)*0.2 xLen,yLen=xLen[0],yLen[0] vertices=np.array([clickPos+np.array(extra) for extra in [[0,0],[0,yLen],[xLen,yLen],[xLen,0]]],dtype=float) self.loadPolygon(vertices,alreadyProj=True) # Send off signal for the polygons pen to be updated self.updatePolygonPenSignal.emit() # Remove polygon from the map def removePolygon(self): if self.polygon is not None: self.map.removeItem(self.polygon) self.polygon=None # Get the positions of the handles on the polygon def getPolygonVertices(self): if self.polygon is None: return np.empty((0,2),dtype=float) positions=[handle['pos'] for handle in self.polygon.handles] vertices=np.array([[entry.x(),entry.y()] for entry in positions]) # Convert from X,Y to Lon,Lat vertices=self.projFuncInv(vertices) return vertices # Set the time the handle menu was created def setHandleMenuTime(self,aTime): self.handleMenuTime=aTime # Function to return the nearest station to the current moused point def getSelectSta(self,mousePos,nearPoints): if len(nearPoints)>0: selPos=np.array([[point.pos().x(),point.pos().y()] for point in nearPoints]) selPoint=nearPoints[np.argmin(np.sum((selPos-mousePos)**2))] return str(self.stas[np.where(self.staItem.points()==selPoint)[0][0]]) else: return None # Load the new station meta data def loadStaLoc(self,staLoc,init): # Enable the autoscaling temporarily self.map.vb.enableAutoRange(enable=True) # Hide the hovered station label self.hoverStaItem.hide() # Clear away the old station spots if self.staItem!=None: self.map.removeItem(self.staItem) # Reset the double clicked station, if reloading the station file entirely if init: self.selectSta=None # Generate the station items if len(staLoc)==0: self.stas=[] else: self.stas=staLoc[:,0] staScatter=CustScatter(size=1,symbol='t1',pen=pg.mkPen(None)) # Project the lon,lat into x,y staLocProj=self.projFunc(staLoc[:,1:4]) # Add in the points if len(staLoc)!=0: staScatter.addPoints(x=staLocProj[:,0], y=staLocProj[:,1]) # Give some clicking ability to the stations staScatter.doubleClicked.connect(self.dblClicked) # For any point being clicked # Add the station scatter items self.map.addItem(staScatter) self.staItem=staScatter # Disable autoscaling the for map items self.map.vb.enableAutoRange(enable=False) # Update the station markers pen values def updateStaPen(self,colorAssign,size,dep): # Do nothing if no stations to edit if len(self.stas)==0: return # Get the brush values to be assigned brushArr=[] for sta in self.stas: color=colorAssign[sta] brushArr.append(pg.mkBrush(color.red(),color.green(),color.blue(),200)) self.staItem.setBrush(brushArr) # Set depth and size self.staItem.setSize(2*size) self.staItem.setZValue(dep) # Load a set of event points def loadEvePoints(self,eveMeta,eveType): if eveType=='cur': item,alpha=self.curEveItem,200 else: item,alpha=self.prevEveItem,160 # Remove the previous item if item is not None: self.map.removeItem(item) # Project the lon,lat into x,y eveLocProj=self.projFunc(eveMeta[:,1:4]) # Add in all of the new points, size & color set in different function scatter=pg.ScatterPlotItem(size=1,symbol='o',pen=pg.mkPen(None),brush=pg.mkBrush(0,0,0,alpha)) scatter.addPoints(x=eveLocProj[:,0],y=eveLocProj[:,1]) self.map.addItem(scatter) # Update the scatter item reference if eveType=='cur': self.curEveItem=scatter else: self.prevEveItem=scatter # Update the event pen values def updateEvePen(self,evePen,eveType): col,size,dep=evePen col=QtGui.QColor(QtGui.QColor(col)) if eveType=='cur': item=self.curEveItem else: item=self.prevEveItem if item!=None: item.setBrush(pg.mkBrush(col.red(),col.green(),col.blue(),200)) item.setSize(size*2) item.setZValue(dep) # Update the pen on the polygon def updatePolygonPen(self,evePen): if self.polygon is None: return col,width,dep=evePen col=QtGui.QColor(QtGui.QColor(col)) self.polygon.setPen(col,width=width) self.polygon.setZValue(dep) self.polygon.setVisible(width!=0) # Set the depth of the handles to be slightly higher for handle in self.polygon.handles: handle['item'].setZValue(dep+2) # Change the pen of the axis and axis labels def setPen(self,pen): for item in self.items(): if type(item)==pg.graphicsItems.AxisItem.AxisItem: item.setPen(pen)
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/MapWidgets.py", "copies": "1", "size": "13437", "license": "mit", "hash": 8888782491449667000, "line_mean": 39.7212121212, "line_max": 116, "alpha_frac": 0.629902508, "autogenerated": false, "ratio": 3.8424363740348872, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9857007722480109, "avg_score": 0.023066231910955484, "num_lines": 330 }
from __future__ import print_function from future.utils import iteritems from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtCore import Qt from lazylyst.UI.Configuration import Ui_ConfDialog from Actions import Action, ActionSetupDialog # Configuration dialog class ConfDialog(QtWidgets.QDialog, Ui_ConfDialog): def __init__(self,parent=None,main=None,actions=None, pref=None,hotVar=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.main=main self.pref=pref self.act=actions self.hotVar=hotVar # Give the dialog some functionaly self.setFunctionality() # Load in the previous lists of preferences and actions self.loadLists() # Set up some functionality to the configuration dialog def setFunctionality(self): # Key press events (also includes left double click) self.confPrefList.keyPressedSignal.connect(self.prefListKeyEvent) self.confActiveList.keyPressedSignal.connect(self.actionListKeyEvent) self.confPassiveList.keyPressedSignal.connect(self.actionListKeyEvent) # Right click menus for the action lists self.confActiveList.setContextMenuPolicy(Qt.CustomContextMenu) self.confPassiveList.setContextMenuPolicy(Qt.CustomContextMenu) self.confActiveList.customContextMenuRequested.connect(self.createActionMenu) self.confPassiveList.customContextMenuRequested.connect(self.createActionMenu) # If the ordering of the passive list ever changes, update actPassiveOrder self.confPassiveList.leaveSignal.connect(self.updatePassiveOrder) # Add and delete action buttons self.confActiveAddButton.clicked.connect(lambda: self.addDelClicked('active','add')) self.confActiveDelButton.clicked.connect(lambda: self.addDelClicked('active','del')) self.confPassiveAddButton.clicked.connect(lambda: self.addDelClicked('passive','add')) self.confPassiveDelButton.clicked.connect(lambda: self.addDelClicked('passive','del')) # Load in all of the lists from previous state def loadLists(self): # Add the passive actions in order for key in self.main.actPassiveOrder: self.confPassiveList.addItem(self.actionItem(key)) # Add the active actions (will be alphabetically ordered) for key in [key for key in self.act.keys() if not self.act[key].passive]: self.confActiveList.addItem(self.actionItem(key)) # Add the preferences for key in self.pref.keys(): item=QtWidgets.QListWidgetItem() item.setText(key) self.setItemSleepColor(item,False) item.setToolTip(self.pref[key].tip) self.confPrefList.addItem(item) # Handle add and delete action button click... # ...mocks key press events def addDelClicked(self,whichList,addDel): # Set the appropriate current list self.curList=self.confActiveList if whichList=='active' else self.confPassiveList # Set the current lists button press self.curList.key=Qt.Key_Insert if addDel=='add' else Qt.Key_Delete # Forward this to the key press event handles self.actionListKeyEvent(mock=True) # Return which action list is in focus def getCurActionList(self): curList=None if self.confActiveList.hasFocus() or self.confPassiveList.hasFocus(): curList=self.confActiveList if self.confActiveList.hasFocus() else self.confPassiveList return curList # Function to handle calls to the preference lists def prefListKeyEvent(self): # If the preference list had focus (again "backspace" is triggered by double click) if self.confPrefList.key==Qt.Key_Backspace: # Grab the key, and update if possible item=self.confPrefList.currentItem() if item.isSelected(): self.pref[item.text()].update(self) # Function to handle calls to the active and passive lists def actionListKeyEvent(self,mock=False): # If this was not a mock event (ie. actually triggered by key press) if not mock: self.curList=self.getCurActionList() # See if either of the action lists had focus, otherwise skip if self.curList==None: return # Skip if no accepted keys were passed if self.curList.key not in [Qt.Key_Insert,Qt.Key_Backspace,Qt.Key_Delete]: return # Creating a new action (Insert Key) if self.curList.key==Qt.Key_Insert: self.createAction() return # Skip if no action was selected if self.curList.currentItem() is None: return if not self.curList.currentItem().isSelected(): return # Mark if the current action is currently in use inUse=(self.curList.currentItem().text() in list(self.main.qTimers.keys())+list(self.main.qThreads.keys())) # Updating an action (Backspace Key -> which is triggered by double click) if self.curList.key==Qt.Key_Backspace: self.updateAction(inUse=inUse) # Delete an action (Delete Key) elif self.curList.key==Qt.Key_Delete: self.deleteAction(inUse=inUse) # Update the passive order every time (ie. do not care how configuration dialog is closed)... # ...a passive action is added or edited self.updatePassiveOrder() # Assign the tool tip to an action def actionItem(self,key): item=QtWidgets.QListWidgetItem() item.setText(key) # Set the tip (which is the trigger value) if not self.act[key].passive: try: item.setToolTip('Keybind: '+self.act[key].trigger.toString()) except: item.setToolTip('Keybind: '+self.act[key].trigger) else: self.setPassiveTip(item) # Set the color of the item displaying the sleep state self.setItemSleepColor(item,self.act[key].sleeping) return item # Set a passive items tip def setPassiveTip(self,item): triggers=self.act[item.text()].trigger # Don't fill the entire screen if many triggers if len(triggers)>3: item.setToolTip('Activated by: '+','.join(triggers[:3]+['...'])) else: item.setToolTip('Activated by: '+','.join(triggers)) # Update the selected action from the specified list def updateAction(self,inUse=False): # Let user know if edits will be accepted later if inUse: print('Only trigger edits are allowed as action is strolling or scheming') # Open the action set-up dialog with selected action action=self.openActionSetup(self.act[self.curList.currentItem().text()],tempLock=inUse) # Do not update if no action returned or action is in use if action==None or inUse: return # Remove the old action self.act.pop(self.curList.currentItem().text()) # Update the action dictionary with new self.act[action.tag]=action # If the action change had anything to do with an active action if (self.curList==self.confActiveList and action.passive) or (not action.passive): self.curList.takeItem(self.curList.currentRow()) oList=self.confPassiveList if action.passive else self.confActiveList oList.addItem(self.actionItem(action.tag)) # Otherwise just update the existing passive item (to preserve the passive order) else: self.curList.currentItem().setText(action.tag) self.setPassiveTip(self.curList.currentItem()) # Open the action set-up dialog with a blank new action def createAction(self): # Make the new action if self.confActiveList==self.curList: action=self.openActionSetup(Action(passive=False,trigger='Set Trigger')) else: action=self.openActionSetup(Action(passive=True,trigger=[])) self.insertLazyAction(action) # Insert a new action def insertLazyAction(self,action): if action==None: return # Insert new action to the action dictionary self.act[action.tag]=action # Create the item for the list widget item=self.actionItem(action.tag) # Add the action to the appropriate list if action.passive: self.confPassiveList.addItem(item) else: self.confActiveList.addItem(item) # Remove the selected action from the specified list def deleteAction(self,inUse=False): if inUse: print('Cannot delete an action which is strolling or scheming') return actTag=self.curList.currentItem().text() # If this is a locked action, the user cannot delete it if self.act[actTag].locked: print(actTag+' is a built-in action, it cannot be deleted') return # Remove from the list self.curList.takeItem(self.curList.currentRow()) # As well as from the action dictionary self.act.pop(actTag) # Menu activated upon right clicking of action entries def createActionMenu(self,pos): # Get the key of the clicked on action self.curList=self.getCurActionList() item=self.curList.currentItem() if not item.isSelected(): return self.menuAction=self.act[str(item.text())] # Can not edit locked actions, skip if locked if self.menuAction.locked: print('Cannot sleep or copy locked actions') return # Create the menu, and fill with options... self.actionMenu= QtWidgets.QMenu() # ...sleep or awake if self.menuAction.sleeping: menuItem=self.actionMenu.addAction("Awake") else: menuItem=self.actionMenu.addAction("Sleep") menuItem.triggered.connect(self.toggleSleep) # ...copy the action menuItem=self.actionMenu.addAction("Copy") menuItem.triggered.connect(self.copyAction) # Move to cursor position and show parentPosition = self.curList.mapToGlobal(QtCore.QPoint(0, 0)) self.actionMenu.move(parentPosition + pos) self.actionMenu.show() # Toggle the action sleeping state on/off def toggleSleep(self): item=self.curList.currentItem() if self.menuAction.sleeping: self.menuAction.sleeping=False else: self.menuAction.sleeping=True self.setItemSleepColor(item,self.menuAction.sleeping) # Set the color of a list widget item based on the actions sleeping state def setItemSleepColor(self,item,sleeping): if sleeping: item.setForeground(QtGui.QColor(150,150,150)) else: item.setForeground(QtGui.QColor(40,40,40)) # Copy an action, triggered from the action menu def copyAction(self): # Make a copy of the action newAction=Action() for key,val in iteritems(self.menuAction.__dict__): if key!='func': setattr(newAction,key,val) newAction.linkToFunction(self.main) # Set up the new actions tag seenKeys=self.act.keys() i=0 while self.menuAction.tag+'('+str(i)+')' in seenKeys: i+=1 # Assign the unique tag, and give a meaningless trigger (if an active action) newAction.tag=self.menuAction.tag+'('+str(i)+')' if not newAction.passive: print('Update '+newAction.tag+' trigger value, will be deleted upon configuration closure otherwise') newAction.trigger='Set Trigger' # Insert the copied action self.insertLazyAction(newAction) # Update the passive list ordering to what it seen by the user def updatePassiveOrder(self): self.main.actPassiveOrder=self.confPassiveList.visualListOrder() # Open the setup action dialog def openActionSetup(self,action,tempLock=False): self.dialog=ActionSetupDialog(self.main,action,self.act, self.hotVar,self.pref,tempLock) if self.dialog.exec_(): action=self.dialog.returnAction() return action # On close, make sure that no new actions have incorrect triggers def closeEvent(self,ev): popKeys=[actKey for actKey in self.act.keys() if (self.act[actKey].trigger=='Set Trigger' and not self.act[actKey].passive)] for key in popKeys: print('Action '+key+' was removed, as its trigger value was not set') self.act.pop(key)
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/ConfigurationDialog.py", "copies": "1", "size": "12963", "license": "mit", "hash": -7470182811746006000, "line_mean": 43.8581314879, "line_max": 118, "alpha_frac": 0.6436010183, "autogenerated": false, "ratio": 4.1816129032258065, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5325213921525807, "avg_score": null, "num_lines": null }
from __future__ import print_function,division import os import sys import ctypes as C if sys.version_info[0]==2: from scandir import scandir else: from os import scandir import numpy as np from obspy.core.stream import read from obspy.core.stream import Stream as EmptyStream from obspy.core.utcdatetime import UTCDateTime from obspy.io.mseed.headers import clibmseed,VALID_CONTROL_HEADERS,SEED_CONTROL_HEADERS from PyQt5 import QtWidgets, QtCore # If the stream was not able to be merged, check to see if multiple sampling rates on the same channel... # ... and remove the ones with the uncommon sampling rate def RemoveOddRateTraces(stream): unqStaRates=[] # Array to hold rates, per channel rates,chas=[],[] for tr in stream: anID=tr.stats.station+'.'+tr.stats.channel+'.'+str(tr.stats.delta) if anID not in unqStaRates: unqStaRates.append(anID) rates.append(tr.stats.delta) chas.append(tr.stats.station+'.'+tr.stats.channel) # ...figure out which station has two rates unqRate,countRate=np.unique(rates,return_counts=True) if len(unqRate)==1: print('merge will fail, not issue of multiple sampling rates on same station') else: # ... and remove the traces with less common rates unqCha,countCha=np.unique(chas,return_counts=True) rmChas=unqCha[np.where(countCha!=1)] rmRates=unqRate[np.where(unqRate!=(unqRate[np.argmax(countRate)]))] trimRateStream=EmptyStream() for tr in stream: if tr.stats.station+'.'+tr.stats.channel in rmChas and tr.stats.delta in rmRates: continue trimRateStream+=tr print('station.channel:',str(rmChas),'had some traces removed (duplicate rates same channel)') stream=trimRateStream return stream # Given two timestamps, extract all information... # fileTimes contains [startTime,endTime] of the archive files def extractDataFromArchive(t1,t2,fileNames,fileTimes,wantedStaChas=[['*','*']]): # Return nothing if there is no data if len(fileTimes)==0: return EmptyStream() # Catch the case where the asked time range is completely outside the archive data availability if t1>fileTimes[-1,1] or t2<fileTimes[0,0]: return EmptyStream() # Figure out what set of files are wanted collectArgs=np.where((fileTimes[:,0]<=t2)&(fileTimes[:,1]>=t1))[0] stream=EmptyStream() flagged=False # Read in all of the information for aFile in fileNames[collectArgs]: # Flag to user if the archive structure has changed if not os.path.exists(aFile): flagged=True continue aStream=read(aFile) for aSta,aCha in wantedStaChas: stream+=aStream.select(station=aSta,channel=aCha) if flagged: print('Archive structure as changed, reload the current archive') # Merge traces which are adjacent try: stream.merge(method=1) except: stream=RemoveOddRateTraces(stream) stream.merge(method=1) # If any trace has masked values, split if True in [isinstance(tr.data, np.ma.masked_array) for tr in stream]: stream=stream.split() # Trim to wanted times stream.trim(UTCDateTime(t1),UTCDateTime(t2)) return stream # Get a list of all files of the accepted extension types, and their metadata def getDirFiles(mainDir,acceptedExtensions): metaData=[] # The returned metadata [path,mtime,ctime,fileSize] # Check first to see that the folder exists, return nothing otherwise if not os.path.isdir(mainDir): return metaData # The directories yet to be scanned toScanDirs=[mainDir] # print('Scanning archive directory for changes...') while len(toScanDirs)!=0: toAddToScan=[] # Directories to be found in this iteration for aDir in toScanDirs: for entry in scandir(aDir): # If this is a directory, scan it later if entry.is_dir(): toAddToScan.append(entry.path) continue # Add to the file metadata list if is an accepted file type if entry.name.split('.')[-1] in acceptedExtensions: aStat=entry.stat() metaData.append([entry.path,aStat.st_mtime, aStat.st_ctime,aStat.st_size]) # Add all of the new directories which were found toScanDirs=toAddToScan # print('...scan complete') return metaData # Get the previously loaded archives file metadata and start/end times def getPrevArchive(mainDir): try: meta=np.load(mainDir+'/lazylystArchiveMeta.npy') times=np.load(mainDir+'/lazylystArchiveTimes.npy') return meta,times except: return np.empty((0,4)),np.empty((0,2)) # Empty class to be able to pass objects to the progress widget class ValueObj(object): def __init__(self): self.value=[] # Read in all the start and stop times of the files def getArchiveAvail(archDir,acceptFileTypes=['seed','miniseed','mseed'],showBar=True): # Get the currently present files metadata curMeta=getDirFiles(archDir,acceptFileTypes) curMeta=np.array(curMeta,dtype=str) curTimes=np.zeros((len(curMeta),2)) # If there are no files in archDir if len(curMeta)==0: return np.array([]),curTimes # Get the previously loaded archive metadata if it exists prevMeta,prevTimes=getPrevArchive(archDir) # If the arrays are already exactly the same, do not bother updating if np.array_equal(prevMeta,curMeta): return prevMeta[:,0],prevTimes # See which files are common among current and previous metadata (check, which may be added to load)... prevFiles=list(prevMeta[:,0]) if len(prevMeta)!=0: checkIdxs=[[i,prevFiles.index(item)] for i, item in enumerate(curMeta[:,0]) if item in set(prevFiles)] else: checkIdxs=[] checkIdxs=np.array(checkIdxs) # ...as well as which files were not previously present (load) if len(checkIdxs)==0: loadIdxs=list(range(len(curMeta))) else: loadIdxs=[i for i in range(len(curMeta)) if i not in checkIdxs[:,0]] # Set the current time to be the previous times (where present) by default if len(checkIdxs)!=0: curTimes[checkIdxs[:,0]]=prevTimes[checkIdxs[:,1]] # See which current files need to be loaded loadIdxs+=[i for i,j in checkIdxs if not np.array_equal(curMeta[i],prevMeta[j])] loadIdxs=np.array(loadIdxs,dtype=int) # Go get all of these times ## ## holder=ValueObj() if len(loadIdxs)!=0: # Have the option to show the progress bar, or run all and now show progress bar=ArchLoadProgressBar(holder,curMeta[loadIdxs,0],useTimer=showBar) if showBar: bar.exec_() else: while len(holder.value)==0: bar.getFileLims() times=np.array(holder.value) # As the new times loading could have been canceled, update just the ones which were updated curTimes[loadIdxs[:len(times)]]=times # Keep the times which are not still [0,0] keepIdxs=np.where((curTimes[:,0]!=0)|(curTimes[:,1]!=0))[0] curMeta=curMeta[keepIdxs] curTimes=curTimes[keepIdxs] # Finally save the new metadata and times... np.save(archDir+'/lazylystArchiveMeta',curMeta) np.save(archDir+'/lazylystArchiveTimes',curTimes) # ...and return the file names and times return curMeta[:,0],curTimes # Progress bar for the archive... class ArchLoadProgressBar(QtWidgets.QDialog): def __init__(self,holder,toReadFiles,useTimer=True, parent=None): super(ArchLoadProgressBar, self).__init__(parent) self.holder=holder # Set up values to for scanning file times self.files=toReadFiles self.nFiles=float(len(self.files)) self.fileMinMaxs=[] self.nextFileIdx=0 # Marker if the quick MSEED reading fails self.quickReadFail=False # Set up progress bar size and min/max values self.resize(300,40) self.progressbar = QtWidgets.QProgressBar() self.progressbar.setMinimum(1) self.progressbar.setMaximum(100) # Add cancel button self.button = QtWidgets.QPushButton('Cancel') self.button.clicked.connect(self.cancelLoad) main_layout = QtWidgets.QVBoxLayout() # Add widgets and text to the layout main_layout.addWidget(self.progressbar) main_layout.addWidget(self.button) self.setLayout(main_layout) self.setWindowTitle('Loading archive changes...') # Add a timer and start loading self.timer = QtCore.QTimer() if useTimer: self.timer.timeout.connect(self.getFileLims) self.timer.start(5) # 5 millisecond interval # Stop the timer from loading files def cancelLoad(self): self.timer.stop() self.holder.value=self.fileMinMaxs print(len(self.fileMinMaxs),'archive files were updated') self.close() # If closed, treat as canceled def closeEvent(self, event): if self.timer.isActive(): self.cancelLoad() # Get the earliest and latest time data exists in the wanted files def getFileLims(self): # Stop if no more files to load if self.nextFileIdx>=self.nFiles: self.cancelLoad() return nextFile=self.files[self.nextFileIdx] # Try the quick read function if not self.quickReadFail: try: startEnds=getMseedStartEnds(nextFile) minTime,maxTime=np.min(startEnds[:,0]),np.max(startEnds[:,1]) except: print('Quick MSEED reading failed on file: '+nextFile) self.quickReadFail=True if self.quickReadFail: try: st=read(nextFile,headonly=True,format='MSEED') stats=[tr.stats for tr in st] # Get min and max times from file minTime=np.min([stat.starttime for stat in stats]).timestamp maxTime=np.max([stat.endtime for stat in stats]).timestamp except: print('Regular MSEED reading failed on file: '+nextFile) minTime,maxTime=0,0 # Assign 0,0 to be removed later # Get a measure of progress and update the GUI perc=int(100*(self.nextFileIdx+1)/self.nFiles) if perc>self.progressbar.value(): self.progressbar.setValue(perc) # Update the GUI every Xth loop if self.nextFileIdx%10==0: QtWidgets.qApp.processEvents() # Update the index, and add this min/max time self.nextFileIdx+=1 self.fileMinMaxs.append([minTime,maxTime]) # Functions used for getMseedStartEnds def passFunc(*args): pass def isdigit(x): return True if (x - ord('0')).max() <= 9 else False # Read the just start and end time from all traces in MSEED def getMseedStartEnds(aFile): # Read file bfr_np = np.fromfile(aFile, dtype=np.int8) # Parameters wanted for reading just the header unpack_data,verbose,offset=0,0,0 details,selections=False,None reclen,header_byteorder=-1,-1 # Check if starting position of data read should change while True: if (isdigit(bfr_np[offset:offset + 6]) is False) or \ (bfr_np[offset + 6] not in VALID_CONTROL_HEADERS): msg = 'Not a valid (Mini-)SEED file' raise Exception(msg) elif bfr_np[offset + 6] in SEED_CONTROL_HEADERS: # Get the record length try: record_length = pow(2, int(''.join([chr(_i) for _i in bfr_np[19:21]]))) except ValueError: record_length = 4096 offset += record_length continue break bfr_np = bfr_np[offset:] buflen = len(bfr_np) # Make useless functions to accomodate clibmseed.readMSEEDBuffer requirements alloc_data = C.CFUNCTYPE(C.c_longlong, C.c_int, C.c_char)(passFunc) log_print = C.CFUNCTYPE(C.c_void_p, C.c_char_p)(passFunc) # Read the data with C function inputs=[bfr_np, buflen, selections, C.c_int8(unpack_data), reclen, C.c_int8(verbose), C.c_int8(details), header_byteorder, alloc_data,log_print,log_print] # Allow for different versions of obspy try: lil = clibmseed.readMSEEDBuffer(*inputs) except: lil = clibmseed.readMSEEDBuffer(*inputs[:-2]) # Read first section of the miniseed current_id = lil.contents timeInfo=np.zeros((0,2),dtype=float) # Loop over each NSLC while True: try: current_segment = current_id.firstSegment.contents except ValueError: break # Loop over traces for this NSLC while True: # Get the starttime and duration startStr=str(current_segment.starttime) startTime,duration=startStr[:-6]+'.'+startStr[-6:],(1./current_segment.samprate)*(current_segment.samplecnt) try: current_segment = current_segment.next.contents except ValueError: # Append these values to array timeInfo=np.vstack((timeInfo,np.array([startTime,duration],dtype=float))) break try: current_id = current_id.next.contents except ValueError: break # Remove the mseed info from memory clibmseed.lil_free(lil) del lil # Return start and end times if len(timeInfo)==0: return timeInfo else: # Make the second entry the end time (start time + duration) timeInfo[:,1]=np.sum(timeInfo,axis=1) return timeInfo
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/Archive.py", "copies": "1", "size": "14263", "license": "mit", "hash": 1765866074117298200, "line_mean": 39.2283236994, "line_max": 120, "alpha_frac": 0.6234312557, "autogenerated": false, "ratio": 3.841368165903582, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9863730962634084, "avg_score": 0.02021369179389951, "num_lines": 346 }
from __future__ import print_function, division import numpy as np from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtCore import Qt # Widget which return key presses, however double click replaces backspace class MixListWidget(QtWidgets.QListWidget): # Return signal if key was pressed while in focus keyPressedSignal=QtCore.pyqtSignal() leaveSignal=QtCore.pyqtSignal() def __init__(self, parent=None): super(MixListWidget, self).__init__(parent) # Update this widgets last pressed key, and return a signal def keyPressEvent(self, ev): self.key=ev.key() if self.key not in [Qt.Key_Insert,Qt.Key_Delete]: return self.keyPressedSignal.emit() # Deselect all items if in a blank space def mousePressEvent(self, ev): if self.itemAt(ev.pos()) is None: self.clearSelection() QtWidgets.QListWidget.mousePressEvent(self, ev) # Swapping a double click with the backspace button... # ...wanted to transmit double click as a key def mouseDoubleClickEvent(self,ev): # Only allow left-double clicks if ev.button()!=1: return self.key=Qt.Key_Backspace self.keyPressedSignal.emit() # Ensure that key presses are sent to the widget which the mouse is hovering over def enterEvent(self,ev): super(MixListWidget, self).enterEvent(ev) self.setFocus() # If ever the list if left by the mouse, emit (used to trigger ordering of passive functions) def leaveEvent(self,ev): self.leaveSignal.emit() # Return the lists entries in the order which it appears def visualListOrder(self): txt=np.array([self.item(i).text() for i in range(self.count())]) args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())]) return list(txt[np.argsort(args)]) # Generic widget for QListWidget with remove only keyPresses... # ...currently only used for key bind of delete (if want more keys, must check appropriate lists) class KeyListWidget(QtWidgets.QListWidget): # Return signal if key was pressed while in focus keyPressedSignal = QtCore.pyqtSignal() def __init__(self, parent=None): super(KeyListWidget, self).__init__(parent) # Update this widgets last pressed key, and return a signal def keyPressEvent(self, ev): self.key=ev.key() if self.key not in [Qt.Key_Delete]: return self.keyPressedSignal.emit() # Deselect all items if in a blank space def mousePressEvent(self, ev): if self.itemAt(ev.pos()) is None: self.clearSelection() QtWidgets.QListWidget.mousePressEvent(self, ev) # Ensure that key presses are sent to the widget which the mouse is hovering over def enterEvent(self,ev): super(KeyListWidget, self).enterEvent(ev) self.setFocus() # Return a lists entries in the order which is appears def visualListOrder(self): txt=np.array([self.item(i).text() for i in range(self.count())]) args=np.array([self.indexFromItem(self.item(i)).row() for i in range(self.count())]) return list(txt[np.argsort(args)]) # Convert any key press signal to a human readable string (ignores modifiers like shift, ctrl) def keyPressToString(ev): MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META) keyname = None key = ev.key() modifiers = int(ev.modifiers()) if key in [Qt.Key_Shift,Qt.Key_Alt,Qt.Key_Control,Qt.Key_Meta]: pass elif (modifiers and modifiers & MOD_MASK==modifiers and key>0): keyname=QtGui.QKeySequence(modifiers+key).toString() else: keyname=QtGui.QKeySequence(key).toString() return keyname # Line edit which returns key-bind strings class KeyBindLineEdit(QtWidgets.QLineEdit): keyPressed=QtCore.pyqtSignal(str) def __init__(self, parent=None): super(KeyBindLineEdit, self).__init__(parent) self.MOD_MASK = (Qt.CTRL | Qt.ALT | Qt.SHIFT | Qt.META) # If any usual key bind was pressed, return the human recognizable string def keyPressEvent(self, ev): keyname = keyPressToString(ev) if keyname==None: return self.keyPressed.emit(keyname) # Line edit which returns signal upon being double cliced class DblClickLineEdit(QtWidgets.QLineEdit): doubleClicked=QtCore.pyqtSignal() def __init__(self, parent=None): super(DblClickLineEdit, self).__init__(parent) def mouseDoubleClickEvent(self,ev): self.doubleClicked.emit() # Line edit which returns a signal upon being hovered out of class HoverLineEdit(QtWidgets.QLineEdit): hoverOut = QtCore.pyqtSignal() def __init__(self, parent=None): super(HoverLineEdit, self).__init__(parent) self.changeState=False self.textChanged.connect(self.updateChangeState) def leaveEvent(self, ev): # Only emit if the text was changed if self.changeState: self.hoverOut.emit() self.changeState=False def updateChangeState(self,ev): self.changeState=True # Generic widget for QListWidget with remove only keyPresses class DblClickLabelWidget(QtWidgets.QLabel): # Return signal if label was double clicked doubleClicked=QtCore.pyqtSignal() def __init__(self, parent=None): super(DblClickLabelWidget, self).__init__(parent) def mouseDoubleClickEvent(self,ev): self.doubleClicked.emit() # Widget to show/edit the source dictionary class SourceDictWidget(QtWidgets.QTreeWidget): def __init__(self, parent = None): QtWidgets.QTreeWidget.__init__(self, parent) self.setColumnCount(3) self.setHeaderLabels(["Name", "Type", "Value"]) self.setColumnWidth(0,130) self.setColumnWidth(1,90) # Check any edits which are made self.itemChanged.connect(self.checkEdits) # Value of an item prior to edit self.oldVal='' # Allowed variable data types self.varTypes=['str','int','float', 'array(str)', 'array(int)', 'array(float)'] self.varConverts=[str,int,float, lambda x: np.array(x.split(','),dtype=str), lambda x: np.array(x.split(','),dtype=int), lambda x: np.array(x.split(','),dtype=float)] # Keep default mouse presses def clickEvent(self,event): QtWidgets.QTreeWidget.mousePressEvent(self,event) # Clear selection if nothing clicked if self.itemAt(event.pos()) is None: self.clearSelection() def mousePressEvent(self, event): self.clickEvent(event) # If wanting to make add/remove an item (right click) if event.button() == QtCore.Qt.RightButton: self.createMenu(event) # Make a note of values prior to edits def mouseDoubleClickEvent(self,event): self.clickEvent(event) curItem=self.selectedItem() # Do nothing if no item selected if curItem is None: return # Allow group name to be edited, and the variable name/value curCol=self.currentColumn() if (curItem.parent() is None and curCol==0) or curCol!=1: self.oldVal=curItem.text(curCol) self.editItem(curItem,curCol) # Return list of the current group names def currentGroupNames(self): return[self.getName(groupItem) for groupItem in self.currentGroupItems()] # Return list of the current group items def currentGroupItems(self): return [self.topLevelItem(i) for i in range(self.topLevelItemCount())] # Return list of the variable names in a group item def currentVariableNames(self,groupItem): return [self.getName(varItem) for varItem in self.currentVariableItems(groupItem)] # Return list of variable items in a group item def currentVariableItems(self,groupItem): return [groupItem.child(i) for i in range(groupItem.childCount())] # Get the name of an item def getName(self,item): return str(item.text(0)) # Generate widget for a new group def addGroup(self,groupName='NewGroup'): # Check to see that the default name is not taken if groupName in self.currentGroupNames(): print('Name "'+groupName+'" already taken, edit before adding') return groupItem=QtWidgets.QTreeWidgetItem([groupName,'','']) # Allow the item to be edited groupItem.setFlags(groupItem.flags() | QtCore.Qt.ItemIsEditable) self.addTopLevelItem(groupItem) return groupItem # Generate widget for a new variable within a group def addVariable(self,groupItem,varName='NewVariable',varVal=None): # Check to see that the default name is not taken if varName in self.currentVariableNames(groupItem): print('Name "'+varName+'" already taken, edit before adding') return varText,varType=self.getVarTextAndType(varVal) # Give default values for new variable varItem=QtWidgets.QTreeWidgetItem([varName,'',varText]) # Allow the item to be edited varItem.setFlags(varItem.flags() | QtCore.Qt.ItemIsEditable) # Add the variable to the group groupItem.addChild(varItem) # Show what types are accepted comboBox=QtWidgets.QComboBox() comboBox.addItems(self.varTypes) # Set the current combo item comboBox.setCurrentIndex(self.varTypes.index(varType)) self.setItemWidget(varItem,1,comboBox) # Connect to check edits if this value is changed comboBox.currentIndexChanged.connect(lambda: self.checkEdits(varItem,1)) comboBox.highlighted.connect(lambda: self.setOldVal(comboBox.itemText(comboBox.currentIndex()))) # Used to set the previous comboBox value def setOldVal(self,val): self.oldVal=val # Import and display a given source dictionary def showSourceDict(self,sourceDict): # Clear the old for groupItem in self.currentGroupItems(): self.removeGroup(groupItem) # Load the new for groupName in sorted(sourceDict.keys()): groupItem=self.addGroup(groupName=str(groupName)) for varName in sorted(sourceDict[groupName].keys()): self.addVariable(groupItem,varName=str(varName), varVal=sourceDict[groupName][varName]) # Extract the displayed source dictionary def getSourceDict(self): sourceDict={} for groupItem in self.currentGroupItems(): groupName=self.getName(groupItem) sourceDict[groupName]={self.getName(varItem):self.stringToVarType(varItem) for varItem in self.currentVariableItems(groupItem)} return sourceDict # Remove currently selected group def removeGroup(self,item): self.takeTopLevelItem(self.indexFromItem(item).row()) # Remove currently selected variable def removeVariable(self,item): item.parent().takeChild(self.indexFromItem(item).row()) # Get the user visible value from the value and variable type def getVarTextAndType(self,val): # If the value is none, convert to string if val is None: return '','str' # Check first if a numpy array if type(val)==type(np.array([])): for aType in ['float','int','str']: match='|S' if aType=='str' else aType if match in str(val.dtype): if len(val.shape)==0: return str(val),'array('+aType+')' else: return ','.join(val.astype(str)),'array('+aType+')' # Otherwise check float,int,str for i in range(3)[::-1]: try: self.varConverts[i](val) return str(val),self.varTypes[i] except: continue return str(val),'str' # Convert the variable value to its appropriate type def stringToVarType(self,item): comboBox=self.itemWidget(item,1) varType=comboBox.itemText(comboBox.currentIndex()) convertFunc=self.varConverts[self.varTypes.index(varType)] if item.text(2).replace(' ','')=='': return None else: return convertFunc(item.text(2)) # Revert to an older value def revertEdits(self,item,col,message): # Disconnect from changed edits, revert to old value, reconnect print(message) self.itemChanged.disconnect(self.checkEdits) item.setText(col,self.oldVal) self.itemChanged.connect(self.checkEdits) # Check recent edits for errors def checkEdits(self,item,col): # Ensure names are unique if col==0: # Make a list of the names currently present if item.parent() is None: takenNames=self.currentGroupNames() else: takenNames=self.currentVariableNames(item.parent()) # If name already taken, revert to old if np.sum(np.array(takenNames,dtype=str)==str(item.text(col)))>1: self.revertEdits(item,col,'Name already taken') # Ensure type matches the value elif col==1 and item.parent() is not None: # Do not check if string (should always work) comboBox=self.itemWidget(item,1) if comboBox.itemText(comboBox.currentIndex())=='str': return try: self.stringToVarType(item) except Exception as error: # Disconnect from changed edits, revert to type string, reconnect print(str(error)+', reverting to old type') comboBox.setCurrentIndex(self.varTypes.index(self.oldVal)) # Ensure value matches the type elif col==2 and item.parent() is not None: try: self.stringToVarType(item) except Exception as error: self.revertEdits(item,col,str(error)+', reverting to old value') # Get the currently selected item def selectedItem(self): items=self.selectedItems() if len(items)==0: return None else: return items[0] # Create pop up menu to add/remove groups/variables def createMenu(self,event, parent=None): self.menu=QtWidgets.QMenu(parent) self.menu.addAction('Add Group', self.addGroup) if self.selectedItem() is not None: if self.selectedItem().parent() is None: self.menu.addAction('Add Variable',lambda: self.addVariable(self.selectedItem())) self.menu.addSeparator() self.menu.addAction('Remove Group',lambda: self.removeGroup(self.selectedItem())) elif self.selectedItem().parent().parent() is None: self.menu.addAction('Add Variable',lambda: self.addVariable(self.selectedItem().parent())) self.menu.addSeparator() self.menu.addAction('Remove Variable',lambda: self.removeVariable(self.selectedItem())) self.menu.move(self.mapToGlobal(QtCore.QPoint(0,0))+event.pos()) self.menu.show()
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/CustomWidgets.py", "copies": "1", "size": "16059", "license": "mit", "hash": 560402469127446200, "line_mean": 39.7116883117, "line_max": 106, "alpha_frac": 0.6123046267, "autogenerated": false, "ratio": 4.172252533125487, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.024936360854165132, "num_lines": 385 }
from __future__ import print_function from copy import deepcopy from future.utils import iteritems from PyQt5 import QtWidgets,QtGui,QtCore from PyQt5.QtCore import Qt import pyproj from CustomFunctions import dict2Text, text2Dict from lazylyst.UI.CustomPen import Ui_customPenDialog from lazylyst.UI.BasePen import Ui_basePenDialog from lazylyst.UI.ComboBox import Ui_comboBoxDialog from lazylyst.UI.MapProj import Ui_mapProjDialog from lazylyst.UI.ListEntry import Ui_listEntryDialog # Default Preferences def defaultPreferences(main): pref={ 'staPerPage':Pref(tag='staPerPage',val=6,dataType=int, func=main.updateStaPerPage,condition={'bound':[1,30]}, tip='Number of stations (trace widgets) to display on each page'), 'evePreTime':Pref(tag='evePreTime',val=-30,dataType=float, tip='Time in seconds prior to the selected pick file names time to grab data'), 'evePostTime':Pref(tag='evePostTime',val=60,dataType=float, tip='Time in seconds after to the selected pick file names time to grab data'), 'eveIdGenStyle':Pref(tag='eveIdGenStyle',val='next',dataType=str, dialog='ComboBoxDialog',condition={'isOneOf':['fill','next']}, tip='Style used to generate a new empty pick files ID (when double clicking the archive event widget)'), 'eveSortStyle':Pref(tag='eveSortStyle',val='time',dataType=str, dialog='ComboBoxDialog',func=main.updateEveSort,condition={'isOneOf':['id','time']}, tip='How the archive list widget is sorted, also sorts hot variable pickFiles and pickTimes'), 'cursorStyle':Pref(tag='cursorStyle',val='arrow',dataType=str, dialog='ComboBoxDialog',func=main.updateCursor,condition={'isOneOf':['arrow','cross']}, tip='Cursor icon to use while hovering over plots'), 'remExcessPicksStyle':Pref(tag='remExcessPicksStyle',val='oldest',dataType=str, dialog='ComboBoxDialog',condition={'isOneOf':['oldest','closest','furthest']}, tip='Which excess pick(s) will be deleted when manually adding picks'), 'mapProj':Pref(tag='mapProj', val={'type':'Simple', 'epsg':'4326', 'simpleType':'AEA Conic', 'zDir':'end', 'units':'km', 'func':None, 'funcInv':None}, dataType=dict, dialog='MapProjDialog',func=main.updateMapProj, tip='Projection to be applied when converting Lat,Lon,Ele to X,Y,Z', loadOrder=0), 'pythonPathAdditions':Pref(tag='pythonPathAdditions',val=[],dataType=list, dialog='ListEntryDialog',tip='Directories to add to the python path', func=main.updatePythonPath), 'pickTypesMaxCountPerSta':Pref(tag='pickTypesMaxCountPerSta',val={'P':1,'S':1},dataType=dict, func=main.updatePagePicks,condition={'bound':[1,999]}, tip='Max number of picks of a given phase type allowed on any individual trace widget'), 'basePen':Pref(tag='basePen',val={'widgetText':[14474460,1.0,0.0,False], # [Color,Width,Depth,UpdateMe] 'traceBackground':[0,1.0,0.0,False], 'timeBackground':[0,1.0,0.0,False], 'imageBackground':[0,1.0,0.0,False], 'imageBorder':[16777215,2.0,-1.0,False], 'mapBackground':[0,1.0,0.0,False], 'mapStaDefault':[16777215,4.0,0.0,False], 'mapCurEve':[16776960,3.0,2.0,False], 'mapPrevEve':[13107400,2.0,1.0,False], 'mapPolygon':[3289800,1.0,10.0,False], 'archiveBackground':[0,1.0,0.0,False], 'archiveAvailability':[65280,1.0,0.0,False], 'archiveSpanSelect':[3289800,1.0,0.0,False], 'archiveCurEve':[16711680,3.0,1.0,False], 'archivePrevEve':[48865,1.0,0.0,False],}, dataType=dict,dialog='BasePenDialog',func=main.updateBaseColors, tip='Defines the base pen values for the main widgets'), 'customPen':Pref(tag='customPen',val={'default':[16777215,1.0,0.0], # [Color,Width,Depth] 'noStaData':[3289650,1.0,0.0], 'noTraceData':[8224125,1.0,0.0], 'goodMap':[65280,1.0,0.0], 'poorMap':[16711680,1.0,0.0], 'highlight':[255,1.0,2.0], 'lowlight':[13158600,0.3,1.0],},dataType=dict, dialog='CustomPenDialog',func=main.updateCustomPen, tip='Defines the custom pen values referenced by PenAssign hot variables'), 'pickPen':Pref(tag='pickPen',val={'default':[16777215,1.0,4.0], 'P':[65280,1.0,5.0], 'S':[16776960,1.0,5.0],},dataType=dict, dialog='CustomPenDialog',func=main.updatePagePicks, tip='Defines the pen values for the pick lines'), } return pref # Capabilities for preferences class Pref(object): def __init__(self,tag=None,val=None,dataType=str, dialog='LineEditDialog', func=None,condition={},tip='',loadOrder=999): self.tag=tag # The preference key, and user visible name self.val=val # The preference value self.dataType=dataType # What kind of data is expected upon update self.dialog=dialog # The dialog which will pop up to return a value self.func=func # Function which is called on successful updates self.condition=condition # Key-word conditionals (see "LineEditDialog" in this file) self.tip=tip # Short description of the preference self.loadOrder=loadOrder # Priority in loading the preferencing (lower value loaded first) # Return a deep copy of the objects value def getVal(self): val=deepcopy(self.val) return val # If the key was asked to be updated def update(self,hostWidget,init=False): # If this is the original initalization, don't ask for new value if not init: # Use the correct dialog... # ...text entry dialog if self.dialog=='LineEditDialog': if self.dataType==dict: initText=dict2Text(self.val) else: initText=str(self.val) val,ok=LineEditDialog.returnValue(tag=self.tag,initText=initText, condition=self.condition, dataType=self.dataType) # ...selecting from a list elif self.dialog=='ComboBoxDialog': val,ok=ComboBoxDialog.returnValue(self.val,self.condition['isOneOf'],self.tag) # ...default widget colors elif self.dialog=='BasePenDialog': BasePenDialog(self.val).exec_() # The checks and updates to the preference value are done within the dialog val,ok=self.val,True # ...custom colors and widths elif self.dialog=='CustomPenDialog': CustomPenDialog(self.val,self.tag).exec_() # The checks and updates to the preference value are done within the dialog val,ok=self.val,True # ...defining the map projection elif self.dialog=='MapProjDialog': val,ok=ProjDialog.returnValue(self.val) # ...editing items on a list elif self.dialog=='ListEntryDialog': val,ok=ListDialog.returnValue(self.tag,self.val) else: print('New dialog?') val,ok=None,False # If the dialog was canceled, skip if not ok: return # If the no value was returned, skip if val==None: print('Value did not conform to '+str(self.dataType)+' and conditionals '+str(self.condition)) return # Update the preference value self.val=val # If the value was updated, queue off its function if self.func!=None: self.func(init=init) # Dialog with line edit, allows for some initial text, and forced data type and condition class LineEditDialog(QtWidgets.QDialog): def __init__(self,parent,tag,initText,condition,dataType): super(LineEditDialog, self).__init__(parent) self.setWindowTitle(tag) self.cond=condition self.dataType=dataType # Set up the layout and line edit layout = QtWidgets.QVBoxLayout(self) self.le = QtWidgets.QLineEdit(self) self.le.setText(initText) layout.addWidget(self.le) # OK and Cancel buttons self.buttons = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, Qt.Horizontal, self) layout.addWidget(self.buttons) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) # Get the text from the line edit def lineEditValue(self): val=self.le.text() # See first that the data type conforms try: # Allow user to type in the dictionary a bit easier if self.dataType==dict: val=text2Dict(val) if val=={}: print('No keys are present in the dictionary') return None else: val=self.dataType(val) except: return None # Loop through all values (usually just one, can be more for dictionary) if self.dataType==dict: vals=[aVal for key,aVal in iteritems(val)] else: vals=[val] # ...and check against the built in conditionals keys=[key for key in self.cond.keys()] for aVal in vals: if 'bound' in keys: if aVal<self.cond['bound'][0] or aVal>self.cond['bound'][1]: return None return val # Static method to create the dialog and return value @staticmethod def returnValue(parent=None,tag='',initText='',condition={},dataType=str): dialog = LineEditDialog(parent,tag,initText,condition,dataType) result = dialog.exec_() return dialog.lineEditValue(), result==QtWidgets.QDialog.Accepted # Dialog window for editing the basic widget colors class BasePenDialog(QtWidgets.QDialog, Ui_basePenDialog): def __init__(self,tpDict,parent=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.tpDict=tpDict self.keyOrder=sorted(self.tpDict.keys()) # Used to reference back before the last user change # Fill in the current customPen information (before setting functionality, as functionality has a "onChanged" signal) self.fillDialog() # Give the dialog some functionaly self.setFunctionality() # Set up some functionality to the custom pen dialog def setFunctionality(self): self.tpTable.itemDoubleClicked.connect(self.updatePenColor) self.tpTable.itemChanged.connect(self.updateItemText) # Fill the dialog with info relating to the current customPen dictionary def fillDialog(self): # Make the table large enough to hold all current information self.tpTable.setRowCount(len(self.tpDict)) self.tpTable.setColumnCount(4) # Set the headers self.tpTable.setHorizontalHeaderLabels(['Tag','Color','Width','Depth']) # Enter data onto Table for m,key in enumerate(sorted(self.tpDict.keys())): # Generate the table items... tagItem=QtWidgets.QTableWidgetItem(key) tagItem.setFlags(Qt.ItemIsEnabled) penItem=QtWidgets.QTableWidgetItem('') penItem.setFlags(Qt.ItemIsEnabled) penItem.setBackground(QtGui.QColor(self.tpDict[key][0])) widItem=QtWidgets.QTableWidgetItem(str(self.tpDict[key][1])) depItem=QtWidgets.QTableWidgetItem(str(self.tpDict[key][2])) # Put items in wanted position self.tpTable.setItem(m,0,tagItem) self.tpTable.setItem(m,1,penItem) self.tpTable.setItem(m,2,widItem) self.tpTable.setItem(m,3,depItem) # Resize the dialog self.tpTable.resizeColumnsToContents() # Update the pen color for a given tag def updatePenColor(self,item): if item.column()!=1: return itemKey=self.keyOrder[item.row()] # Go get a new color colorDialog=QtWidgets.QColorDialog() val=colorDialog.getColor(QtGui.QColor(self.tpDict[itemKey][0]),self) # Set the new color (if the dialog was not canceled) if val.isValid(): val=val.rgba() item.setBackground(QtGui.QColor(val)) self.tpDict[itemKey][0]=val # Mark that this item was edited self.tpDict[itemKey][3]=True # Update the text values, if changed def updateItemText(self,item): if item.column()in [0,1]: return # The key, prior to changes itemKey=self.keyOrder[item.row()] # Updating the width or depth values if item.column() in [2,3]: prefIdx=item.column()-1 try: val=float(item.text()) except: val=-99999 # Ensure the width value is reasonable, if not change back the original if prefIdx==1 and (val<0 or val>10): print('Width should be in the range [0,10]') item.setText(str(self.tpDict[itemKey][prefIdx])) elif prefIdx==2 and (val<-10 or val>=10): print('Depth should be in the range [-10,10)') item.setText(str(self.tpDict[itemKey][prefIdx])) # If passed checks, update the tpDict with the new width or depth else: self.tpDict[itemKey][prefIdx]=float(item.text()) # Mark that this item was edited self.tpDict[itemKey][3]=True # Dialog window for editing the custom colors and widths class CustomPenDialog(QtWidgets.QDialog, Ui_customPenDialog): def __init__(self,tpDict,tag,parent=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.setWindowTitle(tag) self.tpDict=tpDict self.keyOrder=sorted(self.tpDict.keys()) # Used to reference back before the last user change # Fill in the current customPen information (before setting functionality, as functionality has a "onChanged" signal) self.fillDialog() # Give the dialog some functionaly self.setFunctionality() # Set up some functionality to the custom pen dialog def setFunctionality(self): self.tpTable.itemDoubleClicked.connect(self.updatePenColor) self.tpTable.itemChanged.connect(self.updateItemText) self.tpInsertButton.clicked.connect(self.insertPen) self.tpDeleteButton.clicked.connect(self.deletePen) # Fill the dialog with info relating to the current customPen dictionary def fillDialog(self): # Make the table large enough to hold all current information self.tpTable.setRowCount(len(self.tpDict)) self.tpTable.setColumnCount(4) # Set the headers self.tpTable.setHorizontalHeaderLabels(['Tag','Color','Width','Depth']) # Enter data onto Table for m,key in enumerate(sorted(self.tpDict.keys())): # Generate the table items... tagItem=QtWidgets.QTableWidgetItem(key) if key=='default': tagItem.setFlags(Qt.ItemIsEnabled) penItem=QtWidgets.QTableWidgetItem('') penItem.setFlags(Qt.ItemIsEnabled) penItem.setBackground(QtGui.QColor(self.tpDict[key][0])) widItem=QtWidgets.QTableWidgetItem(str(self.tpDict[key][1])) depItem=QtWidgets.QTableWidgetItem(str(self.tpDict[key][2])) # Put items in wanted position self.tpTable.setItem(m,0,tagItem) self.tpTable.setItem(m,1,penItem) self.tpTable.setItem(m,2,widItem) self.tpTable.setItem(m,3,depItem) # Update the pen color for a given tag def updatePenColor(self,item): if item.column()!=1: return itemKey=self.keyOrder[item.row()] # Go get a new color colorDialog=QtWidgets.QColorDialog() val=colorDialog.getColor(QtGui.QColor(self.tpDict[itemKey][0]),self) # Set the new color (if the dialog was not canceled) if val.isValid(): val=val.rgba() item.setBackground(QtGui.QColor(val)) self.tpDict[itemKey][0]=val # Update the text values, if changed def updateItemText(self,item): if item.column()==1: return # Disconnect itself, changes occur here weird looping otherwise self.tpTable.itemChanged.disconnect(self.updateItemText) # The key, prior to changes itemKey=self.keyOrder[item.row()] # Updating the width or depth values if item.column() in [2,3]: prefIdx=item.column()-1 try: val=float(item.text()) except: val=-99999 # Ensure the width value is reasonable, if not change back the original if prefIdx==1 and (val<0 or val>10): print('Width should be in the range [0,10]') item.setText(str(self.tpDict[itemKey][prefIdx])) elif prefIdx==2 and (val<-10 or val>=10): print('Depth should be in the range [-10,10)') item.setText(str(self.tpDict[itemKey][prefIdx])) # If passed checks, update the tpDict with the new width or depth else: self.tpDict[itemKey][prefIdx]=float(item.text()) # Updating the tag elif item.column()==0: # If the same, do nothing if item.text()==itemKey: pass # Do not allow duplicate tags elif item.text() in [key for key in self.tpDict.keys() if key!=itemKey]: print('This tag is already present, update denied') item.setText(itemKey) else: # If passed checks, update the tpDict with the new tag self.tpDict[str(item.text())]=self.tpDict[itemKey] self.tpDict.pop(itemKey) # Update the key order, so can reference back before changes self.keyOrder[item.row()]=str(item.text()) # Reconnect to OnChanged signal self.tpTable.itemChanged.connect(self.updateItemText) # Insert a new pen def insertPen(self): # If the "NewPen" key is still present, ask to change it... if 'NewPen' in [key for key in self.tpDict.keys()]: print('Change the tag "NewPen", to be able to add another custom pen"') return # Disconnect the OnChanged signal (as this would trigger it) self.tpTable.itemChanged.disconnect(self.updateItemText) # Add a row with the default parameters m=self.tpTable.rowCount() self.tpTable.setRowCount(m+1) self.tpTable.setItem(m,0,QtWidgets.QTableWidgetItem('NewPen')) penItem=QtWidgets.QTableWidgetItem('') penItem.setFlags(Qt.ItemIsEnabled) self.tpTable.setItem(m,1,penItem) self.tpTable.setItem(m,2,QtWidgets.QTableWidgetItem('1.0')) self.tpTable.setItem(m,3,QtWidgets.QTableWidgetItem('0.0')) # Add it also to the dictionary self.tpDict['NewPen']=[4294967295,1.0,0.0] # Update the keyOrder self.keyOrder.append('NewPen') # Reconnect to OnChanged signal self.tpTable.itemChanged.connect(self.updateItemText) # Delete the currently selected pen def deletePen(self): idx=self.tpTable.currentRow() key=str(self.tpTable.item(idx,0).text()) # Not allowed to delete default if key=='default': print('Cannot delete the pen tagged default') return # Disconnect the OnChanged signal (as this would trigger it) self.tpTable.itemChanged.disconnect(self.updateItemText) self.tpTable.removeRow(idx) self.keyOrder.pop(idx) self.tpDict.pop(key) # Reconnect to OnChanged signal self.tpTable.itemChanged.connect(self.updateItemText) # Dialog to get a specific date time back class DateDialog(QtWidgets.QDialog): def __init__(self, parent = None): super(DateDialog, self).__init__(parent) # Give a window title self.setWindowTitle('Date Time Select') layout = QtWidgets.QVBoxLayout(self) # Widget for editing the date self.datetime = QtWidgets.QDateTimeEdit(self) self.datetime.setDisplayFormat('yyyy-MM-dd hh:mm:ss') layout.addWidget(self.datetime) # OK and Cancel buttons buttons = QtWidgets.QDialogButtonBox( QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, Qt.Horizontal, self) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) # Get current date and time from the dialog def dateTime(self): return self.datetime.dateTime() # Static method to create the dialog and return [timestamp, accepted] @staticmethod def getDateTime(bound,parent = None): # Start dialog dialog = DateDialog(parent) # Set the previous string value prevDateTime=QtCore.QDateTime() prevDateTime.setTimeSpec(Qt.UTC) prevDateTime.setTime_t(int(bound)) dialog.datetime.setDateTime(prevDateTime) # Get and return value result = dialog.exec_() dateTime=dialog.dateTime() dateTime.setTimeSpec(Qt.UTC) newBound = dateTime.toTime_t() return newBound, result == QtWidgets.QDialog.Accepted # Dialog window for selecting one of a few options class ComboBoxDialog(QtWidgets.QDialog, Ui_comboBoxDialog): def __init__(self,parent,curVal,acceptVals,tag): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.setWindowTitle(tag) # Fill in the combo dialog box self.comboBox.addItems(acceptVals) # Set the current text to be the current preference value index = self.comboBox.findText(curVal) if index >= 0: self.comboBox.setCurrentIndex(index) # Static method to create the dialog and return the selected value @staticmethod def returnValue(curVal,acceptVals,tag,parent=None): dialog=ComboBoxDialog(parent,curVal,acceptVals,tag) result=dialog.exec_() return dialog.comboBox.currentText(), result==QtWidgets.QDialog.Accepted # Dialog to hold a list of strings class ListDialog(QtWidgets.QDialog, Ui_listEntryDialog): def __init__(self,tag,initList,parent=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) # Set name of the preference being changed self.setWindowTitle(tag) self.setFunctionality() self.fillDialog(initList) # Set up some functionality to the list entry dialog def setFunctionality(self): self.entryAddButton.clicked.connect(lambda x:self.addEntry()) self.entryDelButton.clicked.connect(self.removeEntry) self.entryListWidget.keyPressedSignal.connect(self.doKeyPress) # Fill the list with current preference entries def fillDialog(self,initList): for entry in initList: self.addEntry(entry) # Handle the keys given by the list widget def doKeyPress(self): if self.entryListWidget.key==Qt.Key_Insert: self.addEntry() elif self.entryListWidget.key==Qt.Key_Delete: self.removeEntry() elif self.entryListWidget.key==Qt.Key_Backspace: self.editEntry() # Remove an entry from the list def removeEntry(self): try: if not self.entryListWidget.currentItem().isSelected(): return self.entryListWidget.takeItem(self.entryListWidget.currentRow()) except: pass # Add an item to the list def addEntry(self,text='#NewEntry'): if text in self.entryListWidget.visualListOrder(): return item=QtWidgets.QListWidgetItem() item.setText(text) # Allow the item to be edited by clicking on it item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) self.entryListWidget.addItem(item) # Edit an entry in the list def editEntry(self): index = self.entryListWidget.currentIndex() if index.isValid(): item = self.entryListWidget.itemFromIndex(index) if not item.isSelected(): item.setSelected(True) self.entryListWidget.edit(index) # Return the lists unique entries @staticmethod def returnValue(tag,initList): dialog=ListDialog(tag,initList) result=dialog.exec_() return list(set(dialog.entryListWidget.visualListOrder())),result==QtWidgets.QDialog.Accepted # Dialog window for selecting the projection to be used on the map class ProjDialog(QtWidgets.QDialog,Ui_mapProjDialog): def __init__(self,projDict,parent=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.projDict=projDict # Fill the dialog with current values self.fillDialog() # Give the dialog some functionality self.setFunctionality() # Set up some functionality to the action set up dialog def setFunctionality(self): self.epsgLineEdit.editingFinished.connect(self.checkValidEpsg) self.simpleProjComboBox.currentIndexChanged.connect(self.toggleUnitCombo) self.simpleProjRadio.clicked.connect(self.toggleProjType) self.customProjRadio.clicked.connect(self.toggleProjType) # Fill the dialog with info relating to the current map projection def fillDialog(self): # Fill combo boxes self.simpleProjComboBox.addItems(['None','AEA Conic','UTM']) # Set values with current projection... # ...current epsg code self.epsgLineEdit.setText(str(self.projDict['epsg'])) # ...type of the projection (simple/custom) if self.projDict['type']=='Simple': self.simpleProjRadio.setChecked(True) else: self.customProjRadio.setChecked(True) self.setComboValue(self.simpleProjComboBox,self.projDict['simpleType']) # ...direction of the z-axis (positive up/down) self.zDirCheckBox.setChecked(self.projDict['zDir']=='end') # ...projection type and units self.toggleProjType() # Toggle type first to fill unit combo box self.setComboValue(self.unitsComboBox,self.projDict['units']) # Set a combo lists value def setComboValue(self,comboBox,value): # Set the current text to be the current preference value index = comboBox.findText(value) if index >= 0: comboBox.setCurrentIndex(index) else: comboBox.setCurrentIndex(0) # Ensure EPSG code is valid def checkValidEpsg(self): if not self.epsgLineEdit.isEnabled(): return curText=str(self.epsgLineEdit.text()) # Ensure the code is an integer value try: int(curText) # Check if the EPSG code exists try: self.getProjFunc(curText) # If possible to get the code, toggle the units self.toggleUnitCombo() return except: print('The EPSG code was not valid') except: print('The EPSG code must be an integer value') # If got an invalid code revert to old value print('Reverting to intial EPSG') self.epsgLineEdit.setText(str(self.projDict['epsg'])) # Get the projection function for a given EPSG code def getProjFunc(self,epsg): return pyproj.Proj(init='EPSG:'+epsg) # Get the current map projection dictionary def getCurProjDict(self): curDict={'type':'Simple' if self.simpleProjRadio.isChecked() else 'Custom', 'epsg':self.epsgLineEdit.text(), 'simpleType':self.simpleProjComboBox.currentText(), 'zDir':'end' if self.zDirCheckBox.isChecked() else 'enu', 'units':self.unitsComboBox.currentText(), 'func':None, 'funcInv':None} return curDict # Toggle between simple and custom projection types def toggleProjType(self): isSimple=self.simpleProjRadio.isChecked() self.epsgLineEdit.setEnabled(not isSimple) self.simpleProjComboBox.setEnabled(isSimple) # Toggle the available units (as can change between simple/custom) self.toggleUnitCombo() # Toggle which units are available for the current projection def toggleUnitCombo(self): curDict=self.getCurProjDict() self.unitsComboBox.clear() # If the projection is in degrees only if ((curDict['type']=='Simple' and curDict['simpleType']=='None') or (curDict['type']=='Custom' and self.getProjFunc(curDict['epsg']).is_latlong())): self.unitsComboBox.addItems(['deg']) else: self.unitsComboBox.addItems(['m','km','ft','yd','mi']) # Set the units to original if still present self.setComboValue(self.unitsComboBox,curDict['units']) # Static method to create the dialog and return the selected value @staticmethod def returnValue(projDict): dialog=ProjDialog(projDict) result=dialog.exec_() # Recheck the projection dialog.checkValidEpsg() return dialog.getCurProjDict(),result==QtWidgets.QDialog.Accepted
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/Preferences.py", "copies": "1", "size": "31987", "license": "mit", "hash": -2165522249647261200, "line_mean": 44.5633187773, "line_max": 129, "alpha_frac": 0.588145184, "autogenerated": false, "ratio": 4.258687258687258, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.021318452035613465, "num_lines": 687 }
from __future__ import print_function import importlib import sys from future.utils import iteritems from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtCore import Qt from lazylyst.UI.ActionSetup import Ui_actionDialog from CustomFunctions import dict2Text, text2Dict # Default Actions def defaultActions(): act={ 'OpenOptions':Action(tag='OpenOptions',name='openConfiguration', path='$main', trigger=Qt.Key_O,locked=True), 'ChangeSource':Action(tag='ChangeSource',name='openChangeSource', path='$main', trigger=Qt.Key_P,locked=True), 'CloseLazylyst':Action(tag='CloseLazylyst',name='passAction', path='$main',trigger='DoubleClick',locked=True), 'OpenLazylyst':Action(tag='OpenLazylyst',name='passAction', path='$main',trigger='DoubleClick',locked=True), 'ToggleImage':Action(tag='ToggleImage',name='toggleImageWidget', path='$main',trigger=QtGui.QKeySequence('F4'),locked=True), 'ReloadPlugins':Action(tag='ReloadPlugins',name='reloadPlugins', path='$main',trigger=QtGui.QKeySequence('F5'),locked=True), 'ReloadArchive':Action(tag='ReloadArchive',name='updateArchive', path='$main',optionals={'showBar':False,'resetSearch':True}, trigger=QtGui.QKeySequence('F6'),threaded=True), 'SaveSettings':Action(tag='SaveSettings',name='saveSettings', path='$main',optionals={'closing':False}, trigger=QtGui.QKeySequence('Ctrl+S'),locked=True), 'Screenshot':Action(tag='Screenshot',name='takeScreenshot', path='$main',trigger=QtGui.QKeySequence('F8'),locked=True), 'PageNext':Action(tag='PageNext',name='tabCurPage', path='$main',optionals={'nextPage':True}, trigger=Qt.Key_D,locked=True), 'PagePrev':Action(tag='PagePrev',name='tabCurPage', path='$main',optionals={'prevPage':True}, trigger=Qt.Key_A,locked=True), 'FiltNone':Action(tag='FiltNone',name='streamFilter', path='Plugins.Filters',optionals={'type':'raw'}, trigger=QtGui.QKeySequence('Shift+~'),inputs=['stream'],returns=['pltSt']), 'FiltHP1':Action(tag='FiltHP1',name='streamFilter', path='Plugins.Filters',optionals={'type':'highpass','freq':1,'corners':1,'zerophase':True}, trigger=QtGui.QKeySequence('Shift+Q'),inputs=['stream'],returns=['pltSt']), 'FiltHP5':Action(tag='FiltHP5',name='streamFilter', path='Plugins.Filters',optionals={'type':'highpass','freq':5,'corners':1,'zerophase':True}, trigger=QtGui.QKeySequence('Shift+W'),inputs=['stream'],returns=['pltSt']), 'FiltHP10':Action(tag='FiltHP10',name='streamFilter', path='Plugins.Filters',optionals={'type':'highpass','freq':10,'corners':1,'zerophase':True}, trigger=QtGui.QKeySequence('Shift+E'),inputs=['stream'],returns=['pltSt']), 'FiltDeriv':Action(tag='FiltDeriv',name='streamFilter', path='Plugins.Filters',optionals={'type':'derivative'}, trigger=QtGui.QKeySequence('Shift+R'),inputs=['stream'],returns=['pltSt']), 'PickModeP':Action(tag='PickModeP',name='setPickMode', path='Plugins.General',optionals={'wantMode':'P'}, trigger=QtGui.QKeySequence('1'),inputs=['pickTypesMaxCountPerSta'],returns=['pickMode']), 'PickModeS':Action(tag='PickModeS',name='setPickMode', path='Plugins.General',optionals={'wantMode':'S'}, trigger=QtGui.QKeySequence('2'),inputs=['pickTypesMaxCountPerSta'],returns=['pickMode']), 'ToggleTracePen':Action(tag='ToggleTracePen',name='setTracePenAssign', path='Plugins.General',passive=True, trigger=['PickModeP','PickModeS','PickFileSetToClick','PickFileNext','PickFilePrev'], inputs=['pickMode','tracePenAssign'],returns=['tracePenAssign']), 'PickAdd':Action(tag='PickAdd',name='addClickPick', path='$main',trigger='DoubleClick',locked=True), 'PickDelete':Action(tag='PickDelete',name='delPick', path='Plugins.General',trigger=Qt.Key_4, inputs=['pickSet','pickMode','curTraceSta'],returns=['pickSet']), 'PickSetDelete':Action(tag='PickSetDelete',name='delPickSet', path='Plugins.General',trigger=QtGui.QKeySequence('Shift+$'), inputs=[],returns=['pickSet']), 'PickFileCurDelete':Action(tag='PickFileCurDelete',name='removeCurPickFile', path='Plugins.General',trigger=Qt.Key_Delete, inputs=['curPickFile','pickFiles'],returns=['pickFiles']), 'PickFileSetToClick':Action(tag='PickFileSetToClick',name='setCurPickFileOnClick', path='$main',trigger='DoubleClick',returns=['curPickFile'],locked=True), 'PickFileNext':Action(tag='PickFileNext',name='setCurPickFile',path='Plugins.General', optionals={'nextFile':True},trigger=QtGui.QKeySequence('Shift+D'),locked=True, inputs=['curPickFile','pickFiles'],returns=['curPickFile']), 'PickFilePrev':Action(tag='PickFilePrev',name='setCurPickFile',path='Plugins.General', optionals={'prevFile':True},trigger=QtGui.QKeySequence('Shift+A'),locked=True, inputs=['curPickFile','pickFiles'],returns=['curPickFile']), 'SavePickSetOnNewEve':Action(tag='SavePickSetOnNewEve',name='savePickSet', path='$main',passive=True, trigger=['PickFileSetToClick','PickFileNext','PickFilePrev','CloseLazylyst'], beforeTrigger=True), 'MapDblClicked':Action(tag='MapDblClicked',name='updateMapDblClickedVars', path='$main',trigger='DoubleClick',locked=True), 'GoToStaPage':Action(tag='GoToStaPage',name='goToStaPage',path='Plugins.General', passive=True,trigger=['MapDblClicked'], inputs=['curMapSta','staSort','staPerPage','curPage'], returns=['curPage']), 'SimpleLocate':Action(tag='SimpleLocate',name='simpleLocator',path='Plugins.Locate', passive=True, trigger=['PickAdd','PickDelete','PickSetDelete','PickFileCurDelete', 'PickFileNext','PickFilePrev','PickFileSetToClick','ChangeSource'], inputs=['pickSet','staLoc','mapProj','staSort','sourceDict'], returns=['mapCurEve','traceBgPenAssign','mapStaPenAssign']), 'StaSortAlph':Action(tag='StaSortAlph',name='staSortAlph',path='Plugins.Sorting', trigger=QtGui.QKeySequence('Z'), inputs=['staSort'], returns=['staSort']), 'StaSortPickTime':Action(tag='StaSortPickTime',name='staSortPickTime',path='Plugins.Sorting', trigger=QtGui.QKeySequence('X'), inputs=['staSort','pickSet','pickMode'], returns=['staSort']), 'StaSortDist':Action(tag='StaSortDist',name='staSortDist',path='Plugins.Sorting', trigger=QtGui.QKeySequence('C'), inputs=['staSort','staLoc','mapCurEve','mapProj'], returns=['staSort']), 'StaSortResidual':Action(tag='StaSortResidual',name='staSortResidual',path='Plugins.Sorting', trigger=QtGui.QKeySequence('V'), inputs=['staSort','staLoc','sourceDict','pickSet','mapCurEve','mapProj'], returns=['staSort']), 'StaSortReverse':Action(tag='StaSortReverse',name='staSortReverse',path='Plugins.Sorting', trigger=QtGui.QKeySequence('B'), inputs=['staSort'], returns=['staSort']), 'ImageSpectVert':Action(tag='ImageSpectVert',name='spectrogramVert',path='Plugins.Image', trigger=QtGui.QKeySequence('Ctrl+F'), inputs=['pltSt','curTraceSta'], returns=['image']), } return act # Give the passive actions above some default ordering (ie. which is called first) def defaultPassiveOrder(actions): order=sorted([act.tag for tag,act in iteritems(actions) if act.passive]) # order=['SavePickSetOnNewEve','SimpleLocate'] ## Ensure this includes ALL default passive return order # Capabilities of an action class Action(object): def __init__(self,tag='New action',name='Function name', path='Add path to function',optionals={}, passive=False,beforeTrigger=False,timer=False, trigger='Add Trigger',inputs=[],returns=[], timerInterval=60,func=None,locked=False, sleeping=False,threaded=False): self.tag=tag # User visible name for the action self.name=name # Function name self.path=path # Function path (uses "." instead of "\", path is relative a directory in the systems PATH variable) self.optionals=optionals # Dictionary of the optional values which can be sent to the function self.passive=passive # If the action is passive, this is true self.beforeTrigger=beforeTrigger # If the passive function should be applied before/after the function self.timer=timer # If active, can use this to use a QTimer to set things off self.timerInterval=timerInterval # Interval time in seconds for the timer self.trigger=trigger # Trigger of the action self.inputs=inputs # Hot variables to be sent as inputs to the function (in the correct order) self.returns=returns # Hot variables to be returned for update self.func=func # Function which is called upon trigger self.locked=locked # If the action is allowed to be altered (other than the trigger) self.sleeping=sleeping # If the action is responding to triggers or not self.threaded=threaded # If the action is to be run on a seperate thread ("in background") # convert the trigger to a key sequence, if the trigger was a key if type(trigger)==type(Qt.Key_1): self.trigger=QtGui.QKeySequence(self.trigger) # When loading the previous settings, must link the action to its functions again def linkToFunction(self,main,reloadMod=False): # If the path does not relate to already defined function locations if self.path not in ['$main']: # Extract the function try: mod=importlib.import_module(self.path) # Force reloading of the module if wanted if reloadMod: if sys.version_info[0]==2: reload(mod) else: importlib.reload(mod) func=getattr(mod,self.name) except Exception as error: print(error) print('Action '+self.tag+' did not load from '+self.path+'.'+self.name) return # Otherwise, grab function from predefined location else: try: if self.path=='$main': func=getattr(main,self.name) except: print(self.tag+' did not load from '+self.path+'.'+self.name) return # Assign the function to the action self.func=func return # Assign the default attributes which were are added in newer versions... # ...if not already present def fillMissingAttrib(self): defAct=Action() for attrib in ['sleeping','threaded']: try: getattr(self,attrib) except: setattr(self,attrib,getattr(defAct,attrib)) # Action setup dialog class ActionSetupDialog(QtWidgets.QDialog, Ui_actionDialog): def __init__(self,main,action,actDict,hotVar,pref,tempLock,parent=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.trigReminder=False # Used for reminder to user if toggling between active/passive self.main=main # The main window self.action=action # The action to update self.actDict=actDict # All other actions self.hotVar=hotVar # Inputs/returns to go to/from function self.pref=pref # Additional inputs to go to the function # Give the dialog some functionaly self.setFunctionality() # Load in the text to the related action self.fillDialog() # Disable the majority of this gui if the action is locked... if self.action.locked or tempLock: self.lockDialog() # ...also, if this is only click event (double click for adding one pick) if self.action.trigger=='DoubleClick': self.actTriggerLineEdit.setEnabled(False) # Set up some functionality to the action set up dialog def setFunctionality(self): # For radio buttons, passive/active self.actActiveRadio.clicked.connect(lambda: self.togglePassiveActive()) self.actPassiveRadio.clicked.connect(lambda: self.togglePassiveActive()) # For the tag line edit, to remind if a tag is already being used self.actTagLineEdit.hoverOut.connect(self.unqTagName) # For the trigger line (active) and lists (passive) self.actTriggerLineEdit.keyPressed.connect(self.updateKeyBind) self.actAvailTriggerList.itemDoubleClicked.connect(lambda: self.addAvailVar('trigger')) self.actSelectTriggerList.keyPressedSignal.connect(lambda: self.removeSelectVar('trigger')) self.actSelectTriggerList.itemDoubleClicked.connect(lambda: self.removeSelectVar('trigger')) # For the input/return, avail/select lists self.actAvailInputList.itemDoubleClicked.connect(lambda: self.addAvailVar('input')) self.actAvailReturnList.itemDoubleClicked.connect(lambda: self.addAvailVar('return')) self.actSelectInputList.keyPressedSignal.connect(lambda: self.removeSelectVar('input')) self.actSelectReturnList.keyPressedSignal.connect(lambda: self.removeSelectVar('return')) self.actSelectInputList.itemDoubleClicked.connect(lambda: self.removeSelectVar('input')) self.actSelectReturnList.itemDoubleClicked.connect(lambda: self.removeSelectVar('return')) # Fill the dialog with info relating to action def fillDialog(self): # Fill in the text... # ...line edit entries self.actTagLineEdit.setText(self.action.tag) self.actNameLineEdit.setText(self.action.name) self.actPathLineEdit.setText(self.action.path) # ...optionals line edit self.actOptionalsLineEdit.setText(dict2Text(self.action.optionals)) # ...trigger line edit entry if self.action.passive or self.action.trigger=='Set Trigger': self.actTriggerLineEdit.setText('Set Trigger') elif self.action.trigger=='DoubleClick': self.actTriggerLineEdit.setText(self.action.trigger) else: self.actTriggerLineEdit.setText(self.action.trigger.toString()) # ...trigger list, use only triggers which are active self.passiveTriggers=[action.tag for key,action in iteritems(self.actDict) if not action.passive] self.actAvailTriggerList.addItems(sorted(self.passiveTriggers)) # Set the appropriate radio button on if self.action.passive: self.actPassiveRadio.setChecked(True) else: self.actActiveRadio.setChecked(True) # Set the state of the beforeTrigger check box (used for passive only) self.passiveBeforeCheck.setChecked(self.action.passive and self.action.beforeTrigger) # Set the state of the activeTimer check box (used for active only) if not self.action.passive and self.action.timer: self.activeTimerCheck.setChecked(True) else: self.activeTimerCheck.setChecked(False) # Set the state of the activeThreaded check box self.activeThreadedCheck.setChecked(self.action.threaded) # Set the timer interval value self.actIntervalLineEdit.setText(str(self.action.timerInterval)) # Toggle the appropriate radio button self.togglePassiveActive(init=True) # Fill in the available inputs and returns... # ...hot variables can go into inputs and outputs self.addTipItems(self.actAvailInputList,[hotVar for key,hotVar in iteritems(self.hotVar)]) self.addTipItems(self.actAvailReturnList,[hotVar for key,hotVar in iteritems(self.hotVar) if hotVar.returnable]) # ...preferences are only allowed as inputs (no need to add colors here, just adds clutter) self.addTipItems(self.actAvailInputList,[pref for key,pref in iteritems(self.pref) if not (key in ['basePen','customPen','pickPen','cursorStyle'])]) # Fill in the selected triggers (passive),inputs and returns if self.action.passive: self.actSelectTriggerList.addItems(self.action.trigger) self.addTipItems(self.actSelectInputList,self.action.inputs,useKey=True) self.addTipItems(self.actSelectReturnList,self.action.returns,useKey=True) # Add hot variable or preference to a designated list widget def addTipItems(self,listWidget,tipObjects,useKey=False): for tipObject in tipObjects: # If the key was passed, instead of the object - get the object if useKey: if tipObject in self.pref.keys(): tipObject=self.pref[tipObject] else: tipObject=self.hotVar[tipObject] item=QtWidgets.QListWidgetItem() item.setText(tipObject.tag) item.setToolTip(tipObject.tip) listWidget.addItem(item) # Lock the dialog so that values cannot be updated, for some built-in actions def lockDialog(self): for widget in [self.actNameLineEdit,self.actPathLineEdit, self.actOptionalsLineEdit,self.actAvailTriggerList, self.actSelectTriggerList,self.actIntervalLineEdit, self.actAvailInputList,self.actAvailReturnList, self.actSelectInputList,self.actSelectReturnList, self.actPassiveRadio,self.actActiveRadio, self.passiveBeforeCheck,self.activeTimerCheck, self.activeThreadedCheck,self.actTagLineEdit]: widget.setEnabled(False) # Update the key bind to what the user pressed def updateKeyBind(self,keyBindText): # Key binds are only used for active actions if self.actPassiveRadio.isChecked(): return # If the keybind is already in use, do not allow update for tag,action in iteritems(self.actDict): # Only active actions have keybinds (do not need to check passive) if action.passive or action.trigger in ['DoubleClick','Set Trigger']: continue if action.trigger.toString()==keyBindText and action.tag!=self.action.tag: print(action.tag+' already uses Keybind '+keyBindText) return # Otherwise, update the trigger line edit (trigger value is updated upon close) self.actTriggerLineEdit.setText(keyBindText) # Move the user chosen available hot variable or preference to the selected list def addAvailVar(self,listTag): # See which pair of lists was called if listTag=='return': fromList=self.actAvailReturnList toList=self.actSelectReturnList elif listTag=='input': fromList=self.actAvailInputList toList=self.actSelectInputList else: fromList=self.actAvailTriggerList toList=self.actSelectTriggerList # Add to the selected list, if the item is not already there aKey=fromList.currentItem().text() if aKey not in [toList.item(i).text() for i in range(toList.count())]: # If this was from the return/input, add the tag to the item if listTag in ['return','input']: self.addTipItems(toList,[aKey],useKey=True) else: toList.addItem(aKey) # Removes the current item from a selected list of hot variables and/or preferences def removeSelectVar(self,listTag): # See which list was selected potTags=['return','input','trigger'] potLists=[self.actSelectReturnList,self.actSelectInputList,self.actSelectTriggerList] aList=potLists[potTags.index(listTag)] # Remove the item if one is selected if aList.currentItem!=None: if aList.currentItem().isSelected(): aList.takeItem(aList.currentRow()) # Depending on if this is an active or passive action, turn on/off some widgets def togglePassiveActive(self,init=False): active=self.actActiveRadio.isChecked() self.actTriggerLineEdit.setEnabled(active) if active: self.actTriggerLineEdit.setReadOnly(active) self.actIntervalLineEdit.setEnabled(active) self.activeTimerCheck.setEnabled(active) self.activeThreadedCheck.setEnabled(active) self.passiveBeforeCheck.setEnabled(not active) self.actAvailTriggerList.setEnabled(not active) self.actSelectTriggerList.setEnabled(not active) # If the user has change from passive to active, remind that this will not be saved... # ...unless the trigger value is updated if (not self.trigReminder) and (not init): print('If changing between active and passive, update the trigger value') self.trigReminder=True # Check the tag name to ensure that it doesn't conflict with other actions def unqTagName(self): curTag=self.actTagLineEdit.text() for tag,action in iteritems(self.actDict): if curTag==tag and action.tag!=self.action.tag: print('This tag is already in use - if left as is changes will not be accepted') return False return True # Check that the trigger is appropriate relative to the action type def appropTrigger(self): # If a passive action, all triggers should be in the trigger list if self.actPassiveRadio.isChecked(): sendFalse=False for entry in self.actSelectTriggerList.visualListOrder(): if entry not in self.passiveTriggers: print('The active trigger tag '+entry+' no longer exists') sendFalse=True if sendFalse: return False # If a active action, the trigger should be able to convert to a keybind else: if self.actTriggerLineEdit.text()=='Set Trigger': return False try: QtGui.QKeySequence(self.actTriggerLineEdit.text()) except: return False return True # Upon close, fill in the action with all of the selected information and return def returnAction(self): # First check to see that the new parameters make sense and the action is to be updated, # ... checking that the tag and the trigger are appropriate, also that the timer makes sense if self.action.trigger=='DoubleClick': print('No changes can be made to actions with DoubleClick triggers') return None if self.actTagLineEdit.text()=='New action': print('Action update declined, tag was still default') return None if not self.unqTagName(): print('Action update declined, tag is not unique') return None if not self.appropTrigger(): print('Action update declined, trigger was not set correctly') return None if self.activeTimerCheck.isChecked(): try: float(self.actIntervalLineEdit.text()) except: if float(self.actIntervalLineEdit.text())>0: pass print('Action update declined, timer interval was not a positive number') return None # Set information from line edits... self.action.tag=self.actTagLineEdit.text() self.action.name=self.actNameLineEdit.text() self.action.path=self.actPathLineEdit.text() # ...optionals, set the values to the accepted format type (in order: bool,float,int,str) optText=self.actOptionalsLineEdit.text() try: optionals=text2Dict(optText) except: print('optionals were not formatted correctly, leaving as blank') optionals={} self.action.optionals=optionals # ...set whether this is an active or passive action self.action.passive=self.actPassiveRadio.isChecked() # ...trigger value if self.action.passive: self.action.trigger=self.actSelectTriggerList.visualListOrder() else: self.action.trigger=QtGui.QKeySequence(self.actTriggerLineEdit.text()) # Set info from radio buttons (passive/active) self.action.passive=self.actPassiveRadio.isChecked() # If the action should be applied before the trigger (used for passive only) self.action.beforeTrigger=self.passiveBeforeCheck.isChecked() # If the action should set off with a given interval if self.activeTimerCheck.isChecked(): self.action.timer=True self.action.timerInterval=float(self.actIntervalLineEdit.text()) else: self.action.timer=False # If the action should initiate a seperate thread when triggered if self.activeThreadedCheck.isChecked(): self.action.threaded=True else: self.action.threaded=False # Collect the tags of the inputs and returns associated with the action self.action.inputs=self.actSelectInputList.visualListOrder() self.action.returns=self.actSelectReturnList.visualListOrder() # Try to link to the function (given the new path, and name) try: self.action.linkToFunction(self.main) except: print('Failed to link '+self.action.tag+' to '+self.action.name+' at '+self.action.path) return self.action # Custom thread class to execute a queue of actions class QueueThread(QtCore.QThread): setNextInputs=QtCore.pyqtSignal() sendReturns=QtCore.pyqtSignal() def __init__(self,tag,actQueue): QtCore.QThread.__init__(self) self.tag=tag # The tag of the active action which created this queue self.actQueue=actQueue # The queue of all actions relating to the active action self.inputs=None # The inputs of the action currently being processed self.returns=None # The returns of the last action processed self.curIdx=None # Which index within the action queue is being processed def setInputs(self,inputs): self.inputs=inputs def resetInputsAndReturns(self): self.returns=None self.inputs=None # This function is called using the start() function def run(self): # Go through each of the queued action and execute it for i in range(len(self.actQueue)): # Ask to collect the required inputs self.curIdx=i self.setNextInputs.emit() # Wait to collect the inputs before processing the action while self.inputs==None: self.msleep(50) # Run the actions function and send back the return values self.returns=self.actQueue[self.curIdx].func(*self.inputs,**self.actQueue[self.curIdx].optionals) self.sendReturns.emit() # Wait for the return values on the GUI to be updated while self.returns is not None: self.msleep(50) self.exit()
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/Actions.py", "copies": "1", "size": "29771", "license": "mit", "hash": 7297683107285135000, "line_mean": 51.738267148, "line_max": 123, "alpha_frac": 0.6063283061, "autogenerated": false, "ratio": 4.446751306945481, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5553079613045481, "avg_score": null, "num_lines": null }
from __future__ import print_function import os from PyQt5 import QtWidgets from PyQt5.QtCore import Qt from lazylyst.UI.ChangeSource import Ui_CsDialog # Saved sources class, for reading in old (or adding new) archive/pick/station information class SaveSource(object): def __init__(self,tag=None,archDir=None, pickDir=None,staFile=None, sourceDict={}): self.tag=tag self.archDir=archDir self.pickDir=pickDir self.staFile=staFile self.sourceDict=sourceDict # A check to see if all files can be read def pathExist(self): allPathsExist=True for txt,path in [['archive directory',self.archDir], ['pick directory',self.pickDir], ['station file',self.staFile]]: if not os.path.exists(path): # Allow for no station file to be read if txt=='station file' and path.replace(' ','')=='': continue print('The '+txt+' does not exist at: '+path) allPathsExist=False return allPathsExist # Default saved source def defaultSource(): exampleDir=os.path.dirname(os.path.realpath(__file__))+'/ExampleSource/' source=SaveSource(tag='ExampleSource', archDir=exampleDir+'Archive', pickDir=exampleDir+'Picks', staFile=exampleDir+'NX_stations.xml', sourceDict={'Velocity':{'Vp':6.19,'Vs':3.57, 'Dp':0.74,'Ds':1.13, 'tResThresh':1.0}}) return {source.tag:source} # Change source dialog class CsDialog(QtWidgets.QDialog, Ui_CsDialog): def __init__(self,hotVar,savedSources,parent=None): QtWidgets.QDialog.__init__(self,parent) self.setupUi(self) self.hotVar=hotVar self.saveSource=savedSources # Give the dialog some functionaly self.setFunctionality() # Load in the text of the current source self.fillDialog() # Show the list of previous saved sources self.csSaveSourceList.addItems(sorted([key for key in self.saveSource.keys()])) # Set up some functionality to the configuration dialog def setFunctionality(self): self.csSaveSourceList.itemDoubleClicked.connect(self.loadSaveSource) self.csSaveSourceList.keyPressedSignal.connect(self.delSaveSource) self.csSaveSourceButton.clicked.connect(self.addSavedSource) # Allow double click on paths to open up dialogs to extract path names self.csArchiveLineEdit.doubleClicked.connect(lambda: self.getPathName('arch')) self.csPickLineEdit.doubleClicked.connect(lambda: self.getPathName('pick')) self.csStationLineEdit.doubleClicked.connect(self.getFileName) # Fill the dialog with info relating to current source def fillDialog(self): # Fill line edits with current source self.csTagLineEdit.setText(self.hotVar['sourceTag'].val) self.csArchiveLineEdit.setText(self.hotVar['archDir'].val) self.csPickLineEdit.setText(self.hotVar['pickDir'].val) self.csStationLineEdit.setText(self.hotVar['staFile'].val) self.sourceDictWidget.showSourceDict(self.hotVar['sourceDict'].val) # Put the saved source into the saved source list and dictionary def loadSaveSource(self): if self.csSaveSourceList.currentItem() is not None: if self.csSaveSourceList.currentItem().isSelected(): source=self.saveSource[self.csSaveSourceList.currentItem().text()] self.csTagLineEdit.setText(source.tag) self.csArchiveLineEdit.setText(source.archDir) self.csPickLineEdit.setText(source.pickDir) self.csStationLineEdit.setText(source.staFile) # If the source had no source dict, use the default if hasattr(source,'sourceDict'): self.sourceDictWidget.showSourceDict(source.sourceDict) else: self.sourceDictWidget.showSourceDict(SaveSource().sourceDict) # Delete the selected saved source def delSaveSource(self): if self.csSaveSourceList.key != Qt.Key_Delete or self.csSaveSourceList.currentItem()==None: return tag=self.csSaveSourceList.currentItem().text() # Remove from the saved sources dictionary... self.saveSource.pop(tag) # ...and the gui list self.csSaveSourceList.takeItem(self.csSaveSourceList.currentRow()) # Save the edits to the currently selected source def addSavedSource(self): source=self.curSource() # Ensure that atleast the tag, archive directory, and pick directory are filled out for text in [source.tag,source.archDir,source.pickDir]: if text.replace(' ','')=='': print('Fill in the source information to save') return # Add this to the saved sources list if source.tag not in [key for key in self.saveSource.keys()]: self.csSaveSourceList.addItem(source.tag) self.saveSource[source.tag]=source # Function to open a dialog and get the path name def getPathName(self,thisLineEdit): # Check which line was clicked if thisLineEdit=='arch': line=self.csArchiveLineEdit else: line=self.csPickLineEdit # If the value is already set, start from there if os.path.isdir(line.text()): startFolder=line.text() else: startFolder=os.path.dirname(os.path.realpath(__file__)) name=str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Folder",startFolder)) name=name.replace('\\','/') # If a folder was selected, update the line edit if name!='' and os.path.isdir(name): line.setText(name) # Function to open a dialog and get the file name def getFileName(self): # Start the dialog from the previously selected file (if it exists) if os.path.isfile(self.csStationLineEdit.text()): startFolder=os.path.dirname(os.path.realpath(self.csStationLineEdit.text())) else: startFolder=os.path.dirname(os.path.realpath(__file__)) name=str(QtWidgets.QFileDialog.getOpenFileName(self, "Select File",startFolder)[0]) # If a folder was selected, update the line edit if name!='' and os.path.isfile(name): self.csStationLineEdit.setText(name) # Create a source object from the line edit def curSource(self): source=SaveSource(tag=self.csTagLineEdit.text(), archDir=self.csArchiveLineEdit.text(), pickDir=self.csPickLineEdit.text(), staFile=self.csStationLineEdit.text(), sourceDict=self.sourceDictWidget.getSourceDict()) return source # Upon close, return the source currently in the line edits def returnSource(self): return self.curSource()
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/SaveSource.py", "copies": "1", "size": "7419", "license": "mit", "hash": 3205362230666555000, "line_mean": 44.38125, "line_max": 99, "alpha_frac": 0.6138293571, "autogenerated": false, "ratio": 4.308362369337979, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5422191726437978, "avg_score": null, "num_lines": null }
from future.utils import iteritems import numpy as np from obspy import UTCDateTime # Convert a string into easy to read text, assumes no lists def dict2Text(aDict): # Get all values first as strings keys=np.array([key for key,val in iteritems(aDict)]) vals=np.array([str(val) for key,val in iteritems(aDict)]) # Sort them alphabetically (better than random atleast) argSort=np.argsort(keys) vals=vals[argSort] keys=keys[argSort] # Put them all into one larger string string='' for i in range(len(vals)): string+=keys[i]+'='+vals[i]+',' if len(string)>0: string=string[:-1] return string # Convert text into a dictionary,assumes no lists def text2Dict(text): if '=' not in text: return {} aDict=dict(x.split('=') for x in text.split(',')) # Check if any of the values represent type other than string for key,val in iteritems(aDict): # Do not convert numbers to bool if val=='True': aDict[key]=True elif val=='False': aDict[key]=False # Otherwise see if it is a number else: try: if '.' in val: aDict[key]=float(val) else: aDict[key]=int(val) # If none of the above, leave as a string except: aDict[key]=str(val) return aDict # Return the UTCDateTime from the forced file naming convention def getTimeFromFileName(fileName): timeStr=fileName.split('_')[1].replace('.'+fileName.split('.')[-1],'') return UTCDateTime().strptime(timeStr,'%Y%m%d.%H%M%S.%f') # Get the string representing the given station via the trace object def getStaStr(tr): return str('.'.join([tr.stats.network,tr.stats.station,tr.stats.location]))
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/CustomFunctions.py", "copies": "1", "size": "1913", "license": "mit", "hash": -2578040678240619500, "line_mean": 32.1964285714, "line_max": 79, "alpha_frac": 0.5927861997, "autogenerated": false, "ratio": 3.8031809145129225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48959671142129224, "avg_score": null, "num_lines": null }
from obspy import read_inventory import numpy as np import pyproj # Convert a station xml file to a numpy array, containing only [StaCode,Lon,Lat,Ele] def staXml2Loc(staXml): # Loop through just to extract the station codes and locations... # ...with format [Net.Sta.Loc,Lon(deg),Lat(deg),Ele(m)], lon/lat assumed to be in WGS84 datum outArr=np.empty((0,4),dtype='a32') for net in staXml: for sta in net: if len(sta.channels)==0: print(net.code+','+sta.code+' has no channels, could not read location code') for cha in sta: nsl='.'.join([net.code,sta.code,cha.location_code]) # Do not add this station id already present if len(outArr)>0: if nsl in outArr[:,0]: continue entry=np.array([nsl,cha.longitude,cha.latitude,cha.elevation],dtype='a32') outArr=np.vstack((outArr,entry)) # If the file was empty, convert to appropriate shape if len(outArr)==0: outArr=np.empty((0,4),dtype='a32') else: outArr=np.array(outArr,dtype=str) return outArr # Read in a station xml file given the path name def readInventory(staFile): return read_inventory(staFile,format='stationxml') # Conversion factor between meters and given unit def unitConversionDict(): return {'m':1.0, 'km':1000.0, 'ft':0.3048, 'yd':0.9144, 'mi':1609.344} # Set the projection function def setProjFunc(mapProj,staLoc,init=False): inProj=pyproj.Proj(init='EPSG:4326') # Extra key word arguments to be passed to the new projection extraKwargs={'axis':mapProj['zDir'],'preserve_units':True} if mapProj['units']!='deg': extraKwargs['units']=mapProj['units'] # If using a projection defined on station locations... if mapProj['type']=='Simple': # ...no projection if mapProj['simpleType']=='None' or 0 in staLoc.shape: outProj=pyproj.Proj(init='EPSG:4326',**extraKwargs) if 0 in staLoc.shape and mapProj['simpleType']!='None' and not init: print('Cannot determine projection as no stations given, using no projection') # ...Universal Transverse Mercator elif mapProj['simpleType']=='UTM': UTM_Zone=int(np.floor((np.median(staLoc[:,1].astype(float)) + 180.0)/6) % 60) + 1 outProj = pyproj.Proj(proj='utm',zone=UTM_Zone, datum='WGS84',**extraKwargs) # ...Albers Equal Area (Conic) elif mapProj['simpleType']=='AEA Conic': # Use the bounds of the stations for guidelines staLons,staLats=staLoc[:,1].astype(float),staLoc[:,2].astype(float) minLat,maxLat=np.min(staLats),np.max(staLats) minLon,maxLon=np.min(staLons),np.max(staLons) # Latitudes where the cone intersects the ellipsoid lat1,lat2=(maxLat-minLat)*1.0/6+minLat,(maxLat-minLat)*5.0/6+minLat # The origin of the projection lat0,lon0=(maxLat-minLat)*1.0/2+minLat,(maxLon-minLon)*1.0/2+minLon outProj=pyproj.Proj(proj='aea',lat_1=lat1,lat_2=lat2,lat_0=lat0,lon_0=lon0, datum='WGS84',ellps='WGS84',**extraKwargs) # ...catch else: print('Simple projection not defined, how did we get here?') # If using a EPSG code else: outProj=pyproj.Proj(init='EPSG:'+mapProj['epsg'],**extraKwargs) mapProj['func']=lambda xyzArr:np.array(pyproj.transform(inProj,outProj,*xyzArr.T)).T mapProj['funcInv']=lambda xyzArr:np.array(pyproj.transform(outProj,inProj,*xyzArr.T)).T
{ "repo_name": "AndrewReynen/Lazylyst", "path": "lazylyst/StationMeta.py", "copies": "1", "size": "3829", "license": "mit", "hash": -3695801528710851000, "line_mean": 44.7195121951, "line_max": 97, "alpha_frac": 0.5972838861, "autogenerated": false, "ratio": 3.443345323741007, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4540629209841007, "avg_score": null, "num_lines": null }
import random, os, sys; from boxm2_scene_adaptor import *; from vil_adaptor import *; from vpgl_adaptor import *; from bbas_adaptor import *; from helpers import *; from glob import glob from optparse import OptionParser ####################################################### # handle inputs # #scene is given as first arg, figure out paths # parser = OptionParser() parser.add_option("-s", "--sceneroot", action="store", type="string", dest="sceneroot", help="root folder for this scene") parser.add_option("-x", "--xmlfile", action="store", type="string", dest="xml", default="uscene.xml", help="scene.xml file name (model/uscene.xml, model_fixed/scene.xml, rscene.xml)") parser.add_option("-d", "--device", action="store", type="string", dest="device", default="gpu1", help="specify gpu (gpu0, gpu1, etc)") parser.add_option("-p", "--printFile" , action="store", type="string", dest="std_file", default="", help="if given, the std out is redirected to this file") (options, args) = parser.parse_args() print options print args # handle inputs #scene is given as first arg, figure out paths scene_root = options.sceneroot; # Set some update parameters SCENE_NAME = options.xml DEVICE = options.device if options.std_file != "": saveout = sys.stdout # save initial state of stdout print saveout print "STD_OUT is being redirected" set_stdout(options.std_file) ################################# #Initialize a GPU ################################# print "Initializing DEVICE" os.chdir(scene_root) scene_path = os.getcwd() + "/" + SCENE_NAME if not os.path.exists(scene_path): print "SCENE NOT FOUND! ", scene_path sys.exit(5) scene = boxm2_scene_adaptor (scene_path, DEVICE); ################################# #refine ################################# ncells = scene.refine(); if(ncells < 0) : print "Refined Failed, clearing cache and exiting:" scene.clear_cache(); boxm2_batch.clear(); sys.exit(1) ################################# #write and clear cache before exiting ################################# scene.write_cache(); scene.clear_cache(); boxm2_batch.clear(); if options.std_file != "": reset_stdout(); print "STD_OUT is being reset" print "Done" sys.exit(0)
{ "repo_name": "mirestrepo/voxels-at-lems", "path": "boxm2/boxm2_refine_model.py", "copies": "1", "size": "2339", "license": "bsd-2-clause", "hash": -2912833699774768000, "line_mean": 28.6075949367, "line_max": 183, "alpha_frac": 0.6075245832, "autogenerated": false, "ratio": 3.480654761904762, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45881793451047614, "avg_score": null, "num_lines": null }
__author__ = 'Andrew' import math import urllib2 import os import time from xml.dom import minidom as DOM def calculate_distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km latitude = math.radians(lat2 - lat1) longitude = math.radians(lon2 - lon1) a = (math.sin(latitude / 2) * math.sin(latitude / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(longitude / 2) * math.sin(longitude / 2)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) destination = radius * c return destination def get_closest_servers(client, complete=False): connection = urllib2.urlopen('http://speedtest.net/speedtest-servers.php') server_xml = connection.read() if int(connection.code) != 200: return None connection.close() root = DOM.parseString(server_xml) servers = {} for server in root.getElementsByTagName('server'): attrib = dict(server.attributes.items()) d = calculate_distance([float(client['lat']), float(client['lon'])], [float(attrib.get('lat')), float(attrib.get('lon'))]) attrib['d'] = d if d not in servers: servers[d] = [attrib] else: servers[d].append(attrib) closest = [] for d in sorted(servers.keys()): for s in servers[d]: closest.append(s) if len(closest) == 5 and not complete: break else: continue break del servers del root return closest def get_best_server(servers): results = {} for server in servers: cum = 0 url = os.path.dirname(server['url']) for i in xrange(0, 3): uh = urllib2.urlopen('%s/latency.txt' % url) start = time.time() text = uh.read().strip() total = time.time() - start if int(uh.code) == 200 and text == 'test=test': cum += total else: cum += 3600 uh.close() avg = round((cum / 3) * 1000000, 3) results[avg] = server fastest = sorted(results.keys())[0] best = results[fastest] best['latency'] = fastest return best def get_config(): uh = urllib2.urlopen('http://www.speedtest.net/speedtest-config.php') config_xml = uh.read() if int(uh.code) != 200: return None uh.close() root = DOM.parseString(config_xml) config = { 'client': extract_tag_name(root, 'client'), 'times': extract_tag_name(root, 'times'), 'download': extract_tag_name(root, 'download'), 'upload': extract_tag_name(root, 'upload')} del root return config def extract_tag_name(dom, tag_name): elem = dom.getElementsByTagName(tag_name)[0] return dict(elem.attributes.items()) def setup(): print 'Configuring server, one moment.' configs = get_config() closest_server = get_closest_servers(configs['client']) best = get_best_server(closest_server) return best['id']
{ "repo_name": "Codeusa/SpeedTest-Faker", "path": "functions.py", "copies": "1", "size": "3095", "license": "unlicense", "hash": 1472288470539278000, "line_mean": 27.3944954128, "line_max": 144, "alpha_frac": 0.5786752827, "autogenerated": false, "ratio": 3.688915375446961, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9766734637155837, "avg_score": 0.0001712041982246869, "num_lines": 109 }
__author__ = 'Andrew' import threading from random import choice from twython import Twython #terrible array of words below arrayFirstWord = ['the bottle', 'a drainpipe', 'small blue bits', 'a crow caws', 'a dog shakes', 'ferris wheels', 'monkey bars', 'stained table cloths', 'three more shots', 'tear-stained face', 'salted pork', 'luminous', 'underwear', 'haunted moon', 'cold, dark house', 'blood stained face', 'eyes glisten', 'haunted dreams', 'lost, broken', 'in the yard', 'mocking bird', 'wishing star', 'shining sun', 'glowing moon', 'on my knees', 'a blown kiss', 'in my heart', 'on my toes', 'with all hope', 'rain buckets', 'on this day', 'in her eyes', 'in our hearts', 'will stay strong', 'unbelieved', 'remorseful', 'when i died', 'in the trees', 'beneath sky', 'in my room', 'leaving home', 'hardest part', 'whispers fade', 'on stained sheets', 'drunken thoughts', 'sand grains fall', 'on my tongue', 'in my ears', 'lay down now', 'continues', 'lucid dreams', 'lost highway', 'robins call', 'worried glance', 'in a stream', 'menacing', 'ironic', 'messages', 'torn paper', 'heaven and hell', 'snowflakes fall', 'now in bloom', 'my old home'] arraySecondWord = ['thunder', 'solvent', 'lost cause', 'muddle', 'mumbles', 'mutters', 'thoughtless', 'driven', 'stalwart', 'flinches', 'finches', 'finger', 'fingers', 'midnight', 'madness', 'hunger', 'vital', 'alive', 'now dead', 'dreaming', 'swingset', 'heartless', 'grinning', 'new age', 'feelings', 'whimpers', 'arrows', 'struck down', 'lifeless', 'songbird', 'singing', 'burning', 'aching', 'soulful', 'angels', 'reason', 'deeper', 'harder', 'calling', 'heaven', 'gray clouds', 'lightning', 'lamplight', 'stunning', 'on snow', 'in dreams', 'under', 'willows', 'now blessed', 'now lost', 'sadness', 'today', 'never', 'always', 'bereft', 'untold', 'to me', 'my thoughts', 'my eyes', 'in bloom', 'lost soul', 'again', 'forlorn', 'risen', 'rise up', 'children', 'wonder', 'feathers', 'not down', 'away', 'too soft', 'softer', 'soft still', 'wounded', 'for love', 'for hope', 'with joy', 'with pain', 'panic', 'nine lives', 'heartfelt', 'trouble', 'too soon', 'gone now', 'and I', 'I think', 'safely', 'flutters', 'wanders', 'your lips', 'your eyes', 'your smile', 'comforts', 'weighs down', 'upon', 'learning', 'the sky', 'the sea', 'rivers', 'we met', 'eyes met', 'like rain', 'silent'] arrayThirdWord = ['bitterest fog', 'hard-pressed and strong', 'willowy hair', 'standing still silent', 'the clouds reveal', 'the wind takes words', 'under blessed skies', 'a sparrow weeps', 'a hummingbird', 'wet noodles steam', 'steaming mud waits', 'broken hearts beat', 'lost memories', 'shadows silent', 'dust specks gather', 'spiders spin webs', 'ants signal code', 'the river sleeps', 'traffic moves slow', 'rain on rooftops', 'lost in silence', 'long lost dreams gone', 'a park bench calls', 'streets full of rain', 'pails of tears spill', 'a glass of wine', 'these days i think', 'witness the lack', 'can it begin?', 'pull out my eyes', 'ending begins', 'planted in soil', 'a wolf calls out', 'darting salmon', 'laundry hangs dry', 'roaches scuttle', 'tiny fractures', 'a roiling stream', 'as sparrows sing', 'the last ash falls', 'rusted leaves fall', 'scars slow to heal', 'complicated'] #API Stuff APP_KEY = '' APP_SECRET = '' OAUTH_TOKEN = '' OAUTH_TOKEN_SECRET = '' #Initates Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) #Actually does the tweeting def tweet_haiku(): haiku = make_haiku() hash_tags = '#haiku #poem #shittyhaiku #qtbot' threading.Timer(3600.0, tweet_haiku).start() twitter.update_status(status=haiku + '\n' + hash_tags) print 'Created: ' + haiku + '\n' + hash_tags #Makes the haiku def make_haiku(): haiku = choice(arrayFirstWord) + \ ' ' + choice(arraySecondWord) + '\n' + \ choice(arrayThirdWord) + ' ' + choice(arrayFirstWord) + '\n' + \ choice(arrayFirstWord) + ' ' + choice(arraySecondWord) return haiku tweet_haiku()
{ "repo_name": "Codeusa/QTHaikus", "path": "qttweets.py", "copies": "1", "size": "4946", "license": "mit", "hash": -3990717856427407400, "line_mean": 52.7608695652, "line_max": 120, "alpha_frac": 0.5327537404, "autogenerated": false, "ratio": 3.348679756262695, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9298541078329545, "avg_score": 0.01657848366662974, "num_lines": 92 }
__author__ = 'Andrew' import time import urllib.request from functions import stdout import workerpool class DownloadJob(workerpool.Job): "Job for downloading a given URL." def __init__(self, url, poster_id): self.url = url # The url we'll need to download when the job runs self.poster_id = poster_id #need a file name that is the actual id def run(self): save_to = "C:/posters/%s.jpg" % self.poster_id urllib.request.urlretrieve(self.url, save_to) # Initialize a pool, 5 threads in this case pool = workerpool.ShrinkWrapWorker(size=100) # Loop over urls.txt and create a job to download the URL on each line def download_posters(poster_file, size): for url in open("%s" % poster_file, encoding="utf8"): job = DownloadJob(url.split(":")[1].replace("\n", ""), url.split(":")[0].replace("\n", "")) pool.put(job) stdout.write("\r%s/%s" % (str(poster_file), str(size))) stdout.flush() # Send shutdown jobs to all threads, and wait until all the jobs have been completed pool.shutdown() pool.wait()
{ "repo_name": "Codeusa/Shrinkwrap-worker", "path": "shrinkwrap-worker/example.py", "copies": "1", "size": "1097", "license": "mit", "hash": 3660011270642280400, "line_mean": 31.2647058824, "line_max": 99, "alpha_frac": 0.6517775752, "autogenerated": false, "ratio": 3.4825396825396826, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46343172577396824, "avg_score": null, "num_lines": null }
__author__ = 'andrew' from .core import APIConnection import uuid class SteamIngameStore(object): def __init__(self, appid, debug=False): self.appid = appid self.interface = 'ISteamMicroTxnSandbox' if debug else 'ISteamMicroTxn' def get_user_microtxh_info(self, steamid): return APIConnection().call(self.interface, 'GetUserInfo', 'v1', steamid=steamid, appid=self.appid) def init_purchase(self, steamid, itemid, amount, itemcount=1, language='en', currency='USD', qty=1, description='Some description'): params = { 'steamid': steamid, 'itemid[0]': itemid, 'amount[0]': amount, 'appid': self.appid, 'orderid': uuid.uuid1().int >> 64, 'itemcount': itemcount, 'language': language, 'currency': currency, 'qty[0]': qty, 'description[0]': description, } return APIConnection().call(self.interface, 'InitTxn', 'v3', method='POST', **params) def query_txh(self, orderid): return APIConnection().call(self.interface, 'QueryTxn', 'v1', appid=self.appid, orderid=orderid) def refund_txh(self, orderid): return APIConnection().call(self.interface, 'RefundTxn', 'v1', method='POST', appid=self.appid, orderid=orderid) def finalize_txh(self, orderid): return APIConnection().call(self.interface, 'FinalizeTxn', 'v1', method='POST', appid=self.appid, orderid=orderid)
{ "repo_name": "smiley/steamapi", "path": "steamapi/store.py", "copies": "1", "size": "1682", "license": "mit", "hash": 6177731816466648000, "line_mean": 37.2272727273, "line_max": 105, "alpha_frac": 0.548156956, "autogenerated": false, "ratio": 3.68859649122807, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9733267395653493, "avg_score": 0.0006972103149154487, "num_lines": 44 }
__author__ = 'Andrew' class Card: RANKS = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A') SUITS = ('hearts', 'diamonds', 'spades', 'clubs') def __init__(self, card_data): self.suit = card_data['suit'].lower() self.rank = card_data['rank'] self.value = Card.RANKS.index(self.rank) + 2 def __hash__(self): return self.value def __str__(self): return '%s of %s' % (self.rank, self.suit) def data(self): return { 'rank': Card.RANKS[self.value - 2], 'suit': self.suit.lower() } def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value < other.value def __le__(self, other): return self.value <= other.value def __gt__(self, other): return self.value > other.value def __ge__(self, other): return self.value >= other.value def __cmp__(self, other): return self.value - other.value
{ "repo_name": "Medvezhopok/poker-player-pythonpokerteam", "path": "handtype/card.py", "copies": "1", "size": "1026", "license": "mit", "hash": -4996505157707097000, "line_mean": 24.0487804878, "line_max": 78, "alpha_frac": 0.5068226121, "autogenerated": false, "ratio": 3.1666666666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41734892787666666, "avg_score": null, "num_lines": null }
import sys import re import os import nltk import operator from random import randint from nltk.util import ngrams from ngramFunctions import * from XMLParser import * from frequencyFunctions import * from lxml import etree def features(sentence): words = sentence.lower().split() return dict(('contains(%s)' %w, True) for w in words) if __name__ == '__main__': xmldoc = sys.argv[1] knownJava = sys.argv[2] knownCpp = sys.argv[3] ################################################################### # Section 1: Gather known data to create frequencies for known information ################################################################### knownJavaFile = open(knownJava) knownJavaString = "" for line in knownJavaFile: knownJavaString += line # knownJavaGram = ngramsFunction(knownJavaString, 3) knownJavaGram = ngrams(knownJavaString.split(' '),3)#ngramsFunction(knownJavaString, 3) knownJavaHashFreq = nltk.FreqDist(knownJavaGram) # javaMaxGram = max(knownJavaHashFreq, key=knownJavaHashFreq.get) # print(javaMaxGram, knownJavaHashFreq[javaMaxGram]) knownCPPFile = open(knownCpp) knownCPPString = "" for line in knownCPPFile: knownCPPString += line # print(knownCPPString) knownCPPGram = ngrams(knownCPPString.split(' '),3) knownCPPHashFreq = nltk.FreqDist(knownCPPGram) # cppMaxGram = max(knownCPPHashFreq, key=knownCPPHashFreq.get) # print(cppMaxGram, knownCPPHashFreq[cppMaxGram]) ############################################################################################# # Section 2: to calculate trigram Probability ############################################################################################# kneserJava = nltk.KneserNeyProbDist(knownJavaHashFreq) kneserCPP = nltk.KneserNeyProbDist(knownCPPHashFreq) kneserJavaHash = convertProbListToHash(kneserJava) kneserCPPHash = convertProbListToHash(kneserCPP) cpp = 0 java = 0 totalCppWithTag = 0 totalJavaWithTag = 0 totalJavaTags = 0 totalCppTags = 0 totalEval = 0 resultsFile = open('Results.txt', 'a') codeFile = open('Code.txt', 'a') analyticsFile = open('Analytics.txt', 'a') resultsFileString = codeFileString = analyticsString = '' presencePosCpp = presenceNegCpp = absencePosCpp = absenceNegCpp =0 presencePosJava = presenceNegJava = absencePosJava = absenceNegJava = 0 # tree = ET.parse(xmldoc) # root = tree.getroot() for event, element in etree.iterparse(xmldoc, tag="row"): body = element.get('Body') # Only allow posts with a code tag to be added if '<code>' in body: postId = element.get('Id') # Tags for comment post tags = element.get('Tags') if tags == None: continue tags.lower() # if not ('<java>' or 'c++' or '<c>' or '<c++-faq>' or '<android>' or '<spring>' or '<swing>' or '<pass-by-reference>' or '<eclipse>' or '<regex>' or '<recursion>' or '<binary-tree>' or '<software-engineering>' or '<divide-by-zero>' or '<arraylist>' or '<garbage-collection>' or '<object>' or '<arrays>' or '<iterator>' or '<hashcode>' or '<inheritance>' or '<tostring>' or '<unicode>' or '<quicksort>' or '<sorting>' or '<jar>' or '<bubble-sort>' or '<hashcode>' or '<multidimensional-array>' or '<codebase>' or '<class>') in tags: # continue # Skip if post contains tags from multiple languauges # if (('<c++>' or '<c++-faq>' or '<c>' in tags) and ('<java>' or '<android>' or '<spring>' or '<swing>' in tags)) : # continue code = parseBodyForTagCode(body) codeString = '' for item in code: snipetLength = len(item.split()) if snipetLength > 5: codeString = codeString+re.sub('<code>|</code>',' ',item) codeString = re.sub('\n|\r|/\s\s+/g}',' ',codeString) codeString = re.sub('\.', ' ', codeString) codeString = re.sub('\t', '',codeString) codeString = re.sub(re.compile("/\*.*?\*/",re.DOTALL ) ,"" ,codeString) codeString = re.sub(re.compile("//.*?\n" ) ,"" ,codeString) codeString = re.sub( '[^0-9a-zA-Z]+', ' ', codeString ) codeString = re.sub( '\s+', ' ', codeString).strip() codeFileString = codeFileString+codeString codeLength = len(codeString.split()) # print(codeLength) if(codeLength < 3): continue totalEval += 1# total posts not skipped # In some cases a post can include tags associated with more than one languauge if ('c++' or '<c++-faq>' or '<c>') in tags: totalCppTags += 1 if ('<java>' or '<android>' or '<spring>' or '<swing>') in tags: totalJavaTags += 1 # print(codeString) codeList = ngrams(codeString.split(' '),5) codeGram = nltk.FreqDist(codeList) for gram in codeGram: cppValue = kneserCPPHash.get(str(gram)) javaValue = kneserJavaHash.get(str(gram)) if cppValue != None and javaValue != None: # Compare to the frequency values if cppValue > javaValue: cpp += 1 else: java += 1 # if there is a hit for either one then add to hit value elif cppValue == None and javaValue != None: java += 1 elif cppValue != None and javaValue == None: cpp += 1 # if hit values are the same make a guess on language if java == cpp: ran = randint(0,1) if(ran == 0): java += 1 else: cpp += 1 # Done looking for gram hit values ################################# # fix absence ################################# # if java == 0 and ('<java>' or '<android>' or '<spring>' or '<swing>') in tags: # absenceNegJava += 1 # if cpp == 0 and ('c++' or '<c++-faq>' or '<c>') in tags: # absenceNegCpp += 1 # if java > cpp and not ('java' or '<android>' or '<spring>' or '<swing>') in tags: # print('absence is true') # absencePosJava += 1 # if cpp > java and not ('c++' or '<c++-faq>' or '<c>') in tags: # absencePosCpp += 1 ################################# # if no values where hit then move on to next post row # if java == 0 and cpp == 0: # continue determinedCpp = determinedJava = False resultsFileString = resultsFileString+'Grams assigned as followed:\n' resultsFileString = resultsFileString+'PostId: {}\nC++: {} Java: {}\nCode: {} \n'.format(postId,cpp,java,codeString) if cpp > java: resultsFileString = resultsFileString+'Snippet determined to be C++\nTags include {}\n\n'.format(tags) determinedCpp = True # if ('c++' or '<c++-faq>' or '<c>') in tags: # totalCppWithTag += 1 elif java > cpp: resultsFileString = resultsFileString+'Snippet determined to be Java\nTags include {}\n\n'.format(tags) determinedJava = True # if ('<java>' or '<android>' or '<spring>' or '<swing>') in tags: # totalJavaWithTag += 1 # analyze results if determinedCpp == True and ('c++' or '<c++-faq>' or '<c>') in tags: presencePosCpp += 1 if determinedCpp == False and ('c++' or '<c++-faq>' or '<c>') in tags: presenceNegCpp += 1 if determinedCpp == True and not('c++' or '<c++-faq>' or '<c>') in tags: absencePosCpp += 1 if determinedCpp == False and not('c++' or '<c++-faq>' or '<c>') in tags: absenceNegCpp += 1 if determinedJava == True and ('<java>' or '<android>' or '<spring>' or '<swing>') in tags: presencePosJava += 1 if determinedJava == False and ('<java>' or '<android>' or '<spring>' or '<swing>') in tags: presenceNegJava += 1 if determinedJava == True and not('<java>' or '<android>' or '<spring>' or '<swing>') in tags: absencePosJava += 1 if determinedJava == False and not('<java>' or '<android>' or '<spring>' or '<swing>') in tags: absenceNegJava += 1 # if ('c++' or '<c++-faq>' or '<c>') in tags: # # presence is true # if cpp > java: # # positive is true # # true positive # presencePosCpp += 1 # else: # # false negative # presenceNegCpp += 1 # # elif cpp > java: # # # been determined cpp but no cpp tags # # # incorectly determined # # # false positive # # absencePosCpp += 1 # # else: # # # determined not to be cpp correctly # # # true negative # # absenceNegCpp += 1 # if ('<java>' or '<android>' or '<spring>' or '<swing>') in tags: # # presence is true # if java > cpp: # presencePosJava += 1 # else: # presenceNegJava += 1 # # elif java > cpp: # absencePosJava += 1 # else: # absenceNegJava += 1 java = 0 cpp = 0 element.clear() for ancestor in element.xpath('ancestor-or-self::*'): while ancestor.getprevious() is not None: del ancestor.getparent()[0] javaSensitivity = presencePosJava / (presencePosJava+presenceNegJava) javaSpecificity = absenceNegJava / (absenceNegJava+absencePosJava) javaRateFalsePos = absencePosJava / (absencePosJava+absenceNegJava) javaRateFalseNeg = presenceNegJava / (presenceNegJava+presencePosJava) javaPosPredict = presencePosJava / (presencePosJava+ absencePosJava) javaNegPredict = presenceNegJava / (presenceNegJava+ absenceNegJava) javaRelativeRisk = (presencePosJava/ (presencePosJava + presenceNegJava)) / (absencePosJava / (absencePosJava + absenceNegJava)) cppSensitivity = presencePosCpp / (presencePosCpp+presenceNegCpp) cppSpecificity = absenceNegCpp / (absenceNegCpp+absencePosCpp) cppRateFalsePos = absencePosCpp / (absencePosCpp+absenceNegCpp) cppRateFalseNeg = presenceNegCpp / (presenceNegCpp+presencePosCpp) cppPosPredict = presencePosCpp / (presencePosCpp+ absencePosCpp) cppNegPredict = presenceNegCpp / (presenceNegCpp+absenceNegCpp) cppRelativeRisk = (presencePosCpp/ (presencePosCpp + presenceNegCpp)) / (absencePosCpp / (absencePosCpp + absenceNegCpp)) analyticsString = 'Java\n------\nTrue Positive: {}\nFalse Negative: {}\nFalse Positive: {}\nTrue Negative: {}'.format(presencePosJava,presenceNegJava,absencePosJava,absenceNegJava) analyticsString += '\nSensitivity: {}\nSpecificity: {}'.format(javaSensitivity, javaSpecificity) analyticsString += '\nRate False Positives: {}\nRate False Negatives: {}'.format(javaRateFalsePos, javaRateFalseNeg) analyticsString += '\nEstimate Positive Predictive Value: {}\nEstimate Negative Predictive Value: {}'.format(javaPosPredict, javaNegPredict) analyticsString += '\nRelative Risk: {}'.format(javaRelativeRisk) analyticsString += '\n\nC++\n------\nTrue Positive: {}\nFalse Negative: {}\nFalse Positive: {}\nTrue Negative: {}'.format(presencePosCpp,presenceNegCpp,absencePosCpp,absenceNegCpp) analyticsString += '\nSensitivity: {}\nSpecificity: {}'.format(cppSensitivity, cppSpecificity) analyticsString += '\nRate False Positives: {}\nRate False Negatives: {}'.format(cppRateFalsePos, cppRateFalseNeg) analyticsString += '\nEstimate Positive Predictive Value: {}\nEstimate Negative Predictive Value: {}'.format(cppPosPredict, cppNegPredict) analyticsString += '\nRelative Risk: {}'.format(cppRelativeRisk) ############################################################################################# # Section Output ############################################################################################# resultsFile.write(resultsFileString) codeFile.write(codeFileString) analyticsFile.write(analyticsString) # print('Total Java snippets determined and also have tags (java, android, spring, swing): {}'.format(totalJavaWithTag)) # print('Total Java snippets: {}'.format(totalJavaTags)) # print('Total C++ snippets determined and also have tags (c++, c++-faq, c): {}'.format(totalCppWithTag)) # print('Total C++ snippets: {}'.format(totalCppTags)) # print('Total snippets evaluated: {}'.format(totalEval))
{ "repo_name": "sainzad/stackOverflowCodeIdentifier", "path": "XMLAnalyze.py", "copies": "1", "size": "12120", "license": "mit", "hash": -7472677183187494000, "line_mean": 38.5418060201, "line_max": 535, "alpha_frac": 0.6214521452, "autogenerated": false, "ratio": 3.3196384552177487, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9186325101751349, "avg_score": 0.05095309973327977, "num_lines": 299 }
__author__ = 'andrews' from enum import IntEnum from time import sleep import threading import re import logging from libpebble2.services.voice import * from .base import PebbleCommand logger = logging.getLogger("pebble_tool.commands.transcription_server") mapping = { 'connectivity': TranscriptionResult.FailNoInternet, 'disabled': SetupResult.FailDisabled, 'no-speech-detected': TranscriptionResult.FailSpeechNotRecognized, # works because there's no mic on qemu. } class TranscriptionServer(PebbleCommand): ''' Starts a voice server listening for voice transcription requests from the app ''' command = 'transcribe' def _send_result(self): self._voice_service.send_stop_audio() if isinstance(self._error, TranscriptionResult): result = self._error else: result = TranscriptionResult.Success self._voice_service.send_dictation_result(result=result, sentences=[self._words], app_uuid=self._app_uuid) def _handle_session_setup(self, app_uuid, encoder_info): RESULT_DELAY = 4 if self._timer is not None: self._timer.cancel() self._app_uuid = app_uuid if isinstance(self._error, SetupResult): result = self._error else: result = SetupResult.Success self._voice_service.send_session_setup_result(result, self._app_uuid) if result == SetupResult.Success: self._timer = threading.Timer(RESULT_DELAY, self._send_result) self._timer.start() def _handle_audio_stop(self): if self._timer is not None: self._timer.cancel() self._send_result() def __call__(self, args): super(TranscriptionServer, self).__call__(args) if args.error is not None: self._error = mapping[args.error] else: self._error = None self._voice_service = VoiceService(self.pebble) self._timer = None # Separate the sentence into individual words. Punctuation marks are treated as words if args.transcription: stripped = [w.strip() for w in re.split(r'(\W)', args.transcription) if w.strip() != ''] # prefix punctuation marks with backspace character self._words = [(z if re.match(r'\w', z) else '\b' + z) for z in stripped] else: self._words = [] self._voice_service.register_handler("session_setup", self._handle_session_setup) self._voice_service.register_handler("audio_stop", self._handle_audio_stop) logger.debug("Transcription server listening") try: while True: sleep(1) except KeyboardInterrupt: return @classmethod def add_parser(cls, parser): parser = super(TranscriptionServer, cls).add_parser(parser) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('transcription', nargs='?', type=str, help="Transcribed message to send in the dictation result") group.add_argument('--error', type=str, nargs='?', choices=mapping.keys(), help='Error code to respond with, if simulating a failure.') return parser
{ "repo_name": "gregoiresage/pebble-tool", "path": "pebble_tool/commands/transcription_server.py", "copies": "2", "size": "3278", "license": "mit", "hash": -3093568538927724500, "line_mean": 35.021978022, "line_max": 114, "alpha_frac": 0.6278218426, "autogenerated": false, "ratio": 4.149367088607595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5777188931207595, "avg_score": null, "num_lines": null }
__author__ = "Andrew Szymanski" __version__ = "0.1.0" """ Forms playground """ #from django.views.decorators.http import require_safe import urllib import urllib2 from django.template import Context, loader from django.http import HttpResponse from django.shortcuts import render,render_to_response, get_object_or_404, redirect from django.conf import settings from django.utils import simplejson from django.http import QueryDict from django.contrib.sites.models import Site #import inspect from types import * from votuition.forms import VoteForm from votuition.forms import JsonForm # Get an instance of a logger import logging from django.utils.log import getLogger logger = getLogger('django') logger.setLevel(logging.DEBUG) LOG_INDENT = " " def form_response(request): #logger.debug("entering [%s]:[%s]" % (__file__, inspect.stack()[0][3]) ) method_name = "form_response" logger.debug("entering [%s]:[%s]" % (__file__, method_name) ) #logger.debug("entering [%s]:[%s], form=[%s]" % (__file__, method_name, form) ) template_response = "debug/form_sample_result.html" host = request.get_host() # hack - request is made by server so we should get server's url logger.debug("host: [%s]" % host) api_url = "http://%s/api/v1.0/vote" % host json_str = "" output_lines = list() if request.method == 'GET': # get json string query_dict = request.GET json_str = query_dict.get("json", "{}") line = "json_str: %s" % json_str logger.debug(line) output_lines.append(line) # call API line = "preparing to POST to: [%s]" % api_url logger.debug(line) output_lines.append(line) #data = simplejson.dumps(values) req = urllib2.Request(api_url, json_str, {'Content-Type': 'application/json'}) line = "posting data to server..." logger.debug(line) output_lines.append(line) return_message = "" return_status = True try: line = "sending request..." logger.debug(line) output_lines.append(line) f = urllib2.urlopen(req) line = "reading response..." logger.debug(line) output_lines.append(line) response = f.read() line = "response: [%s]" % response logger.debug(line) output_lines.append(line) line = "closing connection..." logger.debug(line) output_lines.append(line) f.close() except urllib2.HTTPError, e: return_status = False return_message = "%s (%s)" % (e.read(), e) logger.error(return_message) output_lines.append(return_message) except urllib2.URLError, e: return_status = False return_message = "%s %s" % (return_message, e) logger.error(return_message) output_lines.append(return_message) except Exception, e: return_status = False return_message = "%s %s" % (return_message, e) logger.error(return_message) output_lines.append(return_message) return render_to_response(template_response, { 'view_type': "lala", 'output_lines': output_lines, } ) def form_json(request): #logger.debug("entering [%s]:[%s]" % (__file__, inspect.stack()[0][3]) ) logger.debug("entering [%s]:form_json" % (__file__) ) template_form = "debug/form_sample_json.html" template_next = "/debug/form_response" logger.debug("template: [%s], request method: [%s]" % (template_form, request.method) ) show_errors = False json_str = "{}" if request.method == 'POST': # If the form has been submitted... form = JsonForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # convert data to JSON json_data = form.cleaned_data['json'] logger.debug("json_data: [%s]" % json_data) # construct query string query_dict = QueryDict('json=%s' % json_data) query_string = query_dict.urlencode() logger.debug("query_string: [%s]" % query_string) # full_redirect_url = template_next + "?" + query_string logger.debug("full_redirect_url: [%s]" % full_redirect_url) return redirect(full_redirect_url ) else: show_errors = True else: if request.method == 'GET': # get json string query_dict = request.GET json_str = query_dict.get("json", "{}") logger.debug("json_str: [%s]" % json_str) form = JsonForm({'json': json_str}) # bound form return render(request, template_form, { 'form': form, 'show_errors': show_errors, }) #@require_safe def form_sample(request): #logger.debug("entering [%s]:[%s]" % (__file__, inspect.stack()[0][3]) ) logger.debug("entering [%s]:form_sample" % (__file__) ) template_form = "debug/form_sample_input.html" template_next = "/debug/form_json" logger.debug("template: [%s]" % template_form) show_errors = False if request.method == 'POST': # If the form has been submitted... form = VoteForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # convert data to JSON json_data = form.json() logger.debug("json_data: [%s]" % json_data) # construct query string query_dict = QueryDict('json=%s' % json_data) query_string = query_dict.urlencode() logger.debug("query_string: [%s]" % query_string) # full_redirect_url = template_next + "?" + query_string logger.debug("full_redirect_url: [%s]" % full_redirect_url) return redirect(full_redirect_url ) else: show_errors = True else: form = VoteForm() # An unbound form return render(request, template_form, { 'form': form, 'show_errors': show_errors, }) # return render_to_response(template_file, { # 'view_type': "lala", # } # )
{ "repo_name": "andrew-szymanski/gae_django", "path": "votuition/views.py", "copies": "1", "size": "6681", "license": "bsd-3-clause", "hash": -8754530612247372000, "line_mean": 34.9247311828, "line_max": 95, "alpha_frac": 0.5430324802, "autogenerated": false, "ratio": 3.9462492616656824, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4989281741865682, "avg_score": null, "num_lines": null }
__author__ = 'Andrew Taylor' class Filter(object): def __init__(self, config=None): self.config = config """ Method to override to modify the value of the RGB data. Default here is no modification """ def modify(self, rgb): return rgb class ClearFilter(Filter): """ The same RGB value is returned """ def modify(self, rgb): return rgb class NegativeFilter(Filter): """ RGB value is returned as the opposite """ def modify(self, rgb): return rgb ^ 0xFFFFFF class NeutralDensityFilter(Filter): def __init__(self, config=None): self.factor = 1 """ Reduce the intensity of the value by the prescribed factor """ def modify(self, rgb): red = (rgb >> 16) & 0xFF green = (rgb >> 8) & 0xFF blue = rgb & 0xFF # scale the values red = red / self.factor green = green / self.factor blue = blue / self.factor # Reconstruct and return the RGB value rgb = ((red & 0xFF) << 16) + ((green & 0xFF) << 8) + (blue & 0xFF) return rgb
{ "repo_name": "fraz3alpha/led-disco-dancefloor", "path": "software/controller/lib/filters.py", "copies": "2", "size": "1121", "license": "mit", "hash": -8013783010417579000, "line_mean": 21, "line_max": 74, "alpha_frac": 0.5628902765, "autogenerated": false, "ratio": 3.933333333333333, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5496223609833333, "avg_score": null, "num_lines": null }
__author__ = 'Andrey Alekov' import logging import serial logger = logging.getLogger() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %I:%M:%S') LF = serial.to_bytes([10]) CR = serial.to_bytes([13]) CRTLZ = serial.to_bytes([26]) CRLF = serial.to_bytes([13, 10]) class Modem(object): """ Modem class. """ __port = None def __init__(self, port=r"\\.\COM0"): """ Initialize modem :param port: Int number of serial port :return: None """ self.__port = serial.Serial(port, 115200, timeout=10) logger.debug("Port {desc}".format(desc=self.__port)) self.execute('ATZ') # reset modem state # Modem is active? if self.execute('AT+CPAS')[1] != b'+CPAS: 0': raise Exception("Modem is not active!") if not self.execute('AT+CIMI'): raise Exception("Modem without SIM card!") if self.execute('AT+CREG?')[1] not in [b'+CREG: 0,1', b'+CREG: 0,5']: raise Exception("No registration in home or non-home network!") def close(self): """ Close Serial Port :return: """ self.__port.close() def execute(self, command): """ Execute AT command :return: list of output or False when error. """ self.__port.write(command.encode('latin1')) self.__port.write(CRLF) self.__port.flush() result = [] while True: line = self.__port.readline() if line != b'\r\n': result.append(line[:-2]) # remove \r\n symbols if line in [b'OK\r\n', b'ERROR\r\n']: break logger.info("{cmd} \t>>\t {ret}".format(cmd=command, ret=result[-1].decode('ascii'))) if result[-1] == b'ERROR': return False else: return result def getinfo(self): """ Get information about modem :return: dictionary {company, model, firmware, imei} """ info = dict() info.update({'company': self.execute('AT+CGMI')[1].decode('ascii')}) info.update({'model': self.execute('AT+CGMM')[1].decode('ascii')}) info.update({'firmware': self.execute('AT+CGMR')[1].decode('ascii')}) info.update({'imei': self.execute('AT+CGSN')[1].decode('ascii')}) return info def sendsms(self, pdu): """ Send SMS using PDU format """ self.execute('AT+CMGF=0') self.__port.write(('AT+CMGS=%s' % pdu.len()).encode('latin1')) self.__port.write(CR) self.__port.write(pdu.tostring().encode('latin1')) self.__port.write(CRTLZ) while True: line = self.__port.readline() if line != b'\r\n': logger.debug(line[:-2]) # remove \r\n symbols if line in [b'OK\r\n', b'ERROR\r\n']: break if line == b'OK\r\n': return True else: False
{ "repo_name": "andrey-alekov/gsmmodem_tools", "path": "modem.py", "copies": "1", "size": "3049", "license": "mit", "hash": 7251914292525586000, "line_mean": 31.4468085106, "line_max": 118, "alpha_frac": 0.5211544769, "autogenerated": false, "ratio": 3.612559241706161, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9629571953253573, "avg_score": 0.0008283530705174781, "num_lines": 94 }
__author__ = 'Andrey Alekov' class PDU(object): """ Simple PDU format with hardcoded params. """ def __init__(self, destination, text, smsc=None): if smsc is not None: self.sca = PDU.encode_sca(smsc) else: self.sca = "00" # use SIM card SMSC self.pdu_type = "01" # pdu type / outgoing message self.tp_mr = "00" # tp_message_reference self.da = PDU.encode_dest(destination) self.pid = "00" # protocol identifier self.dcs = "08" # data coding schema UCS2 self.vp = "0" # validity period on SMSC self.ud = PDU.encode_text(text) # user data self.udl = ('%0.2X' % (len(self.ud)/2)) # user data length in bytes self.pdu = self.pdu_type + self.tp_mr + self.da + self.pid + self.dcs + self.udl + self.ud self.pdu_len = int(len(self.pdu) / 2) self.pdu = self.sca + self.pdu def encode_number(number): number = number.replace('+', '') number += 'F' res = "" for i in range(0, len(number), 2): if (i+1) < len(number): res = res + number[i+1] res = res + number[i] return res def encode_sca(number): res = PDU.encode_number(number) size = int(len(res)/2 + 1) return ('%0.2X' % size) + '91' + res def encode_dest(number): res = PDU.encode_number(number) size = len(res) - 1 return ('%0.2X' % size) + '91' + res def encode_text(text): res = "" for s in text: res += (str(hex(ord(s))[2:].zfill(4)).upper()) return res def tostring(self): return self.pdu def len(self): return self.pdu_len
{ "repo_name": "andrey-alekov/gsmmodem_tools", "path": "pdu.py", "copies": "1", "size": "1872", "license": "mit", "hash": 9155705729512226000, "line_mean": 33.0545454545, "line_max": 98, "alpha_frac": 0.4823717949, "autogenerated": false, "ratio": 3.499065420560748, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9477151938448198, "avg_score": 0.000857055402509948, "num_lines": 55 }
__author__ = "Andrey Nikishaev" __copyright__ = "Copyright 2010, http://creotiv.in.ua" __license__ = "GPL" __version__ = "0.3" __maintainer__ = "Andrey Nikishaev" __email__ = "creotiv@gmail.com" __status__ = "Production" """ Simple local cache. It saves local data in singleton dictionary with convenient interface Examples of use: # Initialize SimpleCache({'data':{'example':'example data'}}) # Getting instance c = SimpleCache.getInstance() c.set('re.reg_exp_compiled',re.compile(r'\W*')) reg_exp = c.get('re.reg_exp_compiled',default=re.compile(r'\W*')) or c = SimpleCache.getInstance() reg_exp = c.getset('re.reg_exp_compiled',re.compile(r'\W*')) or @scache def func1(): return 'OK' """ class SimpleCache(dict): def __new__(cls,*args): if not hasattr(cls,'_instance'): cls._instance = dict.__new__(cls) else: raise Exception('SimpleCache already initialized') return cls._instance @classmethod def getInstance(cls): if not hasattr(cls,'_instance'): cls._instance = dict.__new__(cls) return cls._instance def get(self,name,default=None): """Multilevel get function. Code: Config().get('opt.opt_level2.key','default_value') """ if not name: return default levels = name.split('.') data = self for level in levels: try: data = data[level] except: return default return data def set(self,name,value): """Multilevel set function Code: Config().set('opt.opt_level2.key','default_value') """ levels = name.split('.') arr = self for name in levels[:-1]: if not arr.has_key(name): arr[name] = {} arr = arr[name] arr[levels[-1]] = value def getset(self,name,value): """Get cache, if not exists set it and return set value Code: Config().getset('opt.opt_level2.key','default_value') """ g = self.get(name) if not g: g = value self.set(name,g) return g def scache(func): def wrapper(*args, **kwargs): cache = SimpleCache.getInstance() fn = "scache." + func.__module__ + func.__class__.__name__ + \ func.__name__ + str(args) + str(kwargs) val = cache.get(fn) if not val: res = func(*args, **kwargs) cache.set(fn,res) return res return val return wrapper
{ "repo_name": "ActiveState/code", "path": "recipes/Python/577492_Simple_local_cache_cache/recipe-577492.py", "copies": "1", "size": "2724", "license": "mit", "hash": -843309161157631200, "line_mean": 25.9702970297, "line_max": 70, "alpha_frac": 0.516886931, "autogenerated": false, "ratio": 3.8638297872340424, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4880716718234042, "avg_score": null, "num_lines": null }
__author__ = "Andrey Nikishaev" __email__ = "creotiv@gmail.com" import gevent from gevent import core from gevent.hub import getcurrent from gevent.event import Event from gevent.pool import Pool import functools def wrap(method, *args, **kargs): if method is None: return None if args or kargs: method = functools.partial(method, *args, **kargs) def wrapper(*args, **kargs): return method(*args, **kargs) return wrapper class FiredEvent(Exception): pass class Event(object): def __init__(self,events,name,callback): self.events = events self.name = name.lower() self.callback = callback def unsubscribe(self): if not self.events._events.has_key(self.name): return False try: del self.events._events[self.name][self.events._events[self.name].index(self)] except: pass return True def cancel(self): self.unsubscribe() def run(self): gevent.spawn(self.callback) def __del__(self): self.unsubscribe() class Observer(object): def __new__(cls,*args): if not hasattr(cls,'_instance'): cls._instance = object.__new__(cls) cls._instance._events = {} return cls._instance def subscribe(self,name,callback): if not self._events.has_key(name.lower()): self._events[name] = [] ev = Event(self,name,callback) self._events[name].append(ev) return ev def fire(self,name): try: ev = self._events[name.lower()].pop(0) except: return False while ev: gevent.spawn(ev.run) try: ev = self._events[name.lower()].pop(0) except: break return True def wait(self,name): if not self._events.has_key(name.lower()): self._events[name] = [] ev = Event(self,name,wrap(getcurrent().throw,FiredEvent)) self._events[name].append(ev) return ev if __name__ == '__main__': # Testing def in_another_greenlet(): print '001',getcurrent() def test_subscribe(): e = Observer() print '000',getcurrent() getcurrent().in_another_greenlet = in_another_greenlet b = e.subscribe('kill',getcurrent().in_another_greenlet) gevent.sleep(5) print 'END' b.unsubscribe() def test_wait(): e = Observer() ev = e.wait('kill') try: gevent.sleep(3) except FiredEvent: print 'Fired!' else: print 'Not Fired!' finally: ev.cancel() def fire_event(): e2 = Observer() gevent.sleep(2) e2.fire('kill') p = Pool() p.spawn(test_wait) p.spawn(test_subscribe) p.spawn(fire_event) p.join()
{ "repo_name": "ActiveState/code", "path": "recipes/Python/577491_Observer_Design_Pattern_pythgevent_coroutine/recipe-577491.py", "copies": "1", "size": "2950", "license": "mit", "hash": 2258783868037346000, "line_mean": 23.7899159664, "line_max": 90, "alpha_frac": 0.5420338983, "autogenerated": false, "ratio": 3.8562091503267975, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48982430486267975, "avg_score": null, "num_lines": null }
__author__ = "Andrey Nikishaev" __email__ = "creotiv@gmail.com" import pymongo from gevent.queue import PriorityQueue import os import time class MongoPoolException(Exception): pass class MongoPoolCantConnect(MongoPoolException): pass class MongoPoolAutoReconnect(MongoPoolException): pass class GPool(object): """ Rewrited non-thread local implementation of pymongo.connection._Pool """ __slots__ = ["sockets", "socket_factory", "pool_size","sock"] def __init__(self, socket_factory): object.__init__(self) self.pool_size = 1 if not hasattr(self,"sock"): self.sock = None self.socket_factory = socket_factory if not hasattr(self, "sockets"): self.sockets = [] def socket(self): # we store the pid here to avoid issues with fork / # multiprocessing - see # test.test_connection:TestConnection.test_fork for an example # of what could go wrong otherwise pid = os.getpid() if self.sock is not None and self.sock[0] == pid: return self.sock[1] try: self.sock = (pid, self.sockets.pop()) except IndexError: self.sock = (pid, self.socket_factory()) return self.sock[1] def return_socket(self): if self.sock is not None and self.sock[0] == os.getpid(): # There's a race condition here, but we deliberately # ignore it. It means that if the pool_size is 10 we # might actually keep slightly more than that. if len(self.sockets) < self.pool_size: self.sockets.append(self.sock[1]) else: self.sock[1].close() self.sock = None pymongo.connection._Pool = GPool class MongoConnection(object): """Memcache pool auto-destruct connection""" def __init__(self,pool,conn): self.pool = pool self.conn = conn def getDB(self): return self.conn def __getattr__(self, name): return getattr(self.conn, name) def __getitem__(self, name): return self.conn[name] def __del__(self): self.pool.queue.put((time.time(),self.conn)) del self.pool del self.conn class Mongo(object): """MongoDB Pool""" def __new__(cls,size=5,dbname='',*args,**kwargs): if not hasattr(cls,'_instance'): cls._instance = object.__new__(cls) cls._instance.dbname = dbname cls._instance.queue = PriorityQueue(size) for x in xrange(size): try: cls._instance.queue.put( (time.time(),pymongo.Connection(*args,**kwargs)[dbname]) ) except Exception,e: raise MongoPoolCantConnect('Can\'t connect to mongo servers: %s' % e) return cls._instance def get_conn(self,block=True,timeout=None): """Get Mongo connection wrapped in MongoConnection""" obj = MongoConnection return obj(self,self.queue.get(block,timeout)[1]) def autoreconnect(func,*args,**kwargs): while True try: result = func(*args,**kwargs) except pymongo.errors.AutoReconnect: raise MongoPoolAutoReconnect('Can\'t connect to DB, it may gone.') else: return result break
{ "repo_name": "ActiveState/code", "path": "recipes/Python/577490_MongoDB_Pool_gevent_pymongo/recipe-577490.py", "copies": "1", "size": "3544", "license": "mit", "hash": 8713911834384328000, "line_mean": 28.781512605, "line_max": 89, "alpha_frac": 0.5555869074, "autogenerated": false, "ratio": 4.214030915576695, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5269617822976694, "avg_score": null, "num_lines": null }
__author__ = "Andrey Nikishaev" __email__ = "creotiv@gmail.com" import pymongo, sys from gevent.queue import Queue class GeventMongoPool(object): """ Rewrited connection pool for working with global connections. """ # Non thread-locals __slots__ = ["sockets", "socket_factory"] sock = None def __init__(self, socket_factory): self.socket_factory = socket_factory if not hasattr(self, "sockets"): self.sockets = [] def socket(self): # we store the pid here to avoid issues with fork / # multiprocessing - see # test.test_connection:TestConnection.test_fork for an example # of what could go wrong otherwise pid = os.getpid() if self.sock is not None and self.sock[0] == pid: return self.sock[1] try: self.sock = (pid, self.sockets.pop()) except IndexError: self.sock = (pid, self.socket_factory()) return self.sock[1] def return_socket(self): if self.sock is not None and self.sock[0] == os.getpid(): self.sockets.append(self.sock[1]) self.sock = None pymongo.connection.Pool = GeventMongoPool class MongoConnection(object): """Memcache pool auto-destruct connection""" def __init__(self,pool,conn): self.pool = pool self.conn = conn def getDB(self): return self.conn def __getattr__(self, name): return getattr(self.conn, name) def __getitem__(self, name): return self.conn[name] def __del__(self): self.pool.queue.put(self.conn) del self.pool del self.conn class Mongo(object): """MongoDB Pool""" def __new__(cls,db_name,size=5,*args,**kwargs): if not hasattr(cls,'_instance'): # use your own config library cls._instance = object.__new__(cls) cls._instance.queue = Queue(size) for x in xrange(size): try: # use your own config library cls._instance.queue.put( pymongo.Connection(*args,**kwargs)[db_name] ) except: sys.exc_clear() error('Can\'t connect to mongo servers') return cls._instance def get_conn(self,block=True,timeout=None): """Get Mongo connection wrapped in MongoConnection object""" obj = MongoConnection return obj(self,self.queue.get(block,timeout))
{ "repo_name": "sunlightlabs/regulations-scraper", "path": "regscrape/regs_common/gevent_mongo.py", "copies": "1", "size": "2536", "license": "bsd-3-clause", "hash": -6041757762231657000, "line_mean": 28.1494252874, "line_max": 70, "alpha_frac": 0.565851735, "autogenerated": false, "ratio": 4.064102564102564, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5129954299102564, "avg_score": null, "num_lines": null }
__author__ = 'andrey' def print_stats(items): if items is None or len(items) < 1: return print("\n%-50s (%02d)" % (items[0].__class__.__name__ + "s", len(items))) for t in set(i.type for i in items): print("\ttype: %-35s (%02d)" % (t, len([1 for i in items if i.type == t]))) def print_metadata_table(section): import matplotlib.pyplot as plt columns = ['Name', 'Value', 'Unit'] cell_text = [] for p in [(i.name, i) for i in section.props]: for i, v in enumerate(p[1].values): value = str(v.value) if len(value) > 30: value = value[:30] + '...' if i == 0: row_data = [p[0], value, p[1].unit if p[1].unit else '-'] else: row_data = [p[0], value, p[1].unit if p[1].unit else '-'] cell_text.append(row_data) if len(cell_text) > 0: nrows, ncols = len(cell_text)+1, len(columns) hcell, wcell = 1., 5. hpad, wpad = 0.5, 0 fig = plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) ax = fig.add_subplot(111) ax.axis('off') the_table = ax.table(cellText=cell_text, colLabels=columns, loc='center') for cell in the_table.get_children(): cell.set_height(.075) cell.set_fontsize(12) #ax.set_title(section.name, fontsize=12) return fig
{ "repo_name": "G-Node/nix-demo", "path": "utils/notebook.py", "copies": "1", "size": "1496", "license": "bsd-3-clause", "hash": -1552903788730305500, "line_mean": 33, "line_max": 84, "alpha_frac": 0.4872994652, "autogenerated": false, "ratio": 3.33184855233853, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.431914801753853, "avg_score": null, "num_lines": null }
__author__ = 'andrey' def print_stats(items): print("\n%-50s (%02d)" % (items[0].__class__.__name__ + "s", len(items))) for t in set(i.type for i in items): print("\ttype: %-35s (%02d)" % (t, len([1 for i in items if i.type == t]))) def print_metadata_table(section): import matplotlib.pyplot as plt columns = ['Name', 'Value', 'Unit'] cell_text = [] for p in [(i.name, i) for i in section.props]: for i, v in enumerate(p[1].values): value = str(v.value) if len(value) > 30: value = value[:30] + '...' if i == 0: row_data = [p[0], value, p[1].unit if p[1].unit else '-'] else: row_data = [p[0], value, p[1].unit if p[1].unit else '-'] cell_text.append(row_data) if len(cell_text) > 0: nrows, ncols = len(cell_text)+1, len(columns) hcell, wcell = 1., 5. hpad, wpad = 0.5, 0 fig = plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) ax = fig.add_subplot(111) ax.axis('off') the_table = ax.table(cellText=cell_text, colLabels=columns, loc='center') for cell in the_table.get_children(): cell.set_height(.075) cell.set_fontsize(12) #ax.set_title(section.name, fontsize=12) return fig
{ "repo_name": "stoewer/nix-demo", "path": "utils/notebook.py", "copies": "1", "size": "1440", "license": "bsd-3-clause", "hash": -9128905016720810000, "line_mean": 34.1219512195, "line_max": 84, "alpha_frac": 0.4854166667, "autogenerated": false, "ratio": 3.3179723502304146, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43033890169304145, "avg_score": null, "num_lines": null }
__author__ = 'andro' import os def populate(): python_cat = add_cat('Python') add_page(cat=python_cat, title="Official Python Tutorial", url="http://docs.python.org/2/tutorial") add_page(cat=python_cat, title="How to Think like a Computer Scientist", url="http://www.greenteapress.com/thinkpython/") add_page(cat=python_cat, title="Learn Python in 10 Minutes", url="http://www.korokithakis.net/tutorials/python/") django_cat = add_cat("Django") add_page(cat=django_cat, title="Official Django Tutorial", url="https://docs.djangoproject.com/en/1.5/intro/tutorial01/") add_page(cat=django_cat, title="Django Rocks", url="http://www.djangorocks.com/") add_page(cat=django_cat, title="How to Tango with Django", url="http://www.tangowithdjango.com/") frame_cat = add_cat("Other Frameworks") add_page(cat=frame_cat, title="Bottle", url="http://bottlepy.org/docs/dev/") add_page(cat=frame_cat, title="Flask", url="http://flask.pocoo.org") # Print out what we have added to the user. for c in Category.objects.all(): for p in Page.objects.filter(category=c): print "- {0} - {1}".format(str(c), str(p)) def add_page(cat, title, url): print type(cat) p = Page.objects.get_or_create(category = cat, title = title, url = url)[0] return p def add_cat(title): c = Category.objects.get_or_create(name = title)[0] return c if __name__ == '__main__': print "Starting Rango population script..." os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django.settings') from rango.models import Category, Page populate()
{ "repo_name": "andromajid/learndjango", "path": "populate_rango.py", "copies": "1", "size": "1757", "license": "mit", "hash": 3909432771792062000, "line_mean": 28.3, "line_max": 81, "alpha_frac": 0.6180990324, "autogenerated": false, "ratio": 3.321361058601134, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44394600910011345, "avg_score": null, "num_lines": null }
__author__ = "Andrzej Krawczyk - Pep8 test" import os import sys import json class Punkt(object): def __init__(self, x, z, some_data): self.x = x self.z = z self.some_data = some_data def title(self): return "%s" % self.some_data def some_data_processor(a, b, y=10, c=20, e=[1, 2, 3, 4]): result = 0 for x in range(15): result = (a ** 2 + (c / y * e) + b ** b + 10 - 20 + 33 ** 2) if result % 2 == 0: print("oh!") def foo(m, y, d="Ala ma kota", h="7 krasnali"): return d + h def bar(a, b): return sum(a) / float(b) some_results = foo(1, 2, d="zxc", h="askdj") list_of_people = [ "Rama", "John", "Shiva", "Janusz" ] zdanieDoTestow = "To jest bardzo dluga linijka kodu zawierajaca po prostu jakis tekst o jakiejs dlugosci i chyba jest dosyc mocno za dluga" Drugie_Zdanie = 'to jest kolejna dluga linijka tekstu do testow' with open('/path/to/some/file/you/want/to/read') as file_1, \ open('/path/to/some/file/being/written', 'w') as file_2: file_2.write(file_1.read()) income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) wynik1 = "{} {} {}".format(zdanieDoTestow, 2, 3)
{ "repo_name": "andrzejkrawczyk/python-course", "path": "part_1/zadania/data_processing/pep8.py", "copies": "1", "size": "1304", "license": "apache-2.0", "hash": 6024403231699775000, "line_mean": 21.8771929825, "line_max": 139, "alpha_frac": 0.5705521472, "autogenerated": false, "ratio": 2.536964980544747, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8606890561328707, "avg_score": 0.00012531328320802005, "num_lines": 57 }
__author__ = 'Andrzej Skrodzki 292510' from pymongo import MongoClient from pymongo.errors import ConnectionFailure from pymongo.collection import * import datetime def main(): client = None try: client = MongoClient('mongodb://as292510:test1234@ds027699.mongolab.com:27699/zbd2013') except ConnectionFailure: print "Connection to database failed." exit() print "Login succeseed" createDatabase(client["zbd2013"]) exit() def createDatabase(db): assert(db is not None) print "Database creation started." teamId = createTeam(db) playerId = createPlayer(db, teamId) matchId = createMatch(db, teamId) pointId = createPoint(db, matchId) createSquad(db, pointId, playerId) createInjury(db, playerId) createTrainer(db, teamId) print "Database creation finished successfully." return def createTrainer(db, teamId): id = ObjectId() trainer_col = db.Trainer trainer_col.insert({ "_id": id, "Name": "Jan", "Surname": "Kowalski", "Start_time": str(datetime.date(2013, 2, 3)), "End_time": str(datetime.date(2013, 2, 3)), "Team_id": teamId }) def createInjury(db, playerId): id = ObjectId() injury_col = db.Injury injury_col.insert({ "_id": id, "Player_id": playerId, "Start_date": str(datetime.datetime.now()), "End_date": str(datetime.datetime.now()) }) return id def createSquad(db, pointId, playerId): id = ObjectId() squad_col = db.Squad squad_col.insert({ "_id" : id, "Player_id": playerId, "Point_id": pointId, "Position": 1 }) return id def createTeam(db): id = ObjectId() team_col = db.Teams team_col.insert({ "Name": "Polska", "_id": id }) return id pass def createPlayer(db, teamId): id = ObjectId() player_col = db.Player player_col.insert({ "_id": id, "Name": "Jan", "Surname": "Kowalski", "Birth": str(datetime.date(1990, 07, 14)), "Team_id": teamId }) return id def createMatch(db, opponent): id = ObjectId() match_col = db.Match match_col.insert({ "_id": id, "Team_id": opponent, "Won": 1, "Date": str(datetime.datetime.today()), }) return id def createPoint(db, match): id = ObjectId() point_col = db.Point point_col.insert({ "_id": id, "Score": 1, "Serve": 110.2, "Match_id": match }) return id if __name__ == "__main__": main()
{ "repo_name": "endrjuskr/studies", "path": "ZBD/zbd-mongo/mongo-connector.py", "copies": "1", "size": "2622", "license": "apache-2.0", "hash": 201290562687020580, "line_mean": 20.6694214876, "line_max": 95, "alpha_frac": 0.5751334859, "autogenerated": false, "ratio": 3.32319391634981, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9395830845775981, "avg_score": 0.0004993112947658402, "num_lines": 121 }
__author__ = 'Andrzej Skrodzki - as292510' # module: tokrules.py # This module just contains the lexing rules from .LatteExceptions import LexerException import lattepar # Reserved words reserved = ( 'IF', 'ELSE', 'WHILE', 'RETURN', 'INT', 'STRING', 'BOOLEAN', 'VOID', 'TRUE', 'FALSE', 'NULL', 'NEW', 'FOR', 'CLASS', 'EXTENDS') # Token names. tokens = reserved + ( 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD', 'OR', 'AND', 'NOT', 'LT', 'LE', 'GT', 'GE', 'EQ', 'NE', 'EQUALS', 'DOT', 'COL', 'PLUSPLUS', 'MINUSMINUS', 'LPAREN', 'RPAREN', 'LBRACE', 'RBRACE', 'COMMA', 'SEMI', 'NUMBER', 'SENTENCE', 'ID', 'LARRAY', 'RARRAY') # A string containing ignored characters (spaces and tabs) t_ignore = ' \t' t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_MOD = r'%' t_OR = r'\|\|' t_AND = r'&&' t_LT = r'<' t_GT = r'>' t_LE = r'<=' t_GE = r'>=' t_EQ = r'==' t_NE = r'!=' t_NOT = r'!' t_EQUALS = r'=' t_PLUSPLUS = r'\+\+' t_MINUSMINUS = r'--' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACE = r'\{' t_RBRACE = r'\}' t_COMMA = r',' t_SEMI = r';' t_LARRAY = r'\[' t_RARRAY = r'\]' t_DOT = r'\.' t_COL = r'\:' def t_NUMBER(t): r'\d+' t.value = int(t.value) return t reserved_map = {} for r in reserved: reserved_map[r.lower()] = r # String literal t_SENTENCE = r'\"([^\\\n]|(\\.))*?\"' def t_ID(t): r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = reserved_map.get(t.value, 'ID') # Check for reserved words return t def t_comment(t): r'\#.*|//.*|/\*(.|\n)*?\*/' t.lexer.lineno += t.value.count('\n') # Define a rule so we can track line numbers def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) # Error handling rule def t_error(t): lattepar.exception_list.append(LexerException("Illegal character '%s'" % t.value[0], t.lexer.lineno))
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/tokrules.py", "copies": "1", "size": "1882", "license": "apache-2.0", "hash": -3907634433791170000, "line_mean": 17.4607843137, "line_max": 105, "alpha_frac": 0.5281615303, "autogenerated": false, "ratio": 2.4730617608409986, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3501223291140999, "avg_score": null, "num_lines": null }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["Arg", "InitItem", "ItemBase", "NoInitItem", "Field", "exception_list_par"] from .BaseNode import * from .LatteTypes import * from ..LatteExceptions import * exception_list_par = [] class Arg(BaseNode): def __init__(self, type, ident, no_line, pos): super(Arg, self).__init__("arg", no_line, pos) self.argtype = type self.ident = ident def type_check(self, env): if self.argtype.get_type() == Type("void"): exception_list_par.append(SyntaxException("Cannot initialize void variable.", self.no_line, self.pos)) class Field(BaseNode): def __init__(self, type, ident, no_line, pos): super(Field, self).__init__("field", no_line, pos) self.field_type = type self.ident = ident class ItemBase(BaseNode): def __init__(self, ident, no_line, pos, type): super(ItemBase, self).__init__(type, no_line, pos) self.ident = ident self.itemtype = Type("void") def type_check(self, env): pass class InitItem(ItemBase): def __init__(self, ident, expr, no_line, pos): super(InitItem, self).__init__(ident, no_line, pos, "inititem") self.expr = expr def type_check(self, env): if self.itemtype.get_type() == Type("void"): exception_list_par.append(SyntaxException("Cannot initialize void variable.", self.no_line, self.pos)) self.expr.type_check(env, expected_type=self.itemtype) def generate_body(self, env): s = self.expr.generate_body(env) env.add_variable(self.ident, self.itemtype, self.no_line, self.pos, fun_param=False) if self.itemtype == Type("string"): s += "astore " + str(env.get_variable_value([self.ident])) + "\n" else: s += "istore " + str(env.get_variable_value([self.ident])) + "\n" return s def generate_code_asm(self, env, get_value=True): s = self.expr.generate_code_asm(env, get_value) if self.itemtype.is_array(): env.add_variable(self.ident, None, self.no_line, self.pos, fun_param=False) env.add_variable(self.ident, self.itemtype, self.no_line, self.pos, fun_param=False) return s class NoInitItem(ItemBase): def __init__(self, ident, no_line, pos): super(NoInitItem, self).__init__(ident, no_line, pos, "noinititem") def type_check(self, env): if self.itemtype.get_type() == Type("void"): exception_list_par.append(SyntaxException("Cannot initialize void variable.", self.no_line, self.pos)) def generate_body(self, env): s = "" env.add_variable(self.ident, self.itemtype, self.no_line, self.pos, fun_param=False) if self.itemtype == Type("string"): s += "ldc \"\" \n" s += "astore " + str(env.get_variable_value([self.ident])) + "\n" else: s += "iconst_0 \n" s += "istore " + str(env.get_variable_value([self.ident])) + "\n" return s def generate_code_asm(self, env, get_value=True): s = "" env.add_variable(self.ident, self.itemtype, self.no_line, self.pos, fun_param=False) if self.itemtype == Type("string"): s += "mov rax, qword [string_empty]\n" s += "push rax\n" else: s += "mov rax, 0\n" s += "push rax\n" return s
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/LatteParsers/LatteParameters.py", "copies": "1", "size": "3414", "license": "apache-2.0", "hash": -3673788752082578000, "line_mean": 34.9473684211, "line_max": 114, "alpha_frac": 0.5849443468, "autogenerated": false, "ratio": 3.2890173410404624, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4373961687840462, "avg_score": null, "num_lines": null }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["Block", "FnDef", "Program", "PredefinedFun", "ClassDef", "exception_list_fn"] from ..LatteExceptions import * from .LatteTypes import * from .BaseNode import * from ..Env import * exception_list_fn = [] class Block(BaseNode): def __init__(self, stmt_list): super(Block, self).__init__("block", 0, 0) self.stmt_list = stmt_list def type_check(self, env, reset_declarations=True): env_prim = Env(env, reset_declarations=reset_declarations) for stmt in self.stmt_list: stmt.type_check(env_prim) def return_check(self): for stmt in self.stmt_list: if stmt.return_check(): return True return False def generate_body(self, env): s = "" for stmt in self.stmt_list: s += stmt.generate_code_jvm(env) return s def generate_code_asm(self, env, get_value=True): s = "" for stmt in self.stmt_list: s += stmt.generate_code_asm(env, get_value) return s class ClassDef(BaseNode): def __init__(self, ident, extlist, fieldlist, no_line): super(ClassDef, self).__init__("classdef", no_line, 0) self.ident = ident methods = filter(lambda x: hasattr(x, "block"), fieldlist) fields = filter(lambda x: not hasattr(x, "block"), fieldlist) self.fieldpositions = map(lambda x: x.ident, fields) self.fieldlist = dict(zip(map(lambda x: x.ident, fields), fields)) self.methodslist = dict(zip(map(lambda x: x.ident, methods), methods)) self.methodslist_2 = dict(zip(map(lambda x: x.ident, methods), methods)) self.extlist = extlist self.derived = False self.size_s = 0 self.vis = False def prepare_env(self, env): env.add_variable("self", Type(self.ident), 0, 0) for f in self.fieldpositions: v = self.fieldlist[f] if v.field_type.is_array(): env.add_variable(v.ident, None, 0, 0) env.add_variable(v.ident, v.field_type, v.no_line, v.pos, is_field=True) def get_size(self): return self.size_s def get_derived(self, env): if self.vis: exception_list_fn.append(SyntaxException("Cycle in inheritance.", 0)) return None if self.derived: return self.vis = True self.derived = True if len(self.extlist) != 0: cl = env.get_class(self.extlist[0]) if cl is not None: cl.get_derived(env) self.fieldpositions = cl.fieldpositions + self.fieldpositions for k, v in cl.fieldlist.iteritems(): self.fieldlist[k] = v for k, v in cl.methodslist.iteritems(): if k in self.methodslist: exception_list_fn.append(SyntaxException("Overriding method is not possible - " + k, 0)) self.methodslist[k] = v for f in self.fieldpositions: v = self.fieldlist[f] if v.field_type.is_array(): self.size_s += 1 self.size_s += 1 self.vis = False def get_field_position(self, ident): index = 0 for f in self.fieldpositions: v = self.fieldlist[f] if v.ident == ident: return index if v.field_type.is_array(): index += 1 index += 1 def type_check(self, env): env_p = Env(env) for fn in self.methodslist.values(): env_p.add_fun(fn) for fn in self.methodslist.values(): env_prim = Env(env_p) self.prepare_env(env_prim) fn.type_check(env_prim) def contain_field(self, field): return field in self.fieldlist def contain_method(self, method): return method in self.methodslist def get_field_type(self, field): if not field in self.fieldlist: return None return self.fieldlist[field].field_type def get_method_type(self, method): if not method in self.methodslist: return None return self.methodslist[method].funtype def generate_code_asm(self, env, get_value=True): s = "" s_dict = env.string_dict for fn in self.methodslist_2.values(): env_prim = Env(env) self.prepare_env(env_prim) env_prim.string_dict = s_dict fn.is_class_method = True fn.class_id = self.ident s += fn.generate_code_asm(env_prim) s_dict = env_prim.string_dict env.string_dict = s_dict return s class FnDef(BaseNode): def __init__(self, type, ident, arglist, block, no_line): super(FnDef, self).__init__("fndef", no_line, 0) self.funtype = self.calculate_type(type, arglist) self.ident = ident self.arglist = arglist self.block = block self.is_class_method = False self.class_id = None def get_type(self, arg): return arg.argtype def type_check(self, env): self.prepare_env(env) for arg in self.arglist: arg.type_check(env) self.block.type_check(env, reset_declarations=False) if not self.funtype.return_type == Type("void"): if not self.block.return_check(): exception_list_fn.append(ReturnException(self.ident, self.no_line)) def prepare_env(self, env): #if self.is_class_method: # env.add_variable("self", Type(self.class_id), 0, 0) for arg in self.arglist: if arg.argtype.is_array(): env.add_variable(arg.ident, None, 0, 0) env.add_variable(arg.ident, arg.argtype, arg.no_line, arg.pos) env.current_fun_type = self.funtype env.in_main = self.ident == "main" if self.is_class_method: env.class_name = self.class_id def calculate_type(self, type, arglist): return FunType(type, map(self.get_type, arglist)) def generate_header(self): return ".method public static " + self.ident + self.funtype.generate_code_jvm() + "\n" if \ self.ident != "main" else ".method public static main([Ljava/lang/String;)V \n" def generate_body(self, env): self.prepare_env(env) if self.ident == "main": env.add_variable("args", Type("string"), 0, 0) s = self.block.generate_code_jvm(env) s += "return\n" s = ".limit stack " + str(env.get_stack_limit()) + "\n.limit locals " + str(env.get_local_limit()) + "\n" + s return s def generate_footer(self): return ".end method \n" def generate_code_asm(self, env, get_value=True): s = "o_" if self.is_class_method else "" s += self.ident + ":\n" self.prepare_env(env) s += "enter 0, 0\n" env.variables_counter += 1 if not self.ident == "main": env.variables_counter += 1 s += self.block.generate_code_asm(env, get_value) if not s.endswith("ret\n"): s += "leave\n" s += "ret\n" return s class PredefinedFun(FnDef): def __init__(self, type, ident, arglist): super(PredefinedFun, self).__init__(type, ident, arglist, [], 0) def type_check(self, env): pass def calculate_type(self, type, arglist): return FunType(type, arglist) def generate_code_jvm(self, env): return "" def generate_code_asm(self, env, get_value=True): return "" class ErrorFun(PredefinedFun): def __init__(self): super(ErrorFun, self).__init__(Type("void"), "error", []) class PrintIntFun(PredefinedFun): def __init__(self): super(PrintIntFun, self).__init__(Type("void"), "printInt", [Type("int")]) class PrintStringFun(PredefinedFun): def __init__(self): super(PrintStringFun, self).__init__(Type("void"), "printString", [Type("string")]) class ReadIntFun(PredefinedFun): def __init__(self): super(ReadIntFun, self).__init__(Type("int"), "readInt", []) class ReadStringFun(PredefinedFun): def __init__(self): super(ReadStringFun, self).__init__(Type("string"), "readString", []) class ConcatenateStringFun(PredefinedFun): def __init__(self): super(ConcatenateStringFun, self).__init__(Type("string"), "concatenateString", [Type("string"), Type("string")]) class Program(BaseNode): def __init__(self, topdeflist): super(Program, self).__init__("program", -1, 0) self.topdeflist = topdeflist self.topdeflist.append(ErrorFun()) self.topdeflist.append(ReadIntFun()) self.topdeflist.append(ReadStringFun()) self.topdeflist.append(PrintStringFun()) self.topdeflist.append(PrintIntFun()) self.topdeflist.append(ConcatenateStringFun()) self.class_name = "MyClass" def type_check(self): env = Env() for fndef in filter(lambda x: not hasattr(x, "methodslist"), self.topdeflist): env.add_fun(fndef) for classdef in filter(lambda x: hasattr(x, "methodslist"), self.topdeflist): env.add_class(classdef) for classdef in filter(lambda x: hasattr(x, "methodslist"), self.topdeflist): classdef.get_derived(env) if len(exception_list_fn) > 0: return for fndef in filter(lambda x: not hasattr(x, "methodslist"), self.topdeflist): self.fun_check(fndef, env) for classdef in filter(lambda x: hasattr(x, "methodslist"), self.topdeflist): env_prim = Env(env) classdef.type_check(env_prim) if env.contain_main() is False: exception_list_fn.append(SyntaxException("Main funtion is not declared.", self.no_line)) def fun_check(self, fun, env): env_prim = Env(env) fun.type_check(env_prim) def generate_body(self, env): for fndef in self.topdeflist: env.add_fun(fndef) s = "" for fn in self.topdeflist: env_prim = Env(env) s += fn.generate_code_jvm(env_prim) return s def set_class_name(self, name): self.class_name = name def generate_header(self): return ".class public " + self.class_name + \ "\n.super java/lang/Object \n \ .method public <init>()V \n \ aload_0 \n \ invokespecial java/lang/Object/<init>()V \n \ return \n \ .end method \n" def generate_code_asm(self, env, get_value=True): s = "; Code generated by LatteCompiler\n" s += "section .text\n" s += "global main\n" s += "extern printInt, printString, readInt, readString, error, contactString, calloc, malloc\n" for fndef in filter(lambda x: not hasattr(x, "methodslist"), self.topdeflist): env.add_fun(fndef) for classdef in filter(lambda x: hasattr(x, "methodslist"), self.topdeflist): env.add_class(classdef) s_dict = {"string_empty": "\"\""} for fn in self.topdeflist: env_prim = Env(env) env_prim.string_dict = s_dict s += fn.generate_code_asm(env_prim) s_dict = env_prim.string_dict h = "" if len(s_dict) > 0: h += "section .data\n" for k, v in s_dict.iteritems(): h += k + " db " + v + ",0\n" return s + h
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/LatteParsers/LatteTopDefinitions.py", "copies": "1", "size": "11660", "license": "apache-2.0", "hash": -790421273450863000, "line_mean": 32.6051873199, "line_max": 117, "alpha_frac": 0.5638078902, "autogenerated": false, "ratio": 3.584383645865355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4648191536065355, "avg_score": null, "num_lines": null }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["EAdd", "EAnd", "EApp", "ELitBoolean", "ELitInt", "EMul", "ENeg", "ENot", "EOr", "ERel", "EString", "EVar", "ExprBase", "OneArgExpr", "TwoArgExpr", "ZeroArgExpr", "EArrayInit", "EArrayApp", "EObjectInit", "ELitNull", "EObjectField", "exception_list_expr", "EMethodApp", "EObjectFieldApp"] from .BaseNode import * from ..LatteExceptions import * from .LatteTypes import * exception_list_expr = [] class ExprBase(BaseNode): def __init__(self, etype, no_line, pos): super(ExprBase, self).__init__("expr", no_line, pos) self.value = None self.etype = etype def type_check(self, env, expected_type=None): return None def calculate_value(self): pass def return_check(self): return False def get_value(self): return self.value def get_id(self): return None class OneArgExpr(ExprBase): def __init__(self, expr, etype, no_line, pos): super(OneArgExpr, self).__init__(etype, no_line, pos) self.expr = expr def type_check(self, env, expected_type=None): if expected_type is not None and not env.check_types(expected_type, self.etype): exception_list_expr.append(TypeException(expected_type, self.etype, self.no_line, self.pos)) self.expr.type_check(env, self.etype) return self.etype def calculate_value(self): if self.expr.value is not None: self.value = - self.expr.value def generate_body(self, env): return self.expr.generate_code_jvm(env) def generate_code_asm(self, env, get_value=True): s = self.expr.generate_code_asm(env, get_value) s += "pop rax\n" return s class TwoArgExpr(ExprBase): def __init__(self, left, right, op, etype, argtype, no_line, pos): super(TwoArgExpr, self).__init__(etype, no_line, pos) self.left = left self.right = right self.op = op self.argtype = argtype def type_check(self, env, expected_type=None): rtype = self.left.type_check(env, self.argtype) self.arg_type_check(rtype) self.right.type_check(env, rtype) error_occured = False if expected_type is not None and self.etype is not None and not env.check_types(expected_type, self.etype): exception_list_expr.append(TypeException(expected_type, self.etype, self.no_line, self.pos)) error_occured = True if expected_type is not None and self.etype is None and not env.check_types(expected_type, rtype): exception_list_expr.append(TypeException(expected_type, rtype, self.no_line, self.pos)) error_occured = True if not error_occured: self.calculate_value() return self.etype def arg_type_check(self, rtype): pass def generate_body(self, env): s = self.left.generate_code_jvm(env) s += self.right.generate_code_jvm(env) return s def generate_code_asm(self, env, get_value=True): s = self.left.generate_code_asm(env, get_value) env.increment_stack() s += self.right.generate_code_asm(env, get_value) env.decrement_stack() s += "pop rbx\n" s += "pop rax\n" return s class ZeroArgExpr(ExprBase): def __init__(self, value, etype, no_line, pos): super(ZeroArgExpr, self).__init__(etype, no_line, pos) self.value = value def type_check(self, env, expected_type=None): t = self.get_type(env) if expected_type is not None and not env.check_types(expected_type, t): exception_list_expr.append(TypeException(expected_type, t, self.no_line, self.pos)) return t return t def get_type(self, env): return self.etype class EAdd(TwoArgExpr): def __init__(self, left, right, op, no_line, pos): super(EAdd, self).__init__(left, right, op, None, None, no_line, pos) self.type = "eadd" def arg_type_check(self, rtype): if rtype is not None and rtype == Type("boolean"): exception_list_expr.append(SyntaxException("Boolean does not support add operators.", self.no_line, pos=self.pos)) if rtype is not None and rtype == Type("string") and self.op == "-": exception_list_expr.append(SyntaxException("String does not support - operator.", self.no_line, pos=self.pos)) self.etype = rtype def calculate_value(self): try: if self.left.get_value() is not None and self.right.get_value() is not None: if self.op == "+": self.value = self.left.get_value() + self.right.get_value() elif self.op == "-": self.value = self.left.get_value() - self.right.get_value() except TypeError: self.value = None def generate_body(self, env): s = super(EAdd, self).generate_body(env) if self.etype == Type("string"): cFun = "concatenateString" s += "invokestatic " + env.get_fun_class(cFun) + "." + cFun \ + env.get_fun_type(cFun).generate_code_jvm() + "\n" elif self.op == "+": s += "iadd \n" else: s += "isub \n" env.pop_stack(1) return s def generate_code_asm(self, env, get_value=True): s = super(EAdd, self).generate_code_asm(env, get_value) if self.etype == Type("string"): s += "mov rdi, rax\n" s += "mov rsi, rbx\n" s += "call contactString\n" elif self.op == "+": s += "add rax, rbx\n" else: s += "sub rax, rbx\n" s += "push rax\n" return s class EAnd(TwoArgExpr): def __init__(self, left, right, no_line, pos): super(EAnd, self).__init__(left, right, "&&", Type("boolean"), Type("boolean"), no_line, pos) self.type = "eand" self.label_pattern = "and_" + str(self.no_line) + "_" + str(self.pos) def calculate_value(self): if self.left.get_value() is False and self.left.get_value() is None: self.value = self.left.get_value() else: self.value = self.right.get_value() def generate_body(self, env): s = self.left.generate_code_jvm(env) s += "dup\n" s += "ifeq " + self.label_pattern + "\n" s += self.right.generate_code_jvm(env) s += "iand \n" s += self.label_pattern + ":\n" env.pop_stack(1) return s def generate_code_asm(self, env, get_value=True): s = self.left.generate_code_asm(env, get_value) s += "mov rax, [rsp]\n" s += "cmp rax, 0\n" s += "je " + self.label_pattern + "\n" env.increment_stack() s += self.right.generate_code_asm(env, get_value) env.decrement_stack() s += "pop rbx\n" s += "pop rax\n" s += "and rax, rbx \n" s += "push rax\n" s += self.label_pattern + ":\n" return s class EApp(ZeroArgExpr): def __init__(self, funident, exprlist, no_line, pos): super(EApp, self).__init__(None, None, no_line, pos) self.type = "eapp" self.funident = funident self.exprlist = exprlist self.etype = None def get_type(self, env): if self.etype is None: if not env.contain_function(self.funident): exception_list_expr.append(NotDeclaredException(self.funident, True, self.no_line, self.pos)) return Type("void") else: self.etype = env.get_fun_type(self.funident) self.check_arg_list(env) return self.etype.return_type def check_arg_list(self, env): if len(self.exprlist) != len(self.etype.params_types): exception_list_expr.append(SyntaxException("Wrong number of parameters for function " + self.funident + " - expected:" + str(len(self.etype.params_types)) + " actual: " + str(len(self.exprlist)) + ".", self.no_line, pos=self.pos)) for i in range(min(len(self.exprlist), len(self.etype.params_types))): self.exprlist[i].type_check(env, self.etype.params_types[i]) def generate_body(self, env): s = "" for expr in self.exprlist: s += expr.generate_code_jvm(env) s += "invokestatic " + env.get_fun_class(self.funident) + "." + self.funident + self.etype.generate_code_jvm() s += "\n" return s def generate_code_asm(self, env, get_value=True): s = "" shift = 0 for expr in self.exprlist: s += expr.generate_code_asm(env, get_value) if self.funident in env.predefined_fun: s += "pop rdi\n" pass else: if expr.etype.is_array(): env.increment_stack() shift += 8 env.increment_stack() shift += 8 s += "call " + self.funident + "\n" if not self.funident in env.predefined_fun: env.stack_shift -= shift s += "add rsp, " + str(shift) + "\n" if env.get_fun_type(self.funident).return_type != Type("void"): if env.get_fun_type(self.funident).return_type.is_array(): s += "push rbx\n" s += "push rax\n" return s def get_id(self): return [self.funident] class EMethodApp(ZeroArgExpr): def __init__(self, expr, funident, exprlist, no_line, pos): super(EMethodApp, self).__init__(None, None, no_line, pos) self.type = "eapp" self.funident = funident self.objident = expr self.exprlist = exprlist self.etype = None def get_type(self, env): if self.etype is None: t = env.get_variable_type(self.objident.get_id()) if t is None: return None if not env.contain_method(t.type, self.funident): exception_list_expr.append(NotDeclaredException(self.funident, True, self.no_line, self.pos)) return Type("void") else: self.etype = env.get_method_type(t.type, self.funident) self.check_arg_list(env) return self.etype.return_type def check_arg_list(self, env): if len(self.exprlist) != len(self.etype.params_types): exception_list_expr.append(SyntaxException("Wrong number of parameters for function " + self.funident + " - expected:" + str(len(self.etype.params_types)) + " actual: " + str(len(self.exprlist)) + ".", self.no_line, pos=self.pos)) for i in range(min(len(self.exprlist), len(self.etype.params_types))): self.exprlist[i].type_check(env, self.etype.params_types[i]) def generate_code_asm(self, env, get_value=True): s = "" shift = 8 s += self.objident.generate_code_asm(env, True) env.increment_stack() for expr in self.exprlist: s += expr.generate_code_asm(env, get_value) if self.funident in env.predefined_fun: s += "pop rdi\n" pass else: if expr.etype.is_array(): env.increment_stack() shift += 8 env.increment_stack() shift += 8 s += "call o_" + self.funident + "\n" env.stack_shift -= shift s += "add rsp, " + str(shift) + "\n" if self.etype.return_type != Type("void"): if self.etype.return_type.is_array(): s += "push rbx\n" s += "push rax\n" return s def get_id(self): t = self.objident.get_id() t.append(self.funident) return t class ELitBoolean(ZeroArgExpr): def __init__(self, lit, no_line, pos): super(ELitBoolean, self).__init__(True if lit == "true" else False, Type("boolean"), no_line, pos) self.type = "elitboolean" def generate_body(self, env): env.push_stack(1) return "iconst_1\n" if self.value else "iconst_0\n" def generate_code_asm(self, env, get_value=True): s = "mov rax, " + ("1\n" if self.value else "0\n") s += "push rax\n" return s class ELitNull(ZeroArgExpr): def __init__(self, type, no_line, pos): super(ELitNull, self).__init__(None, Type(type), no_line, pos) self.type = "elitnull" def generate_code_asm(self, env, get_value=True): return "push 0\n" # represent null as 0 class ELitInt(ZeroArgExpr): def __init__(self, value, no_line, pos): super(ELitInt, self).__init__(value, Type("int"), no_line, pos) self.type = "number" def generate_body(self, env): env.push_stack(1) return "ldc " + str(self.value) + " \n" def generate_code_asm(self, env, get_value=True): s = "mov rax, " + str(self.value) + "\n" s += "push rax\n" return s class EObjectField(ZeroArgExpr): def __init__(self, obj, field, no_line, pos): super(EObjectField, self).__init__(None, None, no_line, pos) self.type = "objectfield" self.obj = obj self.field = field self.etype = None def get_type(self, env): self.obj.type_check(env) self.etype = env.get_variable_type(self.obj.get_id()) if self.etype is None: return None if self.etype.is_array(): if self.field != "length": exception_list_expr.append(NotDeclaredException("array." + self.field, True, self.no_line, self.pos)) return Type("int") if not env.contain_class(self.etype.type): exception_list_expr.append(SyntaxException(str(self.etype) + " is not an object or class is not defined.", self.no_line)) field_type = env.get_field_type(self.etype.type, self.field) if field_type is None: exception_list_expr.append(SyntaxException(str(self.etype) + "." + self.field + " does not exist.", self.no_line, self.pos)) return field_type def generate_code_asm(self, env, get_value=True): s = self.obj.generate_code_asm(env, True) s += "object_field_" + str(self.pos) + "_" + str(self.no_line) + ":\n" s += "pop rax\n" if self.field == "length": return s else: s += "add rax, " + str(env.get_field_position(self.etype.type, self.field)) + "\n" if get_value and env.get_field_type(self.etype.type, self.field).is_array(): s += "mov rbx, rax\n" s += "add rbx, 8\n" s += "push qword [rbx]\n" if get_value: s += "push qword [rax]\n" else: s += "push rax\n" return s def get_id(self): t = self.obj.get_id() t.append(self.field) return t class EMul(TwoArgExpr): def __init__(self, left, right, op, no_line, pos): super(EMul, self).__init__(left, right, op, Type("int"), Type("int"), no_line, pos) self.type = "emul" def calculate_value(self): try: if self.left.get_value() is not None and self.right.get_value() is not None: if self.op == "/": if self.right.get_value() == 0: exception_list_expr.append(SyntaxException("Division by 0", self.no_line, pos=self.pos)) self.value = self.left.get_value() / self.right.get_value() elif self.op == "*": self.value = self.left.get_value() * self.right.get_value() elif self.op == "%": if self.right.get_value() == 0: exception_list_expr.append(SyntaxException("Modulo by 0", self.no_line, pos=self.pos)) self.value = self.left.get_value() % self.right.get_value() except TypeError: self.value = None except ZeroDivisionError: self.value = None def generate_body(self, env): s = super(EMul, self).generate_body(env) if self.op == "/": s += "idiv\n" elif self.op == "*": s += "imul\n" else: s += "irem\n" env.pop_stack(2) return s def generate_code_asm(self, env, get_value=True): s = super(EMul, self).generate_code_asm(env, get_value) s += "mov rdx, 0\n" # wyzerowac if self.op == "/": s += "idiv rbx\n" elif self.op == "*": s += "imul rax, rbx\n" else: s += "idiv rbx\n" s += "mov rax, rdx\n" s += "push rax\n" return s class ENeg(OneArgExpr): def __init__(self, expr, no_line, pos): super(ENeg, self).__init__(expr, Type("int"), no_line, pos) self.type = "eneg" def generate_body(self, env): s = super(ENeg, self).generate_body(env) s += "ineg\n" return s def generate_code_asm(self, env, get_value=True): s = super(ENeg, self).generate_code_asm(env, get_value) s += "neg rax\n" s += "push rax\n" return s class ENot(OneArgExpr): def __init__(self, expr, no_line, pos): super(ENot, self).__init__(expr, Type("boolean"), no_line, pos) self.type = "enot" def generate_body(self, env): s = super(ENot, self).generate_body(env) env.push_stack(1) s += "iconst_1\n" s += "ixor\n" env.pop_stack(1) return s def generate_code_asm(self, env, get_value=True): s = super(ENot, self).generate_code_asm(env, get_value) s += "xor rax, 1\n" s += "push rax\n" return s class EOr(TwoArgExpr): def __init__(self, left, right, no_line, pos): super(EOr, self).__init__(left, right, "||", Type("boolean"), Type("boolean"), no_line, pos) self.type = "eor" self.label_pattern = "or_" + str(self.no_line) + "_" + str(self.pos) def calculate_value(self): if self.left.get_value() is True: self.value = True else: self.value = self.right.get_value() def generate_body(self, env): s = self.left.generate_code_jvm(env) s += "dup\n" env.push_stack(1) s += "ifne " + self.label_pattern + "\n" env.pop_stack(1) s += self.right.generate_code_jvm(env) s += "ior \n" env.pop_stack(1) s += self.label_pattern + ":\n" return s def generate_code_asm(self, env, get_value=True): s = self.left.generate_code_asm(env, get_value) s += "mov rax, [rsp]\n" s += "cmp rax, 1\n" s += "je " + self.label_pattern + "\n" env.increment_stack() s += self.right.generate_code_asm(env, get_value) env.decrement_stack() s += "pop rbx\n" s += "pop rax\n" s += "or rax, rbx \n" s += "push rax\n" s += self.label_pattern + ":\n" return s class ERel(TwoArgExpr): def __init__(self, left, right, op, no_line, pos): super(ERel, self).__init__(left, right, op, Type("boolean"), None, no_line, pos) self.type = "erel" self.label_pattern = "cmp_" + str(self.no_line) + "_" + str(self.pos) def arg_type_check(self, rtype): if rtype is not None and rtype == Type("boolean") and self.op != "==" and self.op != "!=": exception_list_expr.append(SyntaxException("Boolean does not support rel operators except '==' and '!='.", self.no_line, pos=self.pos)) def calculate_value(self): if self.left.get_value() is not None and self.right.get_value() is not None: if self.op == "==": self.value = self.left.get_value() == self.right.get_value() elif self.op == "!=": self.value = self.left.get_value() != self.right.get_value() elif self.op == "<=": self.value = self.left.get_value() <= self.right.get_value() elif self.op == ">=": self.value = self.left.get_value() >= self.right.get_value() elif self.op == "<": self.value = self.left.get_value() < self.right.get_value() elif self.op == ">": self.value = self.left.get_value() > self.right.get_value() def generate_body(self, env): s = super(ERel, self).generate_body(env) if self.op == "==": s += "if_icmpeq" elif self.op == "!=": s += "if_icmpne" elif self.op == "<=": s += "if_icmple" elif self.op == ">=": s += "if_icmpge" elif self.op == "<": s += "if_icmplt" elif self.op == ">": s += "if_icmpgt" s += " " s += self.label_pattern + "_t\n" s += "goto " + self.label_pattern + "_f\n" s += self.label_pattern + "_t:\n" s += "iconst_1 \n" s += "goto " + self.label_pattern + "\n" s += self.label_pattern + "_f:\n" s += "iconst_0 \n" s += self.label_pattern + ":\n" return s def generate_code_asm(self, env, get_value=True): s = super(ERel, self).generate_code_asm(env, get_value) s += "cmp rax, rbx\n" if self.op == "==": s += "je" elif self.op == "!=": s += "jne" elif self.op == "<=": s += "jle" elif self.op == ">=": s += "jge" elif self.op == "<": s += "jl" elif self.op == ">": s += "jg" s += " " s += self.label_pattern + "_t\n" s += "jmp " + self.label_pattern + "_f\n" s += self.label_pattern + "_t:\n" s += "mov rax, 1\n" s += "jmp " + self.label_pattern + "\n" s += self.label_pattern + "_f:\n" s += "mov rax, 0\n" s += self.label_pattern + ":\n" s += "push rax\n" return s class EString(ZeroArgExpr): def __init__(self, value, no_line, pos): super(EString, self).__init__(value, Type("string"), no_line, pos) self.type = "estring" def generate_body(self, env): env.push_stack(1) return "ldc " + self.value + "\n" def generate_code_asm(self, env, get_value=True): label = env.add_string(self.value) s = "mov rax, " + label + "\n" s += "push rax\n" return s class EVar(ZeroArgExpr): def __init__(self, ident, no_line, pos): super(EVar, self).__init__(ident, None, no_line, pos) self.type = "var" def get_type(self, env): if self.etype is None: if not env.contain_variable(self.value): exception_list_expr.append(NotDeclaredException(self.value, False, self.no_line, self.pos)) return None self.etype = env.get_variable_type([self.value]) return self.etype def get_value(self): return None def get_id(self): return [self.value] def generate_body(self, env): env.push_stack(1) if self.etype == Type("string"): return "aload " + str(env.get_variable_value([self.value])) + "\n" else: return "iload " + str(env.get_variable_value([self.value])) + "\n" def generate_code_asm(self, env, get_value=True): s = "evar_" + str(self.pos) + "_" + str(self.no_line) + ":\n" if env.is_field(self.value): s += "mov rax, rsp\n" s += "add rax, " + str(env.get_variable_position("self")) + "\n" s += "mov rbx, qword [rax]\n" s += "mov rax, rbx\n" s += "add rax, " + str(env.get_field_position(env.class_name, self.value)) + "\n" if env.get_field_type(env.class_name, self.value).is_array() and get_value: s += "mov rbx, rax\n" s += "add rbx, 8\n" s += "push rbx\n" if get_value: # and not env.is_array(self.value): s += "push qword [rax]\n" else: s += "push rax\n" return s if env.is_array(self.value) and get_value: position = env.get_array_length(self.value) s += "mov rax, [rsp + " + str(position) + "]\n" s += "push rax\n" env.increment_stack() s += "mov rax, rsp\n" s += "add rax, " + str(env.get_variable_position(self.value)) + "\n" if get_value: # and not env.is_array(self.value): s += "push qword [rax]\n" else: s += "push rax\n" #env.decrement_stack() if env.is_array(self.value) and get_value: env.decrement_stack() return s class EArrayInit(ZeroArgExpr): def __init__(self, type, array_length, no_line, pos): super(EArrayInit, self).__init__(None, ArrayType(type), no_line, pos) self.array_length = array_length self.a_type = type def get_type(self, env): self.array_length.type_check(env, expected_type=Type("int")) return self.etype def generate_code_asm(self, env, get_value=True): s = self.array_length.generate_code_asm(env, get_value) s += "mov rdi, [rsp]\n" s += "mov rsi, 8\n" s += "call calloc\n" s += "push rax\n" return s class EArrayApp(ZeroArgExpr): def __init__(self, ident, index, no_line, pos): super(EArrayApp, self).__init__(ident, None, no_line, pos) self.index = index def get_type(self, env): t = env.get_variable_type([self.value]) if t is None: return None self.index.type_check(env, expected_type=Type("int")) if not t.is_array(): exception_list_expr.append(SyntaxException("Expected array, but received " + str(t) + ".", self.no_line)) return None return t.array_type def get_id(self): return [self.value, 0] def get_value(self): return None def generate_code_asm(self, env, get_value=True): s = "array_app_" + str(self.pos) + "_" + str(self.no_line) + ":\n" + self.index.generate_code_asm(env) s += "pop rbx\n" s += "mov rax, [rsp + " + str(env.get_variable_position(self.value)) + "]\n" s += "shl rbx, 3\n" # * 8 s += "add rax, rbx\n" if get_value: s += "push qword [rax]\n" else: s += "push rax\n" return s class EObjectInit(ZeroArgExpr): def __init__(self, class_type, no_line, pos): super(EObjectInit, self).__init__(None, class_type, no_line, pos) def get_type(self, env): env.get_class(self.etype.type) return self.etype def generate_code_asm(self, env, get_value=True): s = "mov rdi, " + str(env.get_struct_size(self.etype.type)) + "\n" s += "mov rsi, 8\n" s += "call calloc\n" s += "push rax\n" return s class EObjectFieldApp(ZeroArgExpr): def __init__(self, obj, field, index, no_line, pos): super(EObjectFieldApp, self).__init__(None, None, no_line, pos) self.type = "objectfieldapp" self.obj = obj self.field = field self.index = index self.etype = None def get_type(self, env): self.obj.type_check(env) self.etype = env.get_variable_type(self.obj.get_id()) if self.etype is None: return None if not env.contain_class(self.etype.type): exception_list_expr.append(SyntaxException(str(self.etype) + " is not an object or class is not defined.", self.no_line)) field_type = env.get_field_type(self.etype.type, self.field) if field_type is None: exception_list_expr.append(SyntaxException(str(self.etype) + "." + self.field + " does not exist.", self.no_line)) if not field_type.is_array(): exception_list_expr.append(SyntaxException("Expected array.", self.no_line)) return None self.index.type_check(env, expected_type=Type("int")) return field_type.array_type def generate_code_asm(self, env, get_value=True): s = self.obj.generate_code_asm(env, True) s += "pop rax\n" if self.etype.is_array(): return s else: s += "add rax, " + str(env.get_field_position(self.etype.type, self.field)) + "\n" if get_value: s += "push qword [rax]\n" else: s += "push rax\n" return s def get_id(self): t = self.obj.get_id() t.append(self.field) t.append(0) return t
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/LatteParsers/LatteExpressions.py", "copies": "1", "size": "29197", "license": "apache-2.0", "hash": -4655824964755099000, "line_mean": 34.1771084337, "line_max": 126, "alpha_frac": 0.5269376991, "autogenerated": false, "ratio": 3.365648414985591, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9388089086528297, "avg_score": 0.0008994055114586831, "num_lines": 830 }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["Env", "exception_list_env"] from .LatteExceptions import * from .LatteParsers.LatteTypes import * exception_list_env = [] class Env: def __init__(self, orig=None, reset_declarations=True, class_name="MyClass"): self.predefined_fun = ["readInt", "readString", "error", "printInt", "printString", "concatenateString"] self.stack_var_size = 8 if orig is None: self.field_env = [] self.class_name = class_name self.current_fun_type = None self.current_stack_count = 0 self.in_main = False self.var_env = {} self.class_env = {} self.fun_env = {} self.var_store = {} self.variables_counter = 0 self.max_variable_counter = 0 self.var_decl = [] self.string_dict = {} self.stack_shift = 0 self.array_size = {} else: self.field_env = list(orig.field_env) self.array_size = dict(orig.array_size) self.var_env = dict(orig.var_env) self.fun_env = dict(orig.fun_env) self.class_env = orig.class_env.copy() self.var_store = dict(orig.var_store) self.var_decl = [] if reset_declarations else list(orig.var_decl) self.variables_counter = orig.variables_counter self.max_variable_counter = 0 if len(self.var_store.values()) == 0 else max(self.var_store.values()) + 1 self.current_fun_type = orig.current_fun_type self.current_stack_count = orig.current_stack_count self.max_stack_count = orig.current_stack_count self.in_main = orig.in_main self.class_name = orig.class_name self.string_dict = orig.string_dict.copy() self.stack_shift = orig.stack_shift def add_string(self, s): size = len(self.string_dict) label = "string_" + str(size) self.string_dict[label] = s return label def increment_stack(self): self.stack_shift += self.stack_var_size def decrement_stack(self): self.stack_shift -= self.stack_var_size def add_fun(self, fun): if fun.ident in self.fun_env: exception_list_env.append(DuplicateDeclarationException(fun.ident, True, fun.no_line, 0)) self.fun_env[fun.ident] = fun.funtype def add_class(self, class_def): if class_def.ident in self.class_env: exception_list_env.append(DuplicateDeclarationException(class_def.ident, True, class_def.no_line, 0)) self.class_env[class_def.ident] = class_def def push_stack(self, number): self.current_stack_count += number self.max_stack_count = max(self.current_stack_count, self.max_stack_count) def pop_stack(self, number): self.current_stack_count -= number def contain_function(self, ident): return ident in self.fun_env def contain_variable(self, ident): return ident in self.var_env def contain_class(self, ident): return ident in self.class_env def is_field(self, ident): return ident in self.field_env def contain_field(self, ident, field): return ident in self.class_env and self.class_env[ident].contain_field(field) def contain_method(self, ident, method): return ident in self.class_env and self.class_env[ident].contain_method(method) def get_class(self, ident): if not ident in self.class_env: exception_list_env.append(SyntaxException("Class " + ident + " does not exist.", 0)) return None return self.class_env[ident] def contain_main(self): return "main" in self.fun_env and self.fun_env["main"] == FunType(Type("int"), []) def get_fun_type(self, ident): assert not ident in self.var_env return self.fun_env[ident] def add_variable(self, ident, type, no_line, pos, fun_param=True, is_field=False): if type is None: self.array_size[ident] = self.variables_counter self.variables_counter += 1 return if is_field: self.field_env.append(ident) if ident in self.fun_env: exception_list_env.append(SyntaxException("Trying override function " + ident + ".", no_line)) elif not ident in self.var_decl: self.var_env[ident] = type if not is_field: self.var_store[ident] = self.variables_counter self.variables_counter += 1 self.var_decl.append(ident) elif fun_param: exception_list_env.append(SyntaxException("More than one argument with the name " + ident + ".", no_line, pos=pos)) else: exception_list_env.append(DuplicateDeclarationException(ident, False, no_line, pos)) def get_variable_type(self, ident, ar=True): t = None if not ident[0] in self.var_env: if not ident[0] in self.fun_env: return None else: t = self.fun_env[ident[0]].return_type else: t = self.var_env[ident[0]] for ide in ident[1:]: if t is None: return None if ide is 0: t = t.array_type else: r = self.get_field_type(t.type, ide, ar) if r is None: t = self.get_method_type(t.type, ide) if t is not None: t = t.return_type else: t = r return t def get_array_type(self, ident): t = self.get_variable_type(ident) if t is not None: if t.is_array(): t = t.array_type else: t = None return t def get_method_type(self, ident, method): if not ident in self.class_env: return None return self.class_env[ident].get_method_type(method) def get_field_type(self, ident, field, ar=True): if not ident in self.class_env: return None t = self.class_env[ident].get_field_type(field) if t is None: return t if t.is_fun(): t = t.return_type return t def get_variable_value(self, ident): if len(ident) > 1: return None return self.var_store[ident[0]] def get_variable_position(self, ident): assert not ident in self.fun_env assert self.stack_shift >= 0 assert self.variables_counter > 0 return (self.variables_counter - 1 - self.var_store[ident]) * self.stack_var_size + self.stack_shift def get_field_position(self, obj, field): return self.class_env[obj].get_field_position(field) * 8 def get_array_length(self, ident): return (self.variables_counter - 1 - self.array_size[ident]) * self.stack_var_size + self.stack_shift def is_array(self, ident): return ident in self.array_size.keys() def get_struct_size(self, ident): return self.class_env[ident].get_size() def get_fun_class(self, ident): if ident in self.predefined_fun: return "Runtime" else: return self.class_name def get_stack_limit(self): return self.max_stack_count def get_local_limit(self): return max(self.variables_counter, self.max_variable_counter) def __str__(self): output = "" for key, value in self.var_env.iteritems(): output += str(key) + " - " + str(value) + "\n" for key, value in self.fun_env.iteritems(): output += str(key) + " - " + str(value) + "\n" for key, value in self.var_store.iteritems(): output += str(key) + " - " + str(value) + "\n" return output def get_id_asm(self): pass def check_types(self, type1, type2): if type1 is None or type2 is None: return True if type1.is_simple() or type2.is_simple(): return type1 == type2 if type1 == type2: return True if type2.is_array(): if type1.is_array(): return type1 == type2 return False cl = self.class_env[type2.type] while len(cl.extlist) > 0: cl = self.class_env[cl.extlist[0]] if type1.type == cl.ident: return True return False
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/Env.py", "copies": "1", "size": "8572", "license": "apache-2.0", "hash": -775690222400845000, "line_mean": 33.9918367347, "line_max": 116, "alpha_frac": 0.5632291181, "autogenerated": false, "ratio": 3.704407951598963, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4767637069698963, "avg_score": null, "num_lines": null }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["FunType", "Type", "ArrayType"] from operator import eq class Type(object): def __init__(self, type): self.type = type self.dict = {} self.fill_matches() def __eq__(self, other): return self.type == other.type def __ne__(self, other): return self.type != other.type def __str__(self): return self.type def is_array(self): return False def is_fun(self): return False def is_simple(self): return self.type in ["int", "string", "boolean"] def get_type(self): return self def fill_matches(self): self.dict["int"] = "I" self.dict["string"] = "Ljava/lang/String;" self.dict["void"] = "V" self.dict["boolean"] = "I" def generate_code_jvm(self): return self.dict[self.type] class ArrayType(Type): def __init__(self, array_type): super(ArrayType, self).__init__(array_type.type + "a") self.array_type = array_type def get_type(self): return self.array_type def is_simple(self): return self.array_type.is_simple() def is_array(self): return True class FunType(Type): def __init__(self, return_type, params_types): super(FunType, self).__init__("funtype") self.return_type = return_type self.params_types = params_types def __eq__(self, other): return self.return_type == other.return_type and len(self.params_types) == len(other.params_types) and all( map(eq, self.params_types, other.params_types)) def __str__(self): return "(" + str(self.return_type) + ", " + str(self.params_types) + ")" def is_fun(self): return True def generate_code_jvm(self): s = "(" for t in self.params_types: s += t.generate_code_jvm() s += ")" + self.return_type.generate_code_jvm() return s class ClassType(Type): def __init__(self, var_dict): super(ClassType, self).__init__("funtype") self.var_dict = var_dict def get_field_type(self, ident): if not ident in self.var_dict: return None return self.var_dict[ident] def is_simple(self): return False
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/LatteParsers/LatteTypes.py", "copies": "1", "size": "2309", "license": "apache-2.0", "hash": 3527560722335099000, "line_mean": 22.5612244898, "line_max": 115, "alpha_frac": 0.5612819402, "autogenerated": false, "ratio": 3.5251908396946563, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9530948593110207, "avg_score": 0.011104837356889902, "num_lines": 98 }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["LatteBaseException", "DuplicateDeclarationException", "LexerException", "NotDeclaredException", "ReturnException", "SyntaxException", "TypeException"] class LatteBaseException(Exception): def __init__(self, no_line, pos): self.no_line = no_line self.pos = pos self.code = None self.column = 0 def find_column(self): last_cr = self.code.rfind('\n', 0, self.pos) if last_cr < 0: last_cr = 0 self.pos = (self.pos - last_cr) + 1 def __str__(self): if self.pos != 0: self.find_column() return "(Line:" + str(self.no_line) + ", Character:" + str(self.pos) + ") " if self.no_line != -1 else "" class DuplicateDeclarationException(LatteBaseException): def __init__(self, ident, is_fun, no_line, pos): super(DuplicateDeclarationException, self).__init__(no_line, pos) self.type = "Function" if is_fun else "Variable" self.ident = ident def __str__(self): return super(DuplicateDeclarationException, self).__str__() + \ "Duplicate Declaration Error: " + str(self.type) + " " + str(self.ident) \ + " was already declared in the scope." class LexerException(LatteBaseException): def __init__(self, inner_exception, no_line, pos=0): super(LexerException, self).__init__(no_line, pos) self.inner_exception = inner_exception def __str__(self): return super(LexerException, self).__str__() + "Lexer Error: " + self.inner_exception class NotDeclaredException(LatteBaseException): def __init__(self, ident, is_fun, no_line, pos): super(NotDeclaredException, self).__init__(no_line, pos) self.type = "Function" if is_fun else "Variable" self.ident = ident def __str__(self): return super(NotDeclaredException, self).__str__() + \ "Not Declared Error: " + str(self.type) + " " + str(self.ident) \ + " was not declared in the scope." class ReturnException(LatteBaseException): def __init__(self, fun_ident, no_line): super(ReturnException, self).__init__(no_line, 0) self.fun_ident = fun_ident def __str__(self): return super(ReturnException, self).__str__() + "Return Error: Missing return statement for function " \ + str(self.fun_ident) + "." class SyntaxException(LatteBaseException): def __init__(self, inner_exception, no_line, pos=0): super(SyntaxException, self).__init__(no_line, pos) self.inner_exception = inner_exception def __str__(self): return super(SyntaxException, self).__str__() + "Syntax Error: " + self.inner_exception class TypeException(LatteBaseException): def __init__(self, expected_type, received_type, no_line, pos): super(TypeException, self).__init__(no_line, pos) self.expected_type = expected_type self.received_type = received_type def __str__(self): return super(TypeException, self).__str__() \ + "Type Error: Expected type is " + str(self.expected_type) + ", but " \ + str(self.received_type) + " was received."
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/LatteExceptions.py", "copies": "1", "size": "3229", "license": "apache-2.0", "hash": -6371515293186403000, "line_mean": 36.1264367816, "line_max": 113, "alpha_frac": 0.6048312171, "autogenerated": false, "ratio": 3.694508009153318, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9794296539303632, "avg_score": 0.0010085373899370587, "num_lines": 87 }
__author__ = 'Andrzej Skrodzki - as292510' __all__ = ["VarAssStmt", "BStmt", "CondElseStmt", "CondStmt", "DeclStmt", "DecrStmt", "EmptyStmt", "IncrStmt", "RetStmt", "SExpStmt", "StmtBase", "VRetStmt", "WhileStmt", "ForStmt", "exception_list_stmt"] from .LatteTypes import * from ..LatteExceptions import * from .BaseNode import * from ..Env import * exception_list_stmt = [] class StmtBase(BaseNode): def __init__(self, type, no_line, pos): super(StmtBase, self).__init__(type, no_line, pos) def type_check(self, env): pass def return_check(self): return False class VarAssStmt(StmtBase): def __init__(self, ident, expr, no_line, pos): super(VarAssStmt, self).__init__("varassstmt", no_line, pos) self.ident = ident self.expr = expr self.idtype = None def type_check(self, env): self.ident.type_check(env) self.idtype = env.get_variable_type(self.ident.get_id()) self.expr.type_check(env, expected_type=self.idtype) def return_check(self): return False def generate_body(self, env): s = self.expr.generate_code_jvm(env) if self.idtype == Type("string"): s += "astore " else: s += "istore " s += str(env.get_variable_value(self.ident.get_id())) + "\n" env.pop_stack(1) return s def generate_code_asm(self, env, get_value=True): s = self.expr.generate_code_asm(env, get_value) env.increment_stack() if self.idtype.is_array(): env.increment_stack() s += self.ident.generate_code_asm(env, get_value=False) env.decrement_stack() if self.idtype.is_array(): env.decrement_stack() s += "pop rbx\n" s += "pop rax\n" if self.idtype.is_array(): s += "pop rcx\n" s += "mov [rbx], rax\n" if self.idtype.is_array(): s += "mov [rbx + 8], rcx\n" return s class BStmt(StmtBase): def __init__(self, block, no_line): super(BStmt, self).__init__("blockstmt", no_line, 0) self.block = block def type_check(self, env): self.block.type_check(env) def return_check(self): return self.block.return_check() def generate_body(self, env): env_prim = Env(env) s = self.block.generate_code_jvm(env_prim) env.max_variable_counter = max(env.max_variable_counter, env_prim.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim.max_stack_count) return s def generate_code_asm(self, env, get_value=True): env_prim = Env(env) s = self.block.generate_code_asm(env_prim) s += "add rsp, " + str((env_prim.variables_counter - env.variables_counter) * 8) + "\n" env.string_dict = env_prim.string_dict return s class CondElseStmt(StmtBase): def __init__(self, expr, stmt1, stmt2, no_line, pos): super(CondElseStmt, self).__init__("condelsestmt", no_line, pos) self.expr = expr self.stmt1 = stmt1 self.stmt2 = stmt2 self.label_pattern = "condelse_" + str(self.no_line) + "_" + str(self.pos) def type_check(self, env): env_prim = Env(env) env_prim2 = Env(env) self.expr.type_check(env, expected_type=Type("boolean")) self.stmt1.type_check(env_prim) self.stmt2.type_check(env_prim2) def return_check(self): if self.expr.get_value() is None: return self.stmt1.return_check() and self.stmt2.return_check() elif self.expr.get_value(): return self.stmt1.return_check() else: return self.stmt2.return_check() def generate_body(self, env): if self.expr.get_value() is True: env_prim = Env(env) s = self.stmt1.generate_code_jvm(env_prim) env.max_variable_counter = max(env.max_variable_counter, env_prim.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim.max_stack_count) return s elif self.expr.get_value() is False: env_prim = Env(env) s = self.stmt2.generate_code_jvm(env_prim) env.max_variable_counter = max(env.max_variable_counter, env_prim.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim.max_stack_count) return s else: env_prim = Env(env) env_prim2 = Env(env) s = self.expr.generate_code_jvm(env) s += "ifeq " + self.label_pattern + "_f\n" env.pop_stack(1) s += self.stmt1.generate_code_jvm(env_prim) s += "goto " + self.label_pattern + "\n" s += self.label_pattern + "_f:\n" s += self.stmt2.generate_code_jvm(env_prim2) s += self.label_pattern + ":\n" env.max_variable_counter = max(env.max_variable_counter, env_prim.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim.max_stack_count) env.max_variable_counter = max(env.max_variable_counter, env_prim2.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim2.max_stack_count) return s def generate_code_asm(self, env, get_value=True): if self.expr.get_value() is True: env_prim = Env(env) s = self.stmt1.generate_code_asm(env_prim) env.string_dict = env_prim.string_dict return s elif self.expr.get_value() is False: env_prim = Env(env) s = self.stmt2.generate_code_asm(env_prim) env.string_dict = env_prim.string_dict return s else: env_prim = Env(env) env_prim2 = Env(env) s = self.expr.generate_code_asm(env, get_value) s += "pop rax\n" s += "cmp rax, 0\n" s += "je " + self.label_pattern + "_f\n" s += self.stmt1.generate_code_asm(env_prim) env_prim2.string_dict = env_prim.string_dict s += "jmp " + self.label_pattern + "\n" s += self.label_pattern + "_f:\n" s += self.stmt2.generate_code_asm(env_prim2) s += self.label_pattern + ":\n" env.string_dict = env_prim2.string_dict return s class CondStmt(StmtBase): def __init__(self, expr, stmt, no_line, pos): super(CondStmt, self).__init__("condstmt", no_line, pos) self.expr = expr self.stmt = stmt self.label_pattern = "cond_" + str(self.no_line) + "_" + str(self.pos) def type_check(self, env): env_prim = Env(env) self.expr.type_check(env, expected_type=Type("boolean")) self.stmt.type_check(env_prim) def return_check(self): if self.expr.get_value() is True: return self.stmt.return_check() else: return False def generate_body(self, env): env_prim = Env(env) s = self.expr.generate_code_jvm(env) s += "ifeq " + self.label_pattern + "\n" env.pop_stack(1) s += self.stmt.generate_code_jvm(env_prim) s += self.label_pattern + ":\n" env.max_variable_counter = max(env.max_variable_counter, env_prim.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim.max_stack_count) return s def generate_code_asm(self, env, get_value=True): env_prim = Env(env) s = self.expr.generate_code_asm(env, get_value) s += "pop rax\n" s += "cmp rax, 0\n" s += "je " + self.label_pattern + "\n" s += self.stmt.generate_code_asm(env_prim) s += self.label_pattern + ":\n" env.string_dict = env_prim.string_dict return s class DeclStmt(StmtBase): def __init__(self, itemtype, itemlist, no_line, pos): super(DeclStmt, self).__init__("declstmt", no_line, pos) self.itemtype = itemtype self.itemlist = itemlist self.settypes() def settypes(self): for item in self.itemlist: item.itemtype = self.itemtype def type_check(self, env): for item in self.itemlist: item.type_check(env) env.add_variable(item.ident, item.itemtype, item.no_line, item.pos, fun_param=False) def generate_body(self, env): s = "" for item in self.itemlist: s += item.generate_code_jvm(env) return s def generate_code_asm(self, env, get_value=True): s = "" for item in self.itemlist: s += item.generate_code_asm(env, get_value) return s class DecrStmt(StmtBase): def __init__(self, ident, no_line, pos): super(DecrStmt, self).__init__("decrstmt", no_line, pos) self.ident = ident def type_check(self, env): t = env.get_variable_type(self.ident.get_id()) if t is not None and t.type != "int": exception_list_stmt.append(SyntaxException("Decrement can be applied only to integers.", self.no_line)) def generate_body(self, env): return "iinc " + str(env.get_variable_value(self.ident.get_id())) + " -1\n" def generate_code_asm(self, env, get_value=True): s = self.ident.generate_code_asm(env, get_value=False) s += "pop rax\n" s += "dec qword [rax]\n" return s class EmptyStmt(StmtBase): def __init__(self, no_line, pos): super(EmptyStmt, self).__init__("emptystmt", no_line, pos) class IncrStmt(StmtBase): def __init__(self, ident, no_line, pos): super(IncrStmt, self).__init__("incrstmt", no_line, pos) self.ident = ident def type_check(self, env): t = env.get_variable_type(self.ident.get_id()) if t is not None and t.type != "int": exception_list_stmt.append(SyntaxException("Increment can be applied only to integers.", self.no_line)) def generate_body(self, env): return "iinc " + str(env.get_variable_value(self.ident.get_id())) + " 1\n" def generate_code_asm(self, env, get_value=True): s = self.ident.generate_code_asm(env, get_value=False) s += "incr_" + str(self.no_line) + ":\npop rax\n" s += "inc qword [rax]\n" return s class RetStmt(StmtBase): def __init__(self, expr, no_line, pos): super(RetStmt, self).__init__("retstmt", no_line, pos) self.expr = expr def type_check(self, env): self.expr.type_check(env, expected_type=env.current_fun_type.return_type) def return_check(self): return True def generate_body(self, env): s = self.expr.generate_code_jvm(env) if env.in_main: s += "invokestatic java/lang/System/exit(I)V\n" s += "return\n" elif env.current_fun_type.return_type == Type("string"): s += "areturn \n" else: s += "ireturn \n" env.pop_stack(1) return s def generate_code_asm(self, env, get_value=True): s = self.expr.generate_code_asm(env, get_value) s += "pop rax\n" if self.expr.etype.is_array(): s += "pop rbx\n" s += "leave\nret\n" return s class SExpStmt(StmtBase): def __init__(self, expr, no_line, pos): super(SExpStmt, self).__init__("sexpstmt", no_line, pos) self.expr = expr def type_check(self, env): # Here we assume that the only expression is invocation of void function. self.expr.type_check(env, expected_type=Type("void")) def generate_body(self, env): return self.expr.generate_code_jvm(env) def generate_code_asm(self, env, get_value=True): return self.expr.generate_code_asm(env, get_value) class VRetStmt(StmtBase): def __init__(self, no_line, pos): super(VRetStmt, self).__init__("vretstmt", no_line, pos) def type_check(self, env): if env.current_fun_type.return_type != Type("void"): exception_list_stmt.append(SyntaxException("Incorrect return type, expected not void.", self.no_line, pos=self.pos)) def generate_body(self, env): return "return \n" def generate_code_asm(self, env, get_value=True): return "mov rax, 0\nleave\nret\n" class WhileStmt(StmtBase): def __init__(self, expr, stmt, no_line, pos): super(WhileStmt, self).__init__("whilestmt", no_line, pos) self.expr = expr self.stmt = stmt self.label_pattern = "while_" + str(self.no_line) + "_" + str(self.pos) def type_check(self, env): env_prim = Env(env) self.expr.type_check(env, expected_type=Type("boolean")) self.stmt.type_check(env_prim) def return_check(self): return self.stmt.return_check() def generate_body(self, env): env_prim = Env(env) s = self.label_pattern + "_w:\n" s += self.expr.generate_code_jvm(env) s += "ifeq " + self.label_pattern + "\n" env.pop_stack(1) s += self.stmt.generate_code_jvm(env_prim) s += "goto " + self.label_pattern + "_w\n" s += self.label_pattern + ":\n" env.max_variable_counter = max(env.max_variable_counter, env_prim.get_local_limit()) env.max_stack_count = max(env.max_stack_count, env_prim.max_stack_count) return s def generate_code_asm(self, env, get_value=True): env_prim = Env(env) s = self.label_pattern + "_w:\n" s += self.expr.generate_code_asm(env, get_value) s += "pop rax\n" s += "cmp rax, 0\n" s += "je " + self.label_pattern + "\n" s += self.stmt.generate_code_asm(env_prim) s += "jmp " + self.label_pattern + "_w\n" s += self.label_pattern + ":\n" env.string_dict = env_prim.string_dict return s class ForStmt(StmtBase): def __init__(self, var_ident, type, collection, stmt, no_line, pos): super(ForStmt, self).__init__("assstmt", no_line, pos) self.var_ident = var_ident self.type = type self.collection = collection self.stmt = stmt self.label = "for_" + str(self.no_line) + "_" + str(self.pos) def type_check(self, env): if self.type.get_type() == Type("void"): exception_list_stmt.append(SyntaxException("Type void is not allowed.", self.no_line, self.pos)) if self.type.is_array(): exception_list_stmt.append(SyntaxException("Multidimensional arrays are not allowed.", self.no_line, self.pos)) env_prim = Env(env) env_prim.add_variable(self.var_ident, self.type, self.no_line, self.pos, False) self.collection.type_check(env, expected_type=ArrayType(self.type)) self.stmt.type_check(env_prim) def return_check(self): return self.stmt.return_check() def generate_code_asm(self, env, get_value=True): s = self.collection.generate_code_asm(env, get_value=True) s += "push 0\n" s += self.label + "_f:\n" s += "mov rcx, [rsp]\n" s += "cmp rcx, [rsp + 16]\n" s += "jge " + self.label + "\n" env_prim = Env(env) env_prim.variables_counter += 3 env_prim.add_variable(self.var_ident, self.type, self.no_line, self.pos, False) s += "mov rax, [rsp+8]\n" s += "shl rcx, 3\n" s += "add rax, rcx\n" s += "push qword [rax]\n" s += self.stmt.generate_code_asm(env_prim) s += "pop rax\n" s += "inc qword [rsp]\n" # next index s += "jmp " + self.label + "_f\n" env.string_dict = env_prim.string_dict s += self.label + ":\n" s += "pop rax\n" s += "pop rax\n" s += "pop rax\n" return s
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/LatteParsers/LatteStatements.py", "copies": "1", "size": "15839", "license": "apache-2.0", "hash": -7189344972357896000, "line_mean": 34.276169265, "line_max": 123, "alpha_frac": 0.5668918492, "autogenerated": false, "ratio": 3.2450317557877484, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43119236049877485, "avg_score": null, "num_lines": null }
__author__ = 'Andrzej Skrodzki - as292510' import sys import subprocess import lattepar import lattelex from .Env import * from .LatteParsers.LatteStatements import exception_list_stmt from .LatteParsers.LatteExpressions import exception_list_expr from .LatteParsers.LatteParameters import exception_list_par from .LatteParsers.LatteTopDefinitions import exception_list_fn def print_usage(): print("##############") print("\n latc - latte compiler written in python using PLY.\n") print("\tUsage:\n") print(" latc [file] - passing file to compile.\n") print(" latc help - showing usage.\n") if __name__ == "__main__": if len(sys.argv) == 1: print("Please provide file name.\n") print_usage() sys.exit(-1) if sys.argv[1] == "help": print_usage() sys.exit() path = sys.argv[1].split('/') program_file = path[len(path) - 1] program_name = program_file.split('.')[0] try: with open(sys.argv[1], 'r') as content_file: content = content_file.read() except IOError: print("File does not exist - '{}'.".format(sys.argv[1])) sys.exit(-1) asm = 0 if len(sys.argv) > 2: asm = 1 lattelexer = lattelex.get_lexer() latteparser = lattepar.get_parser() result = latteparser.parse(content, lexer=lattelexer) if len(lattepar.exception_list) != 0: sys.stderr.write("ERROR\n") for ex in lattepar.exception_list: ex.code = content sys.stderr.write("{}\n".format(ex)) sys.exit(-2) if result is None: sys.stderr.write("ERROR\n") sys.stderr.write("Unexpected end of file.\n") sys.exit(-2) result.set_class_name(program_name) result.type_check() ex_li = exception_list_env ex_li += exception_list_expr ex_li += exception_list_stmt ex_li += exception_list_fn ex_li += exception_list_par if len(ex_li) != 0: sys.stderr.write("ERROR\n") for ex in ex_li: ex.code = content sys.stderr.write("{}\n".format(ex)) sys.exit(-2) # At this point lexer and syntax analysis is done so program is accepted. sys.stderr.write("OK\n") path[len(path) - 1] = program_name + (".j" if asm == 0 else ".s") new_file_path = '/'.join(path) path[len(path) - 1] = program_name + ".o" obj_file_path = '/'.join(path) path[len(path) - 1] = "a.out" out_file_path = '/'.join(path) if asm == 0: f = open(new_file_path, 'w+') f.write(result.generate_code_jvm(Env(class_name=program_name))) f.close() subprocess.call("java -cp lib/*.class -jar lib/jasmin.jar -g -d " + '/'.join(path[0:-1]) + " " + new_file_path, shell=True) else: f = open(new_file_path, 'w+') f.write(result.generate_code_asm(Env(class_name=program_name))) f.close() subprocess.call("nasm -g -f elf64 " + new_file_path, shell=True) subprocess.call("gcc -g -o " + out_file_path + " lib/runtime.o " + obj_file_path, shell=True) sys.exit()
{ "repo_name": "endrjuskr/studies", "path": "MRJP/LatteCompilerPython/src/lattemain.py", "copies": "1", "size": "3112", "license": "apache-2.0", "hash": 3789727451107061000, "line_mean": 31.4166666667, "line_max": 101, "alpha_frac": 0.5857969152, "autogenerated": false, "ratio": 3.1950718685831623, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42808687837831627, "avg_score": null, "num_lines": null }
__author__ = 'Andrzej Taramina' __documentation__ = 'http://sourceforge.net/p/raspberry-gpio-python/wiki/Examples/' RPI_REVISION = 1 VERSION = 1 BOARD = 0 BCM = 1 IN = 0 OUT = 1 INPUT = 0 OUTPUT = 1 SPI = 2 I2C = 3 HARD_PWM = 4 SERIAL = 5 UNKNOWN = -1 PUD_DOWN = 0 PUD_UP = 1 PUD_OFF = -1 LOW = 0 HIGH = 1 FALLING = 0 RISING = 1 BOTH = 2 _setup_mode = BOARD _warnings = False channels = {} def setmode(mode): """ There are two ways of numbering the IO pins on a Raspberry Pi within RPi.GPIO. The first is using the BOARD numbering system. This refers to the pin numbers on the P1 header of the Raspberry Pi board. The advantage of using this numbering system is that your hardware will always work, regardless of the board revision of the RPi. You will not need to rewire your connector or change your code. The second numbering system is the BCM numbers. This is a lower level way of working - it refers to the channel numbers on the Broadcom SOC. You have to always work with a diagram of which channel number goes to which pin on the RPi board. Your script could break between revisions of Raspberry Pi boards. To specify which you are using using (mandatory): :param mode: :return: """ _setup_mode = mode def setwarnings(mode): """ It is possible that you have more than one script/circuit on the GPIO of your Raspberry Pi. As a result of this, if RPi.GPIO detects that a pin has been configured to something other than the default (input), you get a warning when you try to configure a script. To disable these warnings: :param mode: :return: """ _warnings = mode def setup(channel, mode, initial=None, pull_up_down=None): """ You need to set up every channel you are using as an input or an output. To configure a channel as an input: :param channel: :param mode: :param initial: :param pull_up_down: :return: """ channels[ channel ] = dict( mode=mode, initial=initial, pull_up_down=pull_up_down, value=LOW ) def gpio_function(pin): """ Shows the function of a GPIO channel. will return a value from: GPIO.INPUT, GPIO.OUTPUT, GPIO.SPI, GPIO.I2C, GPIO.HARD_PWM, GPIO.SERIAL, GPIO.UNKNOWN :param pin: :return: GPIO.INPUT, GPIO.OUTPUT, GPIO.SPI, GPIO.I2C, GPIO.HARD_PWM, GPIO.SERIAL, GPIO.UNKNOWN """ if pin in channels: return channels[ pin ][ "mode" ] else: return UNKNOWN def input(channel): """ To read the value of a GPIO pin: :param channel: :return: """ if channel in channels: return channels[ channel ][ "value" ] else: return LOW def output(channel, state): """ To set the output state of a GPIO pin: :param channel: :return: """ channels[ channel ][ "value" ] = state def PWM(channel, frequency): """ :param channel: :param frequency: To create a PWM instance: :return: """ return None def cleanup(channel=None): """ At the end any program, it is good practice to clean up any resources you might have used. This is no different with RPi.GPIO. By returning all channels you have used back to inputs with no pull up/down, you can avoid accidental damage to your RPi by shorting out the pins. Note that this will only clean up GPIO channels that your script has used. :param channel: It is possible that you only want to clean up one channel, leaving some set up when your program exits :return: """ if channel is not None: del channels[ channel ] else: channels = {} def wait_for_edge(channel, edge_type): """ The wait_for_edge() function is designed to block execution of your program until an edge is detected. :param channel: :param edge_type: :return: """ pass def add_event_detect(channel, edge_type, callback=None, bouncetime=0): """ The event_detected() function is designed to be used in a loop with other things, but unlike polling it is not going to miss the change in state of an input while the CPU is busy working on other things. This could be useful when using something like Pygame or PyQt where there is a main loop listening and responding to GUI events in a timely basis. :param channel: :param edge_type: :return: """ pass def add_event_callback(channel, callback, bouncetime=0): pass def remove_event_detect(channel): """ If for some reason, your program no longer wishes to detect edge events, it is possible to stop them :param channel: :return: """ pass
{ "repo_name": "jpnos26/thermostat_V3", "path": "FakeRPi/GPIO.py", "copies": "5", "size": "4609", "license": "mit", "hash": 3225785750709278000, "line_mean": 27.6273291925, "line_max": 398, "alpha_frac": 0.6747667607, "autogenerated": false, "ratio": 3.6813099041533546, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6856076664853354, "avg_score": null, "num_lines": null }
__author__ = 'andy' import unittest from pyevent import mixin @mixin class TestClass: pass class PyeventTest(unittest.TestCase): def setUp (self): self.cls = TestClass() def tearDown (self): del self.cls def test_mixin_build_trigger (self): self.assertIsNotNone(self.cls.trigger, 'ensure that trigger method is set') def test_mixin_build_bind (self): self.assertIsNotNone(self.cls.bind, 'ensure that bind method is set') def test_mixin_build_unbind (self): self.assertIsNotNone(self.cls.unbind, 'ensure that unbind method is set') def test_mixin_build_events (self): self.assertIsNotNone(self.cls._events, 'ensure that events dict is set') def test_mixin_bind (self): def go (): pass self.cls.bind('test_mixin_bind', go) self.assertEqual(self.cls._events['test_mixin_bind'][0], go, 'should bind the go function') def test_mixin_unbind (self): def go (): pass self.cls.bind('test_mixin_unbind', go) self.assertEqual(self.cls._events['test_mixin_unbind'][0], go) self.cls.unbind('test_mixin_unbind', go) with self.assertRaises(KeyError): self.cls._events['test_mixin_unbind'] def test_mixin_trigger (self): self.boolean = False def go (): self.boolean = True self.cls.bind('test_mixin_trigger', go) self.cls.trigger('test_mixin_trigger') self.assertTrue(self.boolean, 'ensure value changed') def test_multiple_callbacks (self): self.booleanOne = False self.booleanTwo = False def one (): self.booleanOne = True def two (): self.booleanTwo = True self.cls.bind('test_multiple_callbacks', one) self.cls.bind('test_multiple_callbacks', two) self.cls.trigger('test_multiple_callbacks') self.assertTrue(self.booleanOne, 'ensure first value changed') self.assertTrue(self.booleanTwo, 'ensure second value changed') if __name__ == '__main__': unittest.main()
{ "repo_name": "andy9775/pyevent", "path": "tests/test_mixin.py", "copies": "1", "size": "2258", "license": "mit", "hash": -3951987648470067700, "line_mean": 26.8765432099, "line_max": 71, "alpha_frac": 0.5806023029, "autogenerated": false, "ratio": 4.068468468468469, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0068924507277788255, "num_lines": 81 }
__author__ = 'andy' import unittest from pyevent import Pyevent class PyeventTest(unittest.TestCase): def setUp (self): self.binderTwo = Pyevent() def tearDown (self): del self.binderTwo def test_bind (self): def test (): pass self.binderTwo.bind('test_bind', test) self.assertEqual(self.binderTwo._events['test_bind'][0], test, 'ensure binding') def test_trigger (self): self.boolean = False def change (): self.boolean = True self.binderTwo.bind('test_trigger', change) self.binderTwo.trigger('test_trigger') self.assertTrue(self.boolean, 'should change the value on trigger') def test_unbind (self): def test (): pass self.binderTwo.bind('test_unbind', test) self.assertEqual(self.binderTwo._events['test_unbind'][0], test) self.binderTwo.unbind('test_unbind', test) with self.assertRaises(KeyError): self.binderTwo._events['test_unbind'] def test_multiple_callbacks (self): self.firstBoolean = False self.secondBoolean = False def first (): self.firstBoolean = True def second (): self.secondBoolean = True self.binderTwo.bind('test_multiple_callbacks', first) self.binderTwo.bind('test_multiple_callbacks', second) self.binderTwo.trigger('test_multiple_callbacks') self.assertTrue(self.firstBoolean, 'test first callback') self.assertTrue(self.secondBoolean, 'test second callback') if __name__ == '__main__': unittest.main()
{ "repo_name": "andy9775/pyevent", "path": "tests/test_basic.py", "copies": "1", "size": "1665", "license": "mit", "hash": 2107717137101963300, "line_mean": 26.75, "line_max": 75, "alpha_frac": 0.6054054054, "autogenerated": false, "ratio": 4.002403846153846, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5107809251553845, "avg_score": null, "num_lines": null }
__author__ = 'Andy' from whirlybird.protocols import pilot_input_pb2 class InputDriverBase(object): def __init__(self, transport): self.transport = transport def _to_integer(self, value): return int(value * 255 + 255) def emit(self, left_stick_x, left_stick_y, right_stick_y, right_stick_x, triggers): to_emit = pilot_input_pb2.PilotInput() to_emit.left_stick_x = self._to_integer(left_stick_x) to_emit.left_stick_y = self._to_integer(left_stick_y) to_emit.right_stick_y = self._to_integer(right_stick_y) to_emit.right_stick_x = self._to_integer(right_stick_x) to_emit.triggers = self._to_integer(triggers) # print('LX: {}, LY: {}, RX: {}, RY: {}, Trigger: {}'. format(to_emit.left_stick_x, # to_emit.left_stick_y, # to_emit.right_stick_x, # to_emit.right_stick_y, # to_emit.triggers)) self.transport.emit(to_emit.SerializeToString())
{ "repo_name": "levisaya/whirlybird", "path": "whirlybird/client/input_drivers/input_driver_base.py", "copies": "1", "size": "1271", "license": "mit", "hash": 43094343627514580, "line_mean": 38.71875, "line_max": 92, "alpha_frac": 0.4657749803, "autogenerated": false, "ratio": 3.8283132530120483, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9792389863746831, "avg_score": 0.00033967391304347825, "num_lines": 32 }
__author__ = 'Andy' import asyncio import time from whirlybird.protocols.pilot_input_pb2 import PilotInput from threading import Event from whirlybird.server.devices.Bmp085 import Bmp085 from whirlybird.server.devices.lsm303_accelerometer import Lsm303Accelerometer from whirlybird.server.devices.lsm303_magnetometer import Lsm303Magnetometer from whirlybird.server.devices.l3gd20 import L3gd20 from whirlybird.server.devices.adafruit_pwm import AdafruitPwm from aioprocessing import AioPool, AioQueue, AioEvent, AioProcess from whirlybird.server.device_polling_process import DevicePollingProcess from queue import Empty class PositionController(object): def __init__(self): self.loop = asyncio.get_event_loop() self.num_calls = 0 self.start_time = None self.killed = AioEvent() self.sensor_queue = AioQueue() self.accelerometer = Lsm303Accelerometer() self.magnetometer = Lsm303Magnetometer() self.gyro = L3gd20() self.baro = Bmp085() self.pwm = AdafruitPwm() self.baro_reader = DevicePollingProcess(self.baro.get_pressure, self.sensor_queue, self.killed) self.baro_reader_process = AioProcess(target=self.baro_reader.read) self.baro_reader_process.start() pilot_input_handler = asyncio.start_server(self.handle_pilot_input, '', 8888, loop=self.loop) self.loop.run_until_complete(pilot_input_handler) self.loop.run_until_complete(asyncio.Task(self.position_update())) @asyncio.coroutine def handle_pilot_input(self, reader, writer): while not self.killed.is_set(): numbytes_buffer = yield from reader.read(1) numbytes = ord(numbytes_buffer) read_pilot_data = yield from reader.read(numbytes) pilot_data = PilotInput() try: pilot_data.ParseFromString(read_pilot_data) except: print("Error: Bad Input Message: {}, numbytes: {}".format(read_pilot_data, numbytes)) else: pass # Compute desired yaw, pitch and roll. @asyncio.coroutine def position_update(self): while not self.killed.is_set(): start = time.time() accelerometer_data = self.accelerometer.read() magnetometer_data = self.magnetometer.read() gyro_data = self.gyro.read() try: baro_data = self.sensor_queue.get_nowait() except Empty: baro_data = None print('Accelerometer: {}'.format(accelerometer_data)) print('Magnetometer: {}'.format(magnetometer_data)) print('Gyro: {}'.format(gyro_data)) print('Baro: {}'.format(baro_data)) print('Time: {}'.format(time.time() - start))
{ "repo_name": "levisaya/whirlybird", "path": "whirlybird/server/position_contoller.py", "copies": "1", "size": "2827", "license": "mit", "hash": 1010636740543063300, "line_mean": 35.2564102564, "line_max": 103, "alpha_frac": 0.6466218606, "autogenerated": false, "ratio": 3.498762376237624, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4645384236837624, "avg_score": null, "num_lines": null }
__author__ = 'andy' class Pyevent(object): """ An eventing system based on the javascript microevent framework. It follows a publish subscribe pattern to call certain methods that are linked to events when those events are triggered. """ def __init__ (self): # <String, Array<Function>> dictionary self._events = {} def bind (self, event, callback): """ Bind an event to a call function and ensure that it is called for the specified event :param event: the event that should trigger the callback :type event: str :param callback: the function that should be called :rtype callback: function """ if self._events.has_key(event): self._events[event].append(callback) else: self._events[event] = [callback] def unbind (self, event, callback): """ Unbind the callback from the event and ensure that it is never called :param event: the event that should be unbound :type event: str :param callback: the function that should be unbound :rtype callback: function """ if self._events.has_key(event) and len(self._events[event]) > 0: for _callback in self._events[event]: if _callback == callback: self._events[event].remove(callback) if len(self._events[event]) == 0: del self._events[event] def trigger (self, event, *args, **kwargs): """ Cause the callbacks associated with the event to be called :param event: the event that occurred :type event: str :param data: optional data to pass to the callback :type data: anything that should be passed to the callback """ if self._events.has_key(event): for _callback in self._events[event]: try: _callback(args, kwargs) except TypeError: _callback() def mixin (cls): """ A decorator which adds event methods to a class giving it the ability to bind to and trigger events :param cls: the class to add the event logic to :type cls: class :return: the modified class :rtype: class """ cls._events = {} cls.bind = Pyevent.bind.__func__ cls.unbind = Pyevent.unbind.__func__ cls.trigger = Pyevent.trigger.__func__ return cls
{ "repo_name": "andy9775/pyevent", "path": "pyevent/pyevent.py", "copies": "1", "size": "2472", "license": "mit", "hash": -2291512083205859300, "line_mean": 32.4054054054, "line_max": 77, "alpha_frac": 0.5865695793, "autogenerated": false, "ratio": 4.527472527472527, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003171233545348224, "num_lines": 74 }
# -------------- I-Format ---------------- # o----------------------------------------o # | opcode | rs | rt | OFFSET | # |--------|---------|----------|----------| # | 6 bits | 5 bits | 5 bits | 16 bits | # o----------------------------------------o # ================================== OPCODES ================================= # o-------------------------------------------------------------------------------o # | mNEMONIC | MEANING | TYPE | OPCODE | FUNCTION | # |===============================================================================| # | add | ADD | R | 0x00 | 0x20 | # | sub | Subtract | R | 0x00 | 0x22 | # | and | Bit AND | R | 0x00 | 0x24 | # | or | Bit OR | R | 0x00 | 0x25 | # | slt | Set to 1 if Less than | R | 0x00 | 0x2A | # | lw | Load Word | I | 0x23 | N/A | # | sw | Store Word | I | 0x2B | N/A | # | beq | Branch if Equal | I | 0x04 | N/A | # | bne | Brance if Not Equal | I | 0x05 | N/A | # o-------------------------------------------------------------------------------o # HEX Referance # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # 0 1 2 3 4 5 6 7 8 9 A B C D E F class Disassembler(object): OPCODE = { 0x23 : 'lw', 0x20 : 'lb', 0x2B : 'sw', 0x28 : 'sb', 0x04 : 'beq', 0x05 : 'bne', 0x00 : 'nop'} FUNCT = { 0x20 : 'add', 0x22 : 'sub', 0x24 : 'and', 0x25 : 'or', 0x2A : 'slt', 0x00 : 'nop'} #Constructor def __init__(self): self.PC = 0x7A060 self.PC_Inc = 0x4 self.formatType = None self.instruction = None self.opcode = None self.rs = None self.rt = None self.rd = None self.offset = None self.shamt = None self.funct = None def load(self,instruction): self.instruction = instruction #isolate the OPCODE # 1111 1100 0000 0000 0000 0000 0000 0000 # F C 0 0 0 0 0 0 opcode_MASK = 0xfc000000 #print("OpCode Mask: ","{0:b}".format(opcode_MASK)) #print("Instruction: ","{0:b}".format(self.instruction)) self.opcode = self.instruction & opcode_MASK #print("Result : ","{0:b}".format(self.opcode)) self.opcode = self.opcode >> 26 #print("Bit Shifted: ","{0:b}".format(self.opcode)) #R Format if self.opcode == 0: #We want to designate this object to be of type R self.formatType = 'R' #RS MASK # 0000 0011 1110 0000 0000 0000 0000 0000 # 0 3 E 0 0 0 0 0 #Source Register rs_MASK = 0x03E00000 self.rs = self.instruction & rs_MASK self.rs = self.rs >> 21 #RT MASK # 0000 0000 0001 1111 0000 0000 0000 0000 # 0 0 1 F 0 0 0 0 rt_MASK = 0x001F0000 self.rt = self.instruction & rt_MASK self.rt = self.rt >> 16 #RD MASK # 0000 0000 0000 0000 1111 1000 0000 0000 # 0 0 0 0 F 8 0 rd_MASK = 0x0000F800 self.rd = self.instruction & rd_MASK self.rd = self.rd >> 11 #SHAMT MASK # 0000 0000 0000 0000 0000 0111 1100 0000 # 0 0 0 0 0 7 C 0 shamt_MASK = 0x000007C0 self.shamt = self.instruction & shamt_MASK self.shamt = self.shamt >> 6 #FUNCT MASK # 0000 0000 0000 0000 0000 0000 0011 1111 # 0 0 0 0 0 0 3 F funct_MASK = 0x0000003F self.funct = self.instruction & funct_MASK #I Format elif self.opcode > 0: #We want to designate this object to be of type I self.formatType = 'I' #RS MASK # 0000 0011 1110 0000 0000 0000 0000 0000 # 0 3 E 0 0 0 0 0 #Source Register rs_MASK = 0x03E00000 self.rs = self.instruction & rs_MASK self.rs = self.rs >> 21 #RT MASK # 0000 0000 0001 1111 0000 0000 0000 0000 # 0 0 1 F 0 0 0 0 rt_MASK = 0x001F0000 self.rt = self.instruction & rt_MASK self.rt = self.rt >> 16 #OFFSET MASK # 0000 0000 0000 0000 1111 1111 1111 1111 # 0 0 0 0 F F F F offset_MASK = 0x0000FFFF self.offset = self.instruction & offset_MASK if (Disassembler.OPCODE[self.opcode]) == 'beq' or (Disassembler.OPCODE[self.opcode] == 'bne'): self.offset = (self.offset << 2) + 0x4 if self.offset >= 32768: self.offset = self.offset - 65536 #print(self.__str__()) #self.PC += self.PC_Inc def __str__(self): if self.formatType == 'I': if Disassembler.OPCODE[self.opcode] == 'lw': return '{0:x}'.format(self.PC) + \ ' ' + Disassembler.OPCODE[self.opcode] +\ ' ${0:d}'.format(self.rt) +\ ', {0:d}'.format(self.offset) +\ '(${0:d}'.format(self.rs) + ')' elif Disassembler.OPCODE[self.opcode] == 'lb': return '{0:x}'.format(self.PC) + \ ' ' + Disassembler.OPCODE[self.opcode] +\ ' ${0:d}'.format(self.rt) +\ ', {0:d}'.format(self.offset) +\ '(${0:d}'.format(self.rs) + ')' elif Disassembler.OPCODE[self.opcode] == 'beq': return '{0:x}'.format(self.PC) +\ ' ' + Disassembler.OPCODE[self.opcode] +\ ' ${0:d},'.format(self.rs) +\ ' ${0:d},'.format(self.rt) +\ ' address 0x{0:x}'.format(self.offset+self.PC) elif Disassembler.OPCODE[self.opcode] == 'bne': return '{0:x}'.format(self.PC) +\ ' ' + Disassembler.OPCODE[self.opcode] +\ ' ${0:d},'.format(self.rs) +\ ' ${0:d},'.format(self.rt) +\ ' address 0x{0:x}'.format(self.offset+self.PC) elif Disassembler.OPCODE[self.opcode] == 'sw': return '{0:x}'.format(self.PC) +\ ' ' + Disassembler.OPCODE[self.opcode] +\ ' ${0:d}'.format(self.rt) +\ ' {0:d}'.format(self.offset) +\ '(${0:d}'.format(self.rs) + ')' elif Disassembler.OPCODE[self.opcode] == 'sb': return '{0:x}'.format(self.PC) +\ ' ' + Disassembler.OPCODE[self.opcode] +\ ' ${0:d}'.format(self.rt) +\ ' {0:d}'.format(self.offset) +\ '(${0:d}'.format(self.rs) + ')' else: return '{0:x}'.format(self.PC) +\ ' ' + Disassembler.OPCODE[self.opcode]+\ ' ${0:d}'.format(self.rt) +\ ', ${0:d}'.format(self.offset) +\ '({0:d}'.format(self.rs) + ')' elif self.formatType == 'R': return '{0:x}'.format(self.PC) +\ ' ' + Disassembler.FUNCT[self.funct] +\ ' ${0:d},'.format(self.rd) +' '+\ '${0:d},'.format(self.rs) +' '+\ '${0:d}'.format(self.rt) else: return ('Something Went Wrong....', self.instruction) #Not used # def r(self, register): # print(type(register), register) # try: # tmp = Disassembler.REGISTER[register] # print(tmp) # return tmp # except: # return '{0:d}'.format(register) # # # def debugI(self): # print('\n') # print('RAW: {0:b}'.format(self.instruction)) # print('OPC: {0:b}'.format(self.opcode)) # print('RS: {0:b}'.format(self.rs)) # print('RT: {0:b}'.format(self.rt)) # print('OFFS: {0:b}'.format(self.offset)) # # # def debugR(self): # print('\n') # print('RAW: {0:b}'.format(self.instruction)) # print('OPC: {0:b}'.format(self.opcode)) # print('RS: {0:b}'.format(self.rs)) # print('RT: {0:b}'.format(self.rt)) # print('RD: {0:b}'.format(self.rd)) # print('SHAMT:{0:b}'.format(self.shamt)) # print('FUNCT:{0:b}'.format(self.funct))
{ "repo_name": "andrewoconnell89/CS472_Project3", "path": "src/Pipeline/MIPSDisassembler.py", "copies": "1", "size": "8270", "license": "mit", "hash": -6306062042930677000, "line_mean": 32.4817813765, "line_max": 106, "alpha_frac": 0.4548972189, "autogenerated": false, "ratio": 2.8100577641862046, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37649549830862045, "avg_score": null, "num_lines": null }
from Pipeline.MIPSDisassembler import Disassembler # This is from Project 1 class Pipeline(object): def __init__(self, startProgramCount, InstructionCache): """Initalizes the 5 Stages of the Pipeline. (IF, ID, EX, MEM, WB) """ #Main Memory, Registers. Must be initialized self.Main_Mem = None self.initializeMainMem() self.Regs = None self.initializeRegs() # Instructions to be used. = {0x7A000 : 0xa1020000,} self.InstructionCache = InstructionCache self.PC = startProgramCount #---------------------------------------------------------------------- #IF/ID Write self.IFID_W_Inst = 0 self.IFID_W_IncrPC = 0 #IF/ID Read self.IFID_R_Inst = 0 self.IFID_R_IncrPC = 0 #---------------------------------------------------------------------- #ID/EX Write self.IDEX_W_RegDst = 0 self.IDEX_W_ALUSrc = 0 self.IDEX_W_ALUOp = 0 self.IDEX_W_MemRead = 0 self.IDEX_W_MemWrite = 0 self.IDEX_W_Branch = 0 self.IDEX_W_MemToReg = 0 self.IDEX_W_RegWrite = 0 self.IDEX_W_IncrPC = 0 self.IDEX_W_ReadReg1Value = 0 self.IDEX_W_ReadReg2Value = 0 self.IDEX_W_SEOffset = 0 self.IDEX_W_WriteReg_20_16 = 0 self.IDEX_W_WriteReg_15_11 = 0 self.IDEX_W_Function = 0 #ID/EX Read self.IDEX_R_RegDst = 0 self.IDEX_R_ALUSrc = 0 self.IDEX_R_ALUOp = 0 self.IDEX_R_MemRead = 0 self.IDEX_R_MemWrite = 0 self.IDEX_R_Branch = 0 self.IDEX_R_MemToReg = 0 self.IDEX_R_RegWrite = 0 self.IDEX_R_IncrPC = 0 self.IDEX_R_ReadReg1Value = 0 self.IDEX_R_ReadReg2Value = 0 self.IDEX_R_SEOffset = 0 self.IDEX_R_WriteReg_20_16 = 0 self.IDEX_R_WriteReg_15_11 = 0 self.IDEX_R_Function = 0 #---------------------------------------------------------------------- #EX/MEM Write self.EXMEM_W_MemRead = 0 self.EXMEM_W_MemWrite = 0 self.EXMEM_W_Branch = 0 self.EXMEM_W_MemToReg = 0 self.EXMEM_W_RegWrite = 0 self.EXMEM_W_Zero = 0 self.EXMEM_W_ALUResult = 0 self.EXMEM_W_SWValue = 0 self.EXMEM_W_WriteRegNum = 0 #EX/MEM Read self.EXMEM_R_MemRead = 0 self.EXMEM_R_MemWrite = 0 self.EXMEM_R_Branch = 0 self.EXMEM_R_MemToReg = 0 self.EXMEM_R_RegWrite = 0 self.EXMEM_R_Zero = 0 self.EXMEM_R_ALUResult = 0 self.EXMEM_R_SWValue = 0 self.EXMEM_R_WriteRegNum = 0 #---------------------------------------------------------------------- #MEM/WB Write self.MEMWB_W_MemToReg = 0 self.MEMWB_W_RegWrite = 0 self.MEMWB_W_LWDataValue = 0 self.MEMWB_W_ALUResult = 0 self.MEMWB_W_WriteRegNum = 0 #MEM/WB Read self.MEMWB_R_MemToReg = 0 self.MEMWB_R_RegWrite = 0 self.MEMWB_R_LWDataValue = 0 self.MEMWB_R_ALUResult = 0 self.MEMWB_R_WriteRegNum = 0 def IF_stage(self): """You will fetch the next instruction out of the Instruction Cache. Put it in the WRITE version of the IF/ID pipeline Register """ #IF/ID Write self.IFID_W_Inst = self.InstructionCache[self.PC] self.IFID_W_IncrPC = self.PC + 0x4 self.PC = self.PC + 0x4 def ID_stage(self): """Here you'll read an instruction from the READ version of IF/ID pipeline register, do the decoding and register fetching and write the values to the WRITE version of the ID/EX pipeline register.""" # Null Operation Condition if self.IFID_R_Inst == 0: self.IDEX_W_RegDst = 0 self.IDEX_W_ALUSrc = 0 self.IDEX_W_ALUOp = 0 self.IDEX_W_MemRead = 0 self.IDEX_W_MemWrite = 0 self.IDEX_W_Branch = 0 self.IDEX_W_MemToReg = 0 self.IDEX_W_RegWrite = 0 self.IDEX_W_IncrPC = 0 self.IDEX_W_ReadReg1Value = 0 self.IDEX_W_ReadReg2Value = 0 self.IDEX_W_SEOffset = 0 self.IDEX_W_WriteReg_20_16 = 0 self.IDEX_W_WriteReg_15_11 = 0 self.IDEX_W_Function = 0 #print("ID_stage: nop") return True d = Disassembler() d.load(self.IFID_R_Inst) # Set Control Variables if d.formatType == 'R': self.IDEX_W_RegDst = 1 self.IDEX_W_ALUSrc = 0 self.IDEX_W_ALUOp = 2 self.IDEX_W_MemRead = 0 self.IDEX_W_MemWrite = 0 self.IDEX_W_Branch = 0 self.IDEX_W_MemToReg = 0 self.IDEX_W_RegWrite = 1 # End of Control self.IDEX_W_ReadReg1Value = self.Regs[d.rs] self.IDEX_W_ReadReg2Value = self.Regs[d.rt] self.IDEX_W_SEOffset = 'x' self.IDEX_W_WriteReg_20_16 = d.rs self.IDEX_W_WriteReg_15_11 = d.rd self.IDEX_W_Function = d.funct self.IDEX_W_IncrPC = self.IFID_R_IncrPC elif d.opcode == 0x20: #lb self.IDEX_W_RegDst = 0 self.IDEX_W_ALUSrc = 1 self.IDEX_W_ALUOp = 0 self.IDEX_W_MemRead = 1 self.IDEX_W_MemWrite = 0 self.IDEX_W_Branch = 0 self.IDEX_W_MemToReg = 1 self.IDEX_W_RegWrite = 1 # End of Control self.IDEX_W_ReadReg1Value = self.Regs[d.rs] self.IDEX_W_ReadReg2Value = self.Regs[d.rt] self.IDEX_W_SEOffset = d.offset self.IDEX_W_WriteReg_20_16 = d.rs self.IDEX_W_WriteReg_15_11 = d.rt self.IDEX_W_Function = 'x' self.IDEX_W_IncrPC = self.IFID_R_IncrPC elif d.opcode == 0x28: #sb self.IDEX_W_RegDst = 'x' self.IDEX_W_ALUSrc = 1 self.IDEX_W_ALUOp = 0 self.IDEX_W_MemRead = 0 self.IDEX_W_MemWrite = 1 self.IDEX_W_Branch = 0 self.IDEX_W_MemToReg = 'x' self.IDEX_W_RegWrite = 0 # End of Control self.IDEX_W_ReadReg1Value = self.Regs[d.rs] self.IDEX_W_ReadReg2Value = self.Regs[d.rt] self.IDEX_W_SEOffset = d.offset self.IDEX_W_WriteReg_20_16 = d.rs self.IDEX_W_WriteReg_15_11 = d.rt self.IDEX_W_Function = 'x' self.IDEX_W_IncrPC = self.IFID_R_IncrPC def EX_stage(self): """ Here you'll perform the requested instruction on the spicific operands you read out of the READ version of the ID/EX pipeline register and then write the appropriate values to the WRITE version of the EX/MEM pipeline register. For example, an "add" operation will take the two operands out of the ID/EX pipeline register and add them together like this: EX_MEM_WRITE.ALU_Result = ID_EX_READ.Reg_Val1 + ID_EX_READ.Reg_Val2; """ self.EXMEM_W_MemRead = self.IDEX_R_MemRead self.EXMEM_W_MemWrite = self.IDEX_R_MemWrite self.EXMEM_W_Branch = self.IDEX_R_Branch self.EXMEM_W_MemToReg = self.IDEX_R_MemToReg self.EXMEM_W_RegWrite = self.IDEX_R_RegWrite # Calculate ALUResult based on ALUOp if self.IDEX_R_ALUOp == 2 and self.IDEX_R_Function == 0x20: #R-Type Add self.EXMEM_W_ALUResult = self.IDEX_R_ReadReg1Value + self.IDEX_R_ReadReg2Value elif self.IDEX_R_ALUOp == 2 and self.IDEX_R_Function == 0x22: #R-Type sub self.EXMEM_W_ALUResult = self.IDEX_R_ReadReg1Value + self.IDEX_R_ReadReg2Value elif self.IDEX_R_ALUOp == 0: #lb and sb self.EXMEM_W_ALUResult = self.IDEX_R_ReadReg1Value + self.IDEX_R_SEOffset # Zero if self.EXMEM_W_ALUResult == 0: self.EXMEM_W_Zero = 1 else: self.EXMEM_W_Zero = 0 self.EXMEM_W_SWValue = self.IDEX_R_ReadReg2Value self.EXMEM_W_WriteRegNum = self.IDEX_R_WriteReg_15_11 def MEM_stage(self): """If the instruction is a lb, then use the address you calculated in the EX stage as an index into your Main Memory array and get the value that is there. Otherwise, just pass information from the READ version of the EX_MEM pipeline register to the WRITE version of MEM_WB. """ self.MEMWB_W_MemToReg = self.EXMEM_R_MemToReg self.MEMWB_W_RegWrite = self.EXMEM_R_RegWrite self.MEMWB_W_ALUResult = self.EXMEM_R_ALUResult self.MEMWB_W_WriteRegNum = self.EXMEM_R_WriteRegNum if self.EXMEM_R_MemToReg == 1: #print("Loading x{0:x} from Main Mem[x{1:x}]".format(self.Main_Mem[self.EXMEM_R_ALUResult], self.EXMEM_R_ALUResult)) self.MEMWB_W_LWDataValue = self.Main_Mem[self.EXMEM_R_ALUResult] else: self.MEMWB_W_LWDataValue = 'x' if self.EXMEM_R_MemWrite == 1: #print("Storing x{0:x} to Main Mem[x{1:x}]".format(self.EXMEM_R_SWValue, self.EXMEM_R_ALUResult)) self.Main_Mem[self.EXMEM_R_ALUResult] = self.EXMEM_R_SWValue def WB_stage(self): """Write to the registers based on information you read out of the READ version of MEM_WB. """ # R-Format if (self.MEMWB_R_MemToReg == 0) and (self.MEMWB_R_RegWrite == 1): self.Regs[self.MEMWB_R_WriteRegNum] = self.MEMWB_R_ALUResult # lb elif (self.MEMWB_R_MemToReg == 1) and (self.MEMWB_R_RegWrite == 1): self.Regs[self.MEMWB_R_WriteRegNum] = self.MEMWB_R_LWDataValue def Print_out_everything(self): #IF print("GlobalPC: x{0:x}".format(self.PC)) print("Inst: x{0:x}".format(self.IFID_W_Inst)) print("IncrPC: x{0:x}".format(self.IFID_W_IncrPC)) #IF/ID print('\nIF/ID Write ----------------') print('Inst = x{0:x}'.format(self.IFID_W_Inst)) print('IF/ID Read ------------------') print('Inst = x{0:x}'.format(self.IFID_R_Inst)) #ID/EX print('\nID/EX Write ----------------') print('RegDst: ',self.IDEX_W_RegDst) print('ALUSrc: ',self.IDEX_W_ALUSrc) print('ALUOp: ',self.IDEX_W_ALUOp) print('MemRead: ',self.IDEX_W_MemRead) print('Memwrite: ',self.IDEX_W_MemWrite) print('MemToReg: ',self.IDEX_W_MemToReg) print('RegWrite: ',self.IDEX_W_RegWrite) print('IncrPC: {0:x}'.format(self.IDEX_W_IncrPC)) print('ReadReg1Value: {0:x}'.format(self.IDEX_W_ReadReg1Value)) print('ReadReg2Value: {0:x}'.format(self.IDEX_W_ReadReg2Value)) print('SEOffset: ',self.IDEX_W_SEOffset) print('WriteReg_20_16: ',self.IDEX_W_WriteReg_20_16) print('WriteReg_15_11: ',self.IDEX_W_WriteReg_15_11) print('Function: ',self.IDEX_W_Function) print('\nID/EX Read ------------------') print('RegDst: ',self.IDEX_R_RegDst) print('ALUSrc: ',self.IDEX_R_ALUSrc) print('ALUOp: ',self.IDEX_R_ALUOp) print('MemRead: ',self.IDEX_R_MemRead) print('Memwrite: ',self.IDEX_R_MemWrite) print('MemToReg: ',self.IDEX_R_MemToReg) print('RegWrite: ',self.IDEX_R_RegWrite) print('IncrPC: {0:x}'.format(self.IDEX_R_IncrPC)) print('ReadReg1Value: {0:x}'.format(self.IDEX_R_ReadReg1Value)) print('ReadReg2Value: {0:x}'.format(self.IDEX_R_ReadReg2Value)) print('SEOffset: ',self.IDEX_R_SEOffset) print('WriteReg_20_16: ',self.IDEX_R_WriteReg_20_16) print('WriteReg_15_11: ',self.IDEX_R_WriteReg_15_11) print('Function: ',self.IDEX_R_Function) #EX print('\nEX/MEM Write-------------------') print("MemRead: ", self.EXMEM_W_MemRead) print("MemWrite: ", self.EXMEM_W_MemWrite) print("Branch: ", self.EXMEM_W_Branch) print("MemToReg: ", self.EXMEM_W_MemToReg) print("RegWrite: ", self.EXMEM_W_RegWrite) print("Zero: ", self.EXMEM_W_Zero) print("ALUResult: {0:x}".format(self.EXMEM_W_ALUResult)) print("SWValue: {0:x}".format(self.EXMEM_W_SWValue)) print("WriteRegNum: ", self.EXMEM_W_WriteRegNum) print('\nEX/MEM Read-------------------') print("MemRead: ", self.EXMEM_R_MemRead) print("MemWrite: ", self.EXMEM_R_MemWrite) print("Branch: ", self.EXMEM_R_Branch) print("MemToReg: ", self.EXMEM_R_MemToReg) print("RegWrite: ", self.EXMEM_R_RegWrite) print("Zero: ", self.EXMEM_R_Zero) print("ALUResult: {0:x}".format(self.EXMEM_R_ALUResult)) print("SWValue: {0:x}".format(self.EXMEM_R_SWValue)) print("WriteRegNum: ", self.EXMEM_R_WriteRegNum) #MEM print('\nMEM/WB Write-----------------------') print("MemToReg: ", self.MEMWB_W_MemToReg) print("RegWrite: ", self.MEMWB_W_RegWrite) print("ALUResult: {0:x}".format(self.MEMWB_W_ALUResult)) print("WriteRegNum: ", self.MEMWB_W_WriteRegNum) print("LWDataValue: ", self.MEMWB_W_LWDataValue) print('\nMEM/WB Read-----------------------') print("MemToReg: ", self.MEMWB_R_MemToReg) print("RegWrite: ", self.MEMWB_R_RegWrite) print("ALUResult: {0:x}".format(self.MEMWB_R_ALUResult)) print("WriteRegNum: ", self.MEMWB_R_WriteRegNum) print("LWDataValue: ", self.MEMWB_R_LWDataValue) # #WB # print('\n-------------WB-------------') # print("MemToReg: ",self.MEMWB_R_MemToReg) # print("RegWrite: ",self.MEMWB_R_RegWrite) # print("LWDataValue: ",self.MEMWB_R_LWDataValue) # print("ALUResult: {0:x}".format(self.MEMWB_R_ALUResult)) # print("WriteRegNum: ",self.MEMWB_R_WriteRegNum) print("\n------------Registers-------------") for i in range(len(self.Regs)): print("Regs[{0:d}] = {1:x}".format(i, self.Regs[i])) def Copy_write_to_read(self): #IF/ID Read self.IFID_R_Inst = self.IFID_W_Inst self.IFID_R_IncrPC = self.IFID_W_IncrPC #ID/EX Read self.IDEX_R_RegDst = self.IDEX_W_RegDst self.IDEX_R_ALUSrc = self.IDEX_W_ALUSrc self.IDEX_R_ALUOp = self.IDEX_W_ALUOp self.IDEX_R_MemRead = self.IDEX_W_MemRead self.IDEX_R_MemWrite = self.IDEX_W_MemWrite self.IDEX_R_Branch = self.IDEX_W_Branch self.IDEX_R_MemToReg = self.IDEX_W_MemToReg self.IDEX_R_RegWrite = self.IDEX_W_RegWrite self.IDEX_R_IncrPC = self.IDEX_W_IncrPC self.IDEX_R_ReadReg1Value = self.IDEX_W_ReadReg1Value self.IDEX_R_ReadReg2Value = self.IDEX_W_ReadReg2Value self.IDEX_R_SEOffset = self.IDEX_W_SEOffset self.IDEX_R_WriteReg_20_16 = self.IDEX_W_WriteReg_20_16 self.IDEX_R_WriteReg_15_11 = self.IDEX_W_WriteReg_15_11 self.IDEX_R_Function = self.IDEX_W_Function #EX/MEM Read self.EXMEM_R_MemRead = self.EXMEM_W_MemRead self.EXMEM_R_MemWrite = self.EXMEM_W_MemWrite self.EXMEM_R_Branch = self.EXMEM_W_Branch self.EXMEM_R_MemToReg = self.EXMEM_W_MemToReg self.EXMEM_R_RegWrite = self.EXMEM_W_RegWrite self.EXMEM_R_Zero = self.EXMEM_W_Zero self.EXMEM_R_ALUResult = self.EXMEM_W_ALUResult self.EXMEM_R_SWValue = self.EXMEM_W_SWValue self.EXMEM_R_WriteRegNum = self.EXMEM_W_WriteRegNum #MEM/WB Read self.MEMWB_R_MemToReg = self.MEMWB_W_MemToReg self.MEMWB_R_RegWrite = self.MEMWB_W_RegWrite self.MEMWB_R_LWDataValue = self.MEMWB_W_LWDataValue self.MEMWB_R_ALUResult = self.MEMWB_W_ALUResult self.MEMWB_R_WriteRegNum = self.MEMWB_W_WriteRegNum def initializeMainMem(self): self.Main_Mem = [] for i in range(1024): self.Main_Mem.append( i & 0b000011111111 ) def initializeRegs(self): self.Regs = [] for i in range(32): self.Regs.append( i + 0x100) self.Regs[0] = 0 #Special Case for Reg 0
{ "repo_name": "andrewoconnell89/CS472_Project3", "path": "src/Pipeline/Pipeline.py", "copies": "1", "size": "18121", "license": "mit", "hash": 3898411328623428000, "line_mean": 39.7213483146, "line_max": 128, "alpha_frac": 0.5360631312, "autogenerated": false, "ratio": 2.9657937806873975, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8962762789158196, "avg_score": 0.00781882454584026, "num_lines": 445 }
__author__ = 'Aneil Mallavarapu (http://github.com/aneilbaboo)' from datetime import datetime import dateutil.parser from errors import InvalidTypeException def default_timestamp_parser(s): try: if dateutil.parser.parse(s): return True else: return False except: return False def schema_from_record(record, timestamp_parser=default_timestamp_parser): """Generate a BigQuery schema given an example of a record that is to be inserted into BigQuery. Args: record: dict timestamp_parser: unary function taking a string and return non-NIL if string represents a date Returns: schema: list """ return [describe_field(k, v) for k, v in record.items()] def describe_field(k, v, timestamp_parser=default_timestamp_parser): """Given a key representing a column name and value representing the value stored in the column, return a representation of the BigQuery schema element describing that field. Raise errors if invalid value types are provided. Args: k: str/unicode, key representing the column v: str/unicode/int/float/datetime/object Returns: object describing the field Raises: Exception: if invalid value types are provided. >>> describe_field("username", "Bob") {"name": "username", "type": "string", "mode": "nullable"} >>> describe_field("users", [{"username": "Bob"}]) {"name": "users", "type": "record", "mode": "repeated", "fields": [{"name":"username","type":"string","mode":"nullable"}]} """ def bq_schema_field(name, bq_type, mode): return {"name": name, "type": bq_type, "mode": mode} if isinstance(v, list): if len(v) == 0: raise Exception( "Can't describe schema because of empty list {0}:[]".format(k)) v = v[0] mode = "repeated" else: mode = "nullable" bq_type = bigquery_type(v, timestamp_parser=timestamp_parser) if not bq_type: raise InvalidTypeException(k, v) field = bq_schema_field(k, bq_type, mode) if bq_type == "record": try: field['fields'] = schema_from_record(v) except InvalidTypeException, e: # recursively construct the key causing the error raise InvalidTypeException("%s.%s" % (k, e.key), e.value) return field def bigquery_type(o, timestamp_parser=default_timestamp_parser): """Given a value, return the matching BigQuery type of that value. Must be one of str/unicode/int/float/datetime/record, where record is a dict containing value which have matching BigQuery types. Returns: str or None if no matching type could be found >>> bigquery_type("abc") "string" >>> bigquery_type(123) "integer" """ t = type(o) if t == int: return "integer" elif t == str or t == unicode: if timestamp_parser and timestamp_parser(o): return "timestamp" else: return "string" elif t == float: return "float" elif t == bool: return "boolean" elif t == dict: return "record" elif t == datetime: return "timestamp" else: return None # failed to find a type
{ "repo_name": "blarghmatey/BigQuery-Python", "path": "bigquery/schema_builder.py", "copies": "2", "size": "3332", "license": "apache-2.0", "hash": -3138682770774737400, "line_mean": 27.724137931, "line_max": 79, "alpha_frac": 0.6107442977, "autogenerated": false, "ratio": 4, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.56107442977, "avg_score": null, "num_lines": null }
__author__ = 'angad' import networkx as nx from scipy.spatial.distance import cosine class CompareFeature(object): def __init__(self, graph1, graph2): self._value = (self._compute(graph1)==self._compute(graph2)) def _compute(self, graph): # Should return a comparable for a graph such as int or list pass def get_value(self): # Returns true if both graphs have the same value return self._value class CompareNumOfNodes(CompareFeature): def _compute(self, graph): return len(graph.nodes()) class CompareNumOfEdges(CompareFeature): def _compute(self, graph): return len(graph.edges()) class CompareDegreeDistribution(CompareFeature): def _compute(self, graph): degree = graph.degree().values() degree.sort() # print degree return degree class CompareDirected(CompareFeature): def _compute(self, graph): return graph.is_directed() class CompareLSpectrum(CompareFeature): def __init__(self, graph1, graph2): self._value = abs(cosine(self._compute(graph1), self._compute(graph2))) def _compute(self, graph): s = nx.laplacian_spectrum(graph) return s class CompareASpectrum(CompareFeature): def __init__(self, graph1, graph2): self._value = abs(cosine(self._compute(graph1), self._compute(graph2))) def _compute(self, graph): s = nx.adjacency_spectrum(graph) return s # TODO: Add family of spectra # TODO: Add characteristic polynomial for adjacency matrix
{ "repo_name": "angadgill/ML-Graph-Isomorphism", "path": "scripts/model/features.py", "copies": "1", "size": "1558", "license": "mit", "hash": -8736428881603080000, "line_mean": 24.9666666667, "line_max": 79, "alpha_frac": 0.6604621309, "autogenerated": false, "ratio": 3.885286783042394, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5045748913942394, "avg_score": null, "num_lines": null }
__author__ = 'angad' ''' This implements and tests a naive neural network model to determine if two graphs are isomorphic Input to the neural network are the features used in the naive_model ''' import networkx as nx import random import numpy as np from scripts.model import features from scripts.model import graph_pair_class from scripts.model import permute_graph from scripts.graphScripts import ping from keras.layers.core import Dense from keras.models import Sequential from keras.optimizers import SGD # List of features used in this model feature_list = [features.CompareNumOfNodes, features.CompareNumOfEdges, features.CompareDirected, features.CompareDegreeDistribution, features.CompareLSpectrum, features.CompareASpectrum] # All graph pairs are contained in this list graphPairs = [] # Base graph for all isomorphic graphs g_base_nodes = 10 g_base = nx.watts_strogatz_graph(g_base_nodes, 5, 0.1) # Create a list of isomorphic graph pairs print "Creating list of isomorphic graph pairs..." for _ in xrange(100): g = permute_graph.permute_graph(g_base, random.randint(1,g_base_nodes)) graphPair = graph_pair_class.GraphPair(g_base, g) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" # Create a list of random graph pairs print "Creating list of random graph pairs..." for _ in xrange(100): g = nx.watts_strogatz_graph(g_base_nodes, 5, 0.1) graphPair = graph_pair_class.GraphPair(g_base, g) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" # Create a list of PING graphs print "Creating PING graphs..." for _ in xrange(100): g1, g2 = ping.create(2,10) graphPair = graph_pair_class.GraphPair(g1,g2) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" '''Neural Network model''' X = np.array([g.features for g in graphPairs]) y = np.array([g.is_isomorphic for g in graphPairs]) shuffle = range(len(y)) random.shuffle(shuffle) X = X[shuffle] y = y[shuffle] model = Sequential() model.add(Dense(output_dim=10, input_dim=6, activation='relu')) model.add(Dense(output_dim=1, activation='sigmoid')) sgd = SGD() model.compile(optimizer=sgd, loss='mean_absolute_error') model.fit(X, y, nb_epoch=20, verbose=2, validation_split=0.2, show_accuracy=True)
{ "repo_name": "angadgill/ML-Graph-Isomorphism", "path": "scripts/model/naive_nn_model.py", "copies": "1", "size": "2372", "license": "mit", "hash": 1511981350170778400, "line_mean": 29.4102564103, "line_max": 105, "alpha_frac": 0.7276559865, "autogenerated": false, "ratio": 3.209742895805142, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9430504112853122, "avg_score": 0.0013789538904039756, "num_lines": 78 }
__author__ = 'angad' ''' This implements and tests a neural network model to determine if two graphs are isomorphic Input to the neural network is a pair of adjecency matrices ''' import networkx as nx import random import numpy as np from scripts.model import features from scripts.model import graph_pair_class from scripts.model import permute_graph from scripts.graphScripts import ping from keras.layers.core import Dense from keras.models import Sequential from keras.optimizers import SGD from sklearn.cross_validation import ShuffleSplit # List of features used in this model feature_list = [features.CompareNumOfNodes, features.CompareNumOfEdges, features.CompareDirected, features.CompareDegreeDistribution, features.CompareLSpectrum, features.CompareASpectrum] # All graph pairs are contained in this list graphPairs = [] # Base graph for all isomorphic graphs g_base_nodes = 11 g_base = nx.watts_strogatz_graph(g_base_nodes, 5, 0.1) # Create a list of isomorphic graph pairs print "Creating list of isomorphic graph pairs..." for _ in xrange(100): g = permute_graph.permute_graph(g_base, random.randint(1,g_base_nodes)) graphPair = graph_pair_class.GraphPair(g_base, g) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" # Create a list of random graph pairs print "Creating list of random graph pairs..." for _ in xrange(100): g = nx.watts_strogatz_graph(g_base_nodes, 5, 0.1) graphPair = graph_pair_class.GraphPair(g_base, g) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" # Create a list of PING graphs print "Creating PING graphs..." for _ in xrange(100): g1, g2 = ping.create(2,10) graphPair = graph_pair_class.GraphPair(g1,g2) for f in feature_list: graphPair.add_feature(f) graphPairs += [graphPair] print "Done!" '''Neural Network model''' X = np.array([g.combined_adj_matrix_flat() for g in graphPairs]) y = np.array([g.is_isomorphic for g in graphPairs]) # shuffle = range(len(y)) # random.shuffle(shuffle) # X = X[shuffle] # y = y[shuffle] model = Sequential() model.add(Dense(output_dim=500, input_dim=X.shape[1], activation='relu')) model.add(Dense(output_dim=1, activation='sigmoid')) sgd = SGD() model.compile(optimizer=sgd, loss='mean_absolute_error') # model.fit(X, y, nb_epoch=20, verbose=2, validation_split=0.2, show_accuracy=True) for train, test in ShuffleSplit(X.shape[0], n_iter=1, test_size=0.2): model.fit(X[train], y[train], nb_epoch=20, verbose=2, validation_split=0.2, show_accuracy=True) print "Score: ", model.evaluate(X[test], y[test], verbose=2)
{ "repo_name": "angadgill/ML-Graph-Isomorphism", "path": "scripts/model/nn_model.py", "copies": "1", "size": "2683", "license": "mit", "hash": 2453957407553526000, "line_mean": 30.5647058824, "line_max": 105, "alpha_frac": 0.7223257548, "autogenerated": false, "ratio": 3.1343457943925235, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9290909915307608, "avg_score": 0.01315232677698292, "num_lines": 85 }
__author__ = 'Angus Bishop' def get_setup_drinks(): setup_pos = {} setup_type = {} with open('data/setup.txt', 'r') as setupfile: for line in setupfile: if line[0] != '#' and line != '': pos = 0 dtype = '' name = '' separated = line.split(',') for val in separated: val = val.strip() if not name: name = val.lower() elif (val.lower() == 'spirit') or (val.lower() == 'mixer'): dtype = val.lower() else: if pos == 0: pos = eval(val) setup_pos[name] = pos setup_type[name] = dtype return [setup_pos, setup_type] def get_solenoid(drink_id): solenoid_number = 'No Solenoid Found' with open('data/setup.txt', 'r') as setupfile: for line in setupfile: if line[0] != '#' and line != '\n': separated = line.split(',') if (separated[0].lower() == drink_id) and (separated[1].lower().strip() == 'mixer'): solenoid_number == separated[3].strip() print separated[3].strip() return solenoid_number
{ "repo_name": "angusgbishop/biast", "path": "setup.py", "copies": "1", "size": "1320", "license": "apache-2.0", "hash": 3611726216168131000, "line_mean": 33.7631578947, "line_max": 100, "alpha_frac": 0.4325757576, "autogenerated": false, "ratio": 4.125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5057575757599999, "avg_score": null, "num_lines": null }
__author__ = 'AniaF' import os import django # set the DJANGO_SETTINGS_MODULE environment variable to "mips.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mips.settings") # setup django.setup() # import proper classes to play with # from mips.models import Mip, Subspecies, SampleSubspecies, Samples, Paralog, Instance from mips.models import Mip, SampleSubspecies, Samples, Paralog, Instance # example data reference_name="c132510_g1_i1" reference_list = ["c132510_g1_i1","c150407_g1_i1","c150408_g1_i1","c107721_g1_i1","c129997_g1_i1", "c129907_g1_i1","c130723_g1_i1"] mip_list = ["177","178","179","180"] sample_list = ["1737","1738","1739","1740","1741","1742","1743"] # How many mips are in a particular reference transcript? #print Mip.objects.filter(reference_id=reference_name).count() # For a reference select and print all mips and their sequences def select_mips_for_reference(reference): for mip in Mip.objects.filter(reference_id=reference): print mip, mip.mip_sequence #select_mips_for_reference(reference_name) # For a list of references, check if they have a mip, how many, and how many mapping mips there are def check_mips_for_reference_list(lista): for ref in lista: if Mip.objects.filter(reference_id=ref).exists(): mapping_mips = [mip.mip_func_mapping for mip in Mip.objects.filter(reference_id=ref)].count(True) print ref, Mip.objects.filter(reference_id=ref).count(), mapping_mips else: print ref, 'no mip' #check_mips_for_reference_list(reference_list) # For a list of references, print mips they have (mip_id), and their function def mips_for_reference_list(lista): for ref in lista: for mip in Mip.objects.filter(reference_id=ref): print ref, mip.mip_id, ['immuno' if mip.mip_func_immuno else '-'][0], ['mapping' if mip.mip_func_mapping else '-'][0], \ ['random' if mip.mip_func_random else '-'][0], ['utr' if mip.mip_func_utr else '-'][0] #mips_for_reference_list(reference_list) # For a list of references check if there are mips, for which individuals they were sequenced and their performance def samples_for_mips(lista): for ref in lista: for mip in Mip.objects.filter(reference_id=ref): for sample in Samples.objects.filter(mip_fk=mip): print ref, mip, sample.sample_fk, sample.mip_performance #samples_for_mips(reference_list) # For a list of references, print all mips and count in how many samples they were sequenced def count_samples_for_mips(lista): for ref in lista: for mip in Mip.objects.filter(reference_id=ref): samp = Samples.objects.filter(mip_fk=mip).count() print ref, mip, samp #count_samples_for_mips(reference_list) # For a list of mips check in which subspecies they are paralogs def mips_with_paralogs(lista): for mip in lista: for subsp in Paralog.objects.filter(mip_fk=mip): print mip, subsp.subspecies_fk, subsp.mip_subspecies_paralog #mips_with_paralogs(mip_list) # Print all mips that are paralogs and in which subspecies def all_mips_paralogs(): for para in Paralog.objects.filter(mip_subspecies_paralog="paralog"): print para.mip_fk, para.subspecies_fk, para.mip_subspecies_paralog #all_mips_paralogs() # Find all mips for montandoni def all_mips_for_species(): for montandoni_samples in SampleSubspecies.objects.filter(subspecies_fk="montandoni"): for mip in Samples.objects.filter(sample_fk=montandoni_samples.sample_id): print mip.mip_fk, mip.sample_fk #all_mips_for_species() # For a list of samples find all mips and their reference def mips_for_samples(lista): for indiv in lista: for samps in Samples.objects.filter(sample_fk=indiv): print samps.sample_fk, samps.mip_fk, samps.mip_fk.reference_id #mips_for_samples(sample_list) # For all mips in montandoni, print only mapping mips def func_mips_for_montandoni(): for montandoni_samples in SampleSubspecies.objects.filter(subspecies_fk="montandoni"): for Sample_mip in Samples.objects.filter(sample_fk=montandoni_samples.sample_id): if Sample_mip.mip_fk.mip_func_mapping is True: print Sample_mip.mip_fk.mip_id #func_mips_for_montandoni() # Select one random mapping mip for a list of references import random def random_mip_for_reference(lista): for ref in lista: if Mip.objects.filter(reference_id=ref, mip_func_mapping=True).exists(): ref_mips = list(Mip.objects.filter(reference_id=ref, mip_func_mapping=True)) one_mip = random.sample(ref_mips, 1)[0] print one_mip.reference_id, one_mip.mip_id #random_mip_for_reference(reference_list) # Read in one column (txt file) and convert it into a list def read_column(txt_file): fh = open(txt_file,'r') linie = fh.readlines() K = [ele.split()[0] for ele in linie] print K #read_column("example_list.txt") # For a list of mips print producer and production date def instance_for_mip(lista): for mip in lista: for mip_inst in Instance.objects.filter(mip_fk=mip): print mip_inst.mip_fk, mip_inst.mip_production_data, mip_inst.mip_producer #instance_for_mip(mip_list) # For a list of mips print producer and production date and write it to a file wh = open('output.tab','w') def instance_for_mip_and_write(lista): for mip in lista: for mip_inst in Instance.objects.filter(mip_fk=mip): output = str(mip_inst.mip_fk) +'\t'+ str(mip_inst.mip_production_data) +'\t'+ str(mip_inst.mip_producer)+'\n' wh.write(output) instance_for_mip_and_write(mip_list) wh.flush() wh.close()
{ "repo_name": "aniafijarczyk/django-mips", "path": "mips/example/examples2.py", "copies": "2", "size": "5789", "license": "mit", "hash": 4379072583444558300, "line_mean": 24.3903508772, "line_max": 132, "alpha_frac": 0.6861288651, "autogenerated": false, "ratio": 3.0277196652719667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9650116557991733, "avg_score": 0.012746394476046963, "num_lines": 228 }
__author__ = 'anicca' # core import math import sys from itertools import izip # 3rd party from PIL import Image, ImageChops import argh def dhash(image, hash_size=8): # Grayscale and shrink the image in one step. image = image.convert('L').resize( (hash_size + 1, hash_size), Image.ANTIALIAS, ) pixels = list(image.getdata()) # Compare adjacent pixels. difference = [] for row in range(hash_size): for col in range(hash_size): pixel_left = image.getpixel((col, row)) pixel_right = image.getpixel((col + 1, row)) difference.append(pixel_left > pixel_right) # Convert the binary array to a hexadecimal string. decimal_value = 0 hex_string = [] for index, value in enumerate(difference): if value: decimal_value += 2 ** (index % 8) if (index % 8) == 7: hex_string.append(hex(decimal_value)[2:].rjust(2, '0')) decimal_value = 0 return ''.join(hex_string) def rosetta(image1, image2): i1 = Image.open(image1) i2 = Image.open(image2) assert i1.mode == i2.mode, "Different kinds of images." print i1.size, i2.size assert i1.size == i2.size, "Different sizes." pairs = izip(i1.getdata(), i2.getdata()) if len(i1.getbands()) == 1: # for gray-scale jpegs dif = sum(abs(p1 - p2) for p1, p2 in pairs) else: dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2)) ncomponents = i1.size[0] * i1.size[1] * 3 retval = (dif / 255.0 * 100) / ncomponents return retval def rmsdiff_2011(im1, im2): "Calculate the root-mean-square difference between two images" im1 = Image.open(im1) im2 = Image.open(im2) diff = ImageChops.difference(im1, im2) h = diff.histogram() sq = (value * (idx ** 2) for idx, value in enumerate(h)) sum_of_squares = sum(sq) rms = math.sqrt(sum_of_squares / float(im1.size[0] * im1.size[1])) return rms def main(image_filename1, image_filename2, dhash=False, rosetta=False, rmsdiff=False): pass if __name__ == '__main__': argh.dispatch_command(main)
{ "repo_name": "metaperl/clickmob", "path": "src/dhash.py", "copies": "2", "size": "2158", "license": "mit", "hash": 5644511999859032000, "line_mean": 25.975, "line_max": 86, "alpha_frac": 0.6051899907, "autogenerated": false, "ratio": 3.1320754716981134, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47372654623981136, "avg_score": null, "num_lines": null }
__author__ = 'anicca' from decimal import * def moneyfmt(value, places=2, curr='', sep=',', dp='.', pos='', neg='-', trailneg=''): """Convert Decimal to a money formatted string. places: required number of places after the decimal point curr: optional currency symbol before the sign (may be blank) sep: optional grouping separator (comma, period, space, or blank) dp: decimal point indicator (comma or period) only specify as blank when places is zero pos: optional sign for positive numbers: '+', space or blank neg: optional sign for negative numbers: '-', '(', space or blank trailneg:optional trailing minus indicator: '-', ')', space or blank >>> d = Decimal('-1234567.8901') >>> moneyfmt(d, curr='$') '-$1,234,567.89' >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') '1.234.568-' >>> moneyfmt(d, curr='$', neg='(', trailneg=')') '($1,234,567.89)' >>> moneyfmt(Decimal(123456789), sep=' ') '123 456 789.00' >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') '<0.02>' """ q = Decimal(10) ** -places # 2 places --> '0.01' sign, digits, exp = value.quantize(q).as_tuple() result = [] digits = map(str, digits) build, next = result.append, digits.pop if sign: build(trailneg) for i in range(places): build(next() if digits else '0') build(dp) if not digits: build('0') i = 0 while digits: build(next()) i += 1 if i == 3 and digits: i = 0 build(sep) build(curr) build(neg if sign else pos) return ''.join(reversed(result))
{ "repo_name": "metaperl/revadbu", "path": "src/money_format.py", "copies": "2", "size": "1707", "license": "mit", "hash": -5843319051278197000, "line_mean": 31.8461538462, "line_max": 73, "alpha_frac": 0.5565319274, "autogenerated": false, "ratio": 3.6165254237288136, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008775946275946275, "num_lines": 52 }
__author__ = 'anicca' import cv2 import numpy as np def drawMatches(img1, kp1, img2, kp2, matches): """ My own implementation of cv2.drawMatches as OpenCV 2.4.9 does not have this function available but it's supported in OpenCV 3.0.0 This function takes in two images with their associated keypoints, as well as a list of DMatch data structure (matches) that contains which keypoints matched in which images. An image will be produced where a montage is shown with the first image followed by the second image beside it. Keypoints are delineated with circles, while lines are connected between matching keypoints. img1,img2 - Grayscale images kp1,kp2 - Detected list of keypoints through any of the OpenCV keypoint detection algorithms matches - A list of matches of corresponding keypoints through any OpenCV keypoint matching algorithm """ # Create a new output image that concatenates the two images together # (a.k.a) a montage rows1 = img1.shape[0] cols1 = img1.shape[1] rows2 = img2.shape[0] cols2 = img2.shape[1] out = np.zeros((max([rows1,rows2]),cols1+cols2,3), dtype='uint8') # Place the first image to the left out[:rows1,:cols1] = np.dstack([img1, img1, img1]) # Place the next image to the right of it out[:rows2,cols1:] = np.dstack([img2, img2, img2]) # For each pair of points we have between both images # draw circles, then connect a line between them for mat in matches: # Get the matching keypoints for each of the images img1_idx = mat.queryIdx img2_idx = mat.trainIdx # x - columns # y - rows (x1,y1) = kp1[img1_idx].pt (x2,y2) = kp2[img2_idx].pt # Draw a small circle at both co-ordinates # radius 4 # colour blue # thickness = 1 cv2.circle(out, (int(x1),int(y1)), 4, (255, 0, 0), 1) cv2.circle(out, (int(x2)+cols1,int(y2)), 4, (255, 0, 0), 1) # Draw a line in between the two points # thickness = 1 # colour blue cv2.line(out, (int(x1),int(y1)), (int(x2)+cols1,int(y2)), (255, 0, 0), 1) # Show the image cv2.imshow('Matched Features', out) cv2.waitKey(0) cv2.destroyWindow('Matched Features') # Also return the image if you'd like a copy return out def similarity_test(img1_filename, img2_filename): img1 = cv2.imread(img1_filename, 0) # queryImage img2 = cv2.imread(img2_filename, 0) # trainImage # Initiate SIFT detector orb = cv2.ORB() # find the keypoints and descriptors with SIFT kp1, des1 = orb.detectAndCompute(img1, None) kp2, des2 = orb.detectAndCompute(img2, None) # create BFMatcher object bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False) # Match descriptors. matches = bf.match(des1, des2) print "Matches={0}".format(matches) # Sort them in the order of their distance. matches = sorted(matches, key = lambda x:x.distance) img3 = drawMatches(img1,kp1,img2,kp2,matches[:10]) for match in matches: print "{0}".format(match.distance) if __name__ == '__main__': filenames=['IMG-0.png', 'IMG-1.png', 'IMG-2.png', 'IMG-3.png'] for filename in filenames: print filename similarity_test(filename, 'candidate_images.png')
{ "repo_name": "metaperl/clickmob", "path": "src/match_image.py", "copies": "1", "size": "3394", "license": "mit", "hash": 1427637793357803800, "line_mean": 29.3125, "line_max": 81, "alpha_frac": 0.6402474956, "autogenerated": false, "ratio": 3.311219512195122, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44514670077951213, "avg_score": null, "num_lines": null }
__author__ = 'anicca' import cv2 def showk(img, kpts): for k in kpts: print 'key' x, y = k.pt x = int(x) y = int(y) cv2.rectangle(img,(x,y), (x+2,y+2),(0,0,255),2) cv2.imshow("Result",img) cv2.waitKey(0); def similarity_test(img1_filename, img2_filename): img1 = cv2.imread(img1_filename, cv2.CV_LOAD_IMAGE_GRAYSCALE) # queryImage img2 = cv2.imread(img2_filename, cv2.CV_LOAD_IMAGE_GRAYSCALE) # trainImage fd = cv2.FeatureDetector_create('ORB') kpts = fd.detect(img1) showk(img1,kpts) print kpts kpts2 = fd.detect(img2) showk(img2,kpts2) # Now that we have the keypoints we must describe these points (x,y) # and match them. descriptor = cv2.DescriptorExtractor_create("BRIEF") matcher = cv2.DescriptorMatcher_create("BruteForce-Hamming") # descriptors (we must describe the points in some way) k1, d1 = descriptor.compute(img1, kpts) k2, d2 = descriptor.compute(img2, kpts2) # match the keypoints matches = matcher.match(d1, d2) # similarity print '#matches:', len(matches) if __name__ == '__main__': filenames=['IMG-0.png', 'IMG-1.png', 'IMG-2.png', 'IMG-3.png'] for filename in filenames: print filename similarity_test(filename, 'image_to_match.png')
{ "repo_name": "metaperl/clickmob", "path": "src/match_image3.py", "copies": "1", "size": "1329", "license": "mit", "hash": -1264154570818625300, "line_mean": 25.6, "line_max": 87, "alpha_frac": 0.6245297216, "autogenerated": false, "ratio": 2.940265486725664, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4064795208325664, "avg_score": null, "num_lines": null }
__author__ = 'anicca' import cv2 from PIL import Image def avhash(im): if not isinstance(im, Image.Image): im = Image.open(im) im = im.resize((8, 8), Image.ANTIALIAS).convert('L') avg = reduce(lambda x, y: x + y, im.getdata()) / 64. return reduce(lambda x, (y, z): x | (z << y), enumerate(map(lambda i: 0 if i < avg else 1, im.getdata())), 0) def hamming(h1, h2): h, d = 0, h1 ^ h2 while d: h += 1 d &= d - 1 return h def distance(img1, img2): hash1 = avhash(img1) hash2 = avhash(img2) return hamming(hash1, hash2) def closest(query, filenames): trial = list() for filename in filenames: _distance=distance(filename, query) print filename print _distance trial.append(dict(filename=filename, distance=_distance)) matches = sorted(trial, key = lambda x:x['distance']) return matches[0]['filename'] if __name__ == '__main__': filenames=['IMG-0.png', 'IMG-1.png', 'IMG-2.png', 'IMG-3.png'] query = 'image_to_match.png' print closest(query, filenames)
{ "repo_name": "metaperl/clickmob", "path": "src/match_image4.py", "copies": "1", "size": "1119", "license": "mit", "hash": 3007250596278954500, "line_mean": 23.8666666667, "line_max": 78, "alpha_frac": 0.5710455764, "autogenerated": false, "ratio": 3.178977272727273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9223583141363582, "avg_score": 0.005287941552738259, "num_lines": 45 }
__author__ = 'aniket' import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('paka.jpg',0) ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) blur = cv2.GaussianBlur(img,(5,5),0) ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) images = [img, 0, th1, img, 0, th2, blur, 0, th3] titles = ['Original Noisy Image','Histogram','Global Thresholding (v = 127)','Original Noisy Image','Histogram', "Otsu's Thresholding",'Gaussian filtered Image','Histogram',"Otsu's Thresholding"] for i in xrange(3): plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray') plt.title(titles[i*3]), plt.xticks([]), plt.yticks([]) plt.subplot(3,3,i*3+2), plt.hist(images[i*3].ravel(),256) plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([]) plt.subplot(3,3,i*3+3), plt.imshow(images[i*3+2],'gray') plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([]) plt.show() """This code gives the comparison of otsu thresholding and binary thresh"""
{ "repo_name": "eyantrainternship/eYSIP_2015_Depth_Mapping_Kinect", "path": "Resources/Examples/PycharmProjects/Image Processing/Image4.py", "copies": "2", "size": "1087", "license": "cc0-1.0", "hash": 779948892138572800, "line_mean": 35.2666666667, "line_max": 112, "alpha_frac": 0.6734130635, "autogenerated": false, "ratio": 2.606714628297362, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4280127691797362, "avg_score": null, "num_lines": null }
__author__ = 'Animesh' import sys import numpy as np from copy import copy, deepcopy class Normalizer: def __init__(self, features): self.max_val = [0] * 13 self.min_val = [1000] * 13 self.mean = [1] * 13 self.std_dev = [1] * 13 #standard deviation self.real_fatures = [0, 3, 4, 7, 9, 11] self.find_max(features) self.find_min(features) # scaled_features = scale_continuous_features(features) def find_max(self, features): for each_row in features: for i, each_val in enumerate(each_row): if self.max_val[i] < each_val: self.max_val[i] = each_val def find_min(self, features): for each_row in features: for i, each_val in enumerate(each_row): if self.min_val[i] > each_val: self.min_val[i] = each_val def scale_continuous_features(self, features): # Real: 1,4,5,8,10,12 real_fatures = [0, 3, 4, 7, 9, 11] scaled_features = [] for each_row in features: new_row = [] for i, each_val in enumerate(each_row): if i in real_fatures: new_row.append((2*each_val - self.max_val[i] - self.min_val[i])/(self.max_val[i] - self.min_val[i])) # sys.stdout.write('%20f' %each_val) # sys.stdout.write(" --> ") # sys.stdout.write('%20f' %new_row[i]) sys.stdout.write("\n") else: new_row.append(each_val) # new_row.append((2*each_val - self.max_val[i] - self.min_val[i])/(self.max_val[i] - self.min_val[i])) scaled_features.append(new_row) return scaled_features def get_mean(self, features): features = np.array(features) mean = features.mean(axis=0) #Take the mean over a column return mean def get_std_dev(self, features): std_dev = [1] * 13 features = np.array(features) for i in range(0, 12): std_dev[i] = np.std(zip(*features)[i]) return std_dev def standardize_features(self, features): mean = self.get_mean(features) #mean of each column #print mean std_dev = self.get_std_dev(features) #Standard dev of each column #print std_dev std_features = [] #Standardized features for each_row in features: new_row = [] for i in range(0, 12): if i in self.real_fatures: new_row.append((each_row[i] - mean[i]) / std_dev[i]) else: new_row.append(each_row[i]) # new_row.append((each_row[i] - mean[i]) / std_dev[i]) std_features.append(new_row) return std_features def binarize_features(self, features): #For all categorical features, represent them as multiple boolean features. new_features = deepcopy(features) for i in range(0, len(features)-1): if features[i][1] == 0.0: #Sex new_features[i][1] = -1.0 if features[i][5] == 0.0: #Sugar level > 120 new_features[i][5] = -1.0 if features[i][8] == 0.0: #Exercise induced chest pain new_features[i][8] = -1.0 return new_features
{ "repo_name": "animeshramesh/pyCardio", "path": "prediction_models/normalize.py", "copies": "1", "size": "3401", "license": "apache-2.0", "hash": -4078582976400119000, "line_mean": 35.1808510638, "line_max": 122, "alpha_frac": 0.5210232285, "autogenerated": false, "ratio": 3.470408163265306, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9417181212101566, "avg_score": 0.014850035932748055, "num_lines": 94 }
__author__ = 'Animesh' from utils import parser import model def load_model(): min_temp = parser.parse_csv("datasets/min_temp.csv") cloud_cover = parser.parse_csv("datasets/cloud_cover.csv") precipitation = parser.parse_csv("datasets/precipitation.csv") vp = parser.parse_csv("datasets/vp.csv") ground_frost = parser.parse_csv("datasets/ground_frost.csv") wet_day_freq = parser.parse_csv("datasets/wet_day_freq.csv") years = min_temp.keys() weather = [] for year in years: yearly_params = list() for i in range(0, 11): monthly_params = list() monthly_params.append(float(min_temp[year][i])) monthly_params.append(float(cloud_cover[year][i])) monthly_params.append(float(vp[year][i])) monthly_params.append(float(wet_day_freq[year][i])) monthly_params.append(float(ground_frost[year][i])) monthly_params.append(float(precipitation[year][i])) yearly_params.append(monthly_params) weather.extend(yearly_params) return weather
{ "repo_name": "animeshramesh/ML-analytics", "path": "utils/load_model.py", "copies": "1", "size": "1087", "license": "apache-2.0", "hash": 6737161581124043000, "line_mean": 36.4827586207, "line_max": 66, "alpha_frac": 0.6375344986, "autogenerated": false, "ratio": 3.3549382716049383, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44924727702049383, "avg_score": null, "num_lines": null }
__author__ = 'Animesh' import os import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use("ggplot") from sklearn import svm from normalize import Normalizer input, data, features, results = ([] for i in range(4)) path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'dataset/statlog/data.txt')) with open(path) as f: input = f.readlines() for line in input: each_row = line.split() each_row = [float(i) for i in each_row] data.append(each_row) results.append(each_row.pop()) features.append(each_row) normalizer = Normalizer(features) features = normalizer.scale_continuous_features(features) features = normalizer.standardize_features(features) # features = normalizer.binarize_features(features) training_count = 200 results = [int(i) for i in results] training_features = features[0:training_count] training_results = results[0:training_count] testing_features = features[training_count:] testing_results = results[training_count:] clf = svm.SVC(kernel='linear', C = 1.0) clf.fit(training_features, training_results) errors = 0 for i in range(len(testing_features)): res = clf.predict(testing_features[i]) if res != testing_results[i]: errors += 1 print errors print len(testing_features) #test_x1 = [float(i) for i in ['70.0', '1.0', '4.0', '130.0', '322.0', '0.0', '2.0', '109.0', '0.0', '2.4', '2.0', '3.0', '3.0']] #print (clf.predict(test_x1)) #plt.scatter(x,y) #plt.show()
{ "repo_name": "animeshramesh/pyCardio", "path": "prediction_models/svm.py", "copies": "1", "size": "1486", "license": "apache-2.0", "hash": -4735753314796164000, "line_mean": 26.5185185185, "line_max": 129, "alpha_frac": 0.6897711978, "autogenerated": false, "ratio": 2.9779559118236474, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9043692245311006, "avg_score": 0.024806972862528417, "num_lines": 54 }
__author__ = 'Animesh' # Imports from utils import load_model from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.tools.shortcuts import buildNetwork import numpy as np import math as pymath from utils import math import matplotlib.pyplot as plt epochs = 500 # Get the dataset in the required format input_matrix = np.array(load_model.load_model()) params = math.normalize_matrix(input_matrix[:, :-1]) rain = np.array(params[:, -1:].tolist()).reshape(-1, 1) # Initialize the layer sizes input_size = params.shape[1] hidden_size = input_size target_size = rain.shape[1] # Feed the data to the network ds = SupervisedDataSet(input_size, target_size) ds.setField('input', params) ds.setField('target', rain) net = buildNetwork(input_size, hidden_size, target_size, bias=False) # Now the magic happens trainer = BackpropTrainer(net, ds) # Write the errors to a file f = open('errors', 'w') errors = [] for i in range(epochs): mse = trainer.train() # returns the error for the corresponding epoch rmse = pymath.sqrt(mse) # obtain the Root Mean Square Error print "training RMSE, epoch {}: {}".format(i + 1, rmse) errors.append(rmse) f.write(str(rmse) + '\n') # Test it on the data set result = net.activateOnDataset(ds) for i in range(len(result)): print result[i], rain[i], " --> ", rain[i] - result[i] # Show the plot plt.plot(errors) plt.ylabel("Error from training") plt.xlabel("Epochs") plt.show()
{ "repo_name": "animeshramesh/ML-analytics", "path": "nn.py", "copies": "1", "size": "1500", "license": "apache-2.0", "hash": 4455366850721329700, "line_mean": 26.2909090909, "line_max": 76, "alpha_frac": 0.716, "autogenerated": false, "ratio": 3.1779661016949152, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4393966101694915, "avg_score": null, "num_lines": null }
__author__ = 'Animesh' class Model: def __init__(self): self.min_temp = [] self.max_temp = [] self.avg_temp = [] self.cloud_cover = [] self.vapour_pressure = [] self.precipitation = [] def set_min_temp(self, min_temp): self.min_temp = min_temp def set_precipitation(self, x): self.precipitation = x def set_max_temp(self, max_temp): self.max_temp = max_temp def set_avg_temp(self, avg_temp): self.avg_temp = avg_temp def set_cloud_cover(self, cloud_cover): self.cloud_cover = cloud_cover def set_vapour_pressure(self, vapour_pressure): self.vapour_pressure = vapour_pressure def get_min_temp(self): return self.min_temp def get_max_temp(self): return self.max_temp def get_avg_temp(self): return self.avg_temp def get_cloud_cover(self): return self.cloud_cover def get_vapour_pressure(self): return self.vapour_pressure def get_precipitation(self): return self.precipitation
{ "repo_name": "animeshramesh/ML-analytics", "path": "model.py", "copies": "1", "size": "1085", "license": "apache-2.0", "hash": -5581000765229196000, "line_mean": 21.625, "line_max": 51, "alpha_frac": 0.5935483871, "autogenerated": false, "ratio": 3.3384615384615386, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44320099255615386, "avg_score": null, "num_lines": null }
__author__ = 'Anindya Guha (aguha@colgate.edu)' from numpy import * import networkx as nx from networkx.algorithms.approximation import * import matplotlib.pyplot as plt from scipy.stats import rv_discrete def is_infected(edge_weight, percentage_infected, timestep): prob = 1 - (1 - edge_weight*percentage_infected/100.0)**timestep xk = (0, 1, 2, 3) pk = ((1-prob), prob/3.0, prob/3.0, prob/3.0) val = rv_discrete(name='val', values=(xk, pk)) R = val.rvs(size=1) return R G = nx.Graph() all_cities = ['Conakry', 'Gueckdou', 'Macenta', 'Kissidougou', 'Boffa', 'Nzerekore', 'Yomou', 'Lola', 'Dubreka', 'Forecariah', 'Kerouane', 'Coyah'] G.add_nodes_from(all_cities) G.add_weighted_edges_from([('Nzerekore', 'Lola', 0.51), ('Nzerekore', 'Yomou', 0.15), ('Nzerekore', 'Macenta', 0.709), ('Macenta', 'Gueckdou', 0.1111), ('Macenta', 'Kissidougou', 0.5478), ('Gueckdou', 'Kissidougou', 0.7261), ('Conakry', 'Boffa', 0.6), ('Conakry', 'Kissidougou', 0.9210), ('Gueckdou', 'Yomou', 0.0134)]) G.add_weighted_edges_from([('Dubreka', 'Conakry', 0.6), ('Dubreka', 'Boffa', 0.45), ('Forecariah', 'Conakry', 0.51), ('Kerouane', 'Kissidougou', 0.54), ('Kerouane', 'Macenta', 0.45), ('Coyah','Dubreka', 0.256), ('Coyah', 'Conakry', 0.782), ('Coyah', 'Forecariah', 0.1567)]) G.add_weighted_edges_from([('Coyah', 'Kissidougou', 0.345), ('Forecariah', 'Kissidougou', 0.275), ('Yomou', 'Lola', 0.1)]) very_infected_cities = ['Macenta'] moderately_infected_cities = ['Conakry', 'Gueckdou'] slightly_infected_cities = ['Nzerekore', 'Yomou', 'Dubreka', 'Kerouane'] infected_cities = very_infected_cities+moderately_infected_cities+slightly_infected_cities for city in (infected_cities): G.node[city]['infected'] = True if city in very_infected_cities: G.node[city]['percentage_infected'] = 10 elif city in moderately_infected_cities: G.node[city]['percentage_infected'] = 5 elif city in slightly_infected_cities: G.node[city]['percentage_infected'] = 2 else: raise uninfected_cities = [] for city in all_cities: if city not in infected_cities: G.node[city]['infected'] = False uninfected_cities.append(city) elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5] esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5] pos = {'Conakry': (2,9), 'Boffa':(1,11), 'Gueckdou':(7,4.5), 'Macenta':(10, 6), 'Kissidougou':(7, 6), 'Nzerekore':(11.5, 5), 'Lola':(13.5, 4.5), 'Yomou':(8, 4), 'Dubreka': (3,10), 'Forecariah': (4, 7), 'Kerouane': (9, 6.5), 'Coyah': (4.5, 8)} for city in infected_cities: for neighbor in G.neighbors(city): if G.node[neighbor]['infected'] == False: infection_amount = is_infected(G.edge[city][neighbor]['weight'], G.node[city]['percentage_infected'], 100) if infection_amount > 0: G.node[neighbor]['infected'] = True if infection_amount == 1: slightly_infected_cities.append(neighbor) elif infection_amount == 2: moderately_infected_cities.append(neighbor) elif infection_amount == 3: very_infected_cities.append(neighbor) else: raise uninfected_cities.remove(neighbor) for (u,v,d) in G.edges(data=True): G.edge[u][v]['weight'] = 1.0/G.edge[u][v]['weight'] dominating_set = ['Conakry', 'Kissidougou', 'Nzerekore'] remaining_cities = [] for city in all_cities: if city not in dominating_set: remaining_cities.append(city) nx.draw_networkx_nodes(G, pos, nodelist=very_infected_cities, node_color='#7f0000') nx.draw_networkx_nodes(G, pos, nodelist=moderately_infected_cities, node_color='r') nx.draw_networkx_nodes(G, pos, nodelist=slightly_infected_cities, node_color='m') nx.draw_networkx_nodes(G, pos, nodelist=uninfected_cities, node_color='b') nx.draw_networkx_edges(G,pos,edgelist=elarge, width=2.5, edge_color='#323234') nx.draw_networkx_edges(G,pos,edgelist=esmall, width=2,alpha=0.5,edge_color='b') nx.draw_networkx_labels(G,pos,font_size=10,font_family='sans-serif') plt.axis('off') plt.savefig('hundred_days_later_correct.png') plt.show() #print is_infected(0.2, 1, 4)
{ "repo_name": "anindyabd/ebola_eradication", "path": "contact_network.py", "copies": "1", "size": "4331", "license": "mit", "hash": 4926152763366409000, "line_mean": 37.6696428571, "line_max": 319, "alpha_frac": 0.6241052875, "autogenerated": false, "ratio": 2.5810488676996424, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8627127321250826, "avg_score": 0.015605366789763356, "num_lines": 112 }
__author__ = 'ANI' try : import requests from bs4 import BeautifulSoup import sqlite3 import time # This import statement is to disable urllib3 'insecure platform warning' exception. import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() except : print "Error in importing the modules \n" print("------BOOKSHELF------") #----------------------------------------------------------------------------------------------------------------------- # Makes use of pygame image module to capture the image of the book cover using the webcam and saved. # The captured image path can be used as the input parameter to the cover_find() function. def img_capture(): try: import pygame.camera except: print " Error in importing pygame.camera" try: pygame.camera.init() cam = pygame.camera.Camera(0,(640,480)) print "Hold the book cover toward the webcam" time.sleep(3) print "Capturing image" cam.start() img = pygame.Surface((640,480)) cam.get_image(img) cover_img = pygame.image.save(img, "img.jpg") cam.stop() time.sleep(2) print "Image captured successfully" print "\n" except: print "There was some problem in capturing the image" #----------------------------------------------------------------------------------------------------------------------- # This function takes in the path to the cover image of the book as the input parameter. # This image is sent to the google reverse image search engine. # The value returned by the reverse image search is returned by the function. def cover_find(filePath): searchUrl = 'http://www.google.hr/searchbyimage/upload' multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''} response = requests.post(searchUrl,files = multipart,allow_redirects=False) url2 = response.headers['Location'] # If proper headers are not given google reverse search returns an empty list. So to get the reverse search name # always use the proper headers. headers = {'user-agent':"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"} r1 = requests.get(url2, headers = headers) data1 = r1.text soup1 = BeautifulSoup(data1,"html.parser") img_reverse = soup1.find_all("a",{"class":"_gUb"}) imgsch_name= img_reverse[0].text #The data that is extracted is of type 'unicode' .This must be converted to 'string 'before passing it to search() fn. return str(imgsch_name) #----------------------------------------------------------------------------------------------------------------------- def search(book_name): # The input is taken in by the user either by text input or by the 'text input field' or # the 'imgsch_name' returned by reverse search image of the book cover. headers = {'user-agent':"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"} para = {"q":book_name,"search_type":"books"} r =requests.get("https://www.goodreads.com/search?utf8=?",params=para,headers=headers) data = r.text soup = BeautifulSoup(data,"html.parser") search_result=soup.find_all("a",{"class":"bookTitle"}) search_list = [] search_url = [] for i in search_result: temp_title = i.span.text search_list.append(temp_title) search_url.append(i.get("href")) print str(search_result.index(i)+1)+ " " + temp_title return search_list,search_url #----------------------------------------------------------------------------------------------------------------------- # Extracts the required data about the book from 'goodreads.com '. # The data is returned by the function in a list. def book_data(url2): headers = {'user-agent':"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"} r =requests.get(url2,headers=headers) data = r.text soup = BeautifulSoup(data,"html.parser") book_desc = [] author_name = soup.find_all("span",{"itemprop":"name"}) book_desc.append(author_name[0].text) cover_name = soup.find_all("h1",{"id":"bookTitle"}) book_desc.append(cover_name[0].text) description = soup.find_all("div" , {"id" : "description"}) book_desc.append(description[0].text) rating = soup.find_all("span" , {"class" : "average"}) book_desc.append(rating[0].text) img_url = soup.find_all("img",{"id":"coverImage"}) book_desc.append(img_url) return book_desc #----------------------------------------------------------------------------------------------------------------------- def main(): print "How may i help you ? \n" \ "1. Book name \n" \ "2. Cover Image \n" \ "3. My books \n" selection = raw_input("Type the option number : ") try : if int(selection) == 1 : input_name = raw_input(" What is the name of the book : ") print("\n") ret_list,ret_url = search(input_name) print ("\n") option_sel = raw_input("Select the appropriate book : ") #print option_sel book_sel = ret_list[int(option_sel)-1] sel_bookurl = "https://www.goodreads.com" + ret_url[int(option_sel)-1] print book_sel,sel_bookurl print "---------------------------------------------------" book_desc = book_data(url2=sel_bookurl) #print book_desc for i in book_desc: print i + "\n" if int(selection) == 2 : #img = img_capture() #img_path= os.path.abspath(img) ret_name = cover_find(filePath="C:\Users\ANIRUDH\Desktop\python\img.jpg") ret_list,ret_url = search(book_name=ret_name) print "\n" option_sel = raw_input("Select the appropriate book number : ") book_sel = ret_list[int(option_sel)-1] sel_bookurl = "https://www.goodreads.com" + ret_url[int(option_sel)-1] print book_sel,sel_bookurl print "----------------------------------------------------------------------------------------------------" book_desc = book_data(url2=sel_bookurl) #print book_desc for i in book_desc: print i + "\n" if int(selection) == 3: pass except: print "Not a valid input" #----------------------------------------------------------------------------------------------------------------------- # This function creates a new database named 'book.db' # In case the database already exists the connection to the db is made. def book_db(): conn = sqlite3.connect(r"D:\PYTHON\book.db") cur = conn.cursor() try: cur.execute(""" CREATE TABLE BOOK ( NAME TEXT NOT NULL, AUTHOR TEXT NOT NULL, DESCRIPTION CHAR(50), RATING DECIMAL ); """) except: return conn,cur #----------------------------------------------------------------------------------------------------------------------- if __name__=="__main__": main()
{ "repo_name": "njanirudh/book-shelf-python", "path": "book-shelf.py", "copies": "1", "size": "7371", "license": "mit", "hash": -9070863007492723000, "line_mean": 31.047826087, "line_max": 131, "alpha_frac": 0.5234025234, "autogenerated": false, "ratio": 4.052226498075866, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5075629021475866, "avg_score": null, "num_lines": null }
__author__="Anjali Gopal Reddy" """ This is a nilearn based machine learning pipeline. Nilearn comes with code to simplify the use of scikit-learn when dealing with neuroimaging data. I have focussed on funcitonal MRI data The following steps were applied before using the machine learning tool 1. Data loading and preprocessing 2. Masking data 3. Resampling images 4. Temporal Filtering and confound removal""" import sys import nilearn def main(arg): #Invoke other functions here print("Menu!\n"); #To be extended, here provide the input files and invoke the functions following if __name__=='__main__': main(sys.argv[1]) def preprocessing(): #downloading the dataset here from nilearn import datasets dataset = datasets.fetch_haxby() list(sorted(dataset.keys())) dataset.func print(haxby_dataset['description']) def load_nonimage(): import numpy as np #behavioral information loading behavioral = np.recfromcsv(haxby_dataset.session_target[0], delimiter=" ") print(behavioral) condition_mask = np.logical_or(conditions == b'face', conditions == b'cat') # apply this mask in the sampe direction to restrict the # classification to the face vs cat discrimination fmri_masked = fmri_masked[condition_mask] def masking_data(): from nilearn.input_data import NiftiMasker masker = NiftiMasker(mask_img=mask_filename, standardize=True) #give the masker a filename and retrieve a 2D array ready # for machine learning with scikit-learn fmri_masked = masker.fit_transform(fmri_filename) def learning(): svc.fit(fmri_masked, conditions) ########################################################################### # predict the labels from the data prediction = svc.predict(fmri_masked) print(prediction) def unmasking(): coef_img = masker.inverse_transform(coef_) print(coef_img) def visualize(): from nilearn.plotting import plot_stat_map, show plot_stat_map(coef_img, bg_img=haxby_dataset.anat[0], title="SVM weights", display_mode="yx") show()
{ "repo_name": "anjaligr05/epilepsy_preprocessing", "path": "pipeline_ml_anjali.py", "copies": "1", "size": "1997", "license": "mit", "hash": 339043345237210500, "line_mean": 32.8474576271, "line_max": 191, "alpha_frac": 0.7255883826, "autogenerated": false, "ratio": 3.3847457627118644, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4610334145311864, "avg_score": null, "num_lines": null }
__author__ = 'ankesh' from .models import BenchmarkLogs, MachineInfo, RtAverage, RtBldg391, RtM35, RtMoss, RtSphflake, RtStar, RtWorld from django.db.models import Sum, Avg, get_model def avgVGRvsProcessorFamily(): """ Returns the aggregated data for Average VGR vs processor Family plot in the form of a dictionary. """ data_dict = {'chart_title': "Average VGR Rating vs Processor Family", 'chart_type': "bar", 'xaxis_title': "Processor Family", 'yaxis_title': "Average VGR Rating", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('vendor_id').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['vendor_id']) for processor in data_dict['categories']: approx_vgr_dict = MachineInfo.objects.filter(vendor_id=processor).aggregate(Avg('benchmark__approx_vgr')) value_pair = [processor, approx_vgr_dict['benchmark__approx_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def avgVGRvsOSType(): """ Returns the aggregated data for Average VGR vs OS Type plot in the form of a dictionary. """ data_dict = {'chart_title': "Average VGR Rating vs Operating System Type", 'chart_type': "bar", 'yaxis_title': "Average VGR Rating", 'xaxis_title': "Operating System Type", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('ostype').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['ostype']) for os in data_dict['categories']: approx_vgr_dict = MachineInfo.objects.filter(ostype=os).aggregate(Avg('benchmark__approx_vgr')) value_pair = [os, approx_vgr_dict['benchmark__approx_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def avgVGRvsNCores(): """ Returns the aggregated data for Average VGR vs Number of CPUs plot in the form of a dictionary. """ data_dict = {'chart_title': "Average VGR Rating vs Number of Cores", 'chart_type': "line", 'yaxis_title': "Average VGR Rating", 'xaxis_title': "Number of CPUs", 'categories': [], 'series_type': "single", 'values': []} distinct_number_dict = MachineInfo.objects.values('cores').distinct() for number in distinct_number_dict: data_dict['categories'].append(number['cores']) for number in data_dict['categories']: approx_vgr_dict = MachineInfo.objects.filter(cores=number).aggregate(Avg('benchmark__approx_vgr')) value_pair = [number, approx_vgr_dict['benchmark__approx_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def avgVGRvsNProcessors(): """ Returns the aggregated data for Average VGR vs Number of Processors plot in the form of a dictionary. """ data_dict = {'chart_title': "Average VGR Rating vs Number of Processors", 'chart_type': "line", 'yaxis_title': "Average VGR Rating", 'xaxis_title': "Number of Processors", 'categories': [], 'series_type': "single", 'values': []} distinct_number_dict = MachineInfo.objects.values('processors').distinct() for number in distinct_number_dict: data_dict['categories'].append(number['processors']) for number in data_dict['categories']: approx_vgr_dict = MachineInfo.objects.filter(processors=number).aggregate(Avg('benchmark__approx_vgr')) value_pair = [number, approx_vgr_dict['benchmark__approx_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def logVGRvsProcessorFamily(): """ Returns the aggregated data for Logarithmic VGR vs Processor Family plot in the form of a dictionary. """ data_dict = {'chart_title': "Logarithmic VGR Rating vs Processor Family", 'chart_type': "bar", 'xaxis_title': "Processor Family", 'yaxis_title': "Logarithmic VGR Rating", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('vendor_id').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['vendor_id']) for processor in data_dict['categories']: log_vgr_dict = MachineInfo.objects.filter(vendor_id=processor).aggregate(Avg('benchmark__log_vgr')) value_pair = [processor, log_vgr_dict['benchmark__log_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def logVGRvsOSType(): """ Returns the aggregated data for Logarithmic VGR vs OS Type plot in the form of a dictionary. """ data_dict = {'chart_title': "Average VGR Rating vs Operating System Type", 'chart_type': "bar", 'yaxis_title': "Average VGR Rating", 'xaxis_title': "Operating System Type", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('ostype').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['ostype']) for os in data_dict['categories']: log_vgr_dict = MachineInfo.objects.filter(ostype=os).aggregate(Avg('benchmark__log_vgr')) value_pair = [os, log_vgr_dict['benchmark__log_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def logVGRvsNCores(): """ Returns the aggregated data for Logarithmic VGR vs Number of CPUs plot in the form of a dictionary. """ data_dict = {'chart_title': "Logarithmic VGR Rating vs Number of Cores", 'chart_type': "line", 'yaxis_title': "Logarithmic VGR Rating", 'xaxis_title': "Number of CPUs", 'categories': [], 'series_type': "single", 'values': []} distinct_number_dict = MachineInfo.objects.values('cores').distinct() for number in distinct_number_dict: data_dict['categories'].append(number['cores']) for number in data_dict['categories']: log_vgr_dict = MachineInfo.objects.filter(cores=number).aggregate(Avg('benchmark__log_vgr')) value_pair = [number, log_vgr_dict['benchmark__log_vgr__avg']] data_dict['values'].append(value_pair) return data_dict def runningTimevsProcessorFamily(): """ Returns the aggregated data for Running Time vs processor Family plot in the form of a dictionary. """ data_dict = {'chart_title': "Running Time against Processor Family", 'chart_type': "bar", 'xaxis_title': "Processor Family", 'yaxis_title': "Running Time", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('vendor_id').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['vendor_id']) for processor in data_dict['categories']: running_time_dict = MachineInfo.objects.filter(vendor_id=processor).aggregate(Avg('benchmark__running_time')) value_pair = [processor, running_time_dict['benchmark__running_time__avg']] data_dict['values'].append(value_pair) return data_dict def runningTimevsOSType(): """ Returns the aggregated data for Running Time vs Operating System Type plot in the form of a dictionary. """ data_dict = {'chart_title': "Running Time against Operating System Type", 'chart_type': "bar", 'xaxis_title': "Operating System Type", 'yaxis_title': "Running Time (in sec)", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('ostype').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['ostype']) for os in data_dict['categories']: running_time_dict = MachineInfo.objects.filter(ostype=os).aggregate(Avg('benchmark__running_time')) value_pair = [os, running_time_dict['benchmark__running_time__avg']] data_dict['values'].append(value_pair) return data_dict def runningTimevsNCores(): """ Returns the aggregated data for Running Time vs Number of Cores plot in the form of a dictionary. """ data_dict = {'chart_title': "Running Time vs Number of Cores", 'chart_type': "line", 'xaxis_title': "Number of Cores", 'yaxis_title': "Running Time", 'categories': [], 'series_type': "single", 'values': []} distinct_categories_dict = MachineInfo.objects.values('cores').distinct() for category in distinct_categories_dict: data_dict['categories'].append(category['cores']) for number in data_dict['categories']: running_time_dict = MachineInfo.objects.filter(cores=number).aggregate(Avg('benchmark__running_time')) value_pair = [number, running_time_dict['benchmark__running_time__avg']] data_dict['values'].append(value_pair) return data_dict def absPerformancevsRefImages(): data_dict = {'chart_title': "Absolute Rays Per Sec against Reference Images", 'chart_type': "bar", 'xaxis_title': "Image", 'yaxis_title': "Absolute Rays per Sec", 'series_type': "single", 'categories': ["Moss", "World", "Star", "Bldg391", "M35", "Sphflake"], 'values': []} for category in data_dict['categories']: model_name = "Rt"+category model_class = get_model('plots', model_name) value_pair = [category, model_class.objects.all().aggregate(Avg('abs_rps'))['abs_rps__avg']] data_dict['values'].append(value_pair) return data_dict def processorFamiliesvsRefImages(): """ Returns the aggregated data for the performance of Processor Families against Reference Images plot in the form of a dictionary. """ data_dict = {'chart_title': "Performance of Processor Families against Reference Images", 'chart_type': "line", 'xaxis_title': "Image", 'yaxis_title': "Absolute Rays per Sec", 'series_type': "multi", 'categories': ["Moss", "World", "Star", "Bldg391", "M35", "Sphflake"], 'labels': [], 'values': []} processor_dict = MachineInfo.objects.values('vendor_id').distinct() series_data = [] for processor in processor_dict: for category in data_dict['categories']: model_name = 'Rt'+category field = model_name.lower() value_pair = [category, BenchmarkLogs.objects.filter(machineinfo__vendor_id=processor['vendor_id']) .aggregate(Avg(field+'__abs_rps'))[field+'__abs_rps__avg']] series_data.append(value_pair) data_dict['labels'].append(processor['vendor_id']) data_dict['values'].append(series_data) return data_dict def avgVGRvsCPUmhz(): """ Returns the aggregated data for Average VGR vs CPU MHz plot in the form of a dictionary. """ data_dict = {'chart_title': "Efficiency: Average VGR Rating vs CPU MHz", 'chart_type': "line", 'yaxis_title': "Average VGR Rating", 'xaxis_title': "CPU MHz", 'categories': [], 'series_type': "single", 'values': []} distinct_number_dict = MachineInfo.objects.values('cpu_mhz').distinct() for number in distinct_number_dict: data_dict['categories'].append(number['cpu_mhz']) for number in data_dict['categories']: approx_vgr_dict = MachineInfo.objects.filter(cpu_mhz=number).aggregate(Avg('benchmark__approx_vgr')) value_pair = [number, approx_vgr_dict['benchmark__approx_vgr__avg']] data_dict['values'].append(value_pair) return data_dict
{ "repo_name": "ankeshanand/benchmark", "path": "plots/data.py", "copies": "1", "size": "12630", "license": "bsd-2-clause", "hash": -5899356648686078000, "line_mean": 43.9501779359, "line_max": 117, "alpha_frac": 0.6005542359, "autogenerated": false, "ratio": 4.021012416427889, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0016365253084768645, "num_lines": 281 }
__author__ = 'ankit' import os from flask import Flask,request, redirect, Response from flask_wtf.csrf import CsrfProtect from backend import set from slashcommands import ndreminder,widgetview,echo from radio import mirchi,gaana import requests import json import re from bs4 import BeautifulSoup from pyflock import FlockClient, verify_event_token # You probably want to copy this entire line from pyflock import Message, SendAs, Attachment, Views, WidgetView, HtmlView, ImageView, Image, Download, Button, OpenWidgetAction, OpenBrowserAction, SendToAppAction app = Flask(__name__) csrf = CsrfProtect(app) @app.route('/events', methods=['post']) @csrf.exempt def doer(): #return redirect('https://github.com/ankit96/flockathon') #body_unicode = request.body.decode("utf-8") content = request.get_json(silent=True) name = content['name'] print str(name) if name=="app.install": userId = content['userId'] token = content['token'] #data = str(name)+","+str(userId)+","+str(token) set(name,userId,token) return json.dumps({'success':True}), 200, {'ContentType':'application/json'} elif name == "client.slashCommand": print "2nd elif" userId = content['userId'] userName = content['userName'] chat = content['chat'] chatName = content['chatName'] command = content['command'] text = content['text'] textarray=text.split(',') try: if textarray[0] == "list" and textarray[1] =="bollywood": data = mirchi() songlist = "" for a in data: if len(songlist)<2: songlist = a[0]+" " +a[1] else: songlist = songlist + "," +a[0] +" "+ a[1] #print songlist echo(str(name),str(userId),str(userName),str(chat),str(chatName),str(command),str(songlist)) elif textarray[0] == "list" and textarray[1] =="int": data = gaana() echo(str(name),str(userId),str(userName),str(chat),str(chatName),str(command),str(data)) else: echo(str(name),str(userId),str(userName),str(chat),str(chatName),str(command),str(text)) return json.dumps({'success':True,'text':'Done'}), 200, {'ContentType':'application/json'} except Exception as e: print str(e) @app.route('/') def hello(): return redirect('https://github.com/ankit96/flockathon') if __name__ == '__main__': port = int(os.environ.get('PORT',5000)) app.run(host='0.0.0.0', port=port)
{ "repo_name": "ankit96/flockathon", "path": "app.py", "copies": "1", "size": "2356", "license": "mit", "hash": -845193386968879700, "line_mean": 28.0864197531, "line_max": 166, "alpha_frac": 0.6735993209, "autogenerated": false, "ratio": 3.0797385620915034, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42533378829915036, "avg_score": null, "num_lines": null }
__author__ = 'ankit' import os from flask import Flask,request, redirect, Response from moodle import main from setuser import set,delete import requests import json import re from bs4 import BeautifulSoup app = Flask(__name__) @app.route('/moodle', methods=['post']) def moodler(): text = request.values.get('text') user_name = request.values.get('user_name') user_id = request.values.get('user_id') data = main(str(text)) if 'Invalid' in data and 'down' in data: data = "<@"+str(user_id)+'|'+str(user_name)+'>'+str(data) return Response(str(data),content_type="text/plain; charset=utf-8" ) else: data = "<@"+str(user_id)+'|'+str(user_name)+'>'+':Your upcoming submission deadlines'+'\n'+str(data) return Response(str(data),content_type="text/plain; charset=utf-8" ) @app.route('/setmoodle', methods=['post']) def setmoodler(): team_id = request.values.get('team_id') team_domain = request.values.get('team_domain') channel_id = request.values.get('channel_id') channel_name = request.values.get('channel_name') user_id = request.values.get('user_id') user_name = request.values.get('user_name') text = request.values.get('text') st=str(team_domain)+'%'+str(team_id)+'%'+str(channel_id)+'%'+str(channel_name)+'%'+str(user_id)+'%'+str(user_name)+'%'+str(text) data= set(str(st)) return Response(str(data),content_type="text/plain; charset=utf-8" ) @app.route('/') def hello(): return redirect('https://github.com/ankit96/moodler') @app.route('/deletemoodle', methods=['post']) def dell(): user_id = request.values.get('user_id') response = delete(user_id) return Response(str(response),content_type="text/plain; charset=utf-8" ) if __name__ == '__main__': port = int(os.environ.get('PORT',5000)) app.run(host='0.0.0.0', port=port)
{ "repo_name": "ankit96/moodler", "path": "app.py", "copies": "1", "size": "1870", "license": "mit", "hash": -1336090018442889200, "line_mean": 29.1612903226, "line_max": 132, "alpha_frac": 0.643315508, "autogenerated": false, "ratio": 3.0505709624796085, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41938864704796086, "avg_score": null, "num_lines": null }
__author__ = 'ank' from chr_sep_human import human_loop as p_loop from chr_sep_human import human_afterloop as p_afterloop import os, errno from pickle import load, dump from kivy.clock import Clock from mock import MagicMock, Mock def safe_mkdir(path): try: os.mkdir(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def count_images(path): namelist = [] for name in os.listdir(path): if os.path.isfile(os.path.join(path, name)) and name.split('.')[-1] in ['jpeg', 'jpg', 'tif',' tiff']: namelist.append(name) return len(namelist) def loop_dir(image_directory, widget): progress_bar, text_field = widget.progress_bar, widget.text_field progress_bar.value = 1 cim = count_images(image_directory) if not cim: t_to_add = 'Failed to find any .jpeg, .jpg, .tif or .tiff in the directory' text_field.text = text_field.text+t_to_add+'\n' progress_bar.value = 1000 widget.append_to_consommables(t_to_add) return '' increment = 1000/cim afterloop_list = [] buffer_directory = os.path.join(image_directory,'buffer') safe_mkdir(buffer_directory) for fle in os.listdir(image_directory): print fle prefix, suffix = ('_'.join(fle.split('.')[:-1]), fle.split('.')[-1]) if suffix in ['jpeg', 'jpg', 'tif',' tiff']: buffer_path = os.path.join(buffer_directory, prefix) pre_time = p_loop(buffer_path, os.path.join(image_directory,fle), widget.stack_type) t_to_add = "file %s pre-processed in %s seconds" %(fle, "{0:.2f}".format(pre_time)) afterloop_list.append((pre_time, prefix, buffer_path)) progress_bar.value = progress_bar.value + increment widget.append_to_consommables(t_to_add) dump((image_directory, afterloop_list), open('DO_NOT_TOUCH.dmp','wb')) progress_bar.value = 1000 return '' def loop_fle(image_directory, file, widget): progress_bar, text_field = widget.progress_bar, widget.text_field progress_bar.value = 300 widget.append_to_consommables('starting to process fle %s'%file) afterloop_list = [] buffer_directory = os.path.join(image_directory,'buffer') safe_mkdir(buffer_directory) prefix, suffix = ('_'.join(file.split('.')[:-1]), file.split('.')[-1]) if suffix in ['jpeg', 'jpg', 'tif',' tiff']: buffer_path = os.path.join(buffer_directory, prefix) print buffer_path safe_mkdir(buffer_path) pre_time = p_loop(buffer_path, os.path.join(image_directory, file), widget.stack_type) t_to_add = "file %s pre-processed in %s seconds" %(file, "{0:.2f}".format(pre_time)) afterloop_list.append((pre_time, prefix, buffer_path)) else: t_to_add = 'file %s has a wrong extension'%file widget.append_to_consommables(t_to_add) progress_bar.value = 1000 dump((image_directory, afterloop_list), open('DO_NOT_TOUCH.dmp', 'wb')) return '' def afterloop(widget): progress_bar, text_field = widget.progress_bar, widget.text_field imdir, afterloop_list = load(open('DO_NOT_TOUCH.dmp','rb')) output_directory = os.path.join(imdir, 'output') safe_mkdir(output_directory) for pre_time, fle_name, buffer_path in afterloop_list: t_to_add = p_afterloop(output_directory, pre_time, fle_name, buffer_path) text_field.text = text_field.text+t_to_add+'\n' class progbar(object): def __init__(self): self.value = 0 class text_fields(object): def __init__(self): self.text = '' class wdg(object): def __init__(self, st_tp): self.progress_bar = progbar() self.text_field = text_fields() self.stack_type = st_tp if __name__ == "__main__": fname = 'img_000000002__000.tif' test_f = 'L:/Akn/mammalian/human chromosome spreads/10-7-14 rpe/rpe WT/rpe WT images 2' st_tp = 0 loop_fle(test_f, fname, wdg(st_tp)) afterloop(wdg(st_tp)) pass
{ "repo_name": "chiffa/Chromosome_counter", "path": "core_app_methods.py", "copies": "1", "size": "4048", "license": "bsd-3-clause", "hash": -8761346151646621000, "line_mean": 35.8, "line_max": 110, "alpha_frac": 0.6277173913, "autogenerated": false, "ratio": 3.207606973058637, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4335324364358637, "avg_score": null, "num_lines": null }
__author__ = 'ank' import numpy as np import matplotlib.pyplot as plt import PIL from time import time import mdp from itertools import product from skimage.segmentation import random_walker, mark_boundaries # TODO: try using the data for the edge detection by assigning a null label to all the edge detectors, so that the data is recovered by diffusion from a skeleton def import_image(): ImageRoot = '/home/ank/projects_files/2014/Image_recognition/' suffix = '/img_11.tif' # suffix = '/img_4jpg.jpeg' col = PIL.Image.open(ImageRoot + suffix) gray = col.convert('L') bw = np.asarray(gray).copy() bw = bw - np.min(bw) bw = bw.astype(np.float64)/float(np.max(bw)) return bw def gabor(bw_image, freq, scale, scale_distortion=1.): # gabor filter normalization with respect to the surface convolution def check_integral(gabor_filter): ones = np.ones(gabor_filter.shape) avg = np.average(ones*gabor_filter) return gabor_filter-avg quality = 16 pi = np.pi orientations = np.arange(0., pi, pi/quality).tolist() phis = [pi/2, pi] size = (10, 10) sgm = (5*scale, 3*scale*scale_distortion) nfilters = len(orientations)*len(phis) gabors = np.empty((nfilters, size[0], size[1])) for i, (alpha, phi) in enumerate(product(orientations, phis)): arr = mdp.utils.gabor(size, alpha, phi, freq, sgm) arr = check_integral(arr) gabors[i,:,:] = arr # plt.subplot(6,6,i+1) # plt.title('%s, %s, %s, %s'%('{0:.2f}'.format(alpha), '{0:.2f}'.format(phi), freq, sgm)) # plt.imshow(arr, cmap = 'gray', interpolation='nearest') # plt.show() node = mdp.nodes.Convolution2DNode(gabors, mode='valid', boundary='fill', fillvalue=0, output_2d=False) cim = node.execute(bw[np.newaxis, :, :]) sum1 = np.zeros(cim[0, 0,:,:].shape) col1 = np.zeros((cim[0,:,:,:].shape[0]/2, cim[0,:,:,:].shape[1], cim[0,:,:,:].shape[2])) sum2 = np.zeros(cim[0, 0,:,:].shape) col2 = np.zeros((cim[0,:,:,:].shape[0]/2, cim[0,:,:,:].shape[1], cim[0,:,:,:].shape[2])) for i in range(0, nfilters): pr_cim = cim[0,i,:,:] if i%2 == 0: sum1 = sum1 + np.abs(pr_cim) col1[i/2,:,:] = pr_cim else: sum2 = sum2 - pr_cim col2[i/2,:,:] = np.abs(pr_cim) sum2[sum2>0] = sum2[sum2>0]/np.max(sum2) sum2[sum2<0] = -sum2[sum2<0]/np.min(sum2) return sum1/np.max(sum1), sum2, col1, col2, # two last ones just in case. def cluster_by_diffusion(data): markers = np.zeros(data.shape, dtype=np.uint) markers[data < -0.00] = 1 markers[data > 0.03] = 2 labels2 = random_walker(data, markers, beta=10, mode='bf') return labels2 if __name__ == "__main__": start = time() bw = import_image() sum1, sum2, _, _= gabor(bw, 1/4., 0.5) # The separator is acting here: sum10, sum20, _, _ = gabor(bw, 1/4., 0.25, 3) sum20[sum20>-0.3]=0 sum2 = sum2 + sum20 sum22 = np.copy(sum2) sum22[sum2<0] = 0 d_c = cluster_by_diffusion(sum2) # align to same shape rebw = bw[4:, :][:,4:] plt.subplot(2,2,1) plt.title('Original image') plt.imshow(bw, cmap = 'gray', interpolation='nearest') plt.subplot(2,2,2) plt.title('Gabor - line detector') plt.imshow(sum2, cmap = 'gray', interpolation='nearest') plt.colorbar() plt.subplot(2,2,3) plt.title('Gabor - line detector, positive compound only') plt.imshow(sum22, cmap = 'gray', interpolation='nearest') plt.colorbar() plt.subplot(2,2,4) plt.title('Segmentation - total time %s'%"{0:.2f}".format(time()-start)) plt.imshow(mark_boundaries(rebw, d_c)) plt.show()
{ "repo_name": "chiffa/Chromosome_counter", "path": "chr_sep_mouse.py", "copies": "1", "size": "3723", "license": "bsd-3-clause", "hash": -2138556363142463500, "line_mean": 30.8205128205, "line_max": 161, "alpha_frac": 0.5976363148, "autogenerated": false, "ratio": 2.839816933638444, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3937453248438444, "avg_score": null, "num_lines": null }
__author__ = 'ank' import numpy as np import matplotlib.pyplot as plt import PIL import mdp from itertools import product from pickle import load, dump from os import path from time import time from skimage.segmentation import random_walker, mark_boundaries from skimage.morphology import convex_hull_image, label, dilation, disk from skimage.filter import gaussian_filter from skimage.measure import perimeter from matplotlib import colors from pylab import get_cmap # from skimage.measure import label # todo and management for varying window sizes for Gabor filters # todo: darkest spot => in testing # todo: threshold-filtering instead of diffusion clustering # todo: selem = disk(20) debug = False timing = False plt.figure(figsize=(30.0, 20.0)) def rs(matrix, name): plt.title(name) plt.imshow(matrix, interpolation='nearest') plt.colorbar() if debug: plt.show() plt.clf() def debug_wrapper(funct): def check_matrix(*args,**kwargs): result = funct(*args, **kwargs) if debug: if type(result) is not tuple: rs(result, funct.__name__) else: rs(result[0], funct.__name__) check_matrix.__name__ = funct.__name__ check_matrix.__doc__ = funct.__doc__ return result return check_matrix def time_wrapper(funct): def time_execution(*args,**kwargs): start = time() result = funct(*args, **kwargs) if timing: print funct.__name__, time()-start time_execution.__doc__ = funct.__doc__ return result return time_execution @time_wrapper @debug_wrapper def import_image(image_to_load): gray = PIL.Image.open(image_to_load).convert('L') bw = np.asarray(gray) bw = bw - np.min(bw) bw = bw.astype(np.float64)/float(np.max(bw)) return bw @time_wrapper @debug_wrapper def import_edited(buffer_directory): if path.exists(buffer_directory+'-'+"EDIT_ME2.tif"): col = PIL.Image.open(buffer_directory+'-'+"EDIT_ME2.tif") else: col = PIL.Image.open(buffer_directory+'-'+"EDIT_ME.tif") gray = col.convert('L') bw = np.asarray(gray).copy() bw[bw<=120] = 0 bw[bw>120] = 1 return bw @time_wrapper @debug_wrapper def gabor(bw_image, freq, scale, scale_distortion=1., self_cross=False, field=10, phi=np.pi, abes=False): # gabor filter normalization with respect to the surface convolution def check_integral(gabor_filter): ones = np.ones(gabor_filter.shape) avg = np.average(ones*gabor_filter) return gabor_filter-avg quality = 16 pi = np.pi orientations = np.arange(0., pi, pi/quality).tolist() size = (field, field) sgm = (5*scale, 3*scale*scale_distortion) nfilters = len(orientations) gabors = np.empty((nfilters, size[0], size[1])) for i, alpha in enumerate(orientations): arr = mdp.utils.gabor(size, alpha, phi, freq, sgm) if self_cross: if self_cross == 1: arr = np.minimum(arr, mdp.utils.gabor(size, alpha+pi/2, phi, freq, sgm)) if self_cross == 2: arr -= mdp.utils.gabor(size, alpha+pi/2, phi, freq, sgm) arr = check_integral(arr) gabors[i, :, :] = arr if debug: plt.subplot(6, 6, i+1) plt.title('%s, %s, %s, %s'%('{0:.2f}'.format(alpha), '{0:.2f}'.format(phi), freq, sgm)) plt.imshow(arr, cmap = 'gray', interpolation='nearest') if debug: plt.show() plt.clf() node = mdp.nodes.Convolution2DNode(gabors, mode='valid', boundary='fill', fillvalue=0, output_2d=False) cim = node.execute(bw_image[np.newaxis, :, :])[0, :, :, :] re_cim = np.zeros((cim.shape[0], cim.shape[1] + field - 1, cim.shape[2] + field - 1)) re_cim[:, field/2-1:-field/2, field/2-1:-field/2] = cim cim = re_cim if abes: sum2 = np.sum(np.abs(cim), axis=0) sum2 /= np.max(sum2) else: sum2 = - np.sum(cim, axis=0) sum2[sum2>0] /= np.max(sum2) sum2[sum2<0] /= -np.min(sum2) return sum2, cim @time_wrapper @debug_wrapper def cluster_by_diffusion(data): markers = np.zeros(data.shape, dtype=np.uint8) markers[data < -0.15] = 1 markers[data > 0.15] = 2 labels2 = random_walker(data, markers, beta=10, mode='cg_mg') return labels2 @time_wrapper @debug_wrapper def cluster_process(labels, original, activations): rbase = np.zeros(labels.shape) rubase = np.zeros(labels.shape) rubase[range(0,20),:] = 1 rubase[:,range(0,20)] = 1 rubase[range(-20,-1),:] = 1 rubase[:,range(-20,-1)] = 1 for i in range(1, int(np.max(labels))+1): base = np.zeros(labels.shape) base[labels==i] = 1 li = len(base.nonzero()[0]) if li>0: hull = convex_hull_image(base) lh =len(hull.nonzero()[0]) sel_org = base*original sel_act = base*activations cond = (li > 4000 and float(lh) / float(li) < 1.07 and perimeter(base)**2.0 / li < 30) or np.max(base * rubase) > 0.5 # print li>4000 and float(lh)/float(li)<1.07, perimeter(base)**2.0/li<30, np.max(base*rubase)>0.5, np.min(original[base>0]) hard_array =[li > 4000, float(lh) / float(li) < 1.07] optional_array = [perimeter(base)**2.0/li < 25, np.percentile(sel_org[sel_org>0], 5) > 0.2, np.percentile(sel_act, 90) - np.percentile(sel_act, 90)] print hard_array, optional_array if debug and li>1000: rs(base,'subspread cluster') if cond: rbase = rbase + base rbase[rubase.astype(np.bool)] = 1 return dilation(rbase, selem) @time_wrapper def repaint_culsters(clusterNo=100): prism_cmap = get_cmap('prism') prism_vals = prism_cmap(np.arange(clusterNo)) prism_vals[0] = [0, 0, 0, 1] costum_cmap = colors.LinearSegmentedColormap.from_list('my_colormap', prism_vals) return costum_cmap @time_wrapper @debug_wrapper def compare_orthogonal_selectors(voluminal_crossed_matrix): var2 = np.max(voluminal_crossed_matrix - np.roll(voluminal_crossed_matrix, voluminal_crossed_matrix.shape[0]/2, 0), axis=0) var2 /= np.max(var2) return var2 @time_wrapper def human_loop(buffer_directory, image_to_import, stack_type): start = time() bw = import_image(image_to_import) lbw = np.log(bw+0.001) lbw = lbw - np.min(lbw) lbw = lbw/np.max(lbw) # rs(lbw, 'log-bw') sum1, _ = gabor(lbw, 1/32., 2, scale_distortion=2., field=40, phi=np.pi/2, abes=True) if stack_type == 0: # Human sum2,_ = gabor(bw, 1/8., 1, self_cross=1, field=20) sum20,_ = gabor(bw, 1/6., 1, field=20) sum20[sum20>-0.2] = 0 sum2 = sum2 + sum20 elif stack_type == 1: # Mice sum2,_ = gabor(bw, 1/8., 1, field=20) sum20,_ = gabor(bw, 1/4., 0.5, field=20) sum20[sum20>-0.1] = 0 sum2 = sum2 + sum20 # crossed antisense selctor _, st = gabor(bw, 1/8., 1, self_cross=2, field=20) sum20 = compare_orthogonal_selectors(st) sum20[sum20<0.65] = 0 if debug: rs(sum20, 'selected cross') sum2 = sum2 - sum20 else: raise Exception('Unrecognized chromosome type') if debug: rs(sum2, 'sum2-definitive') bw_blur = gaussian_filter(lbw, 5) bwth = np.zeros(bw_blur.shape) # if debug: # plt.hist(bw) # plt.show() # plt.hist(bw_blur) # plt.show() bwth[bw_blur > np.percentile(bw_blur, 80)] = 1 #<"we need somehow to adjust this in a non-parametric way." # plt.hist(bw_blur) # plt.show() bwth[sum1 > 0.45] = 0 clsts = (label(bwth)+1)*bwth # rs(clsts, 'cluster_labels') rbase = cluster_process(clsts, bw, sum2) rim = PIL.Image.fromarray((rbase*254).astype(np.uint8)) rim.save(buffer_directory+'-'+"I_AM_UNBROKEN_NUCLEUS.bmp") sum22 = np.copy(sum2) sum22[sum2<0] = 0 d_c = cluster_by_diffusion(sum2) reim = PIL.Image.fromarray((bw/np.max(bw)*254).astype(np.uint8)) reim.save(buffer_directory+'-'+"I_AM_THE_ORIGINAL.tif") seg_dc = (label(d_c, neighbors=4)+1)*(d_c-1) redd = set(seg_dc[rbase>0.01].tolist()) for i in redd: seg_dc[seg_dc==i] = 0 d_c = d_c*0 d_c[seg_dc>0] = 1 int_arr = np.asarray(np.dstack((d_c*254, d_c*254, d_c*0)), dtype=np.uint8) if debug: rs(int_arr, 'segmentation mask') msk = PIL.Image.fromarray(int_arr) msk.save(buffer_directory+'-'+"EDIT_ME.tif") dump(bw ,open(buffer_directory+'-'+'DO_NOT_TOUCH_ME.dmp','wb')) return time()-start @time_wrapper def human_afterloop(output_directory, pre_time, fle_name, buffer_directory): start2 = time() d_c = import_edited(buffer_directory) rebw = load(open(buffer_directory+'-'+'DO_NOT_TOUCH_ME.dmp','rb')) seg_dc = (label(d_c,neighbors=4)+1)*d_c if np.max(seg_dc)<4: return 'FAILED: mask for %s looks unsegmented' % fle_name colormap = repaint_culsters(int(np.max(seg_dc))) segs = len(set(seg_dc.flatten().tolist()))-1 # shows the result before saving the clustering and printing to the user the number of the images plt.subplot(1,2,1) plt.title(fle_name) plt.imshow(rebw, cmap='gray', interpolation='nearest') plt.subplot(1,2,2) plt.title('Segmentation - clusters: %s'%str(segs)) plt.imshow(mark_boundaries(rebw, d_c)) plt.imshow(seg_dc, cmap=colormap, interpolation='nearest', alpha=0.3) plt.show() plt.imshow(mark_boundaries(rebw, d_c)) plt.imshow(seg_dc, cmap=colormap, interpolation='nearest', alpha=0.3) plt.savefig(path.join(output_directory, fle_name+'_%s_clusters.png'%str(segs)), dpi=500, bbox_inches='tight', pad_inches=0.0) return fle_name+'\t clusters: %s,\t total time : %s'%(segs, "{0:.2f}".format(time()-start2+pre_time)) if __name__ == "__main__": pass
{ "repo_name": "chiffa/Chromosome_counter", "path": "chr_sep_human.py", "copies": "1", "size": "10016", "license": "bsd-3-clause", "hash": -4696142811031459000, "line_mean": 30.9012738854, "line_max": 135, "alpha_frac": 0.6007388179, "autogenerated": false, "ratio": 2.9346615880457074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4035400405945707, "avg_score": null, "num_lines": null }
""" Entry-point for generating synthetic text images, as described in: @InProceedings{Gupta16, author = "Gupta, A. and Vedaldi, A. and Zisserman, A.", title = "Synthetic Data for Text Localisation in Natural Images", booktitle = "IEEE Conference on Computer Vision and Pattern Recognition", year = "2016", } """ import numpy as np import h5py import os, sys, traceback import os.path as osp from synthgen import * from common import * import wget, tarfile ## Define some configuration variables: NUM_IMG = -1 # no. of images to use for generation (-1 to use all available): INSTANCE_PER_IMAGE = 1 # no. of times to use the same image SECS_PER_IMG = 5 #max time per image in seconds # path to the data-file, containing image, depth and segmentation: DATA_PATH = 'data' DB_FNAME = osp.join(DATA_PATH,'dset.h5') # url of the data (google-drive public file): DATA_URL = 'http://www.robots.ox.ac.uk/~ankush/data.tar.gz' OUT_FILE = 'results/SynthText.h5' def get_data(): """ Download the image,depth and segmentation data: Returns, the h5 database. """ if not osp.exists(DB_FNAME): try: colorprint(Color.BLUE,'\tdownloading data (56 M) from: '+DATA_URL,bold=True) print sys.stdout.flush() out_fname = 'data.tar.gz' wget.download(DATA_URL,out=out_fname) tar = tarfile.open(out_fname) tar.extractall() tar.close() os.remove(out_fname) colorprint(Color.BLUE,'\n\tdata saved at:'+DB_FNAME,bold=True) sys.stdout.flush() except: print colorize(Color.RED,'Data not found and have problems downloading.',bold=True) sys.stdout.flush() sys.exit(-1) # open the h5 file and return: return h5py.File(DB_FNAME,'r') def add_res_to_db(imgname,res,db): """ Add the synthetically generated text image instance and other metadata to the dataset. """ ninstance = len(res) for i in xrange(ninstance): dname = "%s_%d"%(imgname, i) db['data'].create_dataset(dname,data=res[i]['img']) db['data'][dname].attrs['charBB'] = res[i]['charBB'] db['data'][dname].attrs['wordBB'] = res[i]['wordBB'] db['data'][dname].attrs['txt'] = res[i]['txt'] def main(viz=False): # open databases: print colorize(Color.BLUE,'getting data..',bold=True) db = get_data() print colorize(Color.BLUE,'\t-> done',bold=True) # open the output h5 file: out_db = h5py.File(OUT_FILE,'w') out_db.create_group('/data') print colorize(Color.GREEN,'Storing the output in: '+OUT_FILE, bold=True) # get the names of the image files in the dataset: imnames = sorted(db['image'].keys()) N = len(imnames) global NUM_IMG if NUM_IMG < 0: NUM_IMG = N start_idx,end_idx = 0,min(NUM_IMG, N) RV3 = RendererV3(DATA_PATH,max_time=SECS_PER_IMG) for i in xrange(start_idx,end_idx): imname = imnames[i] try: # get the image: img = Image.fromarray(db['image'][imname][:]) # get the pre-computed depth: # there are 2 estimates of depth (represented as 2 "channels") # here we are using the second one (in some cases it might be # useful to use the other one): depth = db['depth'][imname][:].T depth = depth[:,:,1] # get segmentation: seg = db['seg'][imname][:].astype('float32') area = db['seg'][imname].attrs['area'] label = db['seg'][imname].attrs['label'] # re-size uniformly: sz = depth.shape[:2][::-1] img = np.array(img.resize(sz,Image.ANTIALIAS)) seg = np.array(Image.fromarray(seg).resize(sz,Image.NEAREST)) print colorize(Color.RED,'%d of %d'%(i,end_idx-1), bold=True) res = RV3.render_text(img,depth,seg,area,label, ninstance=INSTANCE_PER_IMAGE,viz=viz) if len(res) > 0: # non-empty : successful in placing text: add_res_to_db(imname,res,out_db) # visualize the output: if viz: if 'q' in raw_input(colorize(Color.RED,'continue? (enter to continue, q to exit): ',True)): break except: traceback.print_exc() print colorize(Color.GREEN,'>>>> CONTINUING....', bold=True) continue db.close() out_db.close() if __name__=='__main__': import argparse parser = argparse.ArgumentParser(description='Genereate Synthetic Scene-Text Images') parser.add_argument('--viz',action='store_true',dest='viz',default=False,help='flag for turning on visualizations') args = parser.parse_args() main(args.viz)
{ "repo_name": "ankush-me/SynthText", "path": "gen.py", "copies": "1", "size": "4535", "license": "apache-2.0", "hash": -4000557173590476300, "line_mean": 31.4, "line_max": 117, "alpha_frac": 0.6363836825, "autogenerated": false, "ratio": 3.16911250873515, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.430549619123515, "avg_score": null, "num_lines": null }
""" Main script for synthetic text rendering. """ from __future__ import division import copy import cv2 import h5py from PIL import Image import numpy as np #import mayavi.mlab as mym import matplotlib.pyplot as plt import os.path as osp import scipy.ndimage as sim import scipy.spatial.distance as ssd import synth_utils as su import text_utils as tu from colorize3_poisson import Colorize from common import * import traceback, itertools class TextRegions(object): """ Get region from segmentation which are good for placing text. """ minWidth = 30 #px minHeight = 30 #px minAspect = 0.3 # w > 0.3*h maxAspect = 7 minArea = 100 # number of pix pArea = 0.60 # area_obj/area_minrect >= 0.6 # RANSAC planar fitting params: dist_thresh = 0.10 # m num_inlier = 90 ransac_fit_trials = 100 min_z_projection = 0.25 minW = 20 @staticmethod def filter_rectified(mask): """ mask : 1 where "ON", 0 where "OFF" """ wx = np.median(np.sum(mask,axis=0)) wy = np.median(np.sum(mask,axis=1)) return wx>TextRegions.minW and wy>TextRegions.minW @staticmethod def get_hw(pt,return_rot=False): pt = pt.copy() R = su.unrotate2d(pt) mu = np.median(pt,axis=0) pt = (pt-mu[None,:]).dot(R.T) + mu[None,:] h,w = np.max(pt,axis=0) - np.min(pt,axis=0) if return_rot: return h,w,R return h,w @staticmethod def filter(seg,area,label): """ Apply the filter. The final list is ranked by area. """ good = label[area > TextRegions.minArea] area = area[area > TextRegions.minArea] filt,R = [],[] for idx,i in enumerate(good): mask = seg==i xs,ys = np.where(mask) coords = np.c_[xs,ys].astype('float32') rect = cv2.minAreaRect(coords) box = np.array(cv2.boxPoints(rect)) h,w,rot = TextRegions.get_hw(box,return_rot=True) f = (h > TextRegions.minHeight and w > TextRegions.minWidth and TextRegions.minAspect < w/h < TextRegions.maxAspect and area[idx]/w*h > TextRegions.pArea) filt.append(f) R.append(rot) # filter bad regions: filt = np.array(filt) area = area[filt] R = [R[i] for i in xrange(len(R)) if filt[i]] # sort the regions based on areas: aidx = np.argsort(-area) good = good[filt][aidx] R = [R[i] for i in aidx] filter_info = {'label':good, 'rot':R, 'area': area[aidx]} return filter_info @staticmethod def sample_grid_neighbours(mask,nsample,step=3): """ Given a HxW binary mask, sample 4 neighbours on the grid, in the cardinal directions, STEP pixels away. """ if 2*step >= min(mask.shape[:2]): return #None y_m,x_m = np.where(mask) mask_idx = np.zeros_like(mask,'int32') for i in xrange(len(y_m)): mask_idx[y_m[i],x_m[i]] = i xp,xn = np.zeros_like(mask), np.zeros_like(mask) yp,yn = np.zeros_like(mask), np.zeros_like(mask) xp[:,:-2*step] = mask[:,2*step:] xn[:,2*step:] = mask[:,:-2*step] yp[:-2*step,:] = mask[2*step:,:] yn[2*step:,:] = mask[:-2*step,:] valid = mask&xp&xn&yp&yn ys,xs = np.where(valid) N = len(ys) if N==0: #no valid pixels in mask: return #None nsample = min(nsample,N) idx = np.random.choice(N,nsample,replace=False) # generate neighborhood matrix: # (1+4)x2xNsample (2 for y,x) xs,ys = xs[idx],ys[idx] s = step X = np.transpose(np.c_[xs,xs+s,xs+s,xs-s,xs-s][:,:,None],(1,2,0)) Y = np.transpose(np.c_[ys,ys+s,ys-s,ys+s,ys-s][:,:,None],(1,2,0)) sample_idx = np.concatenate([Y,X],axis=1) mask_nn_idx = np.zeros((5,sample_idx.shape[-1]),'int32') for i in xrange(sample_idx.shape[-1]): mask_nn_idx[:,i] = mask_idx[sample_idx[:,:,i][:,0],sample_idx[:,:,i][:,1]] return mask_nn_idx @staticmethod def filter_depth(xyz,seg,regions): plane_info = {'label':[], 'coeff':[], 'support':[], 'rot':[], 'area':[]} for idx,l in enumerate(regions['label']): mask = seg==l pt_sample = TextRegions.sample_grid_neighbours(mask,TextRegions.ransac_fit_trials,step=3) if pt_sample is None: continue #not enough points for RANSAC # get-depths pt = xyz[mask] plane_model = su.isplanar(pt, pt_sample, TextRegions.dist_thresh, TextRegions.num_inlier, TextRegions.min_z_projection) if plane_model is not None: plane_coeff = plane_model[0] if np.abs(plane_coeff[2])>TextRegions.min_z_projection: plane_info['label'].append(l) plane_info['coeff'].append(plane_model[0]) plane_info['support'].append(plane_model[1]) plane_info['rot'].append(regions['rot'][idx]) plane_info['area'].append(regions['area'][idx]) return plane_info @staticmethod def get_regions(xyz,seg,area,label): regions = TextRegions.filter(seg,area,label) # fit plane to text-regions: regions = TextRegions.filter_depth(xyz,seg,regions) return regions def rescale_frontoparallel(p_fp,box_fp,p_im): """ The fronto-parallel image region is rescaled to bring it in the same approx. size as the target region size. p_fp : nx2 coordinates of countour points in the fronto-parallel plane box : 4x2 coordinates of bounding box of p_fp p_im : nx2 coordinates of countour in the image NOTE : p_fp and p are corresponding, i.e. : p_fp[i] ~ p[i] Returns the scale 's' to scale the fronto-parallel points by. """ l1 = np.linalg.norm(box_fp[1,:]-box_fp[0,:]) l2 = np.linalg.norm(box_fp[1,:]-box_fp[2,:]) n0 = np.argmin(np.linalg.norm(p_fp-box_fp[0,:][None,:],axis=1)) n1 = np.argmin(np.linalg.norm(p_fp-box_fp[1,:][None,:],axis=1)) n2 = np.argmin(np.linalg.norm(p_fp-box_fp[2,:][None,:],axis=1)) lt1 = np.linalg.norm(p_im[n1,:]-p_im[n0,:]) lt2 = np.linalg.norm(p_im[n1,:]-p_im[n2,:]) s = max(lt1/l1,lt2/l2) if not np.isfinite(s): s = 1.0 return s def get_text_placement_mask(xyz,mask,plane,pad=2,viz=False): """ Returns a binary mask in which text can be placed. Also returns a homography from original image to this rectified mask. XYZ : (HxWx3) image xyz coordinates MASK : (HxW) : non-zero pixels mark the object mask REGION : DICT output of TextRegions.get_regions PAD : number of pixels to pad the placement-mask by """ _, contour, hier = cv2.findContours(mask.copy().astype('uint8'), mode=cv2.RETR_CCOMP, method=cv2.CHAIN_APPROX_SIMPLE) contour = [np.squeeze(c).astype('float') for c in contour] #plane = np.array([plane[1],plane[0],plane[2],plane[3]]) H,W = mask.shape[:2] # bring the contour 3d points to fronto-parallel config: pts,pts_fp = [],[] center = np.array([W,H])/2 n_front = np.array([0.0,0.0,-1.0]) for i in xrange(len(contour)): cnt_ij = contour[i] xyz = su.DepthCamera.plane2xyz(center, cnt_ij, plane) R = su.rot3d(plane[:3],n_front) xyz = xyz.dot(R.T) pts_fp.append(xyz[:,:2]) pts.append(cnt_ij) # unrotate in 2D plane: rect = cv2.minAreaRect(pts_fp[0].copy().astype('float32')) box = np.array(cv2.boxPoints(rect)) R2d = su.unrotate2d(box.copy()) box = np.vstack([box,box[0,:]]) #close the box for visualization mu = np.median(pts_fp[0],axis=0) pts_tmp = (pts_fp[0]-mu[None,:]).dot(R2d.T) + mu[None,:] boxR = (box-mu[None,:]).dot(R2d.T) + mu[None,:] # rescale the unrotated 2d points to approximately # the same scale as the target region: s = rescale_frontoparallel(pts_tmp,boxR,pts[0]) boxR *= s for i in xrange(len(pts_fp)): pts_fp[i] = s*((pts_fp[i]-mu[None,:]).dot(R2d.T) + mu[None,:]) # paint the unrotated contour points: minxy = -np.min(boxR,axis=0) + pad//2 ROW = np.max(ssd.pdist(np.atleast_2d(boxR[:,0]).T)) COL = np.max(ssd.pdist(np.atleast_2d(boxR[:,1]).T)) place_mask = 255*np.ones((int(np.ceil(COL))+pad, int(np.ceil(ROW))+pad), 'uint8') pts_fp_i32 = [(pts_fp[i]+minxy[None,:]).astype('int32') for i in xrange(len(pts_fp))] cv2.drawContours(place_mask,pts_fp_i32,-1,0, thickness=cv2.FILLED, lineType=8,hierarchy=hier) if not TextRegions.filter_rectified((~place_mask).astype('float')/255): return # calculate the homography H,_ = cv2.findHomography(pts[0].astype('float32').copy(), pts_fp_i32[0].astype('float32').copy(), method=0) Hinv,_ = cv2.findHomography(pts_fp_i32[0].astype('float32').copy(), pts[0].astype('float32').copy(), method=0) if viz: plt.subplot(1,2,1) plt.imshow(mask) plt.subplot(1,2,2) plt.imshow(~place_mask) plt.hold(True) for i in xrange(len(pts_fp_i32)): plt.scatter(pts_fp_i32[i][:,0],pts_fp_i32[i][:,1], edgecolors='none',facecolor='g',alpha=0.5) plt.show() return place_mask,H,Hinv def viz_masks(fignum,rgb,seg,depth,label): """ img,depth,seg are images of the same size. visualizes depth masks for top NOBJ objects. """ def mean_seg(rgb,seg,label): mim = np.zeros_like(rgb) for i in np.unique(seg.flat): mask = seg==i col = np.mean(rgb[mask,:],axis=0) mim[mask,:] = col[None,None,:] mim[seg==0,:] = 0 return mim mim = mean_seg(rgb,seg,label) img = rgb.copy() for i,idx in enumerate(label): mask = seg==idx rgb_rand = (255*np.random.rand(3)).astype('uint8') img[mask] = rgb_rand[None,None,:] #import scipy # scipy.misc.imsave('seg.png', mim) # scipy.misc.imsave('depth.png', depth) # scipy.misc.imsave('txt.png', rgb) # scipy.misc.imsave('reg.png', img) plt.close(fignum) plt.figure(fignum) ims = [rgb,mim,depth,img] for i in xrange(len(ims)): plt.subplot(2,2,i+1) plt.imshow(ims[i]) plt.show(block=False) def viz_regions(img,xyz,seg,planes,labels): """ img,depth,seg are images of the same size. visualizes depth masks for top NOBJ objects. """ # plot the RGB-D point-cloud: su.plot_xyzrgb(xyz.reshape(-1,3),img.reshape(-1,3)) # plot the RANSAC-planes at the text-regions: for i,l in enumerate(labels): mask = seg==l xyz_region = xyz[mask,:] su.visualize_plane(xyz_region,np.array(planes[i])) mym.view(180,180) mym.orientation_axes() mym.show(True) def viz_textbb(fignum,text_im, bb_list,alpha=1.0): """ text_im : image containing text bb_list : list of 2x4xn_i boundinb-box matrices """ plt.close(fignum) plt.figure(fignum) plt.imshow(text_im) plt.hold(True) H,W = text_im.shape[:2] for i in xrange(len(bb_list)): bbs = bb_list[i] ni = bbs.shape[-1] for j in xrange(ni): bb = bbs[:,:,j] bb = np.c_[bb,bb[:,0]] plt.plot(bb[0,:], bb[1,:], 'r', linewidth=2, alpha=alpha) plt.gca().set_xlim([0,W-1]) plt.gca().set_ylim([H-1,0]) plt.show(block=False) class RendererV3(object): def __init__(self, data_dir, max_time=None): self.text_renderer = tu.RenderFont(data_dir) self.colorizer = Colorize(data_dir) #self.colorizerV2 = colorV2.Colorize(data_dir) self.min_char_height = 8 #px self.min_asp_ratio = 0.4 # self.max_text_regions = 7 self.max_time = max_time def filter_regions(self,regions,filt): """ filt : boolean list of regions to keep. """ idx = np.arange(len(filt))[filt] for k in regions.keys(): regions[k] = [regions[k][i] for i in idx] return regions def filter_for_placement(self,xyz,seg,regions): filt = np.zeros(len(regions['label'])).astype('bool') masks,Hs,Hinvs = [],[], [] for idx,l in enumerate(regions['label']): res = get_text_placement_mask(xyz,seg==l,regions['coeff'][idx],pad=2) if res is not None: mask,H,Hinv = res masks.append(mask) Hs.append(H) Hinvs.append(Hinv) filt[idx] = True regions = self.filter_regions(regions,filt) regions['place_mask'] = masks regions['homography'] = Hs regions['homography_inv'] = Hinvs return regions def warpHomography(self,src_mat,H,dst_size): dst_mat = cv2.warpPerspective(src_mat, H, dst_size, flags=cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR) return dst_mat def homographyBB(self, bbs, H, offset=None): """ Apply homography transform to bounding-boxes. BBS: 2 x 4 x n matrix (2 coordinates, 4 points, n bbs). Returns the transformed 2x4xn bb-array. offset : a 2-tuple (dx,dy), added to points before transfomation. """ eps = 1e-16 # check the shape of the BB array: t,f,n = bbs.shape assert (t==2) and (f==4) # append 1 for homogenous coordinates: bbs_h = np.reshape(np.r_[bbs, np.ones((1,4,n))], (3,4*n), order='F') if offset != None: bbs_h[:2,:] += np.array(offset)[:,None] # perpective: bbs_h = H.dot(bbs_h) bbs_h /= (bbs_h[2,:]+eps) bbs_h = np.reshape(bbs_h, (3,4,n), order='F') return bbs_h[:2,:,:] def bb_filter(self,bb0,bb,text): """ Ensure that bounding-boxes are not too distorted after perspective distortion. bb0 : 2x4xn martrix of BB coordinates before perspective bb : 2x4xn matrix of BB after perspective text: string of text -- for excluding symbols/punctuations. """ h0 = np.linalg.norm(bb0[:,3,:] - bb0[:,0,:], axis=0) w0 = np.linalg.norm(bb0[:,1,:] - bb0[:,0,:], axis=0) hw0 = np.c_[h0,w0] h = np.linalg.norm(bb[:,3,:] - bb[:,0,:], axis=0) w = np.linalg.norm(bb[:,1,:] - bb[:,0,:], axis=0) hw = np.c_[h,w] # remove newlines and spaces: text = ''.join(text.split()) assert len(text)==bb.shape[-1] alnum = np.array([ch.isalnum() for ch in text]) hw0 = hw0[alnum,:] hw = hw[alnum,:] min_h0, min_h = np.min(hw0[:,0]), np.min(hw[:,0]) asp0, asp = hw0[:,0]/hw0[:,1], hw[:,0]/hw[:,1] asp0, asp = np.median(asp0), np.median(asp) asp_ratio = asp/asp0 is_good = ( min_h > self.min_char_height and asp_ratio > self.min_asp_ratio and asp_ratio < 1.0/self.min_asp_ratio) return is_good def get_min_h(selg, bb, text): # find min-height: h = np.linalg.norm(bb[:,3,:] - bb[:,0,:], axis=0) # remove newlines and spaces: text = ''.join(text.split()) assert len(text)==bb.shape[-1] alnum = np.array([ch.isalnum() for ch in text]) h = h[alnum] return np.min(h) def feather(self, text_mask, min_h): # determine the gaussian-blur std: if min_h <= 15 : bsz = 0.25 ksz=1 elif 15 < min_h < 30: bsz = max(0.30, 0.5 + 0.1*np.random.randn()) ksz = 3 else: bsz = max(0.5, 1.5 + 0.5*np.random.randn()) ksz = 5 return cv2.GaussianBlur(text_mask,(ksz,ksz),bsz) def place_text(self,rgb,collision_mask,H,Hinv): font = self.text_renderer.font_state.sample() font = self.text_renderer.font_state.init_font(font) render_res = self.text_renderer.render_sample(font,collision_mask) if render_res is None: # rendering not successful return #None else: text_mask,loc,bb,text = render_res # update the collision mask with text: collision_mask += (255 * (text_mask>0)).astype('uint8') # warp the object mask back onto the image: text_mask_orig = text_mask.copy() bb_orig = bb.copy() text_mask = self.warpHomography(text_mask,H,rgb.shape[:2][::-1]) bb = self.homographyBB(bb,Hinv) if not self.bb_filter(bb_orig,bb,text): #warn("bad charBB statistics") return #None # get the minimum height of the character-BB: min_h = self.get_min_h(bb,text) #feathering: text_mask = self.feather(text_mask, min_h) im_final = self.colorizer.color(rgb,[text_mask],np.array([min_h])) return im_final, text, bb, collision_mask def get_num_text_regions(self, nregions): #return nregions nmax = min(self.max_text_regions, nregions) if np.random.rand() < 0.10: rnd = np.random.rand() else: rnd = np.random.beta(5.0,1.0) return int(np.ceil(nmax * rnd)) def char2wordBB(self, charBB, text): """ Converts character bounding-boxes to word-level bounding-boxes. charBB : 2x4xn matrix of BB coordinates text : the text string output : 2x4xm matrix of BB coordinates, where, m == number of words. """ wrds = text.split() bb_idx = np.r_[0, np.cumsum([len(w) for w in wrds])] wordBB = np.zeros((2,4,len(wrds)), 'float32') for i in xrange(len(wrds)): cc = charBB[:,:,bb_idx[i]:bb_idx[i+1]] # fit a rotated-rectangle: # change shape from 2x4xn_i -> (4*n_i)x2 cc = np.squeeze(np.concatenate(np.dsplit(cc,cc.shape[-1]),axis=1)).T.astype('float32') rect = cv2.minAreaRect(cc.copy()) box = np.array(cv2.boxPoints(rect)) # find the permutation of box-coordinates which # are "aligned" appropriately with the character-bb. # (exhaustive search over all possible assignments): cc_tblr = np.c_[cc[0,:], cc[-3,:], cc[-2,:], cc[3,:]].T perm4 = np.array(list(itertools.permutations(np.arange(4)))) dists = [] for pidx in xrange(perm4.shape[0]): d = np.sum(np.linalg.norm(box[perm4[pidx],:]-cc_tblr,axis=1)) dists.append(d) wordBB[:,:,i] = box[perm4[np.argmin(dists)],:].T return wordBB def render_text(self,rgb,depth,seg,area,label,ninstance=1,viz=False): """ rgb : HxWx3 image rgb values (uint8) depth : HxW depth values (float) seg : HxW segmentation region masks area : number of pixels in each region label : region labels == unique(seg) / {0} i.e., indices of pixels in SEG which constitute a region mask ninstance : no of times image should be used to place text. @return: res : a list of dictionaries, one for each of the image instances. Each dictionary has the following structure: 'img' : rgb-image with text on it. 'bb' : 2x4xn matrix of bounding-boxes for each character in the image. 'txt' : a list of strings. The correspondence b/w bb and txt is that i-th non-space white-character in txt is at bb[:,:,i]. If there's an error in pre-text placement, for e.g. if there's no suitable region for text placement, an empty list is returned. """ try: # depth -> xyz xyz = su.DepthCamera.depth2xyz(depth) # find text-regions: regions = TextRegions.get_regions(xyz,seg,area,label) # find the placement mask and homographies: regions = self.filter_for_placement(xyz,seg,regions) # finally place some text: nregions = len(regions['place_mask']) if nregions < 1: # no good region to place text on return [] except: # failure in pre-text placement #import traceback traceback.print_exc() return [] res = [] for i in xrange(ninstance): place_masks = copy.deepcopy(regions['place_mask']) print colorize(Color.CYAN, " ** instance # : %d"%i) idict = {'img':[], 'charBB':None, 'wordBB':None, 'txt':None} m = self.get_num_text_regions(nregions)#np.arange(nregions)#min(nregions, 5*ninstance*self.max_text_regions)) reg_idx = np.arange(min(2*m,nregions)) np.random.shuffle(reg_idx) reg_idx = reg_idx[:m] placed = False img = rgb.copy() itext = [] ibb = [] # process regions: num_txt_regions = len(reg_idx) NUM_REP = 5 # re-use each region three times: reg_range = np.arange(NUM_REP * num_txt_regions) % num_txt_regions for idx in reg_range: ireg = reg_idx[idx] try: if self.max_time is None: txt_render_res = self.place_text(img,place_masks[ireg], regions['homography'][ireg], regions['homography_inv'][ireg]) else: with time_limit(self.max_time): txt_render_res = self.place_text(img,place_masks[ireg], regions['homography'][ireg], regions['homography_inv'][ireg]) except TimeoutException, msg: print msg continue except: traceback.print_exc() # some error in placing text on the region continue if txt_render_res is not None: placed = True img,text,bb,collision_mask = txt_render_res # update the region collision mask: place_masks[ireg] = collision_mask # store the result: itext.append(text) ibb.append(bb) if placed: # at least 1 word was placed in this instance: idict['img'] = img idict['txt'] = itext idict['charBB'] = np.concatenate(ibb, axis=2) idict['wordBB'] = self.char2wordBB(idict['charBB'].copy(), ' '.join(itext)) res.append(idict.copy()) if viz: viz_textbb(1,img, [idict['wordBB']], alpha=1.0) viz_masks(2,img,seg,depth,regions['label']) # viz_regions(rgb.copy(),xyz,seg,regions['coeff'],regions['label']) if i < ninstance-1: raw_input(colorize(Color.BLUE,'continue?',True)) return res
{ "repo_name": "ankush-me/SynthText", "path": "synthgen.py", "copies": "1", "size": "24099", "license": "apache-2.0", "hash": 6343746443363677000, "line_mean": 33.9260869565, "line_max": 121, "alpha_frac": 0.5314328395, "autogenerated": false, "ratio": 3.3368872888396566, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43683201283396567, "avg_score": null, "num_lines": null }
""" Visualize the generated localization synthetic data stored in h5 data-bases """ from __future__ import division import os import os.path as osp import numpy as np import matplotlib.pyplot as plt import h5py from common import * def viz_textbb(text_im, charBB_list, wordBB, alpha=1.0): """ text_im : image containing text charBB_list : list of 2x4xn_i bounding-box matrices wordBB : 2x4xm matrix of word coordinates """ plt.close(1) plt.figure(1) plt.imshow(text_im) plt.hold(True) H,W = text_im.shape[:2] # plot the character-BB: for i in xrange(len(charBB_list)): bbs = charBB_list[i] ni = bbs.shape[-1] for j in xrange(ni): bb = bbs[:,:,j] bb = np.c_[bb,bb[:,0]] plt.plot(bb[0,:], bb[1,:], 'r', alpha=alpha/2) # plot the word-BB: for i in xrange(wordBB.shape[-1]): bb = wordBB[:,:,i] bb = np.c_[bb,bb[:,0]] plt.plot(bb[0,:], bb[1,:], 'g', alpha=alpha) # visualize the indiv vertices: vcol = ['r','g','b','k'] for j in xrange(4): plt.scatter(bb[0,j],bb[1,j],color=vcol[j]) plt.gca().set_xlim([0,W-1]) plt.gca().set_ylim([H-1,0]) plt.show(block=False) def main(db_fname): db = h5py.File(db_fname, 'r') dsets = sorted(db['data'].keys()) print "total number of images : ", colorize(Color.RED, len(dsets), highlight=True) for k in dsets: rgb = db['data'][k][...] charBB = db['data'][k].attrs['charBB'] wordBB = db['data'][k].attrs['wordBB'] txt = db['data'][k].attrs['txt'] viz_textbb(rgb, [charBB], wordBB) print "image name : ", colorize(Color.RED, k, bold=True) print " ** no. of chars : ", colorize(Color.YELLOW, charBB.shape[-1]) print " ** no. of words : ", colorize(Color.YELLOW, wordBB.shape[-1]) print " ** text : ", colorize(Color.GREEN, txt) if 'q' in raw_input("next? ('q' to exit) : "): break db.close() if __name__=='__main__': main('results/SynthText.h5')
{ "repo_name": "ankush-me/SynthText", "path": "visualize_results.py", "copies": "1", "size": "2152", "license": "apache-2.0", "hash": 2337062751092615700, "line_mean": 27.6933333333, "line_max": 86, "alpha_frac": 0.5506505576, "autogenerated": false, "ratio": 2.984743411927878, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40353939695278784, "avg_score": null, "num_lines": null }
__author__ = 'anna' from PetersScheme.Vertex import Vertex_DooSabin from PetersScheme.Shape import Shape_DooSabin def DooSabin(vertices, faces, alpha, iter): vertices_refined = [] faces_refined = [] vertices_children = [ [] for _ in range(len(vertices))]#[None]*len(vertices) edges = [] #get list of edges faces_total = faces.__len__() face_count = 0 for face in faces: face_count += 1 if face_count % 100 == 0: print "getting list of edges: face %d of %d."%(face_count,faces_total) for edge in face.getEdges(): if not ((edge in edges) or ([edge[1], edge[0]] in edges)): edges.append(edge) edges_children = [ [] for _ in range(len(edges))] faces_total = faces.__len__() face_count = 0 for face in faces: face_count += 1 if face_count % 100 == 0: print "face %d of %d."%(face_count,faces_total) F = face.centroid numberOfVertices = len(face.vertex_ids) newVertices = [] for j in range(numberOfVertices): # v = Vertex(len(vertices_refined),[face.vertices[j]._coordinates[l]*(1 - alpha) + F[l]*alpha for l in range(3)]) newVertex_xCoord = face._vertices[j]._coordinates[0]*(1 - alpha) + F[0]*alpha newVertex_yCoord = face._vertices[j]._coordinates[1]*(1 - alpha) + F[1]*alpha newVertex_zCoord = face._vertices[j]._coordinates[2]*(1 - alpha) + F[2]*alpha v = Vertex_DooSabin(len(vertices_refined), newVertex_xCoord, newVertex_yCoord, newVertex_zCoord) vertices_children[face._vertices[j]._id].append([face, v]) vertices_refined.append(v) for edge in face.adjacentEdges(face._vertices[j]): if edge in edges: edges_children[edges.index(edge)].append([v, edge.index(face._vertices[j]), face, "asIs"]) else: #positioning is assigned with respect to the orientation of the edge in the list edges_children[edges.index([edge[1], edge[0]])].append([v, 1-edge.index(face._vertices[j]), face, "reversed"]) newVertices.append(v) new_face = Shape_DooSabin(len(faces_refined), newVertices) if iter == 1: new_face.type = "center" new_face.parents.append(face) if iter == 2: new_face.type = "center" new_face.parent_type = face.type if face.type == "center": globalIndicesInOrderedOriginalQuad = [5, 6, 10, 9] for i in range(len(face.parents[0]._vertices)): face.parents[0].ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[i]] = newVertices[i] newVertices[i].parentOrigGrid = face.parents[0] face.parents[0]._vertices[i].A.append([face.parents[0], newVertices[i]]) if face.type == "vertex": globalIndicesInOrderedOriginalQuad = [0, 3, 15, 12] parent_faces = face.parents for i in range(numberOfVertices): face.parent_vertex.C.append([face.parents[i], newVertices[i]]) ind = face.parents[i]._vertices.index(face.parent_vertex) face.parents[i].ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[ind]] = newVertices[i] newVertices[i].parentOrigGrid = face.parents[i] if face.type == "edge": globalIndicesInOrderedOriginalQuad = [[1, 7, 14, 8], [2, 11, 13, 4]] parent_edge = face.parent_edge positioning = face.edge_face_positioning for parent_local_id in range(2): if parent_edge in face.parents[parent_local_id].edges: #ids in the face parent_local_id*2, parent_local_id*2+1 edge_id = face.parents[parent_local_id].edges.index(parent_edge) face.parents[parent_local_id].ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[positioning[parent_local_id*2]][edge_id]] = newVertices[parent_local_id*2] newVertices[parent_local_id*2].parentOrigGrid = face.parents[parent_local_id] face.parents[parent_local_id].ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[positioning[parent_local_id*2+1]][edge_id]] = newVertices[parent_local_id*2+1] newVertices[parent_local_id*2+1].parentOrigGrid = face.parents[parent_local_id] else: edge_id = face.parents[parent_local_id].edges.index([parent_edge[1], parent_edge[0]]) face.parents[parent_local_id].ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[1-positioning[parent_local_id*2]][edge_id]] = newVertices[parent_local_id*2] newVertices[parent_local_id*2].parentOrigGrid = face.parents[parent_local_id] face.parents[parent_local_id].ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[1-positioning[parent_local_id*2+1]][edge_id]] = newVertices[parent_local_id*2+1] newVertices[parent_local_id*2+1].parentOrigGrid = face.parents[parent_local_id] #get the neighbouring "vertex" faces with respect to our current "edge" face neighbouringVertexFaces = [face.parent_edge[i].childFace for i in range(2)] for i in range(2): #for each of the neighbouring faces find the shared edge sharedEdge = neighbouringVertexFaces[i].isAdjacent(face) indexOfSharedEdge = neighbouringVertexFaces[i].edges.index(sharedEdge) #ordered original faces containing the vertices of the "vertex" face for vert in sharedEdge: #the local id of the face in original grid, containing the current vertex localFaceId = neighbouringVertexFaces[i]._vertices.index(vert) grandParentFace = neighbouringVertexFaces[i].parents[localFaceId] # if parent_edge in grandParentFace.edges: # positioning = face.edge_face_positioning # localInd = face._vertices.index(vert) # grandParentFace.ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[positioning[localInd]][grandParentFace.edges.index(parent_edge)]] # else: # positioning = face.edge_face_positioning # localInd = face._vertices.index(vert) # grandParentFace.ordered_refined_vertices[globalIndicesInOrderedOriginalQuad[1-positioning[localInd]][grandParentFace.edges.index([parent_edge[1], parent_edge[0]])]] if localFaceId == indexOfSharedEdge: face.parent_edge[i].B2.append([grandParentFace, newVertices[face._vertices.index(vert)], face.parent_edge]) else: face.parent_edge[i].B1.append([grandParentFace, newVertices[face._vertices.index(vert)], face.parent_edge]) for vertex in newVertices: vertex.addNeighbouringFace(new_face) faces_refined.append(new_face) vertices_total = vertices.__len__() vertex_count = 0 #Loop through vertices, getting the faces of the type "vertex" for vert in vertices: vertex_count += 1 if vertex_count % 100 == 0: print "vertex %d of %d."%(vertex_count,vertices_total) n = len(vertices_children[vert._id]) new_face_vertices = [vertices_children[vert._id][i][1] for i in range(n)] parent_faces = [vertices_children[vert._id][i][0] for i in range(n)] face_ordered = [vertices_children[vert._id][0][1]] parent_faces_ordered = [vertices_children[vert._id][0][0]] current_face = parent_faces[0] for i in range(1, n, 1): j = 0 while (not current_face.isAdjacent(parent_faces[j])) or (new_face_vertices[j] in face_ordered): j += 1 face_ordered.append(new_face_vertices[j]) parent_faces_ordered.append(parent_faces[j]) current_face = parent_faces[j] face_object = Shape_DooSabin(len(faces_refined), face_ordered) vert.childFace = face_object if iter == 1: face_object.type = "vertex" for i in range(len(parent_faces_ordered)): face_object.parents.append(parent_faces_ordered[i]) face_object.parent_vertex = vert for vertex in new_face_vertices: vertex.addNeighbouringFace(face_object) faces_refined.append(face_object) edges_total = edges.__len__() #Loop through edges, getting the faces of the type "edge" for i in range(len(edges)): if i % 100 == 0: print "edge %d of %d."%(i, edges_total) n = 4 #edge always has four children! new_face_vertices_positioning = [edges_children[i][j][1] for j in range(n)] new_face_vertices = [edges_children[i][0][0], edges_children[i][1][0]] if new_face_vertices_positioning[2] == new_face_vertices_positioning[1]: new_face_vertices.append(edges_children[i][2][0]) new_face_vertices.append(edges_children[i][3][0]) else: new_face_vertices.append(edges_children[i][3][0]) new_face_vertices.append(edges_children[i][2][0]) temp = new_face_vertices_positioning[3] new_face_vertices_positioning[3] = new_face_vertices_positioning[2] new_face_vertices_positioning[2] = temp face_object = Shape_DooSabin(len(faces_refined), new_face_vertices) face_object.edge_face_positioning = new_face_vertices_positioning face_object.parent_edge = edges[i] face_object.parents = [edges_children[i][j][2] for j in range(0,4, 2)] if iter == 1: face_object.type = "edge" faces_refined.append(face_object) return [vertices_refined, faces_refined]
{ "repo_name": "BGCECSE2015/CADO", "path": "PYTHON/NURBSReconstruction/DooSabin/DooSabin.py", "copies": "1", "size": "10258", "license": "bsd-3-clause", "hash": 4447109340203719700, "line_mean": 48.3221153846, "line_max": 194, "alpha_frac": 0.5923181907, "autogenerated": false, "ratio": 3.7575091575091575, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9827661991118704, "avg_score": 0.004433071418090799, "num_lines": 208 }
__author__ = 'anna' import numpy as np from DooSabin import DooSabin from PetersScheme.Shape import Shape_DooSabin from PetersScheme.Vertex import Vertex_DooSabin def dooSabin_ABC(verts, faces): quads = [None]*faces.shape[0] listOfVertices = [] for i in range(len(verts)): listOfVertices.append(Vertex_DooSabin(i, verts[i][0], verts[i][1], verts[i][2])) for i in range(faces.shape[0]): face_vertices = [listOfVertices[faces[i].astype(int)[j]] for j in range(len(faces[i]))] quads[i] = Shape_DooSabin(i, face_vertices) for vertex in face_vertices: vertex.addNeighbouringFace(quads[i]) #neighbours_test = quads[4].find_neighbors(quads) print "DooSabin 1st refinement" [vertices_refined, faces_refined] = DooSabin(listOfVertices, quads, 0.5, 1) print "DooSabin 2nd refinement" [vertices_refined1, faces_refined1] = DooSabin(vertices_refined, faces_refined, 0.5, 2) vertA = -1*np.ones((len(verts), 7, 2)) vertB1 = -1*np.ones((len(verts), 7, 4)) vertB2 = -1*np.ones((len(verts), 7, 4)) nonExtraordinaryPoints = -1*np.ones((len(quads), 16)) vertC = -1*np.ones((len(verts), 7, 2)) for i in range(len(quads)): nonExtraordinaryPoints[i] = [quads[i].ordered_refined_vertices[j]._id for j in range(16)] #necessary arrays for i in range(len(listOfVertices)): for j in range(len(listOfVertices[i].A)): vertA[i][j][0] = listOfVertices[i].A[j][1]._id vertA[i][j][1] = listOfVertices[i].A[j][1].parentOrigGrid._id vertB1[i][j][0] = listOfVertices[i].B1[j][1]._id vertB1[i][j][1] = listOfVertices[i].B1[j][1].parentOrigGrid._id vertB1[i][j][2] = listOfVertices[i].B1[j][2][0]._id vertB1[i][j][3] = listOfVertices[i].B1[j][2][1]._id vertB2[i][j][0] = listOfVertices[i].B2[j][1]._id vertB2[i][j][1] = listOfVertices[i].B2[j][1].parentOrigGrid._id vertB2[i][j][2] = listOfVertices[i].B2[j][2][0]._id vertB2[i][j][3] = listOfVertices[i].B2[j][2][1]._id vertC[i][j][0] = listOfVertices[i].C[j][1]._id vertC[i][j][1] = listOfVertices[i].C[j][1].parentOrigGrid._id return vertA, vertB1, vertB2, vertC, nonExtraordinaryPoints
{ "repo_name": "BGCECSE2015/CADO", "path": "PYTHON/NURBSReconstruction/DooSabin/DualCont_to_ABC.py", "copies": "1", "size": "2290", "license": "bsd-3-clause", "hash": 7281524152789436000, "line_mean": 39.9107142857, "line_max": 97, "alpha_frac": 0.6113537118, "autogenerated": false, "ratio": 2.570145903479237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3681499615279237, "avg_score": null, "num_lines": null }
__author__ = 'Annouk' import os import numpy as np import matplotlib.pyplot as plt def read_points(csv_file_name): points = np.loadtxt(csv_file_name, delimiter = ',') return points def plot_clusters(centroids, clusters): # we assume centroids is a list of points and clusters is a dictionary of arrays # we transpose them, so we could get 2 different arrays, representing the X and Y coordinates clusters_no = len(centroids) centroids_transposed = np.array(centroids).T x_centroids = centroids_transposed[0] y_centroids = centroids_transposed[1] for i in range(clusters_no): cluster = np.array(clusters[i]).transpose() x_cluster = cluster[0] y_cluster = cluster[1] # setting a different color for each cluster plt.scatter(x_cluster, y_cluster, c = np.random.rand(1, 3)) plt.scatter(x_centroids, y_centroids, c = 'r') plt.show() def plot_clusters_1d(centroids, clusters): # adapting the above function to work with one dimensional data clusters_no = len(clusters) x_centroids = np.array(centroids) y_centroids = np.zeros(clusters_no) for i in range(clusters_no): x_cluster = np.array(clusters[i]) y_cluster = np.zeros(len(clusters[i])) # setting a different color for each cluster plt.scatter(x_cluster, y_cluster, c = np.random.rand(1, 3)) plt.scatter(x_centroids, y_centroids, c = 'r') plt.show() def convergence(centroids, oldcentroids, threshold): return np.linalg.norm(centroids - oldcentroids) < threshold def print_matrix_to_file(matrix, output_file): for i in range(len(matrix)): output_file.write(','.join(str(nr) for nr in matrix[i])) output_file.write('\n') def print_array_to_file(array, output_file): output_file.write(','.join(str(nr) for nr in array)) output_file.write('\n')
{ "repo_name": "anamariad/ML", "path": "Clusterization/clusterization/utils.py", "copies": "1", "size": "1884", "license": "apache-2.0", "hash": 7350578124336779000, "line_mean": 29.4032258065, "line_max": 97, "alpha_frac": 0.6677282378, "autogenerated": false, "ratio": 3.3824057450628366, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9525238575733577, "avg_score": 0.004979081425851994, "num_lines": 62 }
__author__ = 'annyz' import logging import os import sys import time import psutil import json from hydra.lib import util from hydra.lib.hdaemon import HDaemonRepSrv from hydra.lib.childmgr import ChildManager from pprint import pformat from kafka import KafkaConsumer from pykafka import KafkaClient l = util.createlogger('HSub', logging.INFO) class HDKafkasRepSrv(HDaemonRepSrv): def __init__(self, port): self.msg_cnt = 0 # message count, other option is global, making progress self.recv_rate = 0 HDaemonRepSrv.__init__(self, port) self.register_fn('getstats', self.get_stats) self.register_fn('resetstats', self.reset_stats) def get_stats(self): process = psutil.Process() self.run_data['stats']['msg_cnt'] = self.msg_cnt self.run_data['stats']['net:end'] = json.dumps(psutil.net_io_counters()) self.run_data['stats']['cpu:end'] = json.dumps(process.cpu_times()) self.run_data['stats']['mem:end'] = json.dumps(process.memory_info()) self.run_data['stats']['rate'] = self.run_data['stats']['msg_cnt'] / ( self.run_data['last_msg_time_r'] - self.run_data['first_msg_time_r']) return ('ok', self.run_data['stats']) def reset_stats(self): l.info("RESETTING SUB STATS") process = psutil.Process() self.run_data = {'msg_cnt': 0, 'first_msg_time': 0, 'last_msg_time': 0, 'stats': {}} self.run_data['stats']['net'] = {'start': psutil.net_io_counters()} self.run_data['stats']['cpu'] = {'start': process.cpu_times()} self.run_data['stats']['mem'] = {'start': process.memory_info()} self.run_data['first_msg_time_r'] = 0 self.run_data['last_msg_time_r'] = 1 self.msg_cnt = 0 return ('ok', 'stats reset') def run10(argv): pwd = os.getcwd() l.info("CWD = " + pformat(pwd)) cmgr = ChildManager() myenv = os.environ.copy() cmd = './hydra hydra.kafkatest.kafka_sub.run'.split(' ') + argv[1:] if "mock" in myenv: cmd = 'hydra hydra.kafkatest.kafka_sub.run'.split(' ') + argv[1:] cwd = None for idx in range(0, 10): myenv = os.environ.copy() myenv["PORT0"] = myenv["PORT" + str(idx)] l.info("Launch%d:" % idx + " cwd=" + " CMD=" + pformat(cmd) + " PORT0=" + str(myenv["PORT0"])) cmgr.add_child('p' + str(idx), cmd, cwd, myenv) cmgr.launch_children() cmgr.wait() from subprocess import call call(["kafka/bin/kafka-topics.sh", "--zookeeper", "127.0.0.1:2181", "--delete", "--topic", "base-topic"]) sys.exit(0) def run(argv): old_client = False l.info("JOB RUN : " + pformat(argv)) pub_ip = '' if len(argv) > 3: topic_name = argv[1] pub_ip = argv[2] consumer_max_buffer_size = argv[3] l.info("Kafka SUB will subscribe to topic [%s]" % topic_name) l.info("Kafka Broker is hosted in [%s]" % pub_ip) l.info("Kafka Consumer MAX Buffer size is [%s]" % consumer_max_buffer_size) consumer_max_buffer_size = int(consumer_max_buffer_size) if not topic_name: raise Exception("Kafka-Sub needs a TOPIC to subscribe to.") if not pub_ip: raise Exception("Kafka Broker IP is not provided to consumer.") # Initalize HDaemonRepSrv sub_rep_port = os.environ.get('PORT0') hd = HDKafkasRepSrv(sub_rep_port) hd.reset_stats() hd.run() hd.msg_cnt = 0 # Init Kafka Consumer l.info("Kafka SUB client (consumer) connecting to Kafka Server (broker) at localhost:9092") kafka_server = str(pub_ip) + ":9092" if old_client: consumer = KafkaConsumer(bootstrap_servers=[kafka_server], auto_offset_reset='earliest') consumer.max_buffer_size = consumer_max_buffer_size # Specify the list of topics which the consumer will subscribe to consumer.subscribe([topic_name]) else: client = KafkaClient(hosts=kafka_server) topic = client.topics[topic_name] consumer = topic.get_simple_consumer() while True: if old_client: for message in consumer: # If first message: if hd.msg_cnt == 0: hd.run_data['first_msg_time_r'] = time.time() hd.run_data['stats']['first_msg_time'] = json.dumps(hd.run_data['first_msg_time_r']) l.info("[Kafka-Sub] Setting the 'first_msg_time' to = " + pformat(hd.run_data['stats']['first_msg_time'])) # Increment received message counter hd.msg_cnt = hd.msg_cnt + 1 hd.run_data['last_msg_time_r'] = time.time() hd.run_data['stats']['last_msg_time'] = json.dumps(hd.run_data['last_msg_time_r']) # Limit the 'receive' rate if necessary if hd.recv_rate != 0: # Check the rate from beginning of first message to now duration = float(hd.msg_cnt) / hd.recv_rate current_duration = time.time() - hd.run_data['first_msg_time_r'] if current_duration < duration: sleep_time = duration - current_duration if sleep_time > 1: sleep_time = 1 time.sleep(sleep_time) hd.run_data['msg_cnt'] = hd.msg_cnt else: consumer.consume() # Read one message from Kafka # If first message: if hd.msg_cnt == 0: hd.run_data['first_msg_time_r'] = time.time() hd.run_data['stats']['first_msg_time'] = json.dumps(hd.run_data['first_msg_time_r']) l.info("[Kafka-Sub] Setting the 'first_msg_time' to = " + pformat(hd.run_data['stats']['first_msg_time'])) # Increment received message counter hd.msg_cnt = hd.msg_cnt + 1 hd.run_data['last_msg_time_r'] = time.time() hd.run_data['stats']['last_msg_time'] = json.dumps(hd.run_data['last_msg_time_r']) # Limit the 'receive' rate if necessary if hd.recv_rate != 0: # Check the rate from beginning of first message to now duration = float(hd.msg_cnt) / hd.recv_rate current_duration = time.time() - hd.run_data['first_msg_time_r'] if current_duration < duration: sleep_time = duration - current_duration if sleep_time > 1: sleep_time = 1 time.sleep(sleep_time) hd.run_data['msg_cnt'] = hd.msg_cnt continue
{ "repo_name": "kratos7/hydra", "path": "src/main/python/hydra/kafkatest/kafka_sub.py", "copies": "4", "size": "6720", "license": "apache-2.0", "hash": 1869743067006366700, "line_mean": 40.226993865, "line_max": 109, "alpha_frac": 0.5604166667, "autogenerated": false, "ratio": 3.5, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.60604166667, "avg_score": null, "num_lines": null }
# pylint: disable=C0301,C0111,C0103,C0325 # pylint: disable=R1702,R0912,R0902,R0913,R0914,R0915 import sys import math import random from operator import itemgetter # class Unseen: provides lexical rules for unseen words # class Unseen: # list of part of speech tags for unseen words def __init__(self, filename): self.postags = None self.total = None self.most_likely_tag = None self.total = 0 self.postags = {} for _line in open(filename, 'r'): _line = _line[:-1] (count, tag) = _line.split() if tag in self.postags: raise ValueError("each postag should occur exactly once") self.postags[tag] = int(count) self.total += int(count) self.compute_log_prob() def compute_log_prob(self): for tag in self.postags: self.postags[tag] = math.log(self.postags[tag] / self.total, 2) def tags_for_unseen(self): for tag in self.postags: yield (tag, self.postags[tag]) def get_most_likely_tag(self): if self.most_likely_tag is None: (self.most_likely_tag, _) = sorted(self.postags.items(), key=itemgetter(1)).pop() return self.most_likely_tag # end of class Unseen # class Pcfg: # Implements a non-strict Chomsky Normal Form probabilitic context free grammar # can have rules of the form A -> B C, A -> B (hence non-strict), or A -> a # A, B, C are non-terminals, a are terminals # # Format of the file for a rule lhs -> left right with its count is: # count lhs left [right] # the log_prob for each rule is computed on demand # class Pcfg: # read in the file containing the weighted context-free grammar # the prob for each rule is computed on the fly based on the weights # normalized by the lhs symbol as per the usual definition of PCFGs def __init__(self, filelist, startsym='TOP', allowed_words_file='allowed_words.txt', verbose=0): self.startsym = startsym self.allowed_words = set(line.strip() for line in open(allowed_words_file)) self.verbose = verbose self.last_rule = -1 # each rule is indexed by a number i, where # rule[i] = (lhs, (left, right), count, log_prob) self.rules = {} # forward index from lhs to list of rule numbers self.lhs_rules = {} # reverse index from (left,right) to a rule index self.rhs = {} # total count over all rhs for each lhs in the pcfg self.lhs_count = {} self.lhs_total_count = 0 # special symbol to mark a unary rule A -> B which is written as A -> B <Unary> self.unary = '<Unary>' for filename in filelist: print("#reading grammar file: {}".format(filename), file=sys.stderr) linenum = 0 for _line in open(filename, 'r'): linenum += 1 if _line.find('#') != -1: _line = _line[:_line.find('#')] # strip comments _line = _line.strip() if _line == "": continue f = _line.split() if len(f) > 4: # only CNF rules allowed raise ValueError("Error: >2 symbols in right hand side at line %d: %s" % (linenum, ' '.join(f))) if len(f) < 3: # empty rules not allowed raise ValueError("Error: unexpected line at line %d: %s" % (linenum, ' '.join(f))) # count lhs left [right] try: count = int(f[0]) except ValueError: raise ValueError("Rule must be COUNT LHS RHS. Found {}".format(" ".join(f))) (count, lhs, left) = (count, f[1], f[2]) if len(f) < 4: right = self.unary else: right = f[3] if lhs == left and right == self.unary: print("#Ignored cycle {} -> {}".format(lhs, left), file=sys.stderr) continue self.last_rule += 1 self.rules[self.last_rule] = (lhs, (left, right), count, None) if self.verbose > 1: print("Rule: {}".format(self.rules[self.last_rule]), file=sys.stderr) if lhs in self.lhs_rules: self.lhs_rules[lhs].append(self.last_rule) else: self.lhs_rules[lhs] = [self.last_rule] if (left, right) in self.rhs: self.rhs[left, right].append(self.last_rule) else: self.rhs[left, right] = [self.last_rule] if lhs in self.lhs_count: self.lhs_count[lhs] += count else: self.lhs_count[lhs] = count self.lhs_total_count += count # computes the log_prob of a rule using the counts collected for each lhs # it caches the value into the rules table after computing the probabiilty # for each rule def get_log_prob(self, rule_number): if rule_number in self.rules: (lhs, rhs, count, log_prob) = self.rules[rule_number] if log_prob is not None: return log_prob log_prob = math.log(count / self.lhs_count[lhs], 2) self.rules[rule_number] = (lhs, rhs, count, log_prob) else: raise ValueError("rule number %d not found" % rule_number) return log_prob def get_rule(self, rule_number): log_prob = self.get_log_prob(rule_number) if log_prob is None: raise ValueError("rule has no log_prob: {}".format(self.rules[rule_number])) return self.rules[rule_number] def rule_iterator(self, left, right): if (left, right) in self.rhs: for rule_number in self.rhs[left, right]: yield rule_number else: return # returns the prior probability of a nonTerminal def get_prior(self, lhs): if lhs in self.lhs_count: return math.log(self.lhs_count[lhs] / self.lhs_total_count, 2) raise ValueError("%s: missing lhs" % lhs) def __str__(self): output = "" for _i in range(0, self.last_rule+1): log_prob = self.get_log_prob(_i) (lhs, (left, right), count, log_prob) = self.rules[_i] output += " ".join([lhs, left, right, str(count), str(log_prob), "\n"]) for _i in self.lhs_count: if self.verbose: print("#Prior: {} {}".format(_i, self.get_prior(_i)), file=sys.stderr) return output # end of class Pcfg # class PcfgGenerator contains the functions that allow sampling # of derivations from a PCFG. The output can be either the strings # or the trees. # # There is a small chance that the generator function will not # terminate. To make sure this outcome is avoided we use a limit # on how unlikely the generated derivation should be. If during # generation we go below this limit on the probability we stop # and restart the generation process. class PcfgGenerator: def __init__(self, _gram, verbose=0, limit=1e-300): self.gram = None # PCFG to be used by the generator self.verbose = verbose self.restart_limit = None # can be set using the constructor self.restart_limit = limit self.gram = _gram # num_samples is the number of sampled words from allowed_words # if the grammar produces entirely invalid sentence self.num_samples = 1 random.seed() def flatten_tree(self, tree): sentence = [] if isinstance(tree, tuple): (_, left_tree, right_tree) = tree for n in (self.flatten_tree(left_tree), self.flatten_tree(right_tree)): sentence.extend(n) else: if tree is not self.gram.unary: sentence = [tree] return sentence def check_allowed(self, sentence): if not sentence: print("ERROR: sampled sentence is empty", file=sys.stderr) return random.sample(self.gram.allowed_words, self.num_samples) new_sentence = [] for w in sentence: if w not in self.gram.allowed_words: print("ERROR: word {} was sampled but is not allowed".format(w), file=sys.stderr) new_sentence.append(random.sample(self.gram.allowed_words, 1)[0]) else: new_sentence.append(w) assert(len(new_sentence) == len(sentence)) return new_sentence def generate(self, parsetree=False): try: rule = self.gen_pick_one(self.gram.startsym) except ValueError: return random.sample(self.gram.allowed_words, self.num_samples) if self.verbose: print("#getrule: {}".format(self.gram.get_rule(rule)), file=sys.stderr) try: gen_tree = self.gen_from_rule(rule) except ValueError: return random.sample(self.gram.allowed_words, self.num_samples) return gen_tree if parsetree else self.check_allowed(self.flatten_tree(gen_tree)) def gen_pick_one(self, lhs): r = random.random() if self.verbose: print("#random number: {}".format(r), file=sys.stderr) output_log_prob = math.log(r, 2) accumulator = 0.0 rule_picked = None for r in self.gram.lhs_rules[lhs]: if self.verbose: print("#getrule: {}".format(self.gram.get_rule(r)), file=sys.stderr) log_prob = self.gram.get_log_prob(r) # convert to prob from log_prob in order to add with accumulator prob = math.pow(2, log_prob) if output_log_prob < math.log(prob + accumulator, 2): rule_picked = r break else: accumulator += prob if rule_picked is None: raise ValueError("no rule found for %s" % lhs) if self.verbose: print("#picked rule %d: %s" % (rule_picked, self.gram.rules[rule_picked]), file=sys.stderr) return rule_picked def get_yield(self, sym): return sym if sym not in self.gram.lhs_rules else self.gen_from_rule(self.gen_pick_one(sym)) def gen_from_rule(self, rule_number): (lhs, (left, right), _, _) = self.gram.rules[rule_number] if self.verbose: print("#%s -> %s %s" % (lhs, left, right), file=sys.stderr) left_tree = self.get_yield(left) right_tree = self.gram.unary if right is self.gram.unary else self.get_yield(right) return (lhs, left_tree, right_tree) # class CkyParse contains the main parsing routines # including routines for printing out the best tree and pruning # class CkyParse: def __init__(self, _gram, verbose=0, use_prior=True, use_pruning=True, beamsize=0.0001, unseen_file="unseen.tags"): self.gram = _gram # PCFG to be used by the grammar self.verbose = verbose if unseen_file != "": self.unseen = Unseen(unseen_file) else: self.unseen = None self.use_prior = use_prior self.use_pruning = use_pruning self.beam = math.log(float(beamsize), 2) self.chart = None # chart data structure to be used by the parser self._NINF = float('1e-323') # 64 bit double underflows for math.log(1e-324) self._LOG_NINF = math.log(self._NINF, 2) def prune(self, i, j): if not self.use_pruning: return 0 num_pruned = 0 if (i, j) in self.chart: tbl = self.chart[i, j] max_log_prob = self._LOG_NINF best_lhs = None for lhs in tbl.keys(): (log_prob, back_pointer) = tbl[lhs] max_log_prob = max(log_prob, max_log_prob) if max_log_prob == log_prob: best_lhs = lhs new_table = {} if self.use_prior: lowest = max_log_prob + self.beam + self.gram.get_prior(best_lhs) else: lowest = max_log_prob + self.beam for lhs in tbl.keys(): (log_prob, back_pointer) = tbl[lhs] save_log_prob = log_prob if self.use_prior: log_prob += self.gram.get_prior(lhs) if log_prob < lowest: if self.verbose: print("#pruning: {} {} {} {} {}".format(i, j, lhs, log_prob, lowest), file=sys.stderr) num_pruned += 1 continue new_table[lhs] = (save_log_prob, back_pointer) self.chart[i, j] = new_table return num_pruned def insert(self, i, j, lhs, log_prob, back_pointer): if (i, j) in self.chart: if lhs in self.chart[i, j]: prev_log_prob = self.chart_get_log_prob(i, j, lhs) if log_prob < prev_log_prob: return False else: self.chart[i, j] = {} self.chart[i, j][lhs] = (log_prob, back_pointer) if self.verbose: print("#inserted: {} {} {} {}".format(i, j, lhs, log_prob), file=sys.stderr) return True def handle_unary_rules(self, i, j): # we have to allow for the fact that B -> C might lead # to another rule A -> B for the same span unary_list = [entry for entry in self.chart_entry(i, j)] for rhs in unary_list: rhs_log_prob = self.chart_get_log_prob(i, j, rhs) for rule_number in self.gram.rule_iterator(rhs, self.gram.unary): (lhs, _, _, log_prob) = self.gram.get_rule(rule_number) # rhs == left if lhs == rhs: raise ValueError("Found a cycle", lhs, "->", rhs) back_pointer = (-1, rhs, self.gram.unary) if self.verbose: print("log_prob: {} rhs_log_prob: {}".format(log_prob, rhs_log_prob), file=sys.stderr) if self.insert(i, j, lhs, log_prob + rhs_log_prob, back_pointer): unary_list.append(lhs) def chart_entry(self, i, j): if (i, j) in self.chart: for item in self.chart[i, j].keys(): yield item else: return def chart_get_log_prob(self, i, j, lhs): if (i, j) in self.chart: # Each entry in the chart for i, j is a hash table with key lhs # and value equals the tuple (log_prob, back_pointer) # This function returns the first element of the tuple return self.chart[i, j][lhs][0] raise ValueError("Could not find {}, {} in chart".format(i, j)) def parse(self, input_sent): # chart has max size len(input_sent)*len(input_sent) # each entry in the chart is a hashtable with # key=lhs and value=(log_prob, back_pointer) self.chart = {} num_pruned = 0 # insert all rules of type NonTerminal -> terminal # where terminal matches some word in the input_sent for (i, word) in enumerate(input_sent): j = i+1 if (word, self.gram.unary) in self.gram.rhs: for rule_number in self.gram.rhs[(word, self.gram.unary)]: (lhs, _, _, log_prob) = self.gram.get_rule(rule_number) self.insert(i, j, lhs, log_prob, None) else: print("#using unseen part of speech for {}".format(word), file=sys.stderr) if self.unseen is None: raise ValueError("cannot find terminal symbol", word) else: for (tag, log_prob) in self.unseen.tags_for_unseen(): self.insert(i, j, tag, log_prob, None) self.handle_unary_rules(i, j) # do not prune lexical rules # recursively insert nonterminal lhs # for rule lhs -> left right into chart[(i, j)] # if left belongs to the chart for span i,k # and right belongs to the chart for span k, j N = len(input_sent)+1 for j in range(2, N): for i in range(j-2, -1, -1): # handle the case for the binary branching rules lhs -> left right for k in range(i+1, j): # handle the unary rules lhs -> rhs for left in self.chart_entry(i, k): for right in self.chart_entry(k, j): left_log_prob = self.chart_get_log_prob(i, k, left) right_log_prob = self.chart_get_log_prob(k, j, right) for rule_number in self.gram.rule_iterator(left, right): (lhs, _, _, log_prob) = self.gram.get_rule(rule_number) back_pointer = (k, left, right) self.insert(i, j, lhs, log_prob + left_log_prob + right_log_prob, back_pointer) # handle the unary rules lhs -> rhs self.handle_unary_rules(i, j) # prune each span num_pruned += self.prune(i, j) if self.verbose: print("#number of items pruned: {}".format(num_pruned), file=sys.stderr) sent_log_prob = self._LOG_NINF N = len(input_sent) if (0, N) in self.chart: if self.gram.startsym in self.chart[0, N]: (sent_log_prob, back_pointer) = self.chart[0, N][self.gram.startsym] if self.verbose: print("#sentence log prob = {}".format(sent_log_prob), file=sys.stderr) return sent_log_prob # default_tree provides a parse tree for input_sent w0,..,wN-1 when # the parser is unable to find a valid parse (no start symbol in # span 0, N). The default parse is simply the start symbol with # N children: # (TOP (P0 w0) (P1 w1) ... (PN-1 wN-1)) # where Pi is the most likely part of speech tag for that word # from training data. # If the word is unknown it receives the most likely tag from # training (across all words). # if the Unseen class does not return a tag default_tree uses # a default part of speech tag X. def default_tree(self, input_sent): tag = "X" if self.unseen is None else self.unseen.get_most_likely_tag() taggedInput = map(lambda z: "(" + tag + " " + z + ")", input_sent) return "(" + self.gram.startsym + " " + " ".join(taggedInput) + ")" # best_tree returns the most likely parse # if there was a parse there must be a start symbol S in span 0, N # then the best parse looks like (S (A ...) (B ...)) for some # A in span 0,k and B in span k,N; the function extract_best_tree # recursively fills in the trees under the start symbol S def best_tree(self, input_sent): N = len(input_sent) startsym = self.gram.startsym if (0, N) in self.chart: if startsym in self.chart[0, N]: return self.extract_best_tree(input_sent, 0, N, startsym) print("#No parses found for: {}".format(" ".join(input_sent)), file=sys.stderr) return self.default_tree(input_sent) # extract_best_tree uses back_pointers to recursively find the # best parse top-down: # for each span i, j and non-terminal A (sym below), the parsing # algorithm has recorded the best path to that non-terminal A # using the back_pointer (k, left_sym, right_sym) which means # there is a rule A -> left_sym right_sym and that left_sym spans # i,k and right_sym spans k, j. Recursively calling extract_best_tree # on spans i,k,left_sym and k, j, right_sym will provide the necessary # parts to fill in the dotted parts in the tree: # (A (left_sym ...) (right_sym ...)) # the parser records k == -1 when it inserts a unary rule: # A -> left_sym <Unary> # so a single recursive call to extract_best_tree fills in the # dotted parts of the tree: # (A (left_sym ...)) def extract_best_tree(self, input_sent, i, j, sym): if (i, j) in self.chart: if sym in self.chart[i, j]: (_, back_pointer) = self.chart[i, j][sym] if back_pointer is None: return "(" + sym + " " + input_sent[i] + ")" (k, left_sym, right_sym) = back_pointer if k == -1: # unary rule left_tree = self.extract_best_tree(input_sent, i, j, left_sym) right_tree = "" else: # binary rule left_tree = self.extract_best_tree(input_sent, i, k, left_sym) right_tree = self.extract_best_tree(input_sent, k, j, right_sym) return "(" + sym + " " + left_tree + " " + right_tree + ")" raise ValueError("cannot find span:", i, j, sym) def parse_sentences(self, sentences): corpus_cross_entropy = self._LOG_NINF corpus_len = 0 total_log_prob = None parses = [] for sent in sentences: sent = sent.strip() input_sent = sent.split() length = len(input_sent) if length <= 0: continue if sent[0] == '#': if self.verbose: print("#skipping comment line in input_sent: {}".format(sent), file=sys.stderr) continue corpus_len += length print("#parsing: {}".format(input_sent), file=sys.stderr) try: sent_log_prob = self.parse(input_sent) best_tree = self.best_tree(input_sent) except ValueError: print("#No parses found for: {}".format(" ".join(input_sent)), file=sys.stderr) sent_log_prob = self._LOG_NINF best_tree = self.default_tree(input_sent) total_log_prob = sent_log_prob if total_log_prob is None else total_log_prob + sent_log_prob parses.append(best_tree) print(best_tree) if corpus_len: corpus_cross_entropy = total_log_prob / corpus_len print("#-cross entropy (bits/word): %g" % corpus_cross_entropy, file=sys.stderr) return (corpus_cross_entropy, parses) def parse_file(self, filename): parses = [] with open(filename, 'r') as fh: parses = self.parse_stream(fh) return parses def parse_stream(self, handle): if self.verbose: print("parsing from stream: {}".format(handle), file=sys.stderr) sentences = [] for line in handle: line = line.strip() sentences.append(line) parses = self.parse_sentences(sentences) return parses # end of class CkyParse if __name__ == '__main__': import argparse argparser = argparse.ArgumentParser() argparser.add_argument('-v', '--verbose', action='count', default=0, help="verbose output") argparser.add_argument("-s", "--startsymbol", dest="startsym", type=str, default="TOP", help="start symbol") argparser.add_argument("-i", "--parse", dest="parse_mode", action="store_true", help="parsing mode; takes sentence and produces parse if possible") argparser.add_argument("-o", "--generate", dest="generate_mode", action="store_true", help="generate mode; takes grammar and produces sentences if possible") argparser.add_argument("-n", "--numsentences", dest="num_sentences", type=int, default=20, help="number of sentences to generate; in --generate mode") argparser.add_argument("-r", "--prior", dest="use_prior", action="store_false", help="use prior for pruning") argparser.add_argument("-p", "--pruning", dest="use_pruning", action="store_false", help="use prior for pruning") argparser.add_argument("-u", "--unseentags", dest="unseen_file", type=str, default="", help="unseen tags filename") argparser.add_argument("-b", "--beam", dest="beam", type=float, default=0.0001, help="use prior for pruning") argparser.add_argument("-a", "--allowedwords", dest="allowed_words_file", type=str, default="allowed_words.txt", help="only use this list of words when parsing and generating") argparser.add_argument("-g", "--grammars", nargs=argparse.ONE_OR_MORE, dest="grammar_files", type=str, default=["S1.gr", "S2.gr", "Vocab.gr"], help="list of grammar files; typically: S1.gr S2.gr Vocab.gr") args = argparser.parse_args() if args.parse_mode == args.generate_mode == False: print("ERROR: -i / --parse and -o / --generate cannot both be false", file=sys.stderr) argparser.print_help(sys.stderr) sys.exit(2) if not args.grammar_files: print("ERROR: grammar files required", file=sys.stderr) argparser.print_help(sys.stderr) sys.exit(2) if not args.allowed_words_file: print("ERROR: allowed words filename required", file=sys.stderr) argparser.print_help(sys.stderr) sys.exit(2) if args.verbose: print("#verbose level: {}".format(args.verbose), file=sys.stderr) print("#mode: {}".format("parse" if args.parse_mode else "generate"), file=sys.stderr) print("#grammar: {}".format(" ".join(args.grammar_files)), file=sys.stderr) gram = Pcfg(args.grammar_files, args.startsym, args.allowed_words_file, args.verbose) #print(gram) if args.generate_mode: gen = PcfgGenerator(gram, args.verbose) for _ in range(args.num_sentences): print(" ".join(gen.generate())) if args.parse_mode: parser = CkyParse(gram, args.verbose, args.use_prior, args.use_pruning, args.beam, args.unseen_file) parser.parse_stream(sys.stdin)
{ "repo_name": "anoopsarkar/nlp-class-hw", "path": "cgw/pcfg_parse_gen.py", "copies": "1", "size": "26604", "license": "apache-2.0", "hash": -7348520376482699000, "line_mean": 42.2585365854, "line_max": 119, "alpha_frac": 0.5511201323, "autogenerated": false, "ratio": 3.8240620957309184, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48751822280309187, "avg_score": null, "num_lines": null }
__author__ = 'anson' import requests from monitor_default_format import split_token url = "http://192.168.136.254" send_event_state = { 'ok': ['normal'], 'non-ok': ['abnormal', 'failure'] } class api_setting(): """ Use Paramiko to execute shell command through ssh""" def __init__(self): self.manager_url = requests.session() def manager(self): self.manager_url.headers.update({'Authorization': 'Token 993274943e8a43731b8f35862a7417de3a230411'}) self.manager_url.headers.update({'Content-Type': 'application/json'}) self.manager_url.headers.update({'SERVICE_TYPE': 'appliance'}) return self.manager_url def gen_disk_event(ip, event): json_body = { "node_ip": str(ip), "event_type": "disk_event", } node_event_api = "/v1/event/disk/" json_body["event_status"] = event return json_body, url + node_event_api def gen_network_event(ip, event): json_body = { "node_ip": str(ip), "event_type": "network_event", } node_event_api = "/v1/event/network/" event_split = event.split('_') event_out = ','.join(event_split) json_body["event_status"] = event_out return json_body, url + node_event_api def gen_node_event(ip, state_id, event): json_body = { "node_ip": str(ip), "event_type": "node_event", } node_event_api = "/v1/event/node/" # If monitor return ok state, send normal event if state_id == 0: json_body["event_status"] = "node:node:normal" return json_body, url + node_event_api # If monitor return non-ok state, send the sensor type event that the sensor is non-ok elif state_id > 0 and event.split(split_token)[3] != send_event_state['ok'][0]: event_split = event.split(split_token) json_body["event_status"] = event_split[0] + split_token + event_split[1]\ + split_token + event_split[3] return json_body, url + node_event_api # If monitor return non-ok state, skip sensor type that the state is ok else: return None, None
{ "repo_name": "AnsonShie/system_monitor", "path": "lib_monitor/event_handler_default.py", "copies": "1", "size": "2112", "license": "apache-2.0", "hash": -2485106894122458600, "line_mean": 31.5076923077, "line_max": 108, "alpha_frac": 0.6098484848, "autogenerated": false, "ratio": 3.347068145800317, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4456916630600317, "avg_score": null, "num_lines": null }
"""Class representing audio/* type MIME documents. """ import sndhdr from cStringIO import StringIO from email import Errors from email import Encoders from email.MIMENonMultipart import MIMENonMultipart _sndhdr_MIMEmap = {'au' : 'basic', 'wav' :'x-wav', 'aiff':'x-aiff', 'aifc':'x-aiff', } # There are others in sndhdr that don't have MIME types. :( # Additional ones to be added to sndhdr? midi, mp3, realaudio, wma?? def _whatsnd(data): """Try to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix. """ hdr = data[:512] fakefile = StringIO(hdr) for testfn in sndhdr.tests: res = testfn(hdr, fakefile) if res is not None: return _sndhdr_MIMEmap.get(res[0]) return None class MIMEAudio(MIMENonMultipart): """Class for generating audio/* MIME documents.""" def __init__(self, _audiodata, _subtype=None, _encoder=Encoders.encode_base64, **_params): """Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = _whatsnd(_audiodata) if _subtype is None: raise TypeError, 'Could not find audio MIME subtype' MIMENonMultipart.__init__(self, 'audio', _subtype, **_params) self.set_payload(_audiodata) _encoder(self)
{ "repo_name": "neopoly/rubyfox-server", "path": "lib/rubyfox/server/data/lib/Lib/email/MIMEAudio.py", "copies": "11", "size": "2598", "license": "mit", "hash": 4058878368506360000, "line_mean": 34.5890410959, "line_max": 77, "alpha_frac": 0.6458814473, "autogenerated": false, "ratio": 4.040435458786936, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.003693098763521298, "num_lines": 71 }