content
stringlengths
0
1.55M
"""Traditional-based search space. """<import_stmt>copy<import_stmt>opytimizer.utils.logging<as>l<import_from_stmt>opytimizer.core Space<line_sep>logger=l.get_logger(__name__)<class_stmt>SearchSpace(Space)<block_start>"""A SearchSpace class for agents, variables and methods related to the search space. """<def_stmt>__init__ self n_agents n_variables lower_bound upper_bound<block_start>"""Initialization method. Args: n_agents (int): Number of agents. n_variables (int): Number of decision variables. lower_bound (float, list, tuple, np.array): Minimum possible values. upper_bound (float, list, tuple, np.array): Maximum possible values. """<line_sep>logger.info('Overriding class: Space -> SearchSpace.')<line_sep># Defines missing override arguments n_dimensions=1<line_sep>super(SearchSpace self).__init__(n_agents n_variables n_dimensions lower_bound upper_bound)<line_sep>self.build()<line_sep>logger.info('Class overrided.')<block_end><def_stmt>_initialize_agents self<block_start>"""Initializes agents with their positions and defines a best agent. """<for_stmt>agent self.agents<block_start>agent.fill_with_uniform()<block_end>self.best_agent=copy.deepcopy(self.agents[0])<block_end><block_end>
<def_stmt>get_dataset name="ntu13"<block_start><if_stmt>name<eq>"ntu13"<block_start><import_from_stmt>.ntu13 NTU13<line_sep><return>NTU13<block_end><elif_stmt>name<eq>"uestc"<block_start><import_from_stmt>.uestc UESTC<line_sep><return>UESTC<block_end><elif_stmt>name<eq>"humanact12"<block_start><import_from_stmt>.humanact12poses HumanAct12Poses<line_sep><return>HumanAct12Poses<block_end><block_end><def_stmt>get_datasets parameters<block_start>name=parameters["dataset"]<line_sep>DATA=get_dataset(name)<line_sep>dataset=DATA(split="train" **parameters)<line_sep>train=dataset<line_sep># test: shallow copy (share the memory) but set the other indices <import_from_stmt>copy copy<line_sep>test=copy(train)<line_sep>test.split=test<line_sep>datasets={"train":train "test":test}<line_sep># add specific parameters from the dataset loading dataset.update_parameters(parameters)<line_sep><return>datasets<block_end>
<import_stmt>os.path<as>osp<import_stmt>random<import_stmt>numpy<as>np<import_stmt>pytest<import_from_stmt>numpy.testing assert_array_almost_equal assert_array_equal<import_from_stmt>mmaction.core ActivityNetLocalization average_recall_at_avg_proposals confusion_matrix get_weighted_score mean_average_precision mean_class_accuracy mmit_mean_average_precision pairwise_temporal_iou top_k_accuracy <import_from_stmt>mmaction.core.evaluation.ava_utils ava_eval<def_stmt>gt_confusion_matrix gt_labels pred_labels normalize=<none><block_start>"""Calculate the ground truth confusion matrix."""<line_sep>max_index=max(max(gt_labels) max(pred_labels))<line_sep>confusion_mat=np.zeros((max_index+1 max_index+1) dtype=np.int64)<for_stmt>gt,pred zip(gt_labels pred_labels)<block_start>confusion_mat[gt][pred]<augadd>1<block_end>del_index=[]<for_stmt>i range(max_index)<block_start><if_stmt>sum(confusion_mat[i])<eq>0<and>sum(confusion_mat[: i])<eq>0<block_start>del_index.append(i)<block_end><block_end>confusion_mat=np.delete(confusion_mat del_index axis=0)<line_sep>confusion_mat=np.delete(confusion_mat del_index axis=1)<if_stmt>normalize<is><not><none><block_start>confusion_mat=np.array(confusion_mat dtype=np.float)<block_end>m,n=confusion_mat.shape<if_stmt>normalize<eq>'true'<block_start><for_stmt>i range(m)<block_start>s=np.sum(confusion_mat[i] dtype=float)<if_stmt>s<eq>0<block_start><continue><block_end>confusion_mat[i :]=confusion_mat[i :]/s<line_sep>print(confusion_mat[i :])<block_end><block_end><elif_stmt>normalize<eq>'pred'<block_start><for_stmt>i range(n)<block_start>s=sum(confusion_mat[: i])<if_stmt>s<eq>0<block_start><continue><block_end>confusion_mat[: i]=confusion_mat[: i]/s<block_end><block_end><elif_stmt>normalize<eq>'all'<block_start>s=np.sum(confusion_mat)<if_stmt>s<ne>0<block_start>confusion_mat<augdiv>s<block_end><block_end><return>confusion_mat<block_end><def_stmt>test_activitynet_localization <block_start>data_prefix=osp.normpath(osp.join(osp.dirname(__file__) '../data/eval_localization'))<line_sep>gt_path=osp.join(data_prefix 'gt.json')<line_sep>result_path=osp.join(data_prefix 'result.json')<line_sep>localization=ActivityNetLocalization(gt_path result_path)<line_sep>results=localization.evaluate()<line_sep>mAP=np.array([0.71428571 0.71428571 0.71428571 0.6875 0.6875 0.59722222 0.52083333 0.52083333 0.52083333 0.5])<line_sep>average_mAP=0.6177579365079365<line_sep>assert_array_almost_equal(results[0] mAP)<line_sep>assert_array_almost_equal(results[1] average_mAP)<block_end><def_stmt>test_ava_detection <block_start>data_prefix=osp.normpath(osp.join(osp.dirname(__file__) '../data/eval_detection'))<line_sep>gt_path=osp.join(data_prefix 'gt.csv')<line_sep>result_path=osp.join(data_prefix 'pred.csv')<line_sep>label_map=osp.join(data_prefix 'action_list.txt')<line_sep># eval bbox detection=ava_eval(result_path 'mAP' label_map gt_path <none>)<line_sep>assert_array_almost_equal(detection['mAP@0.5IOU'] 0.09385522)<block_end><def_stmt>test_confusion_matrix # custom confusion_matrix <block_start>gt_labels=[np.int64(random.randint(0 9))<for>_ range(100)]<line_sep>pred_labels=np.random.randint(10 size=100 dtype=np.int64)<for_stmt>normalize [<none> 'true' 'pred' 'all']<block_start>cf_mat=confusion_matrix(pred_labels gt_labels normalize)<line_sep>gt_cf_mat=gt_confusion_matrix(gt_labels pred_labels normalize)<line_sep>assert_array_equal(cf_mat gt_cf_mat)<block_end><with_stmt>pytest.raises(ValueError)# normalize must be in ['true', 'pred', 'all', None] <block_start>confusion_matrix([1] [1] 'unsupport')<block_end><with_stmt>pytest.raises(TypeError)# y_pred must be list or np.ndarray <block_start>confusion_matrix(0.5 [1])<block_end><with_stmt>pytest.raises(TypeError)# y_real must be list or np.ndarray <block_start>confusion_matrix([1] 0.5)<block_end><with_stmt>pytest.raises(TypeError)# y_pred dtype must be np.int64 <block_start>confusion_matrix([0.5] [1])<block_end><with_stmt>pytest.raises(TypeError)# y_real dtype must be np.int64 <block_start>confusion_matrix([1] [0.5])<block_end><block_end><def_stmt>test_topk <block_start>scores=[np.array([-0.2203 -0.7538 1.8789 0.4451 -0.2526]) np.array([-0.0413 0.6366 1.1155 0.3484 0.0395]) np.array([0.0365 0.5158 1.1067 -0.9276 -0.2124]) np.array([0.6232 0.9912 -0.8562 0.0148 1.6413])]<line_sep># top1 acc k=(1 )<line_sep>top1_labels_0=[3 1 1 1]<line_sep>top1_labels_25=[2 0 4 3]<line_sep>top1_labels_50=[2 2 3 1]<line_sep>top1_labels_75=[2 2 2 3]<line_sep>top1_labels_100=[2 2 2 4]<line_sep>res=top_k_accuracy(scores top1_labels_0 k)<assert_stmt>res<eq>[0]<line_sep>res=top_k_accuracy(scores top1_labels_25 k)<assert_stmt>res<eq>[0.25]<line_sep>res=top_k_accuracy(scores top1_labels_50 k)<assert_stmt>res<eq>[0.5]<line_sep>res=top_k_accuracy(scores top1_labels_75 k)<assert_stmt>res<eq>[0.75]<line_sep>res=top_k_accuracy(scores top1_labels_100 k)<assert_stmt>res<eq>[1.0]<line_sep># top1 acc, top2 acc k=(1 2)<line_sep>top2_labels_0_100=[3 1 1 1]<line_sep>top2_labels_25_75=[3 1 2 3]<line_sep>res=top_k_accuracy(scores top2_labels_0_100 k)<assert_stmt>res<eq>[0 1.0]<line_sep>res=top_k_accuracy(scores top2_labels_25_75 k)<assert_stmt>res<eq>[0.25 0.75]<line_sep># top1 acc, top3 acc, top5 acc k=(1 3 5)<line_sep>top5_labels_0_0_100=[1 0 3 2]<line_sep>top5_labels_0_50_100=[1 3 4 0]<line_sep>top5_labels_25_75_100=[2 3 0 2]<line_sep>res=top_k_accuracy(scores top5_labels_0_0_100 k)<assert_stmt>res<eq>[0 0 1.0]<line_sep>res=top_k_accuracy(scores top5_labels_0_50_100 k)<assert_stmt>res<eq>[0 0.5 1.0]<line_sep>res=top_k_accuracy(scores top5_labels_25_75_100 k)<assert_stmt>res<eq>[0.25 0.75 1.0]<block_end><def_stmt>test_mean_class_accuracy <block_start>scores=[np.array([-0.2203 -0.7538 1.8789 0.4451 -0.2526]) np.array([-0.0413 0.6366 1.1155 0.3484 0.0395]) np.array([0.0365 0.5158 1.1067 -0.9276 -0.2124]) np.array([0.6232 0.9912 -0.8562 0.0148 1.6413])]<line_sep># test mean class accuracy in [0, 0.25, 1/3, 0.75, 1.0] mean_cls_acc_0=np.int64([1 4 0 2])<line_sep>mean_cls_acc_25=np.int64([2 0 4 3])<line_sep>mean_cls_acc_33=np.int64([2 2 2 3])<line_sep>mean_cls_acc_75=np.int64([4 2 2 4])<line_sep>mean_cls_acc_100=np.int64([2 2 2 4])<assert_stmt>mean_class_accuracy(scores mean_cls_acc_0)<eq>0<assert_stmt>mean_class_accuracy(scores mean_cls_acc_25)<eq>0.25<assert_stmt>mean_class_accuracy(scores mean_cls_acc_33)<eq>1/3<assert_stmt>mean_class_accuracy(scores mean_cls_acc_75)<eq>0.75<assert_stmt>mean_class_accuracy(scores mean_cls_acc_100)<eq>1.0<block_end><def_stmt>test_mmit_mean_average_precision # One sample <block_start>y_true=[np.array([0 0 1 1])]<line_sep>y_scores=[np.array([0.1 0.4 0.35 0.8])]<line_sep>map=mmit_mean_average_precision(y_scores y_true)<line_sep>precision=[2.0/3.0 0.5 1. 1.]<line_sep>recall=[1. 0.5 0.5 0.]<line_sep>target=-np.sum(np.diff(recall)<times>np.array(precision)[:-1])<assert_stmt>target<eq>map<block_end><def_stmt>test_pairwise_temporal_iou <block_start>target_segments=np.array([])<line_sep>candidate_segments=np.array([])<with_stmt>pytest.raises(ValueError)<block_start>pairwise_temporal_iou(target_segments candidate_segments)<block_end># test temporal iou target_segments=np.array([[1 2] [2 3]])<line_sep>candidate_segments=np.array([[2 3] [2.5 3]])<line_sep>temporal_iou=pairwise_temporal_iou(candidate_segments target_segments)<line_sep>assert_array_equal(temporal_iou [[0 0] [1 0.5]])<line_sep># test temporal overlap_self target_segments=np.array([[1 2] [2 3]])<line_sep>candidate_segments=np.array([[2 3] [2.5 3]])<line_sep>temporal_iou,temporal_overlap_self=pairwise_temporal_iou(candidate_segments target_segments calculate_overlap_self=<true>)<line_sep>assert_array_equal(temporal_overlap_self [[0 0] [1 1]])<line_sep># test temporal overlap_self when candidate_segments is 1d target_segments=np.array([[1 2] [2 3]])<line_sep>candidate_segments=np.array([2.5 3])<line_sep>temporal_iou,temporal_overlap_self=pairwise_temporal_iou(candidate_segments target_segments calculate_overlap_self=<true>)<line_sep>assert_array_equal(temporal_overlap_self [0 1])<block_end><def_stmt>test_average_recall_at_avg_proposals <block_start>ground_truth1={'v_test1':np.array([[0 1] [1 2]]) 'v_test2':np.array([[0 1] [1 2]])}<line_sep>ground_truth2={'v_test1':np.array([[0 1]])}<line_sep>proposals1={'v_test1':np.array([[0 1 1] [1 2 1]]) 'v_test2':np.array([[0 1 1] [1 2 1]])}<line_sep>proposals2={'v_test1':np.array([[10 11 0.6] [11 12 0.4]]) 'v_test2':np.array([[10 11 0.6] [11 12 0.4]])}<line_sep>proposals3={'v_test1':np.array([[i i+1 1/(i+1)]<for>i range(100)])}<line_sep>recall,avg_recall,proposals_per_video,auc=(average_recall_at_avg_proposals(ground_truth1 proposals1 4))<line_sep>assert_array_equal(recall [[0.]<times>49+[0.5]<times>50+[1.]]<times>10)<line_sep>assert_array_equal(avg_recall [0.]<times>49+[0.5]<times>50+[1.])<line_sep>assert_array_almost_equal(proposals_per_video np.arange(0.02 2.02 0.02) decimal=10)<assert_stmt>auc<eq>25.5<line_sep>recall,avg_recall,proposals_per_video,auc=(average_recall_at_avg_proposals(ground_truth1 proposals2 4))<line_sep>assert_array_equal(recall [[0.]<times>100]<times>10)<line_sep>assert_array_equal(avg_recall [0.]<times>100)<line_sep>assert_array_almost_equal(proposals_per_video np.arange(0.02 2.02 0.02) decimal=10)<assert_stmt>auc<eq>0<line_sep>recall,avg_recall,proposals_per_video,auc=(average_recall_at_avg_proposals(ground_truth2 proposals3 100))<line_sep>assert_array_equal(recall [[1.]<times>100]<times>10)<line_sep>assert_array_equal(avg_recall ([1.]<times>100))<line_sep>assert_array_almost_equal(proposals_per_video np.arange(1 101 1) decimal=10)<assert_stmt>auc<eq>99.0<block_end><def_stmt>test_get_weighted_score <block_start>score_a=[np.array([-0.2203 -0.7538 1.8789 0.4451 -0.2526]) np.array([-0.0413 0.6366 1.1155 0.3484 0.0395]) np.array([0.0365 0.5158 1.1067 -0.9276 -0.2124]) np.array([0.6232 0.9912 -0.8562 0.0148 1.6413])]<line_sep>score_b=[np.array([-0.0413 0.6366 1.1155 0.3484 0.0395]) np.array([0.0365 0.5158 1.1067 -0.9276 -0.2124]) np.array([0.6232 0.9912 -0.8562 0.0148 1.6413]) np.array([-0.2203 -0.7538 1.8789 0.4451 -0.2526])]<line_sep>weighted_score=get_weighted_score([score_a] [1])<assert_stmt>np.all(np.isclose(np.array(score_a) np.array(weighted_score)))<line_sep>coeff_a,coeff_b=2. 1.<line_sep>weighted_score=get_weighted_score([score_a score_b] [coeff_a coeff_b])<line_sep>ground_truth=[x<times>coeff_a+y<times>coeff_b<for>x,y zip(score_a score_b)]<assert_stmt>np.all(np.isclose(np.array(ground_truth) np.array(weighted_score)))<block_end><def_stmt>test_mean_average_precision <block_start><def_stmt>content_for_unittest scores labels result<block_start>gt=mean_average_precision(scores labels)<assert_stmt>gt<eq>result<block_end>scores=[np.array([0.1 0.2 0.3 0.4]) np.array([0.2 0.3 0.4 0.1]) np.array([0.3 0.4 0.1 0.2]) np.array([0.4 0.1 0.2 0.3])]<line_sep>label1=np.array([[1 1 0 0] [1 0 1 1] [1 0 1 0] [1 1 0 1]])<line_sep>result1=2/3<line_sep>label2=np.array([[0 1 0 1] [0 1 1 0] [1 0 1 0] [0 0 1 1]])<line_sep>result2=np.mean([0.5 0.5833333333333333 0.8055555555555556 1.0])<line_sep>content_for_unittest(scores label1 result1)<line_sep>content_for_unittest(scores label2 result2)<block_end>
# Lint as: python3 """The base class for all quadrupeds."""<import_from_stmt>typing Any Callable Dict Sequence Tuple Text Union<import_stmt>gin<import_stmt>gym<import_stmt>numpy<as>np<import_from_stmt>pybullet_utils bullet_client<import_from_stmt>pybullet_envs.minitaur.envs_v2.sensors sensor<as>sensor_lib<import_from_stmt>pybullet_envs.minitaur.robots hybrid_motor_model<import_from_stmt>pybullet_envs.minitaur.robots robot_base<import_from_stmt>pybullet_envs.minitaur.robots robot_config<import_from_stmt>pybullet_envs.minitaur.robots robot_urdf_loader<import_from_stmt>pybullet_envs.minitaur.robots.safety data_types<as>safety_data_types<import_from_stmt>pybullet_envs.minitaur.robots.utilities kinematics_utils<line_sep>_UNIT_QUATERNION=(0 0 0 1)<line_sep>_GRAVITY_ACCELERATION_OFFSET=(0 0 10)<line_sep>@gin.configurable<class_stmt>QuadrupedBase(robot_base.RobotBase)<block_start>"""The basic quadruped class for both sim and real robots."""<def_stmt>__init__ self pybullet_client:bullet_client.BulletClient clock:Callable[<ellipsis> float] motor_control_mode:robot_config.MotorControlMode motor_limits:robot_config.MotorLimits motor_model_class:Any=hybrid_motor_model.HybridMotorModel action_filter:Any=<none> sensors:Sequence[sensor_lib.Sensor]=() safety_config:safety_data_types.SafetyConfig=<none> **kwargs <block_start>"""Initializes the class. Args: pybullet_client: The PyBullet client. clock: The sim or real clock. The clock function is typically provided by the gym environment. motor_control_mode: Specifies in which mode the motor operates. motor_limits: The motor limits of the robot. Used by the motor_model_class and action space building. motor_model_class: The motor model to use. Not needed for real robots. action_filter: The filter to smooth and/or regulate the actions. sensors: All sensors mounted on the robot. safety_config: The safety setting for the robot. **kwargs: Additional args. """<line_sep>self._pybullet_client=pybullet_client<line_sep>self._clock=clock<line_sep>self._motor_control_mode=motor_control_mode<line_sep>self._motor_model_class=motor_model_class<line_sep>self._motor_limits=motor_limits<line_sep>self._action_space=<none><line_sep>self._action_names=<none><line_sep>self._action_filter=action_filter<line_sep>self._sensors=sensors<line_sep>self._safety_config=safety_config<line_sep>self._urdf_loader=<none><line_sep>self._last_base_velocity=np.zeros(3)<line_sep>self._last_observation_time=self._clock()<line_sep>self._last_base_acceleration_world=np.zeros(3)<line_sep>self._last_base_acceleration_accelerometer=np.zeros(3)<line_sep>self.load()<block_end><def_stmt>load self base_position:Tuple[float]=<none> base_orientation_quaternion:Tuple[float]=<none> joint_angles:Union[Dict[Text float] Tuple[float]]=<none> <block_start>"""Loads the URDF with the configured pose. Args: base_position: The base position after URDF loading. Will use the configured pose in gin if None. base_orientation_quaternion: The base orientation after URDF loading. Will use the configured values in gin if not specified. joint_angles: The desired joint angles after loading. Will use the configured values if None. """<line_sep># A robot specific pre loading routing. self._pre_load()<if_stmt><not>self._urdf_loader<block_start>self._urdf_loader=robot_urdf_loader.RobotUrdfLoader(pybullet_client=self._pybullet_client)<block_end># Record the urdf pose at loading, which will be used as the rotation # reference for base rotation computation. self._init_urdf_position,self._init_orientation_quat=(self._pybullet_client.getBasePositionAndOrientation(self._urdf_loader.robot_id))<line_sep>unused_position,self._init_orientation_inv_quat=(self._pybullet_client.invertTransform(position=(0 0 0) orientation=self._init_orientation_quat))<line_sep># Joint ids may be different from the motor ids. self._joint_id_dict=self._urdf_loader.get_joint_id_dict()<for_stmt>joint_id self._joint_id_dict.values()# Disables the default motors in PyBullet. <block_start>self._pybullet_client.setJointMotorControl2(bodyIndex=self._urdf_loader.robot_id jointIndex=joint_id controlMode=self._pybullet_client.VELOCITY_CONTROL targetVelocity=0 force=0)<line_sep># Removes the default joint damping in PyBullet. self._pybullet_client.changeDynamics(self._urdf_loader.robot_id joint_id linearDamping=0 angularDamping=0)<block_end># We expect that this is non-empty for all quadrupedes, and should be an # OrderedDict. self._motor_id_dict=self._urdf_loader.get_motor_id_dict()<if_stmt><not>self._motor_id_dict<block_start><raise>ValueError("Motor id dict cannot be empty for quadrupeds.")<block_end>self._motor_ids=self._motor_id_dict.values()<line_sep>self._num_motors=len(self._motor_id_dict)<line_sep>self._build_action_space()<line_sep># Not needed for real robots. <if_stmt>self._motor_model_class# TODO(b/151664871): Also supports position/velocity limits in the motor # model. <block_start>self._motor_model=self._motor_model_class(num_motors=self._num_motors motor_control_mode=self._motor_control_mode torque_lower_limits=self._motor_limits.torque_lower_limits torque_upper_limits=self._motor_limits.torque_upper_limits )<block_end># Caches the variable for faster computation during stepping. self._motor_direction_dict=self._urdf_loader.get_joint_direction_dict(self._motor_id_dict.keys())<line_sep>self._motor_directions=np.array(list(self._motor_direction_dict.values()))<line_sep>self._motor_offset_dict=self._urdf_loader.get_joint_offset_dict(self._motor_id_dict.keys())<line_sep>self._motor_offsets=np.array(list(self._motor_offset_dict.values()))<line_sep># A robot specific routine post loading. self._on_load()<line_sep># Robot sensors may use information from the class. So we initialize them # after the loading is done. <for_stmt>sensor self._sensors<block_start>sensor.set_robot(self)<block_end><block_end><def_stmt>_build_action_space self<block_start>"""Builds the action space of the robot using the motor limits."""<if_stmt>self._motor_control_mode<eq>robot_config.MotorControlMode.POSITION<block_start>self._action_space=gym.spaces.Box(low=self._motor_limits.angle_lower_limits high=self._motor_limits.angle_upper_limits shape=(self._num_motors ) dtype=np.float32)<line_sep># TODO(b/159160184) Make dtype configurable. self._action_names=tuple("POSITION_{}".format(motor)<for>motor self._motor_id_dict.keys())<block_end><elif_stmt>self._motor_control_mode<eq>robot_config.MotorControlMode.TORQUE<block_start>self._action_space=gym.spaces.Box(low=self._motor_limits.torque_lower_limits high=self._motor_limits.torque_upper_limits shape=(self._num_motors ) dtype=np.float32)<line_sep>self._action_names=tuple("TORQUE_{}".format(motor)<for>motor self._motor_id_dict.keys())<block_end><elif_stmt>self._motor_control_mode<eq>robot_config.MotorControlMode.HYBRID<block_start>hybrid_action_limits_low=[self._motor_limits.angle_lower_limits # q # q_dot self._motor_limits.velocity_lower_limits 0 # kp 0 # kd self._motor_limits.torque_lower_limits]<line_sep># tau hybrid_action_limits_high=[self._motor_limits.angle_upper_limits self._motor_limits.velocity_upper_limits np.inf np.inf self._motor_limits.torque_upper_limits]<line_sep>space_low=np.full((self._num_motors robot_config.HYBRID_ACTION_DIMENSION) hybrid_action_limits_low).ravel()<line_sep>space_high=np.full((self._num_motors robot_config.HYBRID_ACTION_DIMENSION) hybrid_action_limits_high).ravel()<line_sep>self._action_space=gym.spaces.Box(low=space_low high=space_high dtype=np.float32)<line_sep>self._action_names=tuple("HYBRID_{}".format(motor)<for>motor self._motor_id_dict.keys())<block_end><else_stmt><block_start><raise>NotImplementedError("Not yet implemented!")<block_end><block_end><def_stmt>_pre_load self<block_start>"""Robot specific pre load routine. For example, this allows configuration of the URDF loader. """<line_sep><pass><block_end><def_stmt>_on_load self<block_start>"""Robot specific post load routine. For example, we need to add add additional hinge constraints to the leg components of Minitaur after loading. """<line_sep><pass><block_end>@gin.configurable<def_stmt>reset self base_position:Tuple[float]=<none> base_orientation_quaternion:Tuple[float]=<none> joint_angles:Union[Dict[Text float] Tuple[float]]=<none> save_base_pose:bool=<false> **kwargs <block_start>"""Resets the robot base and joint pose without reloading the URDF. Base pose resetting only works for simulated robots or visualization of real robots. This routine also updates the initial observation dict. Args: base_position: The desired base position. Will use the configured pose in gin if None. Does not affect the position of the real robots in general. base_orientation_quaternion: The base orientation after resetting. Will use the configured values in gin if not specified. joint_angles: The desired joint angles after resetting. Will use the configured values if None. save_base_pose: Save the base position and orientation as the default pose after resetting. **kwargs: Other args for backward compatibility. TODO(b/151975607): Remove after migration. """<line_sep># Reset the robot's motor model. self._motor_model.reset()<line_sep># Reset the quantities for computing base acceleration. self._last_base_velocity=np.zeros(3)<line_sep>self._last_observation_time=self._clock()<line_sep>self._last_base_acceleration_world=np.zeros(3)<line_sep>self._last_base_acceleration_accelerometer=np.zeros(3)<line_sep># Solves chicken and egg problem. We need to run a control step to obtain # the first motor torques. self._motor_torques=np.zeros(self._num_motors)<line_sep># Receives a set of observation from the robot in case the reset function # needs to use them. self.receive_observation()<line_sep>self._reset_base_pose(base_position base_orientation_quaternion)<line_sep>self._reset_joint_angles(joint_angles)<if_stmt>save_base_pose# Records the base pose at resetting again, in case Reset is called with a # different base orientation. This base pose will be used as zero # rotation reference for base rotation computation. <block_start>self._init_urdf_position,self._init_orientation_quat=(self._pybullet_client.getBasePositionAndOrientation(self._urdf_loader.robot_id))<line_sep>unused_position,self._init_orientation_inv_quat=(self._pybullet_client.invertTransform(position=(0 0 0) orientation=self._init_orientation_quat))<block_end># Updates the observation at the end of resetting. self.receive_observation()<line_sep>self._time_at_reset=self._clock()<block_end><def_stmt>GetTimeSinceReset self<block_start><return>self._clock()-self._time_at_reset<block_end><def_stmt>_reset_base_pose self position=<none> orientation_quat=<none><block_start>"""Resets the pose of the robot's base. Base pose resetting only works for simulated robots or visualization of real robots. Args: position: The desired base position. Will use the configured pose in gin if None. orientation_quat: The desired base rotation. Will use the configured default pose in None. """<line_sep>self._urdf_loader.reset_base_pose(position orientation_quat)<block_end><def_stmt>_reset_joint_angles self joint_angles:Union[Tuple[float] Dict[Text float]]=<none><block_start>"""Resets the joint pose. Real robots need to specify their routine to send joint angles. Simulated Minitaur robots also needs to use dynamics to drive the motor joints, due to the additional hinge joints not present in the URDF. Args: joint_angles: The joint pose if provided. Will use the robot default pose from configuration. """<line_sep># TODO(b/148897311): Supports tuple as the input. self._urdf_loader.reset_joint_angles(joint_angles)<block_end><def_stmt>terminate self<block_start>"""The safe exit routine for the robot. Only implemented for real robots. """<line_sep><pass><block_end><def_stmt>step self action:Any num_sub_steps:int=1<block_start>"""Steps the simulation. This is maintained for backward compatibility with the old robot class. Args: action: The control command to be executed by the robot. num_sub_steps: Each action can be applied (possibly with interpolation) multiple timesteps, to simulate the elapsed time between two consecutive commands on real robots. """<line_sep>action=self.pre_control_step(action)<for_stmt>_ range(num_sub_steps)# TODO(b/149252003): Add sub sampling. <block_start>self.apply_action(action)<line_sep># Timestep is pre-determined at simulation setup. self._pybullet_client.stepSimulation()<line_sep>self.receive_observation()<block_end>self.post_control_step()<block_end><def_stmt>pre_control_step self action:Any control_timestep:float=<none><block_start>"""Processes the action and updates per control step quantities. Args: action: The input control command. control_timestep: The control time step in the environment. TODO(b/153835005), we can remove this once we pass env to the robot. Returns: The filtered action. """<if_stmt>self._action_filter# We assume the filter will create a set of interpolated results. <block_start>action=self._action_filter.filter(action)<block_end><return>action<block_end><def_stmt>apply_action self motor_commands motor_control_mode=<none># TODO(b/148897311): Supports dict in the future. <block_start>motor_commands=np.asarray(motor_commands)<line_sep># We always use torque based control at the lowest level for quadrupeds. unused_observed_torques,actual_torques=(self._motor_model.get_motor_torques(motor_commands motor_control_mode))<line_sep>self._motor_torques=actual_torques<line_sep># Converts the motor torques to URDF joint space, which may have different # directions. applied_motor_torques=np.multiply(actual_torques self._motor_directions)<line_sep>self._pybullet_client.setJointMotorControlArray(bodyIndex=self._urdf_loader.robot_id jointIndices=self._motor_ids controlMode=self._pybullet_client.TORQUE_CONTROL forces=applied_motor_torques)<block_end><def_stmt>_get_base_roll_pitch_yaw_rate self<block_start>_,angular_velocity=self._pybullet_client.getBaseVelocity(self._urdf_loader.robot_id)<line_sep><return>kinematics_utils.rotate_to_base_frame(self._pybullet_client self.urdf_loader.robot_id angular_velocity self._init_orientation_inv_quat)<block_end><def_stmt>_get_base_velocity self<block_start>base_velocity,_=self._pybullet_client.getBaseVelocity(self._urdf_loader.robot_id)<line_sep><return>base_velocity<block_end><def_stmt>_update_base_acceleration self<block_start>"""Update the base acceleration using finite difference."""<if_stmt>self._last_observation_time<l>self.timestamp<block_start>self._last_base_acceleration_world=(np.array(self._base_velocity)-self._last_base_velocity)/(self.timestamp-self._last_observation_time)<line_sep>_,inv_base_orientation=self.pybullet_client.invertTransform(np.zeros(3) np.array(self.base_orientation_quaternion))<line_sep># An offset is added to the acceleration measured in the world frame # because the accelerometer reading is in the frame of free-falling robot. base_acceleration_accelerometer=self.pybullet_client.multiplyTransforms(np.zeros(3) inv_base_orientation self._last_base_acceleration_world+_GRAVITY_ACCELERATION_OFFSET _UNIT_QUATERNION)[0]<line_sep>self._last_base_acceleration_accelerometer=np.array(base_acceleration_accelerometer)<block_end><block_end><def_stmt>receive_observation self<block_start>"""Receives the observations for all sensors."""<line_sep># Update the intrinsic values including the joint angles, joint # velocities, and imu readings. self._base_position,base_orientation_quat=(self._pybullet_client.getBasePositionAndOrientation(self._urdf_loader.robot_id))<line_sep>_,self._base_orientation_quat=self._pybullet_client.multiplyTransforms(positionA=(0 0 0) orientationA=self._init_orientation_inv_quat positionB=(0 0 0) orientationB=base_orientation_quat)<line_sep>self._base_velocity=self._get_base_velocity()<line_sep>self._base_roll_pitch_yaw=self._pybullet_client.getEulerFromQuaternion(self._base_orientation_quat)<line_sep>self._base_roll_pitch_yaw_rate=self._get_base_roll_pitch_yaw_rate()<line_sep>self._joint_states=self._pybullet_client.getJointStates(self._urdf_loader.robot_id self._motor_ids)<line_sep>self._motor_angles=np.array([joint_state[0]<for>joint_state self._joint_states])<line_sep>self._motor_angles=(self._motor_angles-self._motor_offsets)<times>self._motor_directions<line_sep>self._motor_velocities=np.array([joint_state[1]<for>joint_state self._joint_states])<line_sep>self._motor_velocities=self._motor_velocities<times>self._motor_directions<line_sep># We use motor models to track the delayed motor positions and velocities # buffer. <if_stmt>self._motor_model<block_start>self._motor_model.update(self._clock() self._motor_angles self._motor_velocities)<block_end>self._update_base_acceleration()<line_sep># Update the latest base velocity and timestamp at the end of the API. self._last_base_velocity=np.array(self._base_velocity)<line_sep>self._last_observation_time=self.timestamp<block_end><def_stmt>post_control_step self<block_start>"""Called at the end of a control step outside the action repeat loop."""<line_sep><pass><block_end># TODO(tingnan): Change from "foot_positions" to "feet_positions". <def_stmt>motor_angles_from_foot_positions self foot_positions position_in_world_frame=<false><block_start>"""Use IK to compute the motor angles, given the feet links' positions. Args: foot_positions: The foot links' positions in frame specified by the next parameter. The input is a numpy array of size (4, 3). position_in_world_frame: Whether the foot_positions are specified in the world frame. Returns: A tuple. The position indices and the angles for all joints along the leg. The position indices is consistent with the joint orders as returned by GetMotorAngles API. """<line_sep>joint_position_idxs=np.arange(self.num_motors)<line_sep>foot_link_ids=tuple(self._urdf_loader.get_end_effector_id_dict().values())<line_sep>joint_angles=kinematics_utils.joint_angles_from_link_positions(pybullet_client=self.pybullet_client urdf_id=self.robot_id link_positions=foot_positions link_ids=foot_link_ids joint_dof_ids=joint_position_idxs positions_are_in_world_frame=position_in_world_frame)<line_sep>joint_angles=np.multiply(np.asarray(joint_angles)-np.asarray(self._motor_offsets) self._motor_directions)<line_sep><return>joint_position_idxs joint_angles<block_end># TODO(tingnan): Change from "foot_positions" to "feet_positions". <def_stmt>foot_positions self position_in_world_frame=<false><block_start>"""Returns the robot's foot positions in the base/world frame."""<line_sep>foot_positions=[]<line_sep>foot_link_ids=tuple(self._urdf_loader.get_end_effector_id_dict().values())<for_stmt>foot_id foot_link_ids<block_start><if_stmt><not>position_in_world_frame<block_start>foot_positions.append(kinematics_utils.link_position_in_base_frame(pybullet_client=self.pybullet_client urdf_id=self.robot_id link_id=foot_id ))<block_end><else_stmt><block_start>foot_positions.append(kinematics_utils.link_position_in_world_frame(pybullet_client=self.pybullet_client urdf_id=self.robot_id link_id=foot_id ))<block_end><block_end><return>np.array(foot_positions)<block_end><def_stmt>feet_contact_forces self<arrow>Sequence[np.ndarray]<block_start>"""Gets the contact forces on all feet. Reals robot may use a robot specific implementation. For example, the Laikago will measure each contact force in the corresponding foot's local frame, and this force will not be the total contact force due to the sensor limitation. For simulated robots, we wll always report the force in the base frame. Returns: A list of foot contact forces. """<line_sep>foot_link_ids=tuple(self._urdf_loader.get_end_effector_id_dict().values())<line_sep>contact_forces=[np.zeros(3)<for>_ range(len(foot_link_ids))]<line_sep>all_contacts=self._pybullet_client.getContactPoints(bodyA=self._urdf_loader.robot_id)<for_stmt>contact all_contacts<block_start>(unused_flag body_a_id body_b_id link_a_id unused_link_b_id unused_pos_on_a unused_pos_on_b contact_normal_b_to_a unused_distance normal_force friction_1 friction_direction_1 friction_2 friction_direction_2)=contact<line_sep># Ignore self contacts <if_stmt>body_b_id<eq>body_a_id<block_start><continue><block_end><if_stmt>link_a_id<in>foot_link_ids<block_start>normal_force=np.array(contact_normal_b_to_a)<times>normal_force<line_sep>friction_force=np.array(friction_direction_1)<times>friction_1+np.array(friction_direction_2)<times>friction_2<line_sep>force=normal_force+friction_force<line_sep>local_force=kinematics_utils.rotate_to_base_frame(self._pybullet_client self.urdf_loader.robot_id force self._init_orientation_inv_quat)<line_sep>local_force_norm=np.linalg.norm(local_force)<line_sep>toe_link_order=foot_link_ids.index(link_a_id)<if_stmt>local_force_norm<g>0<block_start>contact_forces[toe_link_order]<augadd>local_force<block_end><block_end><else_stmt><block_start><continue><block_end><block_end><return>contact_forces<block_end><def_stmt>compute_jacobian_for_one_leg self leg_id:int<arrow>np.ndarray<block_start>"""Compute the Jacobian for a given leg. Args: leg_id: Index of the leg for which the jacobian is computed. Returns: The 3 x N transposed Jacobian matrix. where N is the total DoFs of the robot. For a quadruped, the first 6 columns of the matrix corresponds to the CoM translation and rotation. The columns corresponds to a leg can be extracted with indices [6 + leg_id * 3: 6 + leg_id * 3 + 3]. Note that the jacobian is calculated for motors, which takes motor directions into consideration. """<line_sep>com_dof=self._urdf_loader.com_dof<line_sep>foot_link_ids=tuple(self._urdf_loader.get_end_effector_id_dict().values())<line_sep><return>kinematics_utils.compute_jacobian(pybullet_client=self.pybullet_client urdf_id=self.robot_id link_id=foot_link_ids[leg_id] all_joint_positions=[state[0]<for>state self._joint_states])<times>np.concatenate([np.ones(com_dof) self._motor_directions])<block_end><def_stmt>map_contact_force_to_joint_torques self leg_id:int contact_force:np.ndarray<arrow>Dict[int float]<block_start>"""Maps the foot contact force to the leg joint torques. Args: leg_id: Index of the leg for which the jacobian is computed. contact_force: Desired contact force experted by the leg. Returns: A dict containing the torques for each motor on the leg. """<line_sep>foot_link_ids=tuple(self._urdf_loader.get_end_effector_id_dict().values())<line_sep>jv=self.compute_jacobian_for_one_leg(leg_id)<line_sep>all_motor_torques=np.matmul(contact_force jv)<line_sep>motor_torques={}<line_sep>motors_per_leg=self.num_motors<floordiv>len(foot_link_ids)<line_sep>com_dof=self._urdf_loader.com_dof<for_stmt>joint_id range(leg_id<times>motors_per_leg (leg_id+1)<times>motors_per_leg)<block_start>motor_torques[joint_id]=all_motor_torques[com_dof+joint_id]<block_end><return>motor_torques<block_end>@classmethod<def_stmt>get_constants cls<block_start><raise>NotImplementedError("Not yet implemented!")<block_end>@property<def_stmt>timestamp self<block_start><return>self._clock()<block_end>@property<def_stmt>action_space self<block_start><return>self._action_space<block_end>@property<def_stmt>action_names self<block_start><return>self._action_names<block_end>@property<def_stmt>base_orientation_quaternion self<block_start>"""Gets the base orientation as a quaternion. The base orientation is always relative to the init_orientation, which can be updated by Reset function. This is necessary as many URDF can have an internal frame that is not z-up, so if we don't provide an init_orientation (through Reset), the loaded robot can have its belly facing the horizontal direction. Returns: The base orientation in quaternion. """<line_sep><return>self._base_orientation_quat<block_end>@property<def_stmt>base_orientation_quaternion_default_frame self<block_start>"""Gets the base orientation in the robot's default frame. This is the base orientation in whatever frame the robot specifies. For simulated robot this is the URDF's internal frame. For real robot this can be based on the rpy reading determined by the IMU. Returns: The base orientation in quaternion in a robot default frame. """<line_sep>_,base_orientation_quat=(self._pybullet_client.getBasePositionAndOrientation(self._urdf_loader.robot_id))<line_sep><return>base_orientation_quat<block_end>@property<def_stmt>sensors self<block_start><return>self._sensors<block_end>@property<def_stmt>base_roll_pitch_yaw self<block_start><return>self._base_roll_pitch_yaw<block_end>@property<def_stmt>base_roll_pitch_yaw_rate self<block_start><return>self._base_roll_pitch_yaw_rate<block_end>@property<def_stmt>base_position self<block_start><return>self._base_position<block_end>@property<def_stmt>base_velocity self<block_start><return>self._base_velocity<block_end>@property<def_stmt>is_safe self<block_start><return><true><block_end>@property<def_stmt>num_motors self<block_start><return>self._num_motors<block_end>@property<def_stmt>motor_model self<block_start><return>self._motor_model<block_end>@property<def_stmt>motor_limits self<arrow>robot_config.MotorLimits<block_start><return>self._motor_limits<block_end>@property<def_stmt>motor_angles self<block_start><return>self._motor_angles<block_end>@property<def_stmt>motor_velocities self<block_start><return>self._motor_velocities<block_end>@property<def_stmt>motor_torques self<block_start><return>self._motor_torques<block_end>@property<def_stmt>pybullet_client self<block_start><return>self._pybullet_client<block_end>@property<def_stmt>urdf_loader self<block_start><return>self._urdf_loader<block_end>@property<def_stmt>robot_id self<block_start><return>self._urdf_loader.robot_id<block_end>@property<def_stmt>initital_orientation_inverse_quaternion self<block_start><return>self._init_orientation_inv_quat<block_end>@property<def_stmt>base_acceleration_accelerometer self<block_start>"""Get the base acceleration measured by an accelerometer. The acceleration is measured in the local frame of a free-falling robot, which is consistent with the robot's IMU measurements. Here the gravitational acceleration is first added to the acceleration in the world frame, which is then converted to the local frame of the robot. """<line_sep><return>np.array(self._last_base_acceleration_accelerometer)<block_end>@property<def_stmt>base_acceleration self<block_start>"""Get the base acceleration in the world frame."""<line_sep><return>np.array(self._last_base_acceleration_world)<block_end><block_end>
# Copyright 2019 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. <import_stmt>model<import_stmt>view_tests_base<class_stmt>AdminStatisticsViewTests(view_tests_base.ViewTestsBase)<block_start><def_stmt>setUp self<block_start>super(AdminStatisticsViewTests self).setUp()<line_sep>self.data_generator.repo()<line_sep>self.counter=model.UsageCounter.create('haiti')<line_sep>self.login_as_manager()<block_end><def_stmt>get_page_doc self<block_start><return>self.to_doc(self.client.get('/global/admin/statistics/' secure=<true>))<block_end><def_stmt>test_person_counter self<block_start>self.counter.person=3<line_sep>self.counter.put()<line_sep>doc=self.get_page_doc()<assert_stmt>'haiti'<in>doc.text<assert_stmt>'# Persons'<in>doc.text<assert_stmt>doc.cssselect_one('#haiti-persons').text<eq>'3'<block_end><def_stmt>test_note_counter self<block_start>self.counter.note=5<line_sep>self.counter.unspecified=5<line_sep>self.counter.put()<line_sep>doc=self.get_page_doc()<assert_stmt>'haiti'<in>doc.text<assert_stmt>'# Note'<in>doc.text<assert_stmt>doc.cssselect_one('#haiti-notes').text<eq>'5'<assert_stmt>doc.cssselect_one('#haiti-num_notes_unspecified').text<eq>'5'<block_end><def_stmt>test_is_note_author_counter self<block_start>self.counter.note=1<line_sep>self.counter.is_note_author=1<line_sep>self.counter.put()<line_sep>doc=self.get_page_doc()<assert_stmt>doc.cssselect_one('#haiti-num_notes_is_note_author').text<eq>'1'<block_end><def_stmt>test_status_counter self<block_start><def_stmt>set_counter_and_check status_name num<block_start>setattr(self.counter status_name num)<line_sep>self.counter.put()<line_sep>doc=self.get_page_doc()<assert_stmt>'haiti'<in>doc.text<assert_stmt>status_name<in>doc.text<assert_stmt>doc.cssselect_one('#haiti-num_notes_%s'%status_name).text<eq>str(num)<block_end>set_counter_and_check('is_note_author' 3)<line_sep>set_counter_and_check('believed_alive' 5)<line_sep>set_counter_and_check('believed_dead' 2)<line_sep>set_counter_and_check('believed_missing' 4)<line_sep>set_counter_and_check('information_sought' 6)<block_end><block_end>
<class_stmt>BaseSubmission<block_start><def_stmt>__init__ self team_name player_names<block_start>self.team_name=team_name<line_sep>self.player_names=player_names<block_end><def_stmt>get_actions self obs<block_start>''' Overview: You must implement this function. '''<line_sep><raise>NotImplementedError<block_end><block_end>
# ***************************************************************************** # # Copyright (c) 2021, the pyEX authors. # # This file is part of the pyEX library, distributed under the terms of # the Apache License 2.0. The full license can be found in the LICENSE file. # <import_from_stmt>.timeseries timeSeries timeSeriesAsync timeSeriesDF timeSeriesInventory timeSeriesInventoryAsync timeSeriesInventoryDF <line_sep>
""" Signals for easy use in django projects """<try_stmt><block_start><import_from_stmt>django dispatch<line_sep>short_task=dispatch.Signal(providing_args=["args" "kwargs"])<line_sep>long_task=dispatch.Signal(providing_args=["args" "kwargs"])<line_sep>message_signal=dispatch.Signal(providing_args=["data" "dispatcher"])<line_sep>USE_DJANGO_SIGNALS=<true><block_end><except_stmt>ImportError<block_start>USE_DJANGO_SIGNALS=<false><block_end>
"""The classic exhibitor of chaos, consisting of 3 coupled ODEs. The ODEs are derived by modelling, with many simplifications, the fluid convection between horizontal plates with different temperatures. Its phase-plot (with typical param settings) looks like a butterfly. See demo.py for more info. """<import_stmt>numpy<as>np<import_stmt>dapper.mods<as>modelling<import_from_stmt>.extras LPs d2x_dtdx dstep_dx<line_sep># Constants sig=10.0<line_sep>rho=28.0<line_sep>beta=8.0/3<line_sep># Suggested values x0=np.array([1.509 -1.531 25.46])<line_sep>Tplot=4.0<line_sep>@modelling.ens_compatible<def_stmt>dxdt x<block_start>"""Evolution equation (coupled ODEs) specifying the dynamics."""<line_sep>x,y,z=x<line_sep>dx=sig<times>(y-x)<line_sep>dy=rho<times>x-y-x<times>z<line_sep>dz=x<times>y-beta<times>z<line_sep><return>np.array([dx dy dz])<block_end>step=modelling.with_rk4(dxdt autonom=<true>)<line_sep>
<import_from_stmt>plex_database.core db<import_from_stmt>plex_database.models.directory Directory<import_from_stmt>plex_database.models.media_item MediaItem<import_from_stmt>peewee *<class_stmt>MediaPart(Model)<block_start><class_stmt>Meta<block_start>database=db<line_sep>db_table='media_parts'<block_end>media_item=ForeignKeyField(MediaItem null=<true> related_name='media_parts')<line_sep>directory=ForeignKeyField(Directory null=<true> related_name='media_parts')<line_sep>hash=CharField(null=<true>)<line_sep>open_subtitle_hash=CharField(null=<true>)<line_sep>file=CharField(null=<true>)<line_sep>index=IntegerField(null=<true>)<line_sep>size=BigIntegerField(null=<true>)<line_sep>duration=IntegerField(null=<true>)<line_sep>created_at=DateTimeField(null=<true>)<line_sep>updated_at=DateTimeField(null=<true>)<line_sep>deleted_at=DateTimeField(null=<true>)<line_sep>extra_data=CharField(null=<true>)<block_end>
# encoding: utf-8 # # Task worker - design 2 # Adds pub-sub flow to receive and respond to kill signal # # Author: <NAME> (brainsik) <spork(dash)zmq(at)theory(dot)org> # <import_stmt>sys<import_stmt>time<import_stmt>zmq<line_sep>context=zmq.Context()<line_sep># Socket to receive messages on receiver=context.socket(zmq.PULL)<line_sep>receiver.connect("tcp://localhost:5557")<line_sep># Socket to send messages to sender=context.socket(zmq.PUSH)<line_sep>sender.connect("tcp://localhost:5558")<line_sep># Socket for control input controller=context.socket(zmq.SUB)<line_sep>controller.connect("tcp://localhost:5559")<line_sep>controller.setsockopt(zmq.SUBSCRIBE b"")<line_sep># Process messages from receiver and controller poller=zmq.Poller()<line_sep>poller.register(receiver zmq.POLLIN)<line_sep>poller.register(controller zmq.POLLIN)<line_sep># Process messages from both sockets <while_stmt><true><block_start>socks=dict(poller.poll())<if_stmt>socks.get(receiver)<eq>zmq.POLLIN<block_start>message=receiver.recv_string()<line_sep># Process task workload=int(message)# Workload in msecs # Do the work time.sleep(workload/1000.0)<line_sep># Send results to sink sender.send_string(message)<line_sep># Simple progress indicator for the viewer sys.stdout.write(".")<line_sep>sys.stdout.flush()<block_end># Any waiting controller command acts as 'KILL' <if_stmt>socks.get(controller)<eq>zmq.POLLIN<block_start><break><block_end><block_end>print("Done")<line_sep># Finished receiver.close()<line_sep>sender.close()<line_sep>controller.close()<line_sep>context.term()<line_sep>
"""Input and output support for data."""<import_from_stmt>.io_dict from_dict<try_stmt><block_start><import_stmt>ujson<as>json<block_end><except_stmt>ImportError# Can't find ujson using json # mypy struggles with conditional imports expressed as catching ImportError: # https://github.com/python/mypy/issues/1153 <block_start><import_stmt>json<block_end># type: ignore <def_stmt>from_json filename<block_start>"""Initialize object from a json file. Will use the faster `ujson` (https://github.com/ultrajson/ultrajson) if it is available. Parameters ---------- filename : str location of json file Returns ------- InferenceData object """<with_stmt>open(filename "rb")<as>file<block_start>idata_dict=json.load(file)<block_end><return>from_dict(**idata_dict save_warmup=<true>)<block_end><def_stmt>to_json idata filename<block_start>"""Save dataset as a json file. Will use the faster `ujson` (https://github.com/ultrajson/ultrajson) if it is available. WARNING: Only idempotent in case `idata` is InferenceData. Parameters ---------- idata : InferenceData Object to be saved filename : str name or path of the file to load trace Returns ------- str filename saved to """<line_sep>file_name=idata.to_json(filename)<line_sep><return>file_name<block_end>
<import_stmt>sublime<import_stmt>sublime_plugin<import_stmt>logging<import_stmt>difflib<import_from_stmt>random random<import_from_stmt>.clipboard g_clipboard_history<import_from_stmt>.recency RecencyManager<import_from_stmt>.terminal Terminal<line_sep>logger=logging.getLogger('Terminus')<class_stmt>TerminusCoreEventListener(sublime_plugin.EventListener)<block_start><def_stmt>on_activated_async self view<block_start>recency_manager=RecencyManager.from_view(view)<if_stmt><not>view.settings().get("terminus_view" <false>)<block_start>recency_manager.cycling_panels=<false><line_sep><return><block_end><if_stmt>random()<g>0.7# occassionally cull zombie terminals <block_start>Terminal.cull_terminals()<line_sep># clear undo stack view.run_command("terminus_clear_undo_stack")<block_end>terminal=Terminal.from_id(view.id())<if_stmt>terminal<block_start>recency_manager.set_recent_terminal(view)<line_sep><return><block_end>settings=view.settings()<if_stmt><not>settings.has("terminus_view.args")<block_start><return><block_end><if_stmt>settings.get("terminus_view.finished" <false>)<block_start><return><block_end>kwargs=settings.get("terminus_view.args")<if_stmt>"cmd"<not><in>kwargs<block_start><return><block_end>sublime.set_timeout(<lambda>:view.run_command("terminus_activate" kwargs) 100)<block_end><def_stmt>on_pre_close self view# panel doesn't trigger on_pre_close <block_start>terminal=Terminal.from_id(view.id())<if_stmt>terminal<block_start>terminal.kill()<block_end><block_end><def_stmt>on_modified self view# to catch unicode input <block_start>terminal=Terminal.from_id(view.id())<if_stmt><not>terminal<or><not>terminal.process.isalive()<block_start><return><block_end>command,args,_=view.command_history(0)<if_stmt>command.startswith("terminus")<block_start><return><block_end><elif_stmt>command<eq>"insert"<and>"characters"<in>args<and>len(view.sel())<eq>1<and>view.sel()[0].empty()<block_start>chars=args["characters"]<line_sep>current_cursor=view.sel()[0].end()<line_sep>region=sublime.Region(max(current_cursor-len(chars) self._cursor) current_cursor)<line_sep>text=view.substr(region)<line_sep>self._cursor=current_cursor<line_sep>logger.debug("text {} detected".format(text))<line_sep>view.run_command("terminus_paste_text" {"text":text "bracketed":<false>})<block_end><elif_stmt>command<block_start>logger.debug("undo {}".format(command))<line_sep>view.run_command("soft_undo")<block_end><block_end><def_stmt>on_selection_modified self view<block_start>terminal=Terminal.from_id(view.id())<if_stmt><not>terminal<or><not>terminal.process.isalive()<block_start><return><block_end><if_stmt>len(view.sel())<ne>1<or><not>view.sel()[0].empty()<block_start><return><block_end>self._cursor=view.sel()[0].end()<block_end><def_stmt>on_text_command self view name args<block_start><if_stmt><not>view.settings().get('terminus_view')<block_start><return><block_end><if_stmt>name<eq>"copy"<block_start><return>("terminus_copy" <none>)<block_end><elif_stmt>name<eq>"paste"<block_start><return>("terminus_paste" <none>)<block_end><elif_stmt>name<eq>"paste_and_indent"<block_start><return>("terminus_paste" <none>)<block_end><elif_stmt>name<eq>"paste_from_history"<block_start><return>("terminus_paste_from_history" <none>)<block_end><elif_stmt>name<eq>"paste_selection_clipboard"<block_start>self._pre_paste=view.substr(view.visible_region())<block_end><elif_stmt>name<eq>"undo"<block_start><return>("noop" <none>)<block_end><block_end><def_stmt>on_post_text_command self view name args<block_start><if_stmt><not>view.settings().get('terminus_view')<block_start><return><block_end><if_stmt>name<eq>'terminus_copy'<block_start>g_clipboard_history.push_text(sublime.get_clipboard())<block_end><elif_stmt>name<eq>"paste_selection_clipboard"<block_start>added=[df[2:]<for>df difflib.ndiff(self._pre_paste view.substr(view.visible_region()))<if>df[0]<eq>'+']<line_sep>view.run_command("terminus_paste_text" {"text":"".join(added)})<block_end><block_end><def_stmt>on_window_command self window command_name args<block_start><if_stmt>command_name<eq>"show_panel"<block_start>panel=args["panel"].replace("output." "")<line_sep>view=window.find_output_panel(panel)<if_stmt>view<block_start>terminal=Terminal.from_id(view.id())<if_stmt>terminal<and>terminal.show_in_panel<block_start>recency_manager=RecencyManager.from_view(view)<line_sep>recency_manager.set_recent_terminal(view)<block_end><block_end><block_end><block_end><block_end>
<import_stmt>torch<def_stmt>conjugate_gradient f_Ax b cg_iters=10 residual_tol=1e-10<block_start>p=b.clone().detach()<line_sep>r=b.clone().detach()<line_sep>x=torch.zeros_like(b).float()<line_sep>rdotr=torch.dot(r r)<for_stmt>i range(cg_iters)<block_start>z=f_Ax(p).detach()<line_sep>v=rdotr/torch.dot(p z)<line_sep>x<augadd>v<times>p<line_sep>r<augsub>v<times>z<line_sep>newrdotr=torch.dot(r r)<line_sep>mu=newrdotr/rdotr<line_sep>p=r+mu<times>p<line_sep>rdotr=newrdotr<if_stmt>rdotr.item()<l>residual_tol<block_start><break><block_end><block_end><return>x.detach()<block_end>
#MenuTitle: Add TTF Autohint Control Instructions for Current Glyph # -*- coding: utf-8 -*- <import_from_future_stmt> division print_function unicode_literals<try_stmt><block_start><import_from_stmt>builtins str<block_end><except_stmt>Exception<as>e<block_start>print("Warning: 'future' module not installed. Run 'sudo pip install future' in Terminal.")<block_end>__doc__=""" Adds a touch line for a given up/down amount to the Control Instructions of the current instance. """<import_from_stmt>AppKit NSPasteboard NSStringPboardType<import_from_stmt>Foundation NSPoint<import_stmt>math vanilla<def_stmt>sizeStringIsOK sizeString<block_start>""" Checks if the size string adheres to the syntax. """<for_stmt>character sizeString<block_start><if_stmt><not>character<in>"1234567890-, "<block_start><return><false><block_end><elif_stmt>character<eq>"#"<block_start><return><true><block_end><block_end><return><true><block_end><def_stmt>italic yOffset italicAngle=0.0 pivotalY=0.0<block_start>""" Returns the italicized position of an NSPoint 'thisPoint' for a given angle 'italicAngle' and the pivotal height 'pivotalY', around which the italic slanting is executed, usually half x-height. Usage: myPoint = italicize(myPoint,10,xHeight*0.5) """<line_sep>x=0.0<line_sep>#yOffset = thisPoint.y - pivotalY # calculate vertical offset italicAngle=math.radians(italicAngle)# convert to radians tangens=math.tan(italicAngle)# math.tan needs radians horizontalDeviance=tangens<times>yOffset# vertical distance from pivotal point <return>horizontalDeviance<block_end><def_stmt>addToInstructions instructionLine currentInstance<block_start>parameterName="TTFAutohint control instructions"<line_sep>currentInstanceName=currentInstance.name<line_sep>commentHeadline="# %s"%currentInstanceName.upper()<line_sep># determine existing instructions: instructions=currentInstance.customParameters[parameterName]<line_sep># normalize single space after comma: instructionLine=instructionLine.replace("," ", ").replace(" " " ").replace(" " " ")<line_sep># add to custom parameter: <if_stmt>instructions<block_start><if_stmt><not>instructions.startswith(commentHeadline)<block_start>instructions="%s\n%s"%(commentHeadline instructions)<block_end>currentInstance.customParameters[parameterName]="%s\n%s"%(instructions instructionLine)<block_end><else_stmt><block_start>currentInstance.customParameters[parameterName]="%s\n%s"%(commentHeadline instructionLine)<block_end># trigger redraw for TTF Control Instructions Palette: thisFont=currentInstance.font<if_stmt>thisFont<block_start>NSNotificationCenter.defaultCenter().postNotificationName_object_("GSUpdateInterface" thisFont)<block_end><block_end><def_stmt>setClipboard myText<block_start>""" Sets the contents of the clipboard to myText. Returns True if successful, False if unsuccessful. """<try_stmt><block_start>myClipboard=NSPasteboard.generalPasteboard()<line_sep>myClipboard.declareTypes_owner_([NSStringPboardType] <none>)<line_sep>myClipboard.setString_forType_(myText NSStringPboardType)<line_sep><return><true><block_end><except_stmt>Exception<as>e<block_start><return><false><block_end><block_end><def_stmt>numberIndexStringFromNumbers indexes<block_start>""" Turns sequence 1,2,3,4,7,8,9,10,14,19,21,22,23,27,30,31,32 into "1-4, 7-10, 14, 19, 21-23, 27, 30-32" """<line_sep>indexes=sorted(indexes)<line_sep>outputString=""<line_sep>previousNumber=-100<for_stmt>i,thisNumber enumerate(indexes)<block_start><if_stmt><not>outputString<block_start>outputString<augadd>str(thisNumber)<block_end><else_stmt><block_start><if_stmt>previousNumber<eq>thisNumber-1<block_start><if_stmt>outputString[-1]<ne>"-"<block_start>outputString<augadd>"-"<block_end><elif_stmt>i<eq>len(indexes)-1<block_start>outputString<augadd>"%i"%thisNumber<block_end><block_end><else_stmt><block_start><if_stmt>outputString[-1]<eq>"-"<block_start>outputString<augadd>"%i"%previousNumber<block_end>outputString<augadd>", %i"%thisNumber<block_end><block_end>previousNumber=thisNumber<block_end><return>outputString<block_end><class_stmt>AddTTFAutohintControlInstructionsForCurrentGlyph(object)<block_start><def_stmt>__init__ self# Window 'self.w': <block_start>windowWidth=155<line_sep>windowHeight=410<line_sep>windowWidthResize=400# user can resize width by this value windowHeightResize=100# user can resize height by this value self.w=vanilla.FloatingWindow((windowWidth windowHeight) # default window size "Add ttfAutohint Control Instructions for Current Glyph" # window title minSize=(windowWidth windowHeight) # minimum size (for resizing) maxSize=(windowWidth+windowWidthResize windowHeight+windowHeightResize) # maximum size (for resizing) autosaveName="com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.mainwindow"# stores last window position and size )<line_sep># UI elements: linePos,inset,lineHeight=12 15 24<line_sep>self.w.explanatoryText=vanilla.TextBox((inset linePos+2 -inset 60) "Touch instruction with px offset for active glyph & instance, respects italic angle." sizeStyle='small' selectable=<true>)<line_sep>linePos<augadd>3<times>lineHeight<line_sep>sectionOptions=("All Points" "Upper Half" "Upper Third" "Upper Quarter" "Lower Half" "Lower Third" "Lower Quarter" )<line_sep>self.w.sectionToMoveText=vanilla.TextBox((inset linePos+2 38 14) u"Touch" sizeStyle='small' selectable=<true>)<line_sep>self.w.sectionToMove=vanilla.PopUpButton((inset+38 linePos -inset 17) sectionOptions sizeStyle='small' callback=self.SavePreferences)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonAdd100=vanilla.Button((inset linePos -inset 20) "+1.00" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonAdd075=vanilla.Button((inset linePos -inset 20) "+0.75" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonAdd050=vanilla.Button((inset linePos -inset 20) "+0.50" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonAdd025=vanilla.Button((inset linePos -inset 20) "+0.25" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonSub025=vanilla.Button((inset linePos -inset 20) "-0.25" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonSub050=vanilla.Button((inset linePos -inset 20) "-0.50" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonSub075=vanilla.Button((inset linePos -inset 20) "-0.75" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.runButtonSub100=vanilla.Button((inset linePos -inset 20) "-1.00" sizeStyle='regular' callback=self.AddTTFAutohintControlInstructionsForCurrentGlyphMain)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.ppmText=vanilla.TextBox((inset linePos+2 14 14) "@" sizeStyle='small' selectable=<true>)<line_sep>self.w.ppm=vanilla.EditText((inset+14 linePos -inset 19) "8-12,20" sizeStyle='small' callback=self.SavePreferences)<line_sep>linePos<augadd>lineHeight<times>1.5<line_sep># self.w.upperHalf = vanilla.CheckBox( (inset, linePos-1, -inset, 20), "Upper half (one)", value=False, callback=self.SavePreferences, sizeStyle='small' ) # linePos += lineHeight self.w.rightAtTop=vanilla.Button((inset linePos -inset 20) "right at top" sizeStyle='regular' callback=self.InsertRightAtTop)<line_sep>linePos<augadd>lineHeight<line_sep>self.w.leftAtTop=vanilla.Button((inset linePos -inset 20) "left at top" sizeStyle='regular' callback=self.InsertLeftAtTop)<line_sep>linePos<augadd>lineHeight<line_sep># Load Settings: <if_stmt><not>self.LoadPreferences()<block_start>print("Note: 'Add ttfAutohint Control Instructions for Current Glyph' could not load preferences. Will resort to defaults")<block_end># Open window and focus on it: self.w.open()<line_sep>self.w.makeKey()<block_end><def_stmt>SavePreferences self sender<block_start><try_stmt><block_start>Glyphs.defaults["com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.ppm"]=self.w.ppm.get()<line_sep>Glyphs.defaults["com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.sectionToMove"]=self.w.sectionToMove.get()<block_end><except_stmt><block_start><return><false><block_end><return><true><block_end><def_stmt>LoadPreferences self<block_start><try_stmt><block_start>Glyphs.registerDefault("com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.ppm" "8-12,20")<line_sep>Glyphs.registerDefault("com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.sectionToMove" 0)<line_sep>self.w.ppm.set(Glyphs.defaults["com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.ppm"])<line_sep>self.w.sectionToMove.set(Glyphs.defaults["com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.sectionToMove"])<block_end><except_stmt><block_start><return><false><block_end><return><true><block_end><def_stmt>fontInstanceToolGlyphLayer self<block_start>Font=Glyphs.font<line_sep># determine current instance: currentInstance=Font.instances[Font.currentTab.selectedInstance()]<line_sep># switch to Instructor tool: ttInstructorClass=NSClassFromString("GlyphsToolTrueTypeInstructor")<line_sep>Font.parent.windowController().setToolForClass_(ttInstructorClass)<line_sep>tool=Font.parent.windowController().toolForClass_(ttInstructorClass)<line_sep># double check Instructor tool is on: <if_stmt><not>tool.className()<eq>"GlyphsToolTrueTypeInstructor"<block_start>Message(title="Tool Error" message="TT Instructor tool (I) must be active" OKButton=<none>)<block_end><else_stmt># determine glyph name: <block_start>layer=Font.currentTab.activeLayer()<if_stmt><not>layer<and>tool.activeLayers()# fallback attempt if line above fails: <block_start>layer=tool.activeLayers()[0]<block_end><if_stmt><not>layer<block_start>Message(title="ttfAutohint Error" message="Cannot determine current glyph. Perhaps try closing and reopening the tab. Sorry." OKButton=<none>)<block_end><else_stmt><block_start>glyph=layer.glyph()<line_sep>glyphName=glyph.name<line_sep># prefix comment with glyph name: addToInstructions("# %s"%glyphName currentInstance)<line_sep># overwrite glyph name with production name, if any: <if_stmt>glyph.productionName<block_start>glyphName=glyph.productionName<block_end># tt outline: glyf=tool.valueForKey_("fontOutlineGlyf")<line_sep>glyfBounds=glyf.bounds()<line_sep># tt points: coords=glyf.coordinates()<line_sep>pointCount=coords.count()<line_sep><return>Font currentInstance tool glyphName layer glyf glyfBounds coords pointCount<block_end><block_end><return><none> <none> <none> <none> <none> <none> <none> <none> <none><block_end><def_stmt>InsertRightAtTop self sender<block_start>Font,currentInstance,tool,glyphName,layer,glyf,glyfBounds,coords,pointCount=self.fontInstanceToolGlyphLayer()<if_stmt><not>Font<block_start>print("ERROR: Could not determine font.")<block_end><else_stmt># add right instruction for topmost point if desired: <block_start>highestPointIndex=-1<line_sep>highestY=-1000<for_stmt>i range(pointCount)<block_start>thisPoint=coords.pointAtIndex_(i)<if_stmt>thisPoint.y<g>highestY<block_start>highestPointIndex=i<line_sep>highestY=thisPoint.y<block_end><block_end><if_stmt>highestPointIndex<g>-1<block_start>instructionLine="%s right %i"%(glyphName highestPointIndex)<line_sep>addToInstructions(instructionLine currentInstance)<block_end><else_stmt><block_start>print("ERROR: Could not determine highest point in %s."%glyphName)<block_end><block_end><block_end><def_stmt>InsertLeftAtTop self sender<block_start>Font,currentInstance,tool,glyphName,layer,glyf,glyfBounds,coords,pointCount=self.fontInstanceToolGlyphLayer()<if_stmt><not>Font<block_start>print("ERROR: Could not determine font.")<block_end><else_stmt># add left instruction for topmost point if desired: <block_start>highestPointIndex=-1<line_sep>highestY=-1000<line_sep>topBound=glyfBounds.origin.y+glyfBounds.size.height<for_stmt>i range(pointCount)<block_start>thisPoint=coords.pointAtIndex_(i)<line_sep>prevPoint=coords.pointAtIndex_((i-1)%pointCount)<line_sep>nextPoint=coords.pointAtIndex_((i+1)%pointCount)<if_stmt>thisPoint.y<l>topBound<and>thisPoint.y<g>highestY<and>thisPoint.y<g>prevPoint.y<and>thisPoint.y<ge>nextPoint.y<and>(thisPoint.x<l>prevPoint.x<or>nextPoint.x<l>thisPoint.x)<block_start>highestPointIndex=i<line_sep>highestY=thisPoint.y<block_end><block_end><if_stmt>highestPointIndex<g>-1<block_start>instructionLine="%s left %i"%(glyphName highestPointIndex)<line_sep>addToInstructions(instructionLine currentInstance)<block_end><else_stmt><block_start>print("ERROR: Could not determine highest point in %s."%glyphName)<block_end><block_end><block_end><def_stmt>AddTTFAutohintControlInstructionsForCurrentGlyphMain self sender<block_start><try_stmt><block_start><if_stmt><not>self.SavePreferences(self)<block_start>print("Note: 'Add ttfAutohint Control Instructions for Current Glyph' could not write preferences.")<block_end>shift=float(sender.getTitle())<line_sep>print(shift)<if_stmt>shift<block_start>Font,currentInstance,tool,glyphName,layer,glyf,glyfBounds,coords,pointCount=self.fontInstanceToolGlyphLayer()<if_stmt>Font# determine x/y move based on italic angle: <block_start>currentMaster=Font.selectedFontMaster<line_sep>italicAngle=currentMaster.italicAngle<if_stmt>italicAngle<block_start>moveString="x %1.2f y %1.2f"%(italic(shift italicAngle) shift)<block_end><else_stmt><block_start>moveString="y %1.2f"%shift<block_end># determine PPMs sizeString=Glyphs.defaults["com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.ppm"]<if_stmt><not>sizeString<block_start>print("ERROR: Could not determine PPMs, will use a default. Did you enter any?")<line_sep>sizeString="17"<block_end><elif_stmt><not>sizeStringIsOK(sizeString)<block_start>print("ERROR: Illegal character found in PPM specification (%s), will use default instead."%sizeString)<line_sep>sizeString="17"<block_end># build point indexes to be moved: sectionChoice=Glyphs.defaults["com.mekkablue.AddTTFAutohintControlInstructionsForCurrentGlyph.sectionToMove"]<line_sep>pointIndexString=<none><if_stmt>sectionChoice<g>0<block_start>pointIndexes=[]<line_sep># ranges: halfHeight=glyfBounds.origin.y+0.5<times>glyfBounds.size.height<line_sep>upperThird=glyfBounds.origin.y+0.666667<times>glyfBounds.size.height<line_sep>lowerThird=glyfBounds.origin.y+0.333333<times>glyfBounds.size.height<line_sep>upperQuarter=glyfBounds.origin.y+0.75<times>glyfBounds.size.height<line_sep>lowerQuarter=glyfBounds.origin.y+0.25<times>glyfBounds.size.height<for_stmt>i range(pointCount)<block_start>thisPoint=coords.pointAtIndex_(i)<if_stmt>sectionChoice<eq>1<and>thisPoint.y<g>halfHeight# Upper Half <block_start>pointIndexes.append(i)<block_end><elif_stmt>sectionChoice<eq>2<and>thisPoint.y<g>upperThird# Upper Third <block_start>pointIndexes.append(i)<block_end><elif_stmt>sectionChoice<eq>3<and>thisPoint.y<g>upperQuarter# Upper Quarter <block_start>pointIndexes.append(i)<block_end><elif_stmt>sectionChoice<eq>4<and>thisPoint.y<l>halfHeight# Lower Half <block_start>pointIndexes.append(i)<block_end><elif_stmt>sectionChoice<eq>5<and>thisPoint.y<l>lowerThird# Lower Third <block_start>pointIndexes.append(i)<block_end><elif_stmt>sectionChoice<eq>6<and>thisPoint.y<l>lowerQuarter# Lower Quarter <block_start>pointIndexes.append(i)<block_end><block_end><if_stmt>pointIndexes<block_start>pointIndexString=numberIndexStringFromNumbers(pointIndexes)<block_end><block_end><else_stmt># all points, choice = 0 # count of tt paths: <block_start>endPoints=glyf.endPtsOfContours()<line_sep>pathCount=len(glyf.endPtsOfContours())<line_sep>pointIndexStrings=[]<line_sep># all points, in ranges, separated by path: j=0<for_stmt>i range(pathCount)<block_start>k=endPoints.elementAtIndex_(i)<line_sep>pointIndexStrings.append("%i-%i"%(j k))<line_sep>j=k+1<block_end>pointIndexString=", ".join(pointIndexStrings)<block_end><if_stmt><not>pointIndexString<block_start>print("ERROR: no point indexes matching your criteria could be found.")<block_end><else_stmt># build the instruction line: <block_start>instructionLine="%s touch %s %s @ %s"%(glyphName pointIndexString moveString sizeString )<line_sep># add the instruction line to the parameter: <if_stmt>instructionLine<block_start>addToInstructions(instructionLine currentInstance)<block_end><block_end><block_end><block_end><block_end><except_stmt>Exception<as>e# brings macro window to front and reports error: <block_start>Glyphs.showMacroWindow()<line_sep>print("Add ttfAutohint Control Instructions for Current Glyph Error: %s"%e)<import_stmt>traceback<line_sep>print(traceback.format_exc())<block_end><block_end><block_end>Glyphs.defaults["TTPreviewAlsoShowOffCurveIndexes"]=<true><line_sep>AddTTFAutohintControlInstructionsForCurrentGlyph()<line_sep>
<import_from_future_stmt> absolute_import<import_from_future_stmt> division<import_from_future_stmt> print_function<import_stmt>shutil<import_stmt>sys<import_stmt>tempfile<import_from_stmt>observations.r.grunfeld1 grunfeld1<def_stmt>test_grunfeld1 <block_start>"""Test module grunfeld1.py by downloading grunfeld1.csv and testing shape of extracted data has 200 rows and 5 columns """<line_sep>test_path=tempfile.mkdtemp()<line_sep>x_train,metadata=grunfeld1(test_path)<try_stmt><block_start><assert_stmt>x_train.shape<eq>(200 5)<block_end><except_stmt><block_start>shutil.rmtree(test_path)<line_sep><raise>()<block_end><block_end>
<import_stmt>arcade<line_sep>CHARACTER_SCALING=0.5<line_sep>GRAVITY=0.5<def_stmt>test_physics_engine window<block_start>arcade.set_background_color(arcade.color.AMAZON)<line_sep>character_list=arcade.SpriteList()<line_sep>character_sprite=arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png" CHARACTER_SCALING)<line_sep>character_sprite.center_x=150<line_sep>character_sprite.center_y=110<line_sep>character_list.append(character_sprite)<line_sep>wall_list=arcade.SpriteList()<for_stmt>x range(0 1200 64)<block_start>sprite=arcade.Sprite(":resources:images/tiles/boxCrate_double.png" CHARACTER_SCALING)<line_sep>sprite.center_x=x<line_sep>sprite.center_y=32<line_sep>wall_list.append(sprite)<block_end>physics_engine=arcade.PhysicsEnginePlatformer(character_sprite wall_list gravity_constant=GRAVITY )<def_stmt>on_draw <block_start>arcade.start_render()<line_sep>wall_list.draw()<line_sep>character_list.draw()<block_end><def_stmt>update td<block_start>physics_engine.update()<block_end>window.on_draw=on_draw<line_sep>window.on_update=update<line_sep>physics_engine.enable_multi_jump(2)<line_sep>physics_engine.jumps_since_ground=0<assert_stmt>physics_engine.can_jump()<is><true><line_sep>character_sprite.change_y=15<line_sep>physics_engine.increment_jump_counter()<line_sep>window.test()<assert_stmt>physics_engine.can_jump()<is><true><line_sep>character_sprite.change_y=15<line_sep>physics_engine.increment_jump_counter()<line_sep>window.test()<assert_stmt>physics_engine.can_jump()<is><false><line_sep>physics_engine.disable_multi_jump()<block_end>
# Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # <import_stmt>pytest<import_from_stmt>cuml.dask.datasets make_regression<import_from_stmt>cuml.dask.linear_model ElasticNet<import_from_stmt>cuml.dask.linear_model Lasso<import_from_stmt>cuml.metrics r2_score<import_from_stmt>cuml.test.utils unit_param quality_param stress_param<import_stmt>numpy<as>np<line_sep>@pytest.mark.mg@pytest.mark.parametrize('dtype' [np.float32 np.float64])@pytest.mark.parametrize('alpha' [0.001])@pytest.mark.parametrize('algorithm' ['cyclic' 'random'])@pytest.mark.parametrize('nrows' [unit_param(50) quality_param(5000) stress_param(500000)])@pytest.mark.parametrize('column_info' [unit_param([20 10]) quality_param([100 50]) stress_param([1000 500])])@pytest.mark.parametrize('n_parts' [unit_param(4) quality_param(32) stress_param(64)])@pytest.mark.parametrize("delayed" [<true> <false>])<def_stmt>test_lasso dtype alpha algorithm nrows column_info n_parts delayed client<block_start>ncols,n_info=column_info<line_sep>X,y=make_regression(n_samples=nrows n_features=ncols n_informative=n_info n_parts=n_parts client=client dtype=dtype)<line_sep>lasso=Lasso(alpha=np.array([alpha]) fit_intercept=<true> normalize=<false> max_iter=1000 selection=algorithm tol=1e-10 client=client)<line_sep>lasso.fit(X y)<line_sep>y_hat=lasso.predict(X delayed=delayed)<assert_stmt>r2_score(y.compute() y_hat.compute())<ge>0.99<block_end>@pytest.mark.mg@pytest.mark.parametrize('dtype' [np.float32 np.float64])@pytest.mark.parametrize('nrows' [unit_param(50) quality_param(5000) stress_param(500000)])@pytest.mark.parametrize('column_info' [unit_param([20 10]) quality_param([100 50]) stress_param([1000 500])])@pytest.mark.parametrize('n_parts' [unit_param(16) quality_param(32) stress_param(64)])<def_stmt>test_lasso_default dtype nrows column_info n_parts client<block_start>ncols,n_info=column_info<line_sep>X,y=make_regression(n_samples=nrows n_features=ncols n_informative=n_info client=client dtype=dtype)<line_sep>lasso=Lasso(client=client)<line_sep>lasso.fit(X y)<line_sep>y_hat=lasso.predict(X)<assert_stmt>r2_score(y.compute() y_hat.compute())<ge>0.99<block_end>@pytest.mark.parametrize('dtype' [np.float32 np.float64])@pytest.mark.parametrize('alpha' [0.5])@pytest.mark.parametrize('algorithm' ['cyclic' 'random'])@pytest.mark.parametrize('nrows' [unit_param(500) quality_param(5000) stress_param(500000)])@pytest.mark.parametrize('column_info' [unit_param([20 10]) quality_param([100 50]) stress_param([1000 500])])@pytest.mark.parametrize('n_parts' [unit_param(16) quality_param(32) stress_param(64)])@pytest.mark.parametrize("delayed" [<true> <false>])<def_stmt>test_elastic_net dtype alpha algorithm nrows column_info n_parts client delayed<block_start>ncols,n_info=column_info<line_sep>X,y=make_regression(n_samples=nrows n_features=ncols n_informative=n_info n_parts=n_parts client=client dtype=dtype)<line_sep>elasticnet=ElasticNet(alpha=np.array([alpha]) fit_intercept=<true> normalize=<false> max_iter=1000 selection=algorithm tol=1e-10 client=client)<line_sep>elasticnet.fit(X y)<line_sep>y_hat=elasticnet.predict(X delayed=delayed)<line_sep># based on differences with scikit-learn 0.22 <if_stmt>alpha<eq>0.2<block_start><assert_stmt>r2_score(y.compute() y_hat.compute())<ge>0.96<block_end><else_stmt><block_start><assert_stmt>r2_score(y.compute() y_hat.compute())<ge>0.80<block_end><block_end>@pytest.mark.parametrize('dtype' [np.float32 np.float64])@pytest.mark.parametrize('nrows' [unit_param(500) quality_param(5000) stress_param(500000)])@pytest.mark.parametrize('column_info' [unit_param([20 10]) quality_param([100 50]) stress_param([1000 500])])@pytest.mark.parametrize('n_parts' [unit_param(16) quality_param(32) stress_param(64)])<def_stmt>test_elastic_net_default dtype nrows column_info n_parts client<block_start>ncols,n_info=column_info<line_sep>X,y=make_regression(n_samples=nrows n_features=ncols n_informative=n_info n_parts=n_parts client=client dtype=dtype)<line_sep>elasticnet=ElasticNet(client=client)<line_sep>elasticnet.fit(X y)<line_sep>y_hat=elasticnet.predict(X)<assert_stmt>r2_score(y.compute() y_hat.compute())<ge>0.96<block_end>
<import_stmt>websocket rel<line_sep>addr="wss://api.gemini.com/v1/marketdata/%s"<if_stmt>__name__<eq>"__main__"<block_start>rel.safe_read()<for_stmt>symbol ["BTCUSD" "ETHUSD" "ETHBTC"]<block_start>ws=websocket.WebSocketApp(addr%(symbol ) on_message=<lambda>w m:print(m))<line_sep>ws.run_forever(dispatcher=rel)<block_end>rel.signal(2 rel.abort)# Keyboard Interrupt rel.dispatch()<block_end>
<import_stmt>pytest<import_from_stmt>wemake_python_styleguide.violations.complexity TooDeepAccessViolation <import_from_stmt>wemake_python_styleguide.visitors.ast.complexity.access AccessVisitor <line_sep># boundary expressions subscript_access='my_matrix[0][0][0][0]'<line_sep>attribute_access='self.attr.inner.wrapper.value'<line_sep>mixed_access='self.attr[0].wrapper[0]'<line_sep>mixed_with_calls_access='self.attr[0]().wrapper[0][0].bar().foo[0]()'<line_sep># correct expressions call_chain='manager.filter().exclude().annotate().values().first()'<line_sep># incorrect expressions deep_access='self.some.other.attr().first.second.third.fourth.boom'<line_sep>@pytest.mark.parametrize('code' [subscript_access attribute_access mixed_access mixed_with_calls_access call_chain ])<def_stmt>test_correct_access assert_errors parse_ast_tree code options mode <block_start>"""Testing that expressions with correct access level work well."""<line_sep>tree=parse_ast_tree(mode(code))<line_sep>option_values=options(max_access_level=4)<line_sep>visitor=AccessVisitor(option_values tree=tree)<line_sep>visitor.run()<line_sep>assert_errors(visitor [])<block_end>@pytest.mark.parametrize(('code' 'access_level') [(subscript_access 4) (attribute_access 4) (mixed_access 4) (mixed_with_calls_access 4) (deep_access 5) ])<def_stmt>test_incorrect_access assert_errors assert_error_text parse_ast_tree code access_level options mode <block_start>"""Testing that violations are raised when reaching too deep access."""<line_sep>tree=parse_ast_tree(mode(code))<line_sep>option_values=options(max_access_level=3)<line_sep>visitor=AccessVisitor(option_values tree=tree)<line_sep>visitor.run()<line_sep>assert_errors(visitor [TooDeepAccessViolation])<line_sep>assert_error_text(visitor access_level option_values.max_access_level )<block_end>
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- <import_from_stmt>enum Enum EnumMeta<import_from_stmt>six with_metaclass<class_stmt>_CaseInsensitiveEnumMeta(EnumMeta)<block_start><def_stmt>__getitem__ self name<block_start><return>super().__getitem__(name.upper())<block_end><def_stmt>__getattr__ cls name<block_start>"""Return the enum member matching `name` We use __getattr__ instead of descriptors or inserting into the enum class' __dict__ in order to support `name` and `value` being both properties for enum members (which live in the class' __dict__) and enum members themselves. """<try_stmt><block_start><return>cls._member_map_[name.upper()]<block_end><except_stmt>KeyError<block_start><raise>AttributeError(name)<block_end><block_end><block_end><class_stmt>DimensionScope(with_metaclass(_CaseInsensitiveEnumMeta str Enum))<block_start>"""The scope at which the quota is applied. """<line_sep>WORKSPACE="Workspace"<line_sep>SUBSCRIPTION="Subscription"<block_end><class_stmt>JobStatus(with_metaclass(_CaseInsensitiveEnumMeta str Enum))<block_start>"""The job status. """<line_sep>WAITING="Waiting"<line_sep>EXECUTING="Executing"<line_sep>SUCCEEDED="Succeeded"<line_sep>FAILED="Failed"<line_sep>CANCELLED="Cancelled"<block_end><class_stmt>MeterPeriod(with_metaclass(_CaseInsensitiveEnumMeta str Enum))<block_start>"""The time period in which the quota's underlying meter is accumulated. Based on calendar year. 'None' is used for concurrent quotas. """<line_sep>NONE="None"<line_sep>MONTHLY="Monthly"<block_end><class_stmt>ProviderAvailability(with_metaclass(_CaseInsensitiveEnumMeta str Enum))<block_start>"""Provider availability. """<line_sep>AVAILABLE="Available"<line_sep>DEGRADED="Degraded"<line_sep>UNAVAILABLE="Unavailable"<block_end><class_stmt>TargetAvailability(with_metaclass(_CaseInsensitiveEnumMeta str Enum))<block_start>"""Target availability. """<line_sep>AVAILABLE="Available"<line_sep>DEGRADED="Degraded"<line_sep>UNAVAILABLE="Unavailable"<block_end>
# make sure configure registrations are executed <import_from_stmt>. deserialize_content# noqa <import_from_stmt>. deserialize_value# noqa <import_from_stmt>. serialize_content# noqa <import_from_stmt>. serialize_schema# noqa <import_from_stmt>. serialize_schema_field# noqa <import_from_stmt>. serialize_value# noqa
## Copyright 2015-2019 <NAME>, <NAME> ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## http://www.apache.org/licenses/LICENSE-2.0 ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. <import_from_stmt>nine str<import_from_stmt>Qt QtCore<import_from_stmt>Qt QtGui<import_from_stmt>Qt.QtWidgets QAction QTextBrowser<import_from_stmt>PyFlow.UI.Tool.Tool DockTool<import_from_stmt>PyFlow.UI.Views.NodeBox NodesBox<import_from_stmt>PyFlow.UI.Utils.stylesheet editableStyleSheet<import_from_stmt>PyFlow.Core.GraphManager GraphManagerSingleton<import_from_stmt>PyFlow.Core.Common SingletonDecorator<import_from_stmt>PyFlow.ConfigManager ConfigManager<import_stmt>sys<import_stmt>logging<import_stmt>json<import_stmt>os<import_stmt>subprocess<line_sep>REDIRECT=ConfigManager().shouldRedirectOutput()<line_sep>logger=logging.getLogger(<none>)<def_stmt>addLoggingLevel levelName levelNum methodName=<none><block_start>""" Comprehensively adds a new logging level to the `logging` module and the currently configured logging class. `levelName` becomes an attribute of the `logging` module with the value `levelNum`. `methodName` becomes a convenience method for both `logging` itself and the class returned by `logging.getLoggerClass()` (usually just `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is used. To avoid accidental clobberings of existing attributes, this method will raise an `AttributeError` if the level name is already an attribute of the `logging` module or if the method name is already present Example ------- >>> addLoggingLevel('TRACE', logging.DEBUG - 5) >>> logging.getLogger(__name__).setLevel("TRACE") >>> logging.getLogger(__name__).trace('that worked') >>> logging.trace('so did this') >>> logging.TRACE 5 """<if_stmt><not>methodName<block_start>methodName=levelName.lower()<block_end><if_stmt>hasattr(logging levelName)<block_start><raise>AttributeError('{} already defined in logging module'.format(levelName))<block_end><if_stmt>hasattr(logging methodName)<block_start><raise>AttributeError('{} already defined in logging module'.format(methodName))<block_end><if_stmt>hasattr(logging.getLoggerClass() methodName)<block_start><raise>AttributeError('{} already defined in logger class'.format(methodName))<block_end># This method was inspired by the answers to Stack Overflow post # http://stackoverflow.com/q/2183233/2988730, especially # http://stackoverflow.com/a/13638084/2988730 <def_stmt>logForLevel self message *args **kwargs<block_start><if_stmt>self.isEnabledFor(levelNum)<block_start>self._log(levelNum message args **kwargs)<block_end><block_end><def_stmt>logToRoot message *args **kwargs<block_start>logging.log(levelNum message *args **kwargs)<block_end>logging.addLevelName(levelNum levelName)<line_sep>setattr(logging levelName levelNum)<line_sep>setattr(logging.getLoggerClass() methodName logForLevel)<line_sep>setattr(logging methodName logToRoot)<block_end>addLoggingLevel('CONSOLEOUTPUT' logging.ERROR+5)<line_sep>@SingletonDecorator<class_stmt>SignalHandler(QtCore.QObject)<block_start>messageWritten=QtCore.Signal(str)<line_sep>errorWritten=QtCore.Signal(str)<line_sep>warningWritten=QtCore.Signal(str)<line_sep>flushSig=QtCore.Signal()<line_sep>progressSig=QtCore.Signal(int)<line_sep>_stdout=<none><line_sep>_stderr=<none><line_sep>text=""<def_stmt>__init__ self parent<block_start>QtCore.QObject.__init__(self parent)<line_sep>sys.stdout=self<block_end><def_stmt>write self msg<block_start><if_stmt>(<not>self.signalsBlocked())<block_start><if_stmt>msg<ne>'\n'<block_start>self.text=msg<line_sep>logger.info(str(msg))<block_end><block_end><block_end><def_stmt>flush self<block_start>print('flusing from handler')<block_end><block_end><class_stmt>QtHandler(logging.Handler)<block_start><def_stmt>__init__ self parent<block_start>logging.Handler.__init__(self)<line_sep>self.messageHolder=SignalHandler(parent)<block_end><def_stmt>emit self record<block_start><if_stmt>record<block_start>msj=self.format(record)<if_stmt>'flusing from handler'<in>msj<block_start>self.messageHolder.flushSig.emit()<block_end><elif_stmt>'bytes Downloaded'<in>msj<block_start>nb=int(float(msj.split('(')[-1][:-2]))<line_sep>self.messageHolder.progressSig.emit(nb)<line_sep>self.messageHolder.messageWritten.emit('%s\n'%msj)<block_end><else_stmt><block_start><if_stmt>record.levelname<in>['ERROR' 'CRITICAL']<block_start>self.messageHolder.errorWritten.emit('%s\n'%msj)<block_end><elif_stmt>record.levelname<eq>'WARNING'<block_start>self.messageHolder.warningWritten.emit('%s\n'%msj)<block_end><else_stmt><block_start>self.messageHolder.messageWritten.emit('%s\n'%msj)<block_end><block_end><block_end><block_end><block_end><class_stmt>LoggerTool(DockTool)<block_start>"""docstring for NodeBox tool."""<line_sep>formater=logging.Formatter("[%(levelname)s %(asctime)s]: %(message)s" "%H:%M:%S")<def_stmt>__init__ self<block_start>super(LoggerTool self).__init__()<line_sep>self.logView=QTextBrowser()<line_sep>self.logView.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)<line_sep>self.logView.setOpenLinks(<false>)<line_sep>self.logView.setReadOnly(<true>)<line_sep>self.logView.setStyleSheet("background-color: %s; Font: 10pt 'Consolas'"%"rgba%s"%str(editableStyleSheet().LoggerBgColor.getRgb()))<line_sep>self.clearAction=QAction("Clear" <none>)<line_sep>self.clearAction.triggered.connect(self.clearView)<line_sep>self.logView.addAction(self.clearAction)<line_sep>self.logView.anchorClicked.connect(self.anchorClickedMethod)<line_sep>self.logView.setTextColor(QtGui.QColor('white'))<line_sep>self.setWidget(self.logView)<line_sep>##################################################### # Sys Output Redirection ##################################################### self.handler=<none><if_stmt>REDIRECT<block_start>self.handler=QtHandler(self)<block_end><else_stmt><block_start>self.handler=logging.StreamHandler(sys.stdout)<block_end>logger.setLevel(logging.DEBUG)<line_sep>sys.excepthook=LoggerTool.exceptHook<if_stmt>self.handler<and>REDIRECT<block_start>self.handler.setFormatter(LoggerTool.formater)<line_sep>logger.addHandler(self.handler)<line_sep>self.handler.messageHolder.messageWritten.connect(<lambda>value:self.logPython(value 0))<line_sep>self.handler.messageHolder.warningWritten.connect(<lambda>value:self.logPython(value 1))<line_sep>self.handler.messageHolder.errorWritten.connect(<lambda>value:self.logPython(value 2))<line_sep>self.handler.messageHolder.flushSig.connect(self.flushPython)<block_end><block_end>##################################################### # Logger ##################################################### @staticmethod<def_stmt>exceptHook excType excValue traceback logger=logger<block_start>logger.error(excValue exc_info=(excType excValue traceback))<block_end><def_stmt>clearView self *args<block_start>self.logView.clear()<block_end>@staticmethod<def_stmt>supportedSoftwares <block_start><return>["standalone"]<block_end><def_stmt>onDestroy self<block_start><if_stmt>REDIRECT<block_start><try_stmt><block_start>sys.stdout=sys.__stdout__<line_sep>self.handler.messageHolder._stdout=<none><line_sep>self.handler.messageHolder._stderr=<none><line_sep>self.handler.messageHolder.messageWritten.disconnect()<line_sep>self.handler.messageHolder.warningWritten.disconnect()<line_sep>self.handler.messageHolder.errorWritten.disconnect()<line_sep>self.handler.messageHolder.flushSig.disconnect()<del_stmt>self.handler<line_sep>self.handler=<none><block_end><except_stmt><block_start><pass><block_end><block_end><block_end><def_stmt>logPython self text mode=0<block_start>colorchart={0:'white' 1:'yellow' 2:'red'}<for_stmt>l text.split('\n')<block_start><if_stmt>len(l)<g>0<block_start>splitted=l.split(",")<if_stmt>len(splitted)<ge>3<block_start><if_stmt>"File"<in>splitted[0]<and>"line"<in>splitted[1]<and>"in"<in>splitted[2]<block_start>file=splitted[0].split('"')[1]<line_sep>line=splitted[1].split("line ")[1]<if_stmt>os.path.exists(file)<block_start>file=file.replace("\\" "//")<line_sep>errorLink="""<a href=%s><span style=" text-decoration: underline; color:red;">%s</span></a></p>"""%(str(file+"::%s"%line) l)<line_sep>self.logView.append(errorLink)<block_end><block_end><else_stmt><block_start>self.logView.append('<span style=" color:%s;">%s<span>'%(colorchart[mode] l))<block_end><block_end><else_stmt><block_start>self.logView.append('<span style=" color:%s;">%s<span>'%(colorchart[mode] l))<block_end><block_end><block_end><block_end><def_stmt>flushPython self<block_start>self.logView.moveCursor(QtWidgets.QTextCursor.End QtWidgets.QTextCursor.MoveAnchor)<line_sep>self.logView.moveCursor(QtWidgets.QTextCursor.Up QtWidgets.QTextCursor.MoveAnchor)<line_sep>self.logView.moveCursor(QtWidgets.QTextCursor.StartOfLine QtWidgets.QTextCursor.MoveAnchor)<line_sep>self.logView.moveCursor(QtWidgets.QTextCursor.End QtWidgets.QTextCursor.KeepAnchor)<line_sep>self.logView.textCursor().removeSelectedText()<block_end><def_stmt>loglevelChanged self int<block_start>logger.setLevel(self.loggerLevels[int])<block_end><def_stmt>anchorClickedMethod self url<block_start><if_stmt>os.path.exists(url.url().split("::")[0])<block_start>editCmd=ConfigManager().getPrefsValue("PREFS" "General/EditorCmd")<line_sep>editCmd=editCmd.replace("@FILE" url.url().replace("::" ":"))<line_sep>subprocess.Popen(editCmd)<block_end><else_stmt><block_start>man=self.pyFlowInstance.graphManager<line_sep>node=man.get().findNode(str(url.url()))<if_stmt>node<block_start>self.pyFlowInstance.getCanvas().clearSelection()<line_sep>node.getWrapper().setSelected(<true>)<line_sep>self.pyFlowInstance.getCanvas().frameSelectedNodes()<block_end><block_end><block_end><def_stmt>update self<block_start>self.logView.setStyleSheet("background-color: %s; Font: 10pt 'Consolas'"%"rgba%s"%str(editableStyleSheet().LoggerBgColor.getRgb()))<line_sep>super(LoggerTool self).update()<block_end><def_stmt>onShow self<block_start>super(LoggerTool self).onShow()<block_end><def_stmt>closeEvent self event<block_start>self.hide()<block_end>@staticmethod<def_stmt>isSingleton <block_start><return><true><block_end>@staticmethod<def_stmt>defaultDockArea <block_start><return>QtCore.Qt.BottomDockWidgetArea<block_end>@staticmethod<def_stmt>toolTip <block_start><return>"Logger"<block_end>@staticmethod<def_stmt>name <block_start><return>str("Logger")<block_end><block_end>
# -*- coding:utf-8 -*- """ Author: <NAME>,<EMAIL> """<import_stmt>tensorflow<as>tf<import_from_stmt>tensorflow.python.keras.layers Flatten<import_from_stmt>tensorflow.python.ops.lookup_ops TextFileInitializer<try_stmt><block_start><import_from_stmt>tensorflow.python.ops.lookup_ops StaticHashTable<block_end><except_stmt>ImportError<block_start><import_from_stmt>tensorflow.python.ops.lookup_ops HashTable<as>StaticHashTable<block_end><class_stmt>NoMask(tf.keras.layers.Layer)<block_start><def_stmt>__init__ self **kwargs<block_start>super(NoMask self).__init__(**kwargs)<block_end><def_stmt>build self input_shape# Be sure to call this somewhere! <block_start>super(NoMask self).build(input_shape)<block_end><def_stmt>call self x mask=<none> **kwargs<block_start><return>x<block_end><def_stmt>compute_mask self inputs mask<block_start><return><none><block_end><block_end><class_stmt>Hash(tf.keras.layers.Layer)<block_start>"""Looks up keys in a table when setup `vocabulary_path`, which outputs the corresponding values. If `vocabulary_path` is not set, `Hash` will hash the input to [0,num_buckets). When `mask_zero` = True, input value `0` or `0.0` will be set to `0`, and other value will be set in range [1,num_buckets). The following snippet initializes a `Hash` with `vocabulary_path` file with the first column as keys and second column as values: * `1,emerson` * `2,lake` * `3,palmer` >>> hash = Hash( ... num_buckets=3+1, ... vocabulary_path=filename, ... default_value=0) >>> hash(tf.constant('lake')).numpy() 2 >>> hash(tf.constant('lakeemerson')).numpy() 0 Args: num_buckets: An `int` that is >= 1. The number of buckets or the vocabulary size + 1 when `vocabulary_path` is setup. mask_zero: default is False. The `Hash` value will hash input `0` or `0.0` to value `0` when the `mask_zero` is `True`. `mask_zero` is not used when `vocabulary_path` is setup. vocabulary_path: default `None`. The `CSV` text file path of the vocabulary hash, which contains two columns seperated by delimiter `comma`, the first column is the value and the second is the key. The key data type is `string`, the value data type is `int`. The path must be accessible from wherever `Hash` is initialized. default_value: default '0'. The default value if a key is missing in the table. **kwargs: Additional keyword arguments. """<def_stmt>__init__ self num_buckets mask_zero=<false> vocabulary_path=<none> default_value=0 **kwargs<block_start>self.num_buckets=num_buckets<line_sep>self.mask_zero=mask_zero<line_sep>self.vocabulary_path=vocabulary_path<line_sep>self.default_value=default_value<if_stmt>self.vocabulary_path<block_start>initializer=TextFileInitializer(vocabulary_path 'string' 1 'int64' 0 delimiter=',')<line_sep>self.hash_table=StaticHashTable(initializer default_value=self.default_value)<block_end>super(Hash self).__init__(**kwargs)<block_end><def_stmt>build self input_shape# Be sure to call this somewhere! <block_start>super(Hash self).build(input_shape)<block_end><def_stmt>call self x mask=<none> **kwargs<block_start><if_stmt>x.dtype<ne>tf.string<block_start>zero=tf.as_string(tf.zeros([1] dtype=x.dtype))<line_sep>x=tf.as_string(x )<block_end><else_stmt><block_start>zero=tf.as_string(tf.zeros([1] dtype='int32'))<block_end><if_stmt>self.vocabulary_path<block_start>hash_x=self.hash_table.lookup(x)<line_sep><return>hash_x<block_end>num_buckets=self.num_buckets<if><not>self.mask_zero<else>self.num_buckets-1<try_stmt><block_start>hash_x=tf.string_to_hash_bucket_fast(x num_buckets name=<none>)<line_sep># weak hash <block_end><except_stmt>AttributeError<block_start>hash_x=tf.strings.to_hash_bucket_fast(x num_buckets name=<none>)<line_sep># weak hash <block_end><if_stmt>self.mask_zero<block_start>mask=tf.cast(tf.not_equal(x zero) dtype='int64')<line_sep>hash_x=(hash_x+1)<times>mask<block_end><return>hash_x<block_end><def_stmt>compute_output_shape self input_shape<block_start><return>input_shape<block_end><def_stmt>get_config self <block_start>config={'num_buckets':self.num_buckets 'mask_zero':self.mask_zero 'vocabulary_path':self.vocabulary_path 'default_value':self.default_value}<line_sep>base_config=super(Hash self).get_config()<line_sep><return>dict(list(base_config.items())+list(config.items()))<block_end><block_end><class_stmt>Linear(tf.keras.layers.Layer)<block_start><def_stmt>__init__ self l2_reg=0.0 mode=0 use_bias=<false> seed=1024 **kwargs<block_start>self.l2_reg=l2_reg<line_sep># self.l2_reg = tf.contrib.layers.l2_regularizer(float(l2_reg_linear)) <if_stmt>mode<not><in>[0 1 2]<block_start><raise>ValueError("mode must be 0,1 or 2")<block_end>self.mode=mode<line_sep>self.use_bias=use_bias<line_sep>self.seed=seed<line_sep>super(Linear self).__init__(**kwargs)<block_end><def_stmt>build self input_shape<block_start><if_stmt>self.use_bias<block_start>self.bias=self.add_weight(name='linear_bias' shape=(1 ) initializer=tf.keras.initializers.Zeros() trainable=<true>)<block_end><if_stmt>self.mode<eq>1<block_start>self.kernel=self.add_weight('linear_kernel' shape=[int(input_shape[-1]) 1] initializer=tf.keras.initializers.glorot_normal(self.seed) regularizer=tf.keras.regularizers.l2(self.l2_reg) trainable=<true>)<block_end><elif_stmt>self.mode<eq>2<block_start>self.kernel=self.add_weight('linear_kernel' shape=[int(input_shape[1][-1]) 1] initializer=tf.keras.initializers.glorot_normal(self.seed) regularizer=tf.keras.regularizers.l2(self.l2_reg) trainable=<true>)<block_end>super(Linear self).build(input_shape)<block_end># Be sure to call this somewhere! <def_stmt>call self inputs **kwargs<block_start><if_stmt>self.mode<eq>0<block_start>sparse_input=inputs<line_sep>linear_logit=reduce_sum(sparse_input axis=-1 keep_dims=<true>)<block_end><elif_stmt>self.mode<eq>1<block_start>dense_input=inputs<line_sep>fc=tf.tensordot(dense_input self.kernel axes=(-1 0))<line_sep>linear_logit=fc<block_end><else_stmt><block_start>sparse_input,dense_input=inputs<line_sep>fc=tf.tensordot(dense_input self.kernel axes=(-1 0))<line_sep>linear_logit=reduce_sum(sparse_input axis=-1 keep_dims=<false>)+fc<block_end><if_stmt>self.use_bias<block_start>linear_logit<augadd>self.bias<block_end><return>linear_logit<block_end><def_stmt>compute_output_shape self input_shape<block_start><return>(<none> 1)<block_end><def_stmt>compute_mask self inputs mask<block_start><return><none><block_end><def_stmt>get_config self <block_start>config={'mode':self.mode 'l2_reg':self.l2_reg 'use_bias':self.use_bias 'seed':self.seed}<line_sep>base_config=super(Linear self).get_config()<line_sep><return>dict(list(base_config.items())+list(config.items()))<block_end><block_end><def_stmt>concat_func inputs axis=-1 mask=<false><block_start><if_stmt><not>mask<block_start>inputs=list(map(NoMask() inputs))<block_end><if_stmt>len(inputs)<eq>1<block_start><return>inputs[0]<block_end><else_stmt><block_start><return>tf.keras.layers.Concatenate(axis=axis)(inputs)<block_end><block_end><def_stmt>reduce_mean input_tensor axis=<none> keep_dims=<false> name=<none> reduction_indices=<none><block_start><try_stmt><block_start><return>tf.reduce_mean(input_tensor axis=axis keep_dims=keep_dims name=name reduction_indices=reduction_indices)<block_end><except_stmt>TypeError<block_start><return>tf.reduce_mean(input_tensor axis=axis keepdims=keep_dims name=name)<block_end><block_end><def_stmt>reduce_sum input_tensor axis=<none> keep_dims=<false> name=<none> reduction_indices=<none><block_start><try_stmt><block_start><return>tf.reduce_sum(input_tensor axis=axis keep_dims=keep_dims name=name reduction_indices=reduction_indices)<block_end><except_stmt>TypeError<block_start><return>tf.reduce_sum(input_tensor axis=axis keepdims=keep_dims name=name)<block_end><block_end><def_stmt>reduce_max input_tensor axis=<none> keep_dims=<false> name=<none> reduction_indices=<none><block_start><try_stmt><block_start><return>tf.reduce_max(input_tensor axis=axis keep_dims=keep_dims name=name reduction_indices=reduction_indices)<block_end><except_stmt>TypeError<block_start><return>tf.reduce_max(input_tensor axis=axis keepdims=keep_dims name=name)<block_end><block_end><def_stmt>div x y name=<none><block_start><try_stmt><block_start><return>tf.div(x y name=name)<block_end><except_stmt>AttributeError<block_start><return>tf.divide(x y name=name)<block_end><block_end><def_stmt>softmax logits dim=-1 name=<none><block_start><try_stmt><block_start><return>tf.nn.softmax(logits dim=dim name=name)<block_end><except_stmt>TypeError<block_start><return>tf.nn.softmax(logits axis=dim name=name)<block_end><block_end><class_stmt>Add(tf.keras.layers.Layer)<block_start><def_stmt>__init__ self **kwargs<block_start>super(Add self).__init__(**kwargs)<block_end><def_stmt>build self input_shape# Be sure to call this somewhere! <block_start>super(Add self).build(input_shape)<block_end><def_stmt>call self inputs **kwargs<block_start><if_stmt><not>isinstance(inputs list)<block_start><return>inputs<block_end><if_stmt>len(inputs)<eq>1<block_start><return>inputs[0]<block_end><if_stmt>len(inputs)<eq>0<block_start><return>tf.constant([[0.0]])<block_end><return>tf.keras.layers.add(inputs)<block_end><block_end><def_stmt>add_func inputs<block_start><return>Add()(inputs)<block_end><def_stmt>combined_dnn_input sparse_embedding_list dense_value_list<block_start><if_stmt>len(sparse_embedding_list)<g>0<and>len(dense_value_list)<g>0<block_start>sparse_dnn_input=Flatten()(concat_func(sparse_embedding_list))<line_sep>dense_dnn_input=Flatten()(concat_func(dense_value_list))<line_sep><return>concat_func([sparse_dnn_input dense_dnn_input])<block_end><elif_stmt>len(sparse_embedding_list)<g>0<block_start><return>Flatten()(concat_func(sparse_embedding_list))<block_end><elif_stmt>len(dense_value_list)<g>0<block_start><return>Flatten()(concat_func(dense_value_list))<block_end><else_stmt><block_start><raise>NotImplementedError("dnn_feature_columns can not be empty list")<block_end><block_end>
<import_stmt>datetime<import_from_stmt>urllib.parse urlencode<import_stmt>scrapy<import_from_stmt>gazette.items Gazette<import_from_stmt>gazette.spiders.base BaseGazetteSpider<class_stmt>PiTeresina(BaseGazetteSpider)<block_start>TERRITORY_ID="2211001"<line_sep>name="pi_teresina"<line_sep>allowed_domains=["dom.pmt.pi.gov.br"]<line_sep>start_date=datetime.date(2005 1 7)<def_stmt>start_requests self<block_start>initial_date=self.start_date.strftime("%d/%m/%Y")<line_sep>end_date=self.end_date.strftime("%d/%m/%Y")<line_sep>params={"pagina":1 "filtra_data":initial_date "filtra_dataf":end_date }<line_sep>url_params=urlencode(params)<line_sep><yield>scrapy.Request(f"http://dom.pmt.pi.gov.br/lista_diario.php?{url_params}" )<block_end><def_stmt>parse self response<block_start><for_stmt>entry response.css("tbody tr")<block_start>edition_number=entry.xpath(".//td[1]/text()").get()<line_sep>gazette_date=entry.xpath(".//td[2]/text()").get()<line_sep>gazette_date=datetime.datetime.strptime(gazette_date "%d/%m/%Y").date()<line_sep>gazettes_pdfs=entry.css("a::attr(href)").getall()<line_sep><yield>Gazette(date=gazette_date edition_number=edition_number file_urls=gazettes_pdfs is_extra_edition=<false> power="executive" )<block_end><for_stmt>next_page_url response.css("a.paginacao::attr(href)").getall()<block_start><yield>scrapy.Request(response.urljoin(next_page_url))<block_end><block_end><block_end>
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 <import_from_stmt>distutils.version LooseVersion<import_stmt>numpy<as>np<import_stmt>pytest<import_from_stmt>common.layer_test_class check_ir_version<import_from_stmt>common.tf_layer_test_class CommonTFLayerTest<import_from_stmt>common.utils.tf_utils permute_nchw_to_nhwc<import_from_stmt>openvino.tools.mo.front.common.partial_infer.utils int64_array<import_from_stmt>unit_tests.utils.graph build_graph<class_stmt>TestLogSoftmax(CommonTFLayerTest)<block_start><def_stmt>create_log_softmax_net self shape reduction_axis ir_version use_new_frontend<block_start>""" Tensorflow net IR net Input->LogSoftmax => Input->Softmax->Log """<line_sep># # Create Tensorflow model # <import_stmt>tensorflow<as>tf<line_sep>tf.compat.v1.reset_default_graph()<line_sep># Create the graph and model <with_stmt>tf.compat.v1.Session()<as>sess<block_start>tf_x_shape=shape.copy()<line_sep>tf_x_shape=permute_nchw_to_nhwc(tf_x_shape use_new_frontend)<line_sep>input=tf.compat.v1.placeholder(tf.float32 tf_x_shape 'Input')<if_stmt>LooseVersion(tf.__version__)<l>LooseVersion('2.0.0')<block_start>tf.nn.log_softmax(input name='Operation' axis=reduction_axis)<block_end><else_stmt><block_start>tf.nn.log_softmax(input axis=reduction_axis name='Operation')<block_end>tf.compat.v1.global_variables_initializer()<line_sep>tf_net=sess.graph_def<block_end>ref_net=<none><line_sep>reduce_sum_shape=np.copy(shape)<line_sep>rank=len(shape)<if_stmt>rank<in>{4 5}<block_start>reduction_axis=reduction_axis<if>reduction_axis<ge>0<else>rank+reduction_axis<if_stmt>rank<eq>4<block_start>reduction_axis={0:0 1:2 2:3 3:1}[reduction_axis]<block_end><else_stmt><block_start>reduction_axis={0:0 1:2 2:3 3:4 4:1}[reduction_axis]<block_end><block_end>reduce_sum_shape[reduction_axis]=1<line_sep>converted_shape=shape<if>rank<ne>1<else>shape[0]<if_stmt>check_ir_version(10 <none> ir_version)<and><not>use_new_frontend<block_start>ref_nodes_attributes={'input':{'kind':'op' 'type':'Parameter' 'shape':converted_shape} 'input_data':{'shape':shape 'kind':'data' 'value':<none>} 'reduce_max_axis_val':{'shape':int64_array([reduction_axis]).shape 'kind':'data' 'value':int64_array([reduction_axis])} 'reduce_max_axis':{'type':'Const' 'kind':'op' 'shape':1} 'reduce_max_axis_data':{'shape':int64_array([1]) 'kind':'data' 'value':<none>} 'reduce_max':{'type':'ReduceMax' 'kind':'op' 'keep_dims':<true>} 'reduce_max_data':{'shape':reduce_sum_shape 'kind':'data' 'value':<none>} 'sub_first':{'type':'Subtract' 'kind':'op'} 'sub_first_data':{'shape':shape 'kind':'data' 'value':<none>} 'reduce_sum_axis_val':{'shape':int64_array([reduction_axis]).shape 'kind':'data' 'value':int64_array([reduction_axis])} 'reduce_sum_axis':{'type':'Const' 'kind':'op' 'shape':1} 'reduce_sum_axis_data':{'shape':int64_array([1]) 'kind':'data' 'value':<none>} 'reduce_sum':{'type':'ReduceSum' 'kind':'op' 'keep_dims':<true>} 'reduce_sum_data':{'shape':reduce_sum_shape 'kind':'data' 'value':<none>} 'exp':{'type':'Exp' 'kind':'op'} 'exp_data':{'shape':shape 'kind':'data' 'value':<none>} 'log':{'type':'Log' 'kind':'op'} 'log_data':{'shape':reduce_sum_shape 'kind':'data' 'value':<none>} 'sub_second':{'type':'Subtract' 'kind':'op'} 'sub_second_data':{'shape':shape 'kind':'data' 'value':<none>} 'result':{'kind':'op' 'type':'Result'} }<line_sep>ref_edges=[('input' 'input_data') ('reduce_max_axis_val' 'reduce_max_axis') ('reduce_max_axis' 'reduce_max_axis_data') ('reduce_max_axis_data' 'reduce_max' {'in':1}) ('reduce_max' 'reduce_max_data') ('input_data' 'reduce_max' {'out':0 'in':0}) ('input_data' 'sub_first' {'out':0 'in':0}) ('reduce_max_data' 'sub_first' {'in':1}) ('sub_first' 'sub_first_data') ('reduce_sum_axis_val' 'reduce_sum_axis') ('reduce_sum_axis' 'reduce_sum_axis_data') ('reduce_sum_axis_data' 'reduce_sum' {'in':1}) ('reduce_sum' 'reduce_sum_data') ('sub_first_data' 'exp') ('exp' 'exp_data') ('exp_data' 'reduce_sum' {'in':0}) ('reduce_sum_data' 'log') ('log' 'log_data') ('log_data' 'sub_second' {'in':1}) ('sub_second' 'sub_second_data') ('sub_first_data' 'sub_second' {'out':0 'in':0}) ('sub_second_data' 'result') ]<line_sep>ref_net=build_graph(ref_nodes_attributes ref_edges)<block_end><return>tf_net ref_net<block_end>test_data_precommit=[pytest.param(dict(shape=[3 2 3 7 6] reduction_axis=-1) marks=pytest.mark.skip(reason="Skipped until fixed"))]<line_sep>@pytest.mark.parametrize("params" test_data_precommit)@pytest.mark.precommit<def_stmt>test_log_softmax_precommit self params ie_device precision ir_version temp_dir use_new_frontend api_2<block_start>self._test(*self.create_log_softmax_net(**params ir_version=ir_version use_new_frontend=use_new_frontend) ie_device precision ir_version temp_dir=temp_dir use_new_frontend=use_new_frontend api_2=api_2)<block_end>test_data=[dict(shape=[1] reduction_axis=-1) dict(shape=[2 5] reduction_axis=-1) dict(shape=[5 3 7 4] reduction_axis=-1) dict(shape=[3 2 3 7 6] reduction_axis=-1)]<line_sep>@pytest.mark.parametrize("params" test_data)@pytest.mark.nightly<def_stmt>test_log_softmax self params ie_device precision ir_version temp_dir use_new_frontend api_2<block_start>self._test(*self.create_log_softmax_net(**params ir_version=ir_version use_new_frontend=use_new_frontend) ie_device precision ir_version temp_dir=temp_dir use_new_frontend=use_new_frontend api_2=api_2)<block_end><block_end>
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. <import_from_stmt>oci.util formatted_flat_dict NONE_SENTINEL value_allowed_none_or_none_sentinel# noqa: F401 <import_from_stmt>oci.decorators init_model_state_from_kwargs<line_sep>@init_model_state_from_kwargs<class_stmt>UpdateEnrollmentStatusDetails(object)<block_start>""" The request object for updating the enrollment status details. """<line_sep>#: A constant which can be used with the status property of a UpdateEnrollmentStatusDetails. #: This constant has a value of "ACTIVE" STATUS_ACTIVE="ACTIVE"<line_sep>#: A constant which can be used with the status property of a UpdateEnrollmentStatusDetails. #: This constant has a value of "INACTIVE" STATUS_INACTIVE="INACTIVE"<def_stmt>__init__ self **kwargs<block_start>""" Initializes a new UpdateEnrollmentStatusDetails object with values from keyword arguments. The following keyword arguments are supported (corresponding to the getters/setters of this class): :param status: The value to assign to the status property of this UpdateEnrollmentStatusDetails. Allowed values for this property are: "ACTIVE", "INACTIVE" :type status: str """<line_sep>self.swagger_types={'status':'str'}<line_sep>self.attribute_map={'status':'status'}<line_sep>self._status=<none><block_end>@property<def_stmt>status self<block_start>""" **[Required]** Gets the status of this UpdateEnrollmentStatusDetails. The Cloud Advisor enrollment status. Allowed values for this property are: "ACTIVE", "INACTIVE" :return: The status of this UpdateEnrollmentStatusDetails. :rtype: str """<line_sep><return>self._status<block_end>@status.setter<def_stmt>status self status<block_start>""" Sets the status of this UpdateEnrollmentStatusDetails. The Cloud Advisor enrollment status. :param status: The status of this UpdateEnrollmentStatusDetails. :type: str """<line_sep>allowed_values=["ACTIVE" "INACTIVE"]<if_stmt><not>value_allowed_none_or_none_sentinel(status allowed_values)<block_start><raise>ValueError("Invalid value for `status`, must be None or one of {0}".format(allowed_values))<block_end>self._status=status<block_end><def_stmt>__repr__ self<block_start><return>formatted_flat_dict(self)<block_end><def_stmt>__eq__ self other<block_start><if_stmt>other<is><none><block_start><return><false><block_end><return>self.__dict__<eq>other.__dict__<block_end><def_stmt>__ne__ self other<block_start><return><not>self<eq>other<block_end><block_end>
<import_stmt>logging<import_stmt>numpy<as>np<import_from_stmt>numpy.linalg norm<import_from_stmt>scipy.stats moment<import_from_stmt>scipy.special cbrt<def_stmt>common_usr molecule ctd=<none> cst=<none> fct=<none> ftf=<none> atoms_type=<none><block_start>"""Function used in USR and USRCAT function Parameters ---------- molecule : oddt.toolkit.Molecule Molecule to compute USR shape descriptor ctd : numpy array or None (default = None) Coordinates of the molecular centroid If 'None', the point is calculated cst : numpy array or None (default = None) Coordinates of the closest atom to the molecular centroid If 'None', the point is calculated fct : numpy array or None (default = None) Coordinates of the farthest atom to the molecular centroid If 'None', the point is calculated ftf : numpy array or None (default = None) Coordinates of the farthest atom to the farthest atom to the molecular centroid If 'None', the point is calculated atoms_type : str or None (default None) Type of atoms to be selected from atom_dict If 'None', all atoms are used to calculate shape descriptor Returns ------- shape_descriptor : numpy array, shape = (12) Array describing shape of molecule """<if_stmt>atoms_type<is><none><block_start>atoms=molecule.atom_dict['coords']<block_end><else_stmt><block_start><if_stmt>atoms_type<eq>'ishydrophobe'<block_start>mask=(molecule.atom_dict['ishalogen']|molecule.atom_dict['ishydrophobe']|(molecule.atom_dict['atomicnum']<eq>16))<block_end><else_stmt><block_start>mask=molecule.atom_dict[atoms_type]<block_end>atoms=molecule.atom_dict[mask]['coords']<block_end><if_stmt>len(atoms)<eq>0<block_start><return>np.zeros(12) ((0. 0. 0.) )<times>4<block_end><if_stmt>ctd<is><none><block_start>ctd=atoms.mean(0)<block_end>distances_ctd=norm(atoms-ctd axis=1)<if_stmt>cst<is><none><block_start>cst=atoms[distances_ctd.argmin()]<block_end>distances_cst=norm(atoms-cst axis=1)<if_stmt>fct<is><none><block_start>fct=atoms[distances_ctd.argmax()]<block_end>distances_fct=norm(atoms-fct axis=1)<if_stmt>ftf<is><none><block_start>ftf=atoms[distances_fct.argmax()]<block_end>distances_ftf=norm(atoms-ftf axis=1)<line_sep>distances_list=[distances_ctd distances_cst distances_fct distances_ftf]<line_sep>shape_descriptor=np.zeros(12)<for_stmt>i,distances enumerate(distances_list)<block_start>shape_descriptor[i<times>3+0]=np.mean(distances)<line_sep>shape_descriptor[i<times>3+1]=np.var(distances)<line_sep>shape_descriptor[i<times>3+2]=moment(distances moment=3)<block_end><return>shape_descriptor (ctd cst fct ftf)<block_end><def_stmt>usr molecule<block_start>"""Computes USR shape descriptor based on <NAME>, <NAME> (2007). Ultrafast shape recognition to search compound databases for similar molecular shapes. Journal of computational chemistry, 28(10):1711-23. http://dx.doi.org/10.1002/jcc.20681 Parameters ---------- molecule : oddt.toolkit.Molecule Molecule to compute USR shape descriptor Returns ------- shape_descriptor : numpy array, shape = (12) Array describing shape of molecule """<line_sep><return>common_usr(molecule)[0]<block_end><def_stmt>usr_cat molecule<block_start>"""Computes USRCAT shape descriptor based on <NAME>, <NAME> (2012). USRCAT: real-time ultrafast shape recognition with pharmacophoric constraints. Journal of Cheminformatics, 2012 4:27. http://dx.doi.org/10.1186/1758-2946-4-27 Parameters ---------- molecule : oddt.toolkit.Molecule Molecule to compute USRCAT shape descriptor Returns ------- shape_descriptor : numpy array, shape = (60) Array describing shape of molecule """<line_sep>all_atoms_shape,points=common_usr(molecule)<line_sep>ctd,cst,fct,ftf=points<line_sep>hydrophobic_shape=common_usr(molecule ctd cst fct ftf 'ishydrophobe')[0]<line_sep>aromatic_shape=common_usr(molecule ctd cst fct ftf 'isaromatic')[0]<line_sep>acceptor_shape=common_usr(molecule ctd cst fct ftf 'isacceptor')[0]<line_sep>donor_shape=common_usr(molecule ctd cst fct ftf 'isdonor')[0]<line_sep>cat_shape=np.hstack((all_atoms_shape hydrophobic_shape aromatic_shape acceptor_shape donor_shape))<line_sep><return>np.nan_to_num(cat_shape)<block_end><def_stmt>electroshape mol<block_start>"""Computes shape descriptor based on <NAME> al. ElectroShape: fast molecular similarity calculations incorporating shape, chirality and electrostatics. J Comput Aided Mol Des 24, 789-801 (2010). http://dx.doi.org/doi:10.1007/s10822-010-9374-0 Aside from spatial coordinates, atoms' charges are also used as the fourth dimension to describe shape of the molecule. Parameters ---------- mol : oddt.toolkit.Molecule Molecule to compute Electroshape descriptor Returns ------- shape_descriptor : numpy array, shape = (15) Array describing shape of molecule """<if_stmt>(mol.atom_dict['coords']<eq>0).all()<block_start><raise>Exception('Molecule needs 3D coordinates')<block_end><if_stmt>(mol.atom_dict['charge']<eq>0).all()<block_start>logging.warning('All partial charges are zero. ElectroShape strongly relies on them.')<block_end><if_stmt>np.isnan(mol.atom_dict['charge']).any()<block_start>logging.warning('Nan values in charge values of molecule '+mol.title)<block_end>charge=np.nan_to_num(mol.atom_dict['charge'])<line_sep>mi=25# scaling factor converting electron charges to Angstroms four_dimensions=np.column_stack((mol.atom_dict['coords'] charge<times>mi))<line_sep>c1=four_dimensions.mean(0)# geometric centre of the molecule distances_c1=norm(four_dimensions-c1 axis=1)<line_sep>c2=four_dimensions[distances_c1.argmax()]# atom position furthest from c1 distances_c2=norm(four_dimensions-c2 axis=1)<line_sep>c3=four_dimensions[distances_c2.argmax()]# atom position furthest from c2 distances_c3=norm(four_dimensions-c3 axis=1)<line_sep>vector_a=c2-c1<line_sep>vector_b=c3-c1<line_sep>vector_as=vector_a[:3]# spatial parts of these vectors - vector_bs=vector_b[:3]# the first three coordinates vector_c=((norm(vector_a)/(2<times>norm(np.cross(vector_as vector_bs))))<times>np.cross(vector_as vector_bs))<line_sep>vector_c1s=c1[:3]<line_sep>max_charge=np.array(np.amax(charge)<times>mi)<line_sep>min_charge=np.array(np.amin(charge)<times>mi)<line_sep>c4=np.append(vector_c1s+vector_c max_charge)<line_sep>c5=np.append(vector_c1s+vector_c min_charge)<line_sep>distances_c4=norm(four_dimensions-c4 axis=1)<line_sep>distances_c5=norm(four_dimensions-c5 axis=1)<line_sep>distances_list=[distances_c1 distances_c2 distances_c3 distances_c4 distances_c5]<line_sep>shape_descriptor=np.zeros(15)<line_sep>i=0<for_stmt>distances distances_list<block_start>mean=np.mean(distances)<line_sep>shape_descriptor[0+i]=mean<line_sep>shape_descriptor[1+i]=np.std(distances)<line_sep>shape_descriptor[2+i]=cbrt(np.sum(((distances-mean)<power>3)/distances.size))<line_sep>i<augadd>3<block_end><return>shape_descriptor<block_end><def_stmt>usr_similarity mol1_shape mol2_shape ow=1. hw=1. rw=1. aw=1. dw=1.<block_start>"""Computes similarity between molecules Parameters ---------- mol1_shape : numpy array USR shape descriptor mol2_shape : numpy array USR shape descriptor ow : float (default = 1.) Scaling factor for all atoms Only used for USRCAT, ignored for other types hw : float (default = 1.) Scaling factor for hydrophobic atoms Only used for USRCAT, ignored for other types rw : float (default = 1.) Scaling factor for aromatic atoms Only used for USRCAT, ignored for other types aw : float (default = 1.) Scaling factor for acceptors Only used for USRCAT, ignored for other types dw : float (default = 1.) Scaling factor for donors Only used for USRCAT, ignored for other types Returns ------- similarity : float from 0 to 1 Similarity between shapes of molecules, 1 indicates identical molecules """<if_stmt>mol1_shape.shape[0]<eq>12<and>mol2_shape.shape[0]<eq>12<block_start>sim=1./(1.+(1./12)<times>np.sum(np.fabs(mol1_shape-mol2_shape)))<block_end><elif_stmt>mol1_shape.shape[0]<eq>60<and>mol2_shape.shape[0]<eq>60<block_start>w=np.array([ow hw rw aw dw])<line_sep># Normalize weights w=w/w.sum()<line_sep>shape_diff=np.abs(mol1_shape-mol2_shape).reshape(-1 12)<line_sep>sim=1./(1+(w<times>(1./12)<times>shape_diff.sum(axis=1)).sum())<block_end><elif_stmt>mol1_shape.shape[0]<eq>15<and>mol2_shape.shape[0]<eq>15<block_start>sim=1./(1+(1./15)<times>np.sum(np.fabs(mol1_shape-mol2_shape)))<block_end><else_stmt><block_start><raise>Exception('Given vectors are not valid USR shape descriptors '<concat>'or come from different methods. Correct vector lengths'<concat>'are: 12 for USR, 60 for USRCAT, 15 for Electroshape')<block_end><return>sim<block_end>
<import_stmt>torch<import_from_stmt>.. utils<line_sep>MODULE=torch<line_sep>FP16_FUNCS=[# Low level functions wrapped by torch.nn layers. # The wrapper layers contain the weights which are then passed in as a parameter # to these functions. 'conv1d' 'conv2d' 'conv3d' 'conv_transpose1d' 'conv_transpose2d' 'conv_transpose3d' 'conv_tbc' 'prelu' # BLAS 'addmm' 'addmv' 'addr' 'matmul' 'mm' 'mv' ]<line_sep>FP32_FUNCS=[# Pointwise 'acos' 'asin' 'cosh' 'erfinv' 'exp' 'expm1' 'log' 'log10' 'log2' 'reciprocal' 'rsqrt' 'sinh' 'tan' # Other math 'pow' # Reduction 'cumprod' 'cumsum' 'dist' # 'mean', 'norm' 'prod' 'std' 'sum' 'var' # Misc 'renorm']<line_sep>version_strings=torch.__version__.split('.')<line_sep>version_major=version_strings[0]<line_sep>version_minor=version_strings[1]<line_sep>version_num=float(version_major+"."+version_minor)<line_sep># Before torch 1.1, mean must be blacklisted. <if_stmt>version_num<l>1.1<block_start>FP32_FUNCS.append('mean')<block_end># Before CUDA 9.1, batched matmul was missing fast FP16 kernels. We # check the CUDA version -- if at least 9.1, then put the bmm # functions on the fp16 list. Otherwise, put them on the fp32 list. _bmms=['addbmm' 'baddbmm' 'bmm']<if_stmt>utils.is_cuda_enabled()# workaround https://github.com/facebookresearch/maskrcnn-benchmark/issues/802 <block_start><if_stmt>utils.get_cuda_version()<ge>(9 1 0)<block_start>FP16_FUNCS.extend(_bmms)<block_end><else_stmt><block_start>FP32_FUNCS.extend(_bmms)<block_end><block_end># Multi-tensor fns that may need type promotion CASTS=[# Multi-tensor math 'addcdiv' 'addcmul' 'atan2' 'cross' 'bilinear' 'dot' # Element-wise _or_ tensor-wise math 'add' 'div' 'mul' # Comparison 'eq' 'equal' 'ge' 'gt' 'le' 'lt' 'ne']<line_sep># Functions that take sequence arguments. We need to inspect the whole # sequence and cast to the widest type. SEQUENCE_CASTS=['cat' 'stack']<line_sep>
# Author: <NAME> <<EMAIL>> # License: BSD 3 clause <import_stmt>warnings<import_stmt>libsvmdata<def_stmt>fetch_libsvm dataset replace=<false> normalize=<true> min_nnz=3<block_start>""" This function is deprecated, we now rely on the libsvmdata package. Parameters ---------- dataset: string Name of the dataset. replace: bool Whether to redownload the data. normalize: bool Whether to divide the columns by their norm. min_nnz: int Columns with strictly less than `nnz` non-zero entries are discarded. """<line_sep>warnings.simplefilter("always" FutureWarning)<line_sep>warnings.warn("celer.datasets.fetch_libsvm is deprecated and will be "<concat>"removed in version 0.6. Use the lightweight "<concat>"libsvmadata package instead." FutureWarning)<line_sep><return>libsvmdata.fetch_libsvm(dataset replace=replace normalize=normalize min_nnz=min_nnz)<block_end><if_stmt>__name__<eq>"__main__"<block_start><for_stmt>dataset libsvmdata.datasets.NAMES<block_start>fetch_libsvm(dataset replace=<false>)<block_end><block_end>
""" This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT. See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details. Author(s): <NAME> Copyright (C) 2016 Inria Modification(s): - YYYY/MM Author: Description of the modification """<import_stmt>gudhi<as>gd<import_stmt>math<import_stmt>numpy<as>np<import_stmt>pytest<try_stmt># python3 <block_start><import_from_stmt>itertools zip_longest<block_end><except_stmt>ImportError# python2 <block_start><import_from_stmt>itertools izip_longest<as>zip_longest<block_end>__author__="<NAME>"<line_sep>__copyright__="Copyright (C) 2016 Inria"<line_sep>__license__="MIT"<def_stmt>_empty_alpha precision<block_start>alpha_complex=gd.AlphaComplex(points=[[0 0]] precision=precision)<assert_stmt>alpha_complex.__is_defined()<eq><true><block_end><def_stmt>test_empty_alpha <block_start><for_stmt>precision ['fast' 'safe' 'exact']<block_start>_empty_alpha(precision)<block_end><block_end><def_stmt>_infinite_alpha precision<block_start>point_list=[[0 0] [1 0] [0 1] [1 1]]<line_sep>alpha_complex=gd.AlphaComplex(points=point_list precision=precision)<assert_stmt>alpha_complex.__is_defined()<eq><true><line_sep>simplex_tree=alpha_complex.create_simplex_tree()<assert_stmt>simplex_tree.__is_persistence_defined()<eq><false><assert_stmt>simplex_tree.num_simplices()<eq>11<assert_stmt>simplex_tree.num_vertices()<eq>4<assert_stmt>list(simplex_tree.get_filtration())<eq>[([0] 0.0) ([1] 0.0) ([2] 0.0) ([3] 0.0) ([0 1] 0.25) ([0 2] 0.25) ([1 3] 0.25) ([2 3] 0.25) ([1 2] 0.5) ([0 1 2] 0.5) ([1 2 3] 0.5) ]<assert_stmt>simplex_tree.get_star([0])<eq>[([0] 0.0) ([0 1] 0.25) ([0 1 2] 0.5) ([0 2] 0.25) ]<assert_stmt>simplex_tree.get_cofaces([0] 1)<eq>[([0 1] 0.25) ([0 2] 0.25)]<assert_stmt>point_list[0]<eq>alpha_complex.get_point(0)<assert_stmt>point_list[1]<eq>alpha_complex.get_point(1)<assert_stmt>point_list[2]<eq>alpha_complex.get_point(2)<assert_stmt>point_list[3]<eq>alpha_complex.get_point(3)<try_stmt><block_start>alpha_complex.get_point(4)<eq>[]<block_end><except_stmt>IndexError<block_start><pass><block_end><else_stmt><block_start><assert_stmt><false><block_end><try_stmt><block_start>alpha_complex.get_point(125)<eq>[]<block_end><except_stmt>IndexError<block_start><pass><block_end><else_stmt><block_start><assert_stmt><false><block_end><block_end><def_stmt>test_infinite_alpha <block_start><for_stmt>precision ['fast' 'safe' 'exact']<block_start>_infinite_alpha(precision)<block_end><block_end><def_stmt>_filtered_alpha precision<block_start>point_list=[[0 0] [1 0] [0 1] [1 1]]<line_sep>filtered_alpha=gd.AlphaComplex(points=point_list precision=precision)<line_sep>simplex_tree=filtered_alpha.create_simplex_tree(max_alpha_square=0.25)<assert_stmt>simplex_tree.num_simplices()<eq>8<assert_stmt>simplex_tree.num_vertices()<eq>4<assert_stmt>point_list[0]<eq>filtered_alpha.get_point(0)<assert_stmt>point_list[1]<eq>filtered_alpha.get_point(1)<assert_stmt>point_list[2]<eq>filtered_alpha.get_point(2)<assert_stmt>point_list[3]<eq>filtered_alpha.get_point(3)<try_stmt><block_start>filtered_alpha.get_point(4)<eq>[]<block_end><except_stmt>IndexError<block_start><pass><block_end><else_stmt><block_start><assert_stmt><false><block_end><try_stmt><block_start>filtered_alpha.get_point(125)<eq>[]<block_end><except_stmt>IndexError<block_start><pass><block_end><else_stmt><block_start><assert_stmt><false><block_end><assert_stmt>list(simplex_tree.get_filtration())<eq>[([0] 0.0) ([1] 0.0) ([2] 0.0) ([3] 0.0) ([0 1] 0.25) ([0 2] 0.25) ([1 3] 0.25) ([2 3] 0.25) ]<assert_stmt>simplex_tree.get_star([0])<eq>[([0] 0.0) ([0 1] 0.25) ([0 2] 0.25)]<assert_stmt>simplex_tree.get_cofaces([0] 1)<eq>[([0 1] 0.25) ([0 2] 0.25)]<block_end><def_stmt>test_filtered_alpha <block_start><for_stmt>precision ['fast' 'safe' 'exact']<block_start>_filtered_alpha(precision)<block_end><block_end><def_stmt>_safe_alpha_persistence_comparison precision#generate periodic signal <block_start>time=np.arange(0 10 1)<line_sep>signal=[math.sin(x)<for>x time]<line_sep>delta=math.pi<line_sep>delayed=[math.sin(x+delta)<for>x time]<line_sep>#construct embedding embedding1=[[signal[i] -signal[i]]<for>i range(len(time))]<line_sep>embedding2=[[signal[i] delayed[i]]<for>i range(len(time))]<line_sep>#build alpha complex and simplex tree alpha_complex1=gd.AlphaComplex(points=embedding1 precision=precision)<line_sep>simplex_tree1=alpha_complex1.create_simplex_tree()<line_sep>alpha_complex2=gd.AlphaComplex(points=embedding2 precision=precision)<line_sep>simplex_tree2=alpha_complex2.create_simplex_tree()<line_sep>diag1=simplex_tree1.persistence()<line_sep>diag2=simplex_tree2.persistence()<for_stmt>(first_p second_p) zip_longest(diag1 diag2)<block_start><assert_stmt>first_p[0]<eq>pytest.approx(second_p[0])<assert_stmt>first_p[1]<eq>pytest.approx(second_p[1])<block_end><block_end><def_stmt>test_safe_alpha_persistence_comparison # Won't work for 'fast' version <block_start>_safe_alpha_persistence_comparison('safe')<line_sep>_safe_alpha_persistence_comparison('exact')<block_end><def_stmt>_delaunay_complex precision<block_start>point_list=[[0 0] [1 0] [0 1] [1 1]]<line_sep>filtered_alpha=gd.AlphaComplex(points=point_list precision=precision)<line_sep>simplex_tree=filtered_alpha.create_simplex_tree(default_filtration_value=<true>)<assert_stmt>simplex_tree.num_simplices()<eq>11<assert_stmt>simplex_tree.num_vertices()<eq>4<assert_stmt>point_list[0]<eq>filtered_alpha.get_point(0)<assert_stmt>point_list[1]<eq>filtered_alpha.get_point(1)<assert_stmt>point_list[2]<eq>filtered_alpha.get_point(2)<assert_stmt>point_list[3]<eq>filtered_alpha.get_point(3)<try_stmt><block_start>filtered_alpha.get_point(4)<eq>[]<block_end><except_stmt>IndexError<block_start><pass><block_end><else_stmt><block_start><assert_stmt><false><block_end><try_stmt><block_start>filtered_alpha.get_point(125)<eq>[]<block_end><except_stmt>IndexError<block_start><pass><block_end><else_stmt><block_start><assert_stmt><false><block_end><for_stmt>filtered_value simplex_tree.get_filtration()<block_start><assert_stmt>math.isnan(filtered_value[1])<block_end><for_stmt>filtered_value simplex_tree.get_star([0])<block_start><assert_stmt>math.isnan(filtered_value[1])<block_end><for_stmt>filtered_value simplex_tree.get_cofaces([0] 1)<block_start><assert_stmt>math.isnan(filtered_value[1])<block_end><block_end><def_stmt>test_delaunay_complex <block_start><for_stmt>precision ['fast' 'safe' 'exact']<block_start>_delaunay_complex(precision)<block_end><block_end><def_stmt>_3d_points_on_a_plane precision default_filtration_value<block_start>alpha=gd.AlphaComplex(off_file='alphacomplexdoc.off' precision=precision)<line_sep>simplex_tree=alpha.create_simplex_tree(default_filtration_value=default_filtration_value)<assert_stmt>simplex_tree.dimension()<eq>2<assert_stmt>simplex_tree.num_vertices()<eq>7<assert_stmt>simplex_tree.num_simplices()<eq>25<block_end><def_stmt>test_3d_points_on_a_plane <block_start>off_file=open("alphacomplexdoc.off" "w")<line_sep>off_file.write("OFF \n"<concat>"7 0 0 \n"<concat>"1.0 1.0 0.0\n"<concat>"7.0 0.0 0.0\n"<concat>"4.0 6.0 0.0\n"<concat>"9.0 6.0 0.0\n"<concat>"0.0 14.0 0.0\n"<concat>"2.0 19.0 0.0\n"<concat>"9.0 17.0 0.0\n")<line_sep>off_file.close()<for_stmt>default_filtration_value [<true> <false>]<block_start><for_stmt>precision ['fast' 'safe' 'exact']<block_start>_3d_points_on_a_plane(precision default_filtration_value)<block_end><block_end><block_end><def_stmt>_3d_tetrahedrons precision<block_start>points=10<times>np.random.rand(10 3)<line_sep>alpha=gd.AlphaComplex(points=points precision=precision)<line_sep>st_alpha=alpha.create_simplex_tree(default_filtration_value=<false>)<line_sep># New AlphaComplex for get_point to work delaunay=gd.AlphaComplex(points=points precision=precision)<line_sep>st_delaunay=delaunay.create_simplex_tree(default_filtration_value=<true>)<line_sep>delaunay_tetra=[]<for_stmt>sk st_delaunay.get_skeleton(4)<block_start><if_stmt>len(sk[0])<eq>4<block_start>tetra=[delaunay.get_point(sk[0][0]) delaunay.get_point(sk[0][1]) delaunay.get_point(sk[0][2]) delaunay.get_point(sk[0][3])]<line_sep>delaunay_tetra.append(sorted(tetra key=<lambda>tup:tup[0]))<block_end><block_end>alpha_tetra=[]<for_stmt>sk st_alpha.get_skeleton(4)<block_start><if_stmt>len(sk[0])<eq>4<block_start>tetra=[alpha.get_point(sk[0][0]) alpha.get_point(sk[0][1]) alpha.get_point(sk[0][2]) alpha.get_point(sk[0][3])]<line_sep>alpha_tetra.append(sorted(tetra key=<lambda>tup:tup[0]))<block_end><block_end># Check the tetrahedrons from one list are in the second one <assert_stmt>len(alpha_tetra)<eq>len(delaunay_tetra)<for_stmt>tetra_from_del delaunay_tetra<block_start><assert_stmt>tetra_from_del<in>alpha_tetra<block_end><block_end><def_stmt>test_3d_tetrahedrons <block_start><for_stmt>precision ['fast' 'safe' 'exact']<block_start>_3d_tetrahedrons(precision)<block_end><block_end>
<import_stmt>os<import_from_stmt>typing Tuple<import_stmt>numpy<as>np<import_stmt>openfermion<as>of<import_stmt>scipy<as>sp<import_stmt>openfermioncirq.experiments.hfvqe<as>hfvqe<import_from_stmt>openfermioncirq.experiments.hfvqe.gradient_hf rhf_minimization<import_from_stmt>openfermioncirq.experiments.hfvqe.objective RestrictedHartreeFockObjective generate_hamiltonian <def_stmt>make_h3_2_5 <arrow>Tuple[RestrictedHartreeFockObjective of.MolecularData np.ndarray np.ndarray np.ndarray]# load the molecule from moelcular data <block_start>h3_2_5_path=os.path.join(hfvqe.__path__[0] 'molecular_data/hydrogen_chains/h_3_p_sto-3g/bond_distance_2.5')<line_sep>molfile=os.path.join(h3_2_5_path 'H3_plus_sto-3g_singlet_linear_r-2.5.hdf5')<line_sep>molecule=of.MolecularData(filename=molfile)<line_sep>molecule.load()<line_sep>S=np.load(os.path.join(h3_2_5_path 'overlap.npy'))<line_sep>Hcore=np.load(os.path.join(h3_2_5_path 'h_core.npy'))<line_sep>TEI=np.load(os.path.join(h3_2_5_path 'tei.npy'))<line_sep>_,X=sp.linalg.eigh(Hcore S)<line_sep>obi=of.general_basis_change(Hcore X (1 0))<line_sep>tbi=np.einsum('psqr' of.general_basis_change(TEI X (1 0 1 0)))<line_sep>molecular_hamiltonian=generate_hamiltonian(obi tbi molecule.nuclear_repulsion)<line_sep>rhf_objective=RestrictedHartreeFockObjective(molecular_hamiltonian molecule.n_electrons)<line_sep>scipy_result=rhf_minimization(rhf_objective)<line_sep><return>rhf_objective molecule scipy_result.x obi tbi<block_end>
""" return the taker/maker commission rate """<class_stmt>CommissionRate<block_start><def_stmt>__init__ self<block_start>self.symbol=""<line_sep>self.makerCommissionRate=0.0<line_sep>self.takerCommissionRate=0.0<block_end>@staticmethod<def_stmt>json_parse json_data<block_start>result=CommissionRate()<line_sep>result.symbol=json_data.get_string("symbol")<line_sep>result.makerCommissionRate=json_data.get_float("makerCommissionRate")<line_sep>result.takerCommissionRate=json_data.get_float("takerCommissionRate")<line_sep><return>result<block_end><block_end>
<import_from_stmt>unittesting DeferrableTestCase<import_from_stmt>GitSavvy.tests.parameterized parameterized<as>p<import_from_stmt>GitSavvy.core.commands.log_graph describe_graph_line<line_sep>examples=[("|" {} <none>) ("● a3062b2 (HEAD -> optimize-graph-render, origin/optimize-graph-render) Abort .. | Thu 21:07, herr kaste" {"origin"} {"commit":"a3062b2" "HEAD":"optimize-graph-render" "branches":["optimize-graph-render" "origin/optimize-graph-render"] "local_branches":["optimize-graph-render"]}) ("● a3062b2 (HEAD, origin/optimize-graph-render) Abort re.. | Thu 21:07, herr kaste" {"origin"} {"commit":"a3062b2" "HEAD":"a3062b2" "branches":["origin/optimize-graph-render"]}) ("● a3062b2 (HEAD -> optimize-graph-render, feat/optimize-graph-render) Abort .. | Thu 21:07, herr kaste" {"origin"} {"commit":"a3062b2" "HEAD":"optimize-graph-render" "branches":["optimize-graph-render" "feat/optimize-graph-render"] "local_branches":["optimize-graph-render" "feat/optimize-graph-render"]}) ("● ad6d88c (HEAD) Use view from the argument instead of on self | Thu 20:56, herr kaste" {"origin"} {"commit":"ad6d88c" "HEAD":"ad6d88c" }) ("● ad6d88c Use view from the argument instead of on self | Thu 20:56, herr kaste" {"origin"} {"commit":"ad6d88c" }) ("| ● 153dca0 (HEAD, tag: 2.20.0) Merge branch 'dev' (2 months ago) <<NAME>>" {"origin"} {"commit":"153dca0" "HEAD":"153dca0" "tags":["2.20.0"]}) ]<class_stmt>TestDescribeGraphLine(DeferrableTestCase)<block_start>@p.expand(examples)<def_stmt>test_a self input_line remotes output<block_start>self.assertEqual(output describe_graph_line(input_line remotes))<block_end><block_end>
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras layers module. """<line_sep># pylint: disable=wildcard-import <import_from_future_stmt> absolute_import<import_from_future_stmt> division<import_from_future_stmt> print_function<import_from_stmt>tensorflow.python.keras._impl.keras.engine Input<import_from_stmt>tensorflow.python.keras._impl.keras.engine InputLayer<import_from_stmt>tensorflow.python.keras._impl.keras.engine InputSpec<import_from_stmt>tensorflow.python.keras._impl.keras.engine Layer<import_from_stmt>tensorflow.python.keras._impl.keras.layers.advanced_activations *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.convolutional *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.convolutional_recurrent *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.core *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.embeddings *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.local *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.merge *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.noise *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.normalization *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.pooling *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.recurrent *<import_from_stmt>tensorflow.python.keras._impl.keras.layers.serialization deserialize<import_from_stmt>tensorflow.python.keras._impl.keras.layers.serialization serialize<import_from_stmt>tensorflow.python.keras._impl.keras.layers.wrappers *<line_sep>
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: atts_assign.py # # Tests: Behavior of assignment for attribute objects. Ensures good cases # succeed and bad cases fail with specific python exceptions. Tests variety # of types present in members of VisIt attribute objects. Tests both # assignment usage (e.g. atts.memberName=...) and setter function usage # (e.g. atts.SetMemberName(...)) # # <NAME>, Tue Jun 8 15:51:59 PDT 2021 # # Modifications: # <NAME>, Tue July 27, 2021 # Assigning Max32BitInt+1 to int on Windows causes TypeError, not # ValueError, so change expected results in those cases. # # ---------------------------------------------------------------------------- <import_stmt>copy io sys<line_sep># Some useful global variables X=[2 4 6]<line_sep>Max32BitInt=2147483647<line_sep>Max32BitInt1=Max32BitInt+1<line_sep>MaxIntAs32BitFloat=16777216<line_sep>MaxIntAs32BitFloat1=MaxIntAs32BitFloat+1<line_sep>MaxIntAs64BitFloat=9007199254740992<line_sep>MaxIntAs64BitFloat1=MaxIntAs64BitFloat+1<line_sep>Max32BitFloat=3.402823E+38<line_sep>Max32BitFloatA=3.402820E+37# One order mag down from Max Max32BitFloatB=3.402823E+39# One order mag up from Max Min32BitFloat=1.175494E-38<line_sep># version of repr that strips parens at end <def_stmt>repr2 s<block_start><return>repr(s).lstrip('(').rstrip(')')<block_end><def_stmt>TestAssignmentToTuple <block_start>TestSection('Assignment to tuple, "point1", member (of CylinderAttributes())')<line_sep>ca=CylinderAttributes()<line_sep># Non-existent member name 'point' <try_stmt><block_start>ca.point=1 2 3<line_sep>TestFOA('ca.point=1,2,3' LINE())<block_end><except_stmt>NameError<block_start>TestPOA('ca.point=1,2,3')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.point=1,2,3' LINE())<line_sep><pass><block_end># Non-existent member name 'point' <try_stmt><block_start>ca.SetPoint(1 2 3)<line_sep>TestFOA('ca.SetPoint(1,2,3)' LINE())<block_end><except_stmt>ValueError<block_start>TestPOA('ca.SetPoint(1,2,3)')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetPoint(1,2,3)' LINE())<line_sep><pass><block_end># CSV too short <try_stmt><block_start>ca.point1=1 2<line_sep>TestFOA('ca.point1=1,2' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.point1=1,2')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.point1=1,2' LINE())<line_sep><pass><block_end># CSV too long <try_stmt><block_start>ca.point1=1 2 3 4<line_sep>TestFOA('ca.point1=1,2,3,4' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.point1=1,2,3,4')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.point1=1,2,3,4' LINE())<line_sep><pass><block_end># The above cases can't be put in a loop. Put remaining cases in a loop fails=[(1 2) (1 2 3 4) '123' (1 1+2j 3) (1 X 3) (1 'b' 3) (1 <none> 3)]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.point1=fails[i]<line_sep>TestFOA('ca.point1=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.point1=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.point1=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.SetPoint1(fails[i])<line_sep>TestFOA('ca.SetPoint1(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.SetPoint1(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetPoint1(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><try_stmt><block_start>ca.point1=1 2 3<line_sep>TestPOA('ca.point1=1,2,3')<block_end><except_stmt><block_start>TestFOA('ca.point1=1,2,3' LINE())<line_sep><pass><block_end>works=[(1 2 3) (1.1 2.2 3.3) tuple(X)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.point1=works[i]<line_sep>TestPOA('ca.point1=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.point1=%s'%repr2(works[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.SetPoint1(*works[i])<line_sep>TestPOA('ca.SetPoint1(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.SetPoint1(%s)'%repr2(works[i]) LINE())<line_sep><pass><block_end><block_end><block_end><def_stmt>TestAssignmentToBool <block_start>TestSection('Assignment to bool member, "inverse", (of CylinderAttributes())')<line_sep>ca=CylinderAttributes()<try_stmt><block_start>ca.inverse=1 2<line_sep>TestFOA('ca.inverse=1,2' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.inverse=1,2')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.inverse=1,2' LINE())<line_sep><pass><block_end>fails=['123' 1+2j X <none> 5]<line_sep>excpts=[TypeError TypeError TypeError TypeError ValueError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.inverse=fails[i]<line_sep>TestFOA('ca.inverse=%s'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ca.inverse=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.inverse=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.SetInverse(fails[i])<line_sep>TestFOA('ca.SetInverse(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ca.SetInverse(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetInverse(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[0 1 <true> <false>]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.inverse=works[i]<line_sep>TestPOA('ca.inverse=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.inverse=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.SetInverse(works[i])<line_sep>TestPOA('ca.SetInverse(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.SetInverse(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToInt <block_start>TestSection('Assignment to int member, "samplesPerRay", (of VolumeAttributes())')<line_sep>va=VolumeAttributes()<try_stmt><block_start>va.samplesPerRay=1 2<line_sep>TestFOA('va.samplesPerRay=1,2' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.samplesPerRay=1,2')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.samplesPerRay=1,2' LINE())<line_sep><pass><block_end>fails=['123' 1+2j <none> X Max32BitInt1]<if_stmt>sys.platform.startswith("win")<block_start>excpts=[TypeError TypeError TypeError TypeError TypeError]<block_end><else_stmt><block_start>excpts=[TypeError TypeError TypeError TypeError ValueError]<block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.samplesPerRay=fails[i]<line_sep>TestFOA('va.samplesPerRay=%s'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('va.samplesPerRay=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.samplesPerRay=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.SetSamplesPerRay(fails[i])<line_sep>TestFOA('va.SetSamplesPerRay(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('va.SetSamplesPerRay(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.SetSamplesPerRay(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[0 1 -1 5 <true> <false> Max32BitInt]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>va.samplesPerRay=works[i]<line_sep>TestPOA('va.samplesPerRay=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('va.samplesPerRay=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>va.SetSamplesPerRay(works[i])<line_sep>TestPOA('va.SetSamplesPerRay(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('va.SetSamplesPerRay(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToFloat <block_start>TestSection('Assignment to float member, "opacityAttenuation", (of VolumeAttributes())')<line_sep>va=VolumeAttributes()<try_stmt><block_start>va.opacityAttenuation=1 2<line_sep>TestFOA('va.opacityAttenuation=1,2' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.opacityAttenuation=1,2')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.opacityAttenuation=1,2' LINE())<line_sep><pass><block_end>fails=['123' 1+2j <none> X Max32BitFloatB]<line_sep>excpts=[TypeError TypeError TypeError TypeError ValueError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.opacityAttenuation=fails[i]<line_sep>TestFOA('va.opacityAttenuation=%s'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('va.opacityAttenuation=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.opacityAttenuation=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.SetOpacityAttenuation(fails[i])<line_sep>TestFOA('va.SetOpacityAttenuation(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('va.SetOpacityAttenuation(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.SetOpacityAttenuation(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[0 1 -1 0.3 Max32BitFloatA <true> <false>]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>va.opacityAttenuation=works[i]<line_sep>TestPOA('va.opacityAttenuation=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('va.opacityAttenuation=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>va.SetOpacityAttenuation(works[i])<line_sep>TestPOA('va.SetOpacityAttenuation(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('va.SetOpacityAttenuation(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToDouble <block_start>TestSection('Assignment to double member, "radius", (of CylinderAttributes())')<line_sep>ca=CylinderAttributes()<try_stmt><block_start>ca.radius=1 2<line_sep>TestFOA('ca.radius=1,2' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.radius=1,2')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.radius=1,2' LINE())<line_sep><pass><block_end>fails=['123' 1+2j <none> X]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.radius=fails[i]<line_sep>TestFOA('ca.radius=%s'%repr(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.radius=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.radius=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.SetRadius(fails[i])<line_sep>TestFOA('ca.SetRadius(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.SetRadius(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetRadius(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[0 1 -1 5.5 1.1E-479 1.1E+479 <true> <false>]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.radius=works[i]<line_sep>TestPOA('ca.radius=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.radius=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.SetRadius(works[i])<line_sep>TestPOA('ca.SetRadius(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.SetRadius(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToString <block_start>TestSection('Assignment to string member, "designator", (of CurveAttributes())')<line_sep>ca=CurveAttributes()<try_stmt><block_start>ca.designator="123" "abc"<line_sep>TestFOA('ca.designator="123","abc"' LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.designator="123","abc"')<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.designator="123","abc"' LINE())<line_sep><pass><block_end>fails=[0 1 1.1 1+2j <none> X]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.designator=fails[i]<line_sep>TestFOA('ca.designator=%s'%repr(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.designator=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.designator=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.SetDesignator(fails[i])<line_sep>TestFOA('ca.SetDesignator(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.SetDesignator(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetDesignator(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=['123' 'abc' '']<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.designator=works[i]<line_sep>TestPOA('ca.designator=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.designator=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.SetDesignator(works[i])<line_sep>TestPOA('ca.SetDesignator(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.SetDesignator(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToGlyphType <block_start>TestSection('Assignment to GlyphType member, "pointType", (of MeshAttributes())')<line_sep>ma=MeshAttributes()<line_sep># Test direct assignment with = operator <try_stmt><block_start>ma.pointType=1<line_sep>TestPOA('ma.pointType=1')<block_end><except_stmt><block_start>TestFOA('ma.pointType=1' LINE())<line_sep><pass><block_end>fails=['123' 1+2j <none> X -1 123123123123123123123123123123]<line_sep>excpts=[TypeError TypeError TypeError TypeError ValueError TypeError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ma.pointType=fails[i]<line_sep>TestFOA('ma.pointType=%s'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ma.pointType=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ma.pointType=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ma.SetPointType(fails[i])<line_sep>TestFOA('ma.SetPointType(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ma.SetPointType(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ma.SetPointType(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[0 1 5 <true> <false> ma.Point]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ma.pointType=works[i]<line_sep>TestPOA('ma.pointType=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ma.pointType=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ma.SetPointType(works[i])<line_sep>TestPOA('ma.SetPointType(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ma.SetPointType(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToEnum <block_start>TestSection('Assignment to Enum member, "smoothingLevel", (of MeshAttributes())')<line_sep>ma=MeshAttributes()<line_sep># Test direct assignment with = operator <try_stmt><block_start>ma.smoothingLevel=1<line_sep>TestPOA('ma.smoothingLevel=1')<block_end><except_stmt><block_start>TestFOA('ma.smoothingLevel=1' LINE())<line_sep><pass><block_end>fails=['123' 1+2j <none> X -1 123123123 123123123123123123123123123123]<line_sep>excpts=[TypeError TypeError TypeError TypeError ValueError ValueError TypeError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ma.smoothingLevel=fails[i]<line_sep>TestFOA('ma.smoothingLevel=%s'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ma.smoothingLevel=%s'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ma.smoothingLevel=%s'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ma.SetSmoothingLevel(fails[i])<line_sep>TestFOA('ma.SetSmoothingLevel(%s)'%repr(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ma.SetSmoothingLevel(%s)'%repr(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ma.SetSmoothingLevel(%s)'%repr(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[0 1 2 <true> <false> ma.Fast]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ma.smoothingLevel=works[i]<line_sep>TestPOA('ma.smoothingLevel=%s'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ma.smoothingLevel=%s'%repr(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ma.SetSmoothingLevel(works[i])<line_sep>TestPOA('ma.SmoothingLevel(%s)'%repr(works[i]))<block_end><except_stmt><block_start>TestFOA('ma.SetSmoothingLevel(%s)'%repr(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToUCharVector <block_start>TestSection('Assignment to ucharVector member, "changedColors", (of MultiCurveAttributes())')<line_sep>mca=MultiCurveAttributes()<line_sep># Test direct assignment with = operator <try_stmt><block_start>mca.changedColors=1 2 3<line_sep>TestPOA('mca.changedColors=1,2,3')<block_end><except_stmt><block_start>TestFOA('mca.changedColors=1,2,3' LINE())<line_sep><pass><block_end>fails=[(1 123123123123123123123123123123 3) (1 1+2j 3) (1 X 3) (1 'b' 3) (1 <none> 3) ('123' )]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>mca.changedColors=fails[i]<line_sep>TestFOA('mca.changedColors=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('mca.changedColors=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('mca.changedColors=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>mca.SetChangedColors(*fails[i])<line_sep>TestFOA('mca.SetChangedColors(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('mca.SetChangedColors(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('mca.SetChangedColors(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[(1 2 3) tuple(X) (1 <true> 3) (1 <false> 3)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>mca.changedColors=works[i]<line_sep>TestPOA('mca.changedColors=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('mca.changedColors=%s'%repr2(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>mca.SetChangedColors(*works[i])<line_sep>TestPOA('mca.SetChangedColors(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('mca.SetChangedColors(%s)'%repr2(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToIntVector <block_start>TestSection('Assignment to intVector member, "index", (of OnionPeelAttributes())')<line_sep>opa=OnionPeelAttributes()<line_sep># Test direct assignment with = operator <try_stmt><block_start>opa.index=1 2 3<line_sep>TestPOA('opa.index=1,2,3')<block_end><except_stmt><block_start>TestFOA('opa.index=1,2,3' LINE())<line_sep><pass><block_end>fails=[(Max32BitInt1 ) (1+2j ) ('b' ) (<none> ) (1 Max32BitInt1 3) (1 1+2j 3) (1 X 3) (1 'b' 3) (1 <none> 3)]<if_stmt>sys.platform.startswith("win")<block_start>excpts=[TypeError TypeError TypeError TypeError TypeError TypeError TypeError TypeError TypeError]<block_end><else_stmt><block_start>excpts=[ValueError TypeError TypeError TypeError ValueError TypeError TypeError TypeError TypeError]<block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>opa.index=fails[i]<line_sep>TestFOA('opa.index=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('opa.index=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('opa.index=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>opa.SetIndex(*fails[i])<line_sep>TestFOA('opa.SetIndex(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('opa.SetIndex(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('opa.SetIndex(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[(1 2 3) X tuple(X) (1 <true> 3) (1 <false> 3) (1 Max32BitInt 3)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>opa.index=works[i]<line_sep>TestPOA('opa.index=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('opa.index=%s'%repr2(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>opa.SetIndex(*works[i])<line_sep>TestPOA('opa.SetIndex(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('opa.SetIndex(%s)'%repr2(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToDoubleVector <block_start>TestSection('Assignment to doubleVector member, "values", (of ContourAttributes())')<line_sep>ca=ContourAttributes()<line_sep># Test direct assignment with = operator <try_stmt><block_start>ca.contourValue=1 2 3<line_sep>TestPOA('ca.contourValue=1,2,3')<block_end><except_stmt><block_start>TestFOA('ca.contourValue=1,2,3' LINE())<line_sep><pass><block_end>fails=[(1+2j ) ('b' ) (<none> ) (1 1+2j 3) (1 X 3) (1 'b' 3) (1 <none> 3)]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.contourValue=fails[i]<line_sep>TestFOA('ca.contourValue=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.contourValue=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.contourValue=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.SetContourValue(*fails[i])<line_sep>TestFOA('ca.SetContourValue(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('ca.SetContourValue(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetContourValue(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[(1 2 3) X tuple(X) (1 <true> 3) (1 <false> 3)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.contourValue=works[i]<line_sep>TestPOA('ca.contourValue=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.contourValue=%s'%repr2(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ca.SetContourValue(*works[i])<line_sep>TestPOA('ca.SetContourValue(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('ca.SetContourValue(%s)'%repr2(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToUCharArray <block_start>TestSection('Assignment to ucharArray member, "freeformOpacity", (of VolumeAttributes())')<line_sep>arr=[17 ]<times>256<line_sep>va=VolumeAttributes()<line_sep># Test assigning to individual entry via direct (operator =) assignment <try_stmt><block_start>va.freeformOpacity=3 17<line_sep>TestPOA('va.freeformOpacity=3,17')<block_end><except_stmt><block_start>TestFOA('va.freeformOpacity=3,17' LINE())<line_sep><pass><block_end># Test assigning to individual entry via Set method <try_stmt><block_start>va.SetFreeformOpacity(3 17)<line_sep>TestPOA('va.SetFreeformOpacity(3,17)')<block_end><except_stmt><block_start>TestFOA('va.SetFreeformOpacity(3,17)' LINE())<line_sep><pass><block_end># Test assigning to whole array via (operator =) assignment <try_stmt><block_start>va.freeformOpacity=tuple(arr)<line_sep>TestPOA('va.freeformOpacity=tuple(arr)')<block_end><except_stmt><block_start>TestFOA('va.freeformOpacity=tuple(arr)' LINE())<line_sep><pass><block_end># Test assigning to whole array via Set method <try_stmt><block_start>va.SetFreeformOpacity(*tuple(arr))<line_sep>TestPOA('va.SetFreeformOpacity(*tuple(arr))')<block_end><except_stmt><block_start>TestFOA('va.SetFreeformOpacity(*tuple(arr))' LINE())<line_sep><pass><block_end># Test assigning to individual entry via direct (operator =) assignment # failures for type of second argument (color value) fails=[(3 <none>) (3 1+2j) (3 X) (3 '123') (<none> 17) (1+2j 17) (X 17) ('123' 17) (-3 17) (3 1700)]<line_sep>excpts=[TypeError TypeError TypeError TypeError TypeError TypeError TypeError TypeError IndexError ValueError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.freeformOpacity=fails[i][0] fails[i][1]<line_sep>TestFOA('va.freeformOpacity=%s,%s'%(repr(fails[i][0]) repr(fails[i][1])) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('va.freeformOpacity=%s,%s'%(repr(fails[i][0]) repr(fails[i][1])))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.freeformOpacity=%s,%s'%(repr(fails[i][0]) repr(fails[i][1])) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.SetFreeformOpacity(fails[i][0] fails[i][1])<line_sep>TestFOA('va.SetFreeformOpacity(%s,%s)'%(repr(fails[i][0]) repr(fails[i][1])) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('va.SetFreeformOpacity(%s,%s)'%(repr(fails[i][0]) repr(fails[i][1])))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.SetFreeformOpacity(%s,%s)'%(repr(fails[i][0]) repr(fails[i][1])) LINE())<line_sep><pass><block_end><block_end># Test assigning to whole member via direct (operator =) assignment <try_stmt><block_start>va.freeformOpacity=(17 )<times>256<line_sep>TestPOA('va.freeformOpacity=(17,)*256')<block_end><except_stmt><block_start>TestFOA('va.freeformOpacity=(17,)*256' LINE())<line_sep><pass><block_end># Test assigning to whole member via Set method <try_stmt><block_start>va.SetFreeformOpacity(*(17 )<times>256)<line_sep>TestPOA('va.SetFreeformOpacity((17,)*256)')<block_end><except_stmt><block_start>TestFOA('va.SetFreeformOpacity((17,)*256)' LINE())<line_sep><pass><block_end># Test assigning to whole member via direct (operator =) assignment # failures for type of first argument (index) arr1=copy.deepcopy(arr)<line_sep>arr2=copy.deepcopy(arr)<line_sep>arr3=copy.deepcopy(arr)<line_sep>arr4=copy.deepcopy(arr)<line_sep>arr5=copy.deepcopy(arr)<line_sep>arr1[3]=<none><line_sep>arr2[3]=1+2j<line_sep>arr3[3]=X<line_sep>arr4[3]=(1 2 3)<line_sep>arr5[3]='123'<line_sep>fails=[tuple(arr1) tuple(arr2) tuple(arr3) tuple(arr4) tuple(arr5)]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.freeformOpacity=fails[i]<line_sep>TestFOA('va.freeformOpacity=%s'%repr(fails[i][:7]).replace(')' ', ...') LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.freeformOpacity=%s'%repr(fails[i][:7]).replace(')' ', ...'))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.freeformOpacity=%s'%repr(fails[i][:7]).replace(')' ', ...') LINE())<line_sep><pass><block_end><block_end># Test star-deref of tuple <for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.SetFreeformOpacity(*fails[i])<line_sep>TestFOA('va.SetFreeformOpacity%s'%repr(fails[i][:7]).replace(')' ', ...)') LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.SetFreeformOpacity%s'%repr(fails[i][:7]).replace(')' ', ...)'))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.SetFreeformOpacity%s'%repr(fails[i][:7]).replace(')' ', ...)') LINE())<line_sep><pass><block_end><block_end># Test just passing the tuple <for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.SetFreeformOpacity(fails[i])<line_sep>TestFOA('va.SetFreeformOpacity(fails[%d])'%i LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.SetFreeformOpacity(fails[%d])'%i)<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.SetFreeformOpacity(fails[%d])'%i LINE())<line_sep><pass><block_end><block_end><block_end><def_stmt>TestAssignmentToIntArray <block_start>TestSection('Assignment to intArray member, "reflections", (of ReflectAttributes())')<line_sep>ra=ReflectAttributes()<line_sep># Test assigning via (operator =) assignment <try_stmt><block_start>ra.reflections=0 1 0 1 0 1 0 1<line_sep>TestPOA('ra.reflections=0,1,0,1,0,1,0,1')<block_end><except_stmt><block_start>TestFOA('ra.reflections=0,1,0,1,0,1,0,1' LINE())<line_sep><pass><block_end>fails=[(0 1 <none> 1 0 1 0 1) (0 1 1+2j 1 0 1 0 1) (0 1 X 1 0 1 0 1) (0 1 Max32BitInt1 1 0 1 0 1) (0 1 '123' 1 0 1 0 1) (0 1 0 1 0 1 0 1 1) (0 1 0 1 0 1 0)]<if_stmt>sys.platform.startswith("win")<block_start>excpts=[TypeError TypeError TypeError TypeError TypeError TypeError TypeError]<block_end><else_stmt><block_start>excpts=[TypeError TypeError TypeError ValueError TypeError TypeError TypeError]<block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ra.reflections=fails[i]<line_sep>TestFOA('ra.reflections=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ra.reflections=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ra.reflections=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ra.SetReflections(*fails[i])<line_sep>TestFOA('ra.SetReflections(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ra.SetReflections(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ra.SetReflections(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[(0 1 0 1 0 1 0 1) (-1 100 -1 100 -1 100 -1 100) (0 <true> <false> 1 0 1 0 1) (0 1 Max32BitInt 1 0 1 0 1)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>ra.reflections=works[i]<line_sep>TestPOA('ra.reflections=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('ra.reflections=%s'%repr2(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>ra.SetReflections(*works[i])<line_sep>TestPOA('ra.SetReflections(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('ra.SetReflections(%s)'%repr2(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToFloatArray <block_start>TestSection('Assignment to floatArray member, "center", (of RadialResampleAttributes())')<line_sep>rra=RadialResampleAttributes()<line_sep># Test assigning via (operator =) assignment <try_stmt><block_start>rra.center=0 1 2<line_sep>TestPOA('rra.center=0,1,2')<block_end><except_stmt><block_start>TestFOA('rra.center=0,1,2' LINE())<line_sep><pass><block_end><try_stmt><block_start>rra.center=0 1<line_sep>TestFOA('rra.center=0,1' LINE())<block_end><except_stmt><block_start>TestPOA('rra.center=0,1')<line_sep><pass><block_end><try_stmt><block_start>rra.center=0 1 2 3<line_sep>TestFOA('rra.center=0,1,2,3' LINE())<block_end><except_stmt><block_start>TestPOA('rra.center=0,1,2,3')<line_sep><pass><block_end>fails=[(0 1) (0 1 2 3) (0 <none> 2) (0 1+2j 2) (0 X 2) (0 '123' 2) (0 Max32BitFloatB 2)]<line_sep>excpts=[TypeError TypeError TypeError TypeError TypeError TypeError ValueError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>rra.center=fails[i]<line_sep>TestFOA('rra.center=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('rra.center=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('rra.center=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>rra.SetCenter(*fails[i])<line_sep>TestFOA('rra.SetCenter(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('rra.SetCenter(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('rra.SetCenter(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[(1 2 3) (1.1 2.2 3.3) tuple(X) (1 <true> 3) (1 <false> 3) (1 Max32BitFloatA 3)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>rra.center=works[i]<line_sep>TestPOA('rra.center=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('rra.center=%s'%repr2(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>rra.SetCenter(*works[i])<line_sep>TestPOA('rra.SetCenter(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('rra.SetCenter(%s)'%repr2(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestAssignmentToDoubleArray <block_start>TestSection('Assignment to doubleArray member, "materialProperties", (of VolumeAttributes())')<line_sep>va=VolumeAttributes()<line_sep># Test assigning via (operator =) assignment <try_stmt><block_start>va.materialProperties=0 1 2 3<line_sep>TestPOA('va.materialProperties=0,1,2,3')<block_end><except_stmt><block_start>TestFOA('va.materialProperites=0,1,2,3' LINE())<line_sep><pass><block_end><try_stmt><block_start>va.materialProperties=0 1 2<line_sep>TestFOA('va.materialProperties=0,1,2' LINE())<block_end><except_stmt><block_start>TestPOA('va.materialProperties=0,1,2')<line_sep><pass><block_end><try_stmt><block_start>va.materialProperties=0 1 2 3 4<line_sep>TestFOA('va.materialProperties=0,1,2,3,4' LINE())<block_end><except_stmt><block_start>TestPOA('va.materialProperties=0,1,2,3,4')<line_sep><pass><block_end>fails=[(0 1) (0 1 2 3 4) (0 <none> 2 3) (0 1+2j 2 3) (0 X 2 3) (0 '123' 2 3)]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.materialProperties=fails[i]<line_sep>TestFOA('va.materialProperties=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.materialProperties=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.materialProperties=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>va.SetMaterialProperties(*fails[i])<line_sep>TestFOA('va.SetMaterialProperties(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>TypeError<block_start>TestPOA('va.SetMaterialProperties(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('va.SetMaterialProperties(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end>works=[(1 2 3 4) (1.1 2.2 3.3 4.4) (1 <true> 3 4) (1 <false> 3 4)]<for_stmt>i range(len(works))<block_start><try_stmt><block_start>va.materialProperties=works[i]<line_sep>TestPOA('va.materialProperties=%s'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('va.materialProperties=%s'%repr2(works[i]) LINE())<block_end><block_end><for_stmt>i range(len(works))<block_start><try_stmt><block_start>va.SetMaterialProperties(*works[i])<line_sep>TestPOA('va.SetMaterialProperties(%s)'%repr2(works[i]))<block_end><except_stmt><block_start>TestFOA('va.SetMaterialProperties(%s)'%repr2(works[i]) LINE())<block_end><block_end><block_end><def_stmt>TestColorAttributeStuff <block_start>TestSection('ColorAttribute stuff')<line_sep>cla=ColorAttributeList()<line_sep>ca=ColorAttribute()<line_sep>fails=[(0 1 2) (0 1 2 3 4) (0 <none> 2 3) (0 1+2j 2 3) (0 X 2 3) (0 '123' 2 3) (0 -1 2 3) (0 256 2 3)]<line_sep>excpts=[TypeError TypeError TypeError TypeError TypeError TypeError ValueError ValueError]<for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.color=fails[i]<line_sep>TestFOA('ca.color=%s'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ca.color=%s'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.color=%s'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><for_stmt>i range(len(fails))<block_start><try_stmt><block_start>ca.SetColor(*fails[i])<line_sep>TestFOA('ca.SetColor(%s)'%repr2(fails[i]) LINE())<block_end><except_stmt>excpts[i]<block_start>TestPOA('ca.SetColor(%s)'%repr2(fails[i]))<line_sep><pass><block_end><except_stmt><block_start>TestFOA('ca.SetColor(%s)'%repr2(fails[i]) LINE())<line_sep><pass><block_end><block_end><try_stmt><block_start>ca.color=(5 5 5 5)<line_sep>cla.AddColors(ca)<line_sep>ca.color=(255 0 0 255)<line_sep>cla.AddColors(ca)<line_sep>TestPOA('cla.AddColors')<block_end><except_stmt><block_start>TestFOA('cla.AddColors' LINE())<line_sep><pass><block_end><try_stmt><block_start>cla.colors<line_sep>TestFOA('cla.colors' LINE())<block_end><except_stmt>NameError<block_start>TestPOA('cla.colors')<block_end><except_stmt><block_start>TestFOA('cla.colors' LINE())<line_sep><pass><block_end><try_stmt><block_start><if_stmt>cla.GetColors(0).color<ne>(5 5 5 5)<or>cla.GetColors(1).color<ne>(255 0 0 255)<block_start><raise>ValueError<block_end>TestPOA('cla.GetColors(0)')<block_end><except_stmt><block_start>TestFOA('cla.Getcolors(0)' LINE())<line_sep><pass><block_end><try_stmt><block_start>cla.GetColors(2)<line_sep>TestFOA('cla.Getcolors(2)' LINE())<block_end><except_stmt>ValueError<block_start>TestPOA('cla.GetColors(2)')<block_end><except_stmt><block_start>TestFOA('cla.Getcolors(2)' LINE())<line_sep><pass><block_end><block_end><def_stmt>TestDirOutput obj minlen=5 names=<none><block_start>TestSection('behavior of dir()')<try_stmt><block_start>x=[f<for>f dir(obj)<if><not>(f.startswith('__')<and>f.endswith('__'))]<if_stmt>minlen<and>len(x)<l>minlen<block_start>TestFOA('dir(%s): minlen: %d < %d'%(repr(obj) len(x) minlen) LINE())<block_end>x=[n<for>n names<if>n<in>x]<if_stmt>len(x)<ne>len(names)<block_start>TestFOA('dir(%s): names: %s'%(repr(obj) names) LINE())<block_end>TestPOA('dir(%s)'%repr())<block_end><except_stmt><block_start>TestFOA('dir(%s)'%repr(obj) LINE())<block_end><block_end># Class to facilitate stdout redirect for testing `help()` <class_stmt>my_redirect_stdout(list)<block_start><def_stmt>__enter__ self<block_start>self._stdout=sys.stdout<line_sep>sys.stdout=self._stringio=io.StringIO()<line_sep><return>self<block_end><def_stmt>__exit__ self *args<block_start>self.extend(self._stringio.getvalue().splitlines())<del_stmt>self._stringio# free up some memory sys.stdout=self._stdout<block_end><block_end># Below import works only for Python > 3.4 # So, we use the class def above # from contextlib import redirect_stdout <def_stmt>TestHelpOutput thing minlen=200 words=<none><block_start>TestSection('behavior of help()')<try_stmt><block_start><with_stmt>my_redirect_stdout()<as>output<block_start>help(thing)<block_end><if_stmt>minlen<and>len(str(output))<l>minlen<block_start>TestFOA('dir(%s): minlen: %d < %d'%(repr(thing) len(output) minlen) LINE())<block_end>x=[w<for>w words<if>w<in>str(output)]<if_stmt>len(x)<ne>len(words)<block_start>TestFOA('dir(%s): words: %s'%(repr(thing) words) LINE())<block_end><block_end><except_stmt><block_start>TestFOA('help(%s)'%repr(thing) LINE())<block_end><block_end># Scalar assignments # TestAssignmentToUChar() No instances in any .xml files TestAssignmentToBool()<line_sep>TestAssignmentToInt()<line_sep>TestAssignmentToFloat()<line_sep>TestAssignmentToDouble()<line_sep>TestAssignmentToString()<line_sep>TestAssignmentToGlyphType()<line_sep>TestAssignmentToEnum()<line_sep>TestAssignmentToTuple()<line_sep># Vector assignments TestAssignmentToUCharVector()<line_sep>#TestAssignmentToBoolVector() No instances in any .xml files TestAssignmentToIntVector()<line_sep>#TestAssignmentToFloatVector() No instances in any .xml files TestAssignmentToDoubleVector()<line_sep># Array assignments TestAssignmentToUCharArray()<line_sep>#TestAssignmentToBoolArray() No instances in any .xml files TestAssignmentToIntArray()<line_sep>TestAssignmentToFloatArray()<line_sep>TestAssignmentToDoubleArray()<line_sep># Attribute Assignments TestColorAttributeStuff()<line_sep># Test that dir(x) appears to work #TestDirOutput(SILRestriction(), None, ['NumSets', 'TurnOnAll', 'Wholes', 'TopSets']) #TestDirOutput(PseudocolorAttributes(), 50) #TestDirOutput(ColorAttributeList(), None, ['AddColors', 'ClearColors', 'GetColors']) # Test Help #TestHelpOutput(AddPlot, None, ['plotType', 'variableName', 'inheritSIL']) #TestHelpOutput(CreateDatabaseCorrelation, None, # ['IndexForIndexCorrelation', 'CycleCorrelation', 'StretchedIndexCorrelation']) Exit()<line_sep>
<import_from_stmt>unittest TestCase<import_from_stmt>pypika Table functions<as>fn <import_stmt>fireant<as>f<import_from_stmt>fireant.tests.dataset.mocks test_database<line_sep>test_table=Table("test")<line_sep>ds=f.DataSet(table=test_table database=test_database fields=[f.Field("date" definition=test_table.date data_type=f.DataType.date) f.Field("text" definition=test_table.text data_type=f.DataType.text) f.Field("number" definition=test_table.number data_type=f.DataType.number) f.Field("boolean" definition=test_table.boolean data_type=f.DataType.boolean) f.Field("aggr_number" definition=fn.Sum(test_table.number) data_type=f.DataType.number ) ] )<line_sep># noinspection SqlDialectInspection,SqlNoDataSourceInspection <class_stmt>ResultSetTests(TestCase)<block_start>maxDiff=<none><def_stmt>test_no_metric_is_removed_when_result_set_metric_filter_is_present self<block_start>queries=ds.query.widget(f.Pandas(ds.fields.aggr_number)).filter(f.ResultSet(ds.fields.aggr_number<g>10)).sql<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN SUM(\"number\")>10 THEN 'set(SUM(number)>10)' "<concat>"ELSE 'complement(SUM(number)>10)' END \"$set(SUM(number)>10)\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'ORDER BY 1 '<concat>'LIMIT 200000' str(queries[0]) )<block_end><def_stmt>test_dimension_is_replaced_by_default_when_result_set_filter_is_present self<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc")).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_is_replaced_by_default_in_the_target_dimension_place_when_result_set_filter_is_present self <block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.date).dimension(ds.fields.text).dimension(ds.fields.boolean).filter(f.ResultSet(ds.fields.text<eq>"abc")).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>'"date" "$date",'<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$text\","<concat>'"boolean" "$boolean",'<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'GROUP BY "$date","$text","$boolean" '<concat>'ORDER BY "$date","$text","$boolean" '<concat>'LIMIT 200000' str(queries[0]) )<block_end><def_stmt>test_dimension_with_dimension_modifier_is_replaced_by_default_when_result_set_filter_is_present self <block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.date).dimension(f.Rollup(ds.fields.boolean)).filter(f.ResultSet(ds.fields.boolean<eq><true>)).sql)<line_sep>self.assertEqual(len(queries) 2)<with_stmt>self.subTest('base query is the same as without totals')<block_start>self.assertEqual("SELECT "<concat>'"date" "$date",'<concat>"CASE WHEN \"boolean\"=true THEN 'set(boolean=true)' ELSE 'complement(boolean=true)' END \"$boolean\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'GROUP BY "$date","$boolean" '<concat>'ORDER BY "$date","$boolean" '<concat>'LIMIT 200000' str(queries[0]) )<block_end><with_stmt>self.subTest('totals dimension is replaced with _FIREANT_ROLLUP_VALUE_')<block_start>self.assertEqual("SELECT "<concat>'"date" "$date",'<concat>'\'_FIREANT_ROLLUP_VALUE_\' "$boolean",'<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'GROUP BY "$date" '<concat>'ORDER BY "$date","$boolean" '<concat>'LIMIT 200000' str(queries[1]) )<block_end><block_end><def_stmt>test_dimension_is_inserted_before_conditional_dimension_when_result_set_filter_wont_ignore_dimensions self <block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" will_replace_referenced_dimension=<false>)).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$set(text='abc')\","<concat>'"text" "$text",'<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'GROUP BY "$set(text=\'abc\')","$text" '<concat>'ORDER BY "$set(text=\'abc\')","$text" '<concat>'LIMIT 200000' str(queries[0]) )<block_end><def_stmt>test_dimension_breaks_complement_down_when_result_set_filter_wont_group_complement self <block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" will_group_complement=<false>)).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE \"text\" END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_is_inserted_in_dimensions_even_when_not_selected self<block_start>queries=ds.query.widget(f.Pandas(ds.fields.aggr_number)).filter(f.ResultSet(ds.fields.text<eq>"abc")).sql<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_is_inserted_as_last_dimension_when_not_selected self<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.date).dimension(ds.fields.boolean).filter(f.ResultSet(ds.fields.text<eq>"abc")).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>'"date" "$date",'<concat>'"boolean" "$boolean",'<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'GROUP BY "$date","$boolean","$text" '<concat>'ORDER BY "$date","$boolean","$text" '<concat>'LIMIT 200000' str(queries[0]) )<block_end><def_stmt>test_dimension_uses_set_label_kwarg_and_None_for_complement self<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" set_label="Text is ABC")).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'Text is ABC' ELSE NULL END "<concat>"\"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_breaks_complement_down_even_when_set_label_is_set_when_result_set_filter_wont_group_complement self <block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" set_label="IS ABC" will_group_complement=<false> )).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'IS ABC' ELSE \"text\" END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_breaks_complement_down_even_when_both_labels_are_set_but_wont_group_complement self <block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" set_label="IS ABC" complement_label="OTHERS" will_group_complement=<false> )).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'IS ABC' ELSE \"text\" END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_uses_complement_label_kwarg_and_None_for_set self<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" complement_label="Text is NOT ABC")).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN NULL ELSE 'Text is NOT ABC' END "<concat>"\"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_uses_both_set_and_complement_label_kwargs_when_available self<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.text).filter(f.ResultSet(ds.fields.text<eq>"abc" set_label="Text is ABC" complement_label="Text is NOT ABC" )).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>"CASE WHEN \"text\"='abc' THEN 'Text is ABC' ELSE 'Text is NOT ABC' END "<concat>"\"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>"GROUP BY \"$text\" "<concat>"ORDER BY \"$text\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><def_stmt>test_dimension_is_replaced_when_references_are_present self<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields.date).dimension(ds.fields.boolean).reference(f.WeekOverWeek(ds.fields.date)).filter(f.ResultSet(ds.fields.text<eq>"abc")).sql)<line_sep>self.assertEqual(len(queries) 2)<with_stmt>self.subTest("base query")<block_start>self.assertEqual("SELECT "<concat>'"date" "$date",'<concat>'"boolean" "$boolean",'<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$text\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>'GROUP BY "$date","$boolean","$text" '<concat>'ORDER BY "$date","$boolean","$text" '<concat>'LIMIT 200000' str(queries[0]) )<block_end><with_stmt>self.subTest("ref query")<block_start>self.assertEqual("SELECT "<concat>'TIMESTAMPADD(week,1,"date") "$date",'<concat>'"boolean" "$boolean",'<concat>"CASE WHEN \"text\"='abc' THEN 'set(text=''abc'')' ELSE 'complement(text=''abc'')' END \"$text\","<concat>'SUM("number") "$aggr_number_wow" '<concat>'FROM "test" '<concat>'GROUP BY "$date","$boolean","$text" '<concat>'ORDER BY "$date","$boolean","$text" '<concat>'LIMIT 200000' str(queries[1]) )<block_end><block_end><def_stmt>test_dimension_filter_variations_with_sets self<block_start><for_stmt>field_alias,fltr [('text' ds.fields.text.like("%abc%")) ('text' ds.fields.text.not_like("%abc%")) ('text' ds.fields.text.like("%abc%" "%cde%")) ('text' ds.fields.text.not_like("%abc%" "%cde%")) ('text' ds.fields.text.isin(["abc"])) ('text' ds.fields.text.notin(["abc"])) ('date' ds.fields.date.between('date1' 'date2')) ('number' ds.fields.number.between(5 15)) ('number' ds.fields.number.isin([1 2 3])) ('number' ds.fields.number.notin([1 2 3])) ]<block_start>fltr_sql=fltr.definition.get_sql(quote_char="")<with_stmt>self.subTest(fltr_sql)<block_start>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields[field_alias]).filter(f.ResultSet(fltr set_label='set_A' complement_label='set_B')).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>f"CASE WHEN {fltr} THEN 'set_A' ELSE 'set_B' END \"${field_alias}\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>f"GROUP BY \"${field_alias}\" "<concat>f"ORDER BY \"${field_alias}\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><block_end><block_end><def_stmt>test_deeply_nested_dimension_filter_with_sets self<block_start>field_alias='text'<line_sep>fltr=ds.fields.text.like(fn.Concat(fn.Upper(fn.Trim(fn.Concat('%ab' ds.fields.number))) ds.fields.aggr_number fn.Concat(ds.fields.date.between('date1' 'date2') 'c%') ))<line_sep>queries=(ds.query.widget(f.Pandas(ds.fields.aggr_number)).dimension(ds.fields[field_alias]).filter(f.ResultSet(fltr set_label='set_A' complement_label='set_B')).sql)<line_sep>self.assertEqual(len(queries) 1)<line_sep>self.assertEqual("SELECT "<concat>f"CASE WHEN {fltr} THEN 'set_A' ELSE 'set_B' END \"${field_alias}\","<concat>'SUM("number") "$aggr_number" '<concat>'FROM "test" '<concat>f"GROUP BY \"${field_alias}\" "<concat>f"ORDER BY \"${field_alias}\" "<concat>"LIMIT 200000" str(queries[0]) )<block_end><block_end>
#encoding:utf-8 subreddit='HermitCraft'<line_sep>t_channel='@r_HermitCraft'<def_stmt>send_post submission r2t<block_start><return>r2t.send_simple(submission min_upvotes_limit=100)<block_end>
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """WikiHop: Reading Comprehension with Multiple Hops"""<import_stmt>json<import_stmt>os<import_stmt>datasets<line_sep>_CITATION="""\ @misc{welbl2018constructing, title={Constructing Datasets for Multi-hop Reading Comprehension Across Documents}, author={<NAME> and <NAME> and <NAME>}, year={2018}, eprint={1710.06481}, archivePrefix={arXiv}, primaryClass={cs.CL} } """<line_sep>_DESCRIPTION="""\ WikiHop is open-domain and based on Wikipedia articles; the goal is to recover Wikidata information by hopping through documents. \ The goal is to answer text understanding queries by combining multiple facts that are spread across different documents. """<line_sep>_URL="https://drive.google.com/uc?export=download&id=1ytVZ4AhubFDOEL7o7XrIRIyhU8g9wvKA"<class_stmt>WikiHopConfig(datasets.BuilderConfig)<block_start>"""BuilderConfig for WikiHop."""<def_stmt>__init__ self masked=<false> **kwargs<block_start>"""BuilderConfig for WikiHop. Args: masked: `bool`, original or maksed data. **kwargs: keyword arguments forwarded to super. """<line_sep>super(WikiHopConfig self).__init__(**kwargs)<line_sep>self.masked=masked<block_end><block_end><class_stmt>WikiHop(datasets.GeneratorBasedBuilder)<block_start>"""WikiHop: Reading Comprehension with Multiple Hops"""<line_sep>VERSION=datasets.Version("1.0.0")<line_sep>BUILDER_CONFIGS=[WikiHopConfig(name="original" version=datasets.Version("1.0.0") description="The un-maksed WikiHop dataset" masked=<false> ) WikiHopConfig(name="masked" version=datasets.Version("1.0.0") description="Masked WikiHop dataset" masked=<true>) ]<line_sep>BUILDER_CONFIG_CLASS=WikiHopConfig<line_sep>DEFAULT_CONFIG_NAME="original"<def_stmt>_info self<block_start><return>datasets.DatasetInfo(description=_DESCRIPTION features=datasets.Features({"id":datasets.Value("string") "question":datasets.Value("string") "answer":datasets.Value("string") "candidates":datasets.Sequence(datasets.Value("string")) "supports":datasets.Sequence(datasets.Value("string")) "annotations":datasets.Sequence(datasets.Sequence(datasets.Value("string"))) }) supervised_keys=<none> homepage="http://qangaroo.cs.ucl.ac.uk/" citation=_CITATION )<block_end><def_stmt>_split_generators self dl_manager<block_start>extracted_path=dl_manager.download_and_extract(_URL)<line_sep>wikihop_path=os.path.join(extracted_path "qangaroo_v1.1" "wikihop")<line_sep>train_file="train.json"<if>self.config.name<eq>"original"<else>"train.masked.json"<line_sep>dev_file="dev.json"<if>self.config.name<eq>"original"<else>"dev.masked.json"<line_sep><return>[datasets.SplitGenerator(name=datasets.Split.TRAIN gen_kwargs={"filepath":os.path.join(wikihop_path train_file) "split":"train"} ) datasets.SplitGenerator(name=datasets.Split.VALIDATION gen_kwargs={"filepath":os.path.join(wikihop_path dev_file) "split":"dev"} ) ]<block_end><def_stmt>_generate_examples self filepath split<block_start><with_stmt>open(filepath encoding="utf-8")<as>f<block_start>examples=json.load(f)<for_stmt>i,example enumerate(examples)# there are no annotations for train split, setting it to empty list <block_start><if_stmt>split<eq>"train"<block_start>example["annotations"]=[]<block_end>example["question"]=example.pop("query")<line_sep><yield>example["id"] example<block_end><block_end><block_end><block_end>
<import_from_future_stmt> annotations<import_from_stmt>.util._common _prints<import_from_stmt>.exceptions ParseError# noqa <class_stmt>Tokenizer<block_start><def_stmt>error self *args **kwargs<block_start><raise>ParseError(_prints(*args **kwargs))<block_end>@property<def_stmt>filename self<block_start><raise>NotImplementedError<block_end>@property<def_stmt>ignorecase self<block_start><raise>NotImplementedError<block_end>@property<def_stmt>pos self<block_start><raise>NotImplementedError<block_end><def_stmt>goto self pos<block_start><raise>NotImplementedError<block_end><def_stmt>atend self<block_start><raise>NotImplementedError<block_end><def_stmt>ateol self<block_start><raise>NotImplementedError<block_end>@property<def_stmt>token self<block_start><raise>NotImplementedError<block_end>@property<def_stmt>current self<block_start><return>self.token<block_end><def_stmt>next self<block_start><raise>NotImplementedError<block_end><def_stmt>next_token self<block_start><raise>NotImplementedError<block_end><def_stmt>match self token ignorecase=<false><block_start><raise>NotImplementedError<block_end><def_stmt>matchre self pattern ignorecase=<false><block_start><raise>NotImplementedError<block_end><def_stmt>posline self pos<block_start><raise>NotImplementedError<block_end><def_stmt>line_info self pos=<none><block_start><raise>NotImplementedError<block_end><def_stmt>get_lines self start=<none> end=<none><block_start><raise>NotImplementedError<block_end><def_stmt>lookahead self<block_start><raise>NotImplementedError<block_end><def_stmt>lookahead_pos self<block_start><if_stmt>self.atend()<block_start><return>''<block_end>info=self.line_info()<line_sep><return>'~%d:%d'%(info.line+1 info.col+1)<block_end><block_end>
<import_stmt>torch<import_stmt>json<import_from_stmt>os PathLike<import_from_stmt>typing List Tuple Union Optional<import_from_stmt>allennlp.common.file_utils cached_path<import_from_stmt>allennlp.data Vocabulary<import_from_stmt>allennlp.data.tokenizers.tokenizer Tokenizer<def_stmt>_convert_word_to_ids_tensor word tokenizer vocab namespace all_cases# function does NOT strip special tokens if tokenizer adds them <block_start><if_stmt>all_cases<block_start>words_list=[word.lower() word.title() word.upper()]<block_end><else_stmt><block_start>words_list=[word]<block_end>ids=[]<for_stmt>w words_list# if vocab is None, use tokenizer vocab (only works for Huggingface PreTrainedTokenizer) <block_start><if_stmt>vocab<block_start>tokens=tokenizer.tokenize(w)<line_sep>ids.append(torch.tensor([vocab.get_token_index(t.text namespace)<for>t tokens]))<block_end><else_stmt><block_start>ids.append(torch.tensor(tokenizer.tokenizer(w)["input_ids"]))<block_end><block_end><return>ids<block_end><def_stmt>load_words fname:Union[str PathLike] tokenizer:Tokenizer vocab:Optional[Vocabulary]=<none> namespace:str="tokens" all_cases:bool=<true> <arrow>List[torch.Tensor]<block_start>""" This function loads a list of words from a file, tokenizes each word into subword tokens, and converts the tokens into IDs. # Parameters fname : `Union[str, PathLike]` Name of file containing list of words to load. tokenizer : `Tokenizer` Tokenizer to tokenize words in file. vocab : `Vocabulary`, optional (default=`None`) Vocabulary of tokenizer. If `None`, assumes tokenizer is of type `PreTrainedTokenizer` and uses tokenizer's `vocab` attribute. namespace : `str` Namespace of vocab to use when tokenizing. all_cases : `bool`, optional (default=`True`) Whether to tokenize lower, title, and upper cases of each word. # Returns word_ids : `List[torch.Tensor]` List of tensors containing the IDs of subword tokens for each word in the file. """<line_sep>word_ids=[]<with_stmt>open(cached_path(fname))<as>f<block_start>words=json.load(f)<for_stmt>w words<block_start>word_ids.extend(_convert_word_to_ids_tensor(w tokenizer vocab namespace all_cases))<block_end><block_end><return>word_ids<block_end><def_stmt>load_word_pairs fname:Union[str PathLike] tokenizer:Tokenizer vocab:Optional[Vocabulary]=<none> namespace:str="token" all_cases:bool=<true> <arrow>Tuple[List[torch.Tensor] List[torch.Tensor]]<block_start>""" This function loads a list of pairs of words from a file, tokenizes each word into subword tokens, and converts the tokens into IDs. # Parameters fname : `Union[str, PathLike]` Name of file containing list of pairs of words to load. tokenizer : `Tokenizer` Tokenizer to tokenize words in file. vocab : `Vocabulary`, optional (default=`None`) Vocabulary of tokenizer. If `None`, assumes tokenizer is of type `PreTrainedTokenizer` and uses tokenizer's `vocab` attribute. namespace : `str` Namespace of vocab to use when tokenizing. all_cases : `bool`, optional (default=`True`) Whether to tokenize lower, title, and upper cases of each word. # Returns word_ids : `Tuple[List[torch.Tensor], List[torch.Tensor]]` Pair of lists of tensors containing the IDs of subword tokens for words in the file. """<line_sep>word_ids1=[]<line_sep>word_ids2=[]<with_stmt>open(cached_path(fname))<as>f<block_start>words=json.load(f)<for_stmt>w1,w2 words<block_start>word_ids1.extend(_convert_word_to_ids_tensor(w1 tokenizer vocab namespace all_cases))<line_sep>word_ids2.extend(_convert_word_to_ids_tensor(w2 tokenizer vocab namespace all_cases))<block_end><block_end><return>word_ids1 word_ids2<block_end>
# -*- coding: utf-8 -*- # pylint: disable=E1101 r'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2018, 2019, 2020 <NAME> <<EMAIL>> 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. This module contains implementations of the calculation of pure-component EOS :math:`a \alpha` parameters in a vectorized way. Functions for calculating their temperature derivatives as may be necessary are included as well. For certain alpha functions, a class is available to provide these functions to and class that inherits from it. A mixing rule must be used on the `a_alphas` to get the overall `a_alpha` term. .. contents:: :local: Vectorized Alpha Functions -------------------------- .. autofunction:: thermo.eos_alpha_functions.PR_a_alphas_vectorized .. autofunction:: thermo.eos_alpha_functions.SRK_a_alphas_vectorized .. autofunction:: thermo.eos_alpha_functions.PRSV_a_alphas_vectorized .. autofunction:: thermo.eos_alpha_functions.PRSV2_a_alphas_vectorized .. autofunction:: thermo.eos_alpha_functions.APISRK_a_alphas_vectorized .. autofunction:: thermo.eos_alpha_functions.RK_a_alphas_vectorized Vectorized Alpha Functions With Derivatives ------------------------------------------- .. autofunction:: thermo.eos_alpha_functions.PR_a_alpha_and_derivatives_vectorized .. autofunction:: thermo.eos_alpha_functions.SRK_a_alpha_and_derivatives_vectorized .. autofunction:: thermo.eos_alpha_functions.PRSV_a_alpha_and_derivatives_vectorized .. autofunction:: thermo.eos_alpha_functions.PRSV2_a_alpha_and_derivatives_vectorized .. autofunction:: thermo.eos_alpha_functions.APISRK_a_alpha_and_derivatives_vectorized .. autofunction:: thermo.eos_alpha_functions.RK_a_alpha_and_derivatives_vectorized Class With Alpha Functions -------------------------- The class-based ones van save a little code when implementing a new EOS. If there is not a standalone function available for an alpha function, it has not yet been accelerated in a nice vectorized way. .. autoclass:: thermo.eos_alpha_functions.a_alpha_base :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Almeida_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Androulakis_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Chen_Yang_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Coquelet_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Gasem_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Gibbons_Laughton_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Haghtalab_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Harmens_Knapp_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Heyen_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Mathias_1983_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Mathias_Copeman_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Mathias_Copeman_poly_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Mathias_Copeman_untruncated_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Melhem_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Poly_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Saffari_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Schwartzentruber_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Soave_1972_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Soave_1984_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Soave_1979_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Soave_1993_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Trebble_Bishnoi_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Twu91_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.TwuPR95_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.TwuSRK95_a_alpha :members: :undoc-members: :show-inheritance: .. autoclass:: thermo.eos_alpha_functions.Yu_Lu_a_alpha :members: :undoc-members: :show-inheritance: Pure Alpha Functions -------------------- .. autofunction:: thermo.eos_alpha_functions.Twu91_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Soave_1972_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Soave_1979_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Heyen_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Harmens_Knapp_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Mathias_1983_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Mathias_Copeman_untruncated_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Gibbons_Laughton_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Soave_1984_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Yu_Lu_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Trebble_Bishnoi_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Melhem_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Androulakis_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Schwartzentruber_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Almeida_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Soave_1993_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Gasem_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Coquelet_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Haghtalab_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Saffari_alpha_pure .. autofunction:: thermo.eos_alpha_functions.Chen_Yang_alpha_pure '''<import_from_future_stmt> division print_function<line_sep>__all__=['PR_a_alphas_vectorized' 'PR_a_alpha_and_derivatives_vectorized' 'RK_a_alphas_vectorized' 'RK_a_alpha_and_derivatives_vectorized' 'SRK_a_alphas_vectorized' 'SRK_a_alpha_and_derivatives_vectorized' 'PRSV_a_alphas_vectorized' 'PRSV_a_alpha_and_derivatives_vectorized' 'PRSV2_a_alphas_vectorized' 'PRSV2_a_alpha_and_derivatives_vectorized' 'APISRK_a_alphas_vectorized' 'APISRK_a_alpha_and_derivatives_vectorized' 'a_alpha_base' 'Poly_a_alpha' 'Soave_1972_a_alpha' 'Heyen_a_alpha' 'Harmens_Knapp_a_alpha' 'Mathias_1983_a_alpha' 'Mathias_Copeman_untruncated_a_alpha' 'Mathias_Copeman_poly_a_alpha' 'Gibbons_Laughton_a_alpha' 'Soave_1984_a_alpha' 'Yu_Lu_a_alpha' 'Trebble_Bishnoi_a_alpha' 'Melhem_a_alpha' 'Androulakis_a_alpha' 'Schwartzentruber_a_alpha' 'Almeida_a_alpha' 'Twu91_a_alpha' 'Soave_1993_a_alpha' 'Gasem_a_alpha' 'Coquelet_a_alpha' 'Haghtalab_a_alpha' 'Saffari_a_alpha' 'Chen_Yang_a_alpha' 'TwuSRK95_a_alpha' 'TwuPR95_a_alpha' 'Soave_1979_a_alpha' 'Twu91_alpha_pure' 'Soave_1972_alpha_pure' 'Soave_1979_alpha_pure' 'Heyen_alpha_pure' 'Harmens_Knapp_alpha_pure' 'Mathias_1983_alpha_pure' 'Mathias_Copeman_untruncated_alpha_pure' 'Gibbons_Laughton_alpha_pure' 'Soave_1984_alpha_pure' 'Yu_Lu_alpha_pure' 'Trebble_Bishnoi_alpha_pure' 'Melhem_alpha_pure' 'Androulakis_alpha_pure' 'Schwartzentruber_alpha_pure' 'Almeida_alpha_pure' 'Soave_1993_alpha_pure' 'Gasem_alpha_pure' 'Coquelet_alpha_pure' 'Haghtalab_alpha_pure' 'Saffari_alpha_pure' 'Chen_Yang_alpha_pure' 'Mathias_Copeman_a_alpha']<import_from_stmt>fluids.numerics horner horner_and_der2 numpy<as>np <import_from_stmt>chemicals.utils log exp sqrt copysign<try_stmt><block_start>array=np.array<block_end><except_stmt><block_start><pass><block_end><def_stmt>PR_a_alphas_vectorized T Tcs ais kappas a_alphas=<none><block_start>r'''Calculates the `a_alpha` terms for the Peng-Robinson equation of state given the critical temperatures `Tcs`, constants `ais`, and `kappas`. .. math:: a_i\alpha(T)_i=a_i [1+\kappa_i(1-\sqrt{T_{r,i}})]^2 Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}}`, [Pa*m^6/mol^2] kappas : list[float] `kappa` parameters of Peng-Robinson EOS; formulas vary, but the original form uses :math:`\kappa_i=0.37464+1.54226\omega_i-0.26992\omega^2_i`, [-] a_alphas : list[float], optional Vector for pure component `a_alpha` terms in the cubic EOS to be calculated and stored in, [Pa*m^6/mol^2] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] Notes ----- Examples -------- >>> Tcs = [469.7, 507.4, 540.3] >>> ais = [2.0698956357716662, 2.7018068455659545, 3.3725793885832323] >>> kappas = [0.74192743008, 0.819919992, 0.8800122140799999] >>> PR_a_alphas_vectorized(322.29, Tcs=Tcs, ais=ais, kappas=kappas) [2.6306811679, 3.6761503348, 4.8593286234] '''<line_sep>N=len(Tcs)<line_sep>x0_inv=1.0/sqrt(T)<line_sep>x0=T<times>x0_inv<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>x1=1.0/sqrt(Tcs[i])<line_sep>x2=kappas[i]<times>(x0<times>x1-1.)-1.<line_sep>a_alphas[i]=ais[i]<times>x2<times>x2<block_end><return>a_alphas<block_end><def_stmt>PR_a_alpha_and_derivatives_vectorized T Tcs ais kappas a_alphas=<none> da_alpha_dTs=<none> d2a_alpha_dT2s=<none><block_start>r'''Calculates the `a_alpha` terms and their first two temperature derivatives for the Peng-Robinson equation of state given the critical temperatures `Tcs`, constants `ais`, and `kappas`. .. math:: a_i\alpha(T)_i=a_i[1+\kappa_i(1-\sqrt{T_{r,i}})]^2 .. math:: \frac{d a_i\alpha_i}{dT} = - \frac{a_i \kappa_i}{T^{0.5} {T_c}_i^{0.5}} \left(\kappa_i \left(- \frac{T^{0.5}}{{T_c}_i^{0.5}} + 1\right) + 1\right) .. math:: \frac{d^2 a_i\alpha_i}{dT^2} = 0.5 a_i \kappa_i \left(- \frac{1}{T^{1.5} {T_c}_i^{0.5}} \left(\kappa_i \left(\frac{T^{0.5}}{{T_c}_i^{0.5}} - 1\right) - 1\right) + \frac{\kappa_i}{T {T_c}_i}\right) Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}}` [Pa*m^6/mol^2] kappas : list[float] `kappa` parameters of Peng-Robinson EOS; formulas vary, but the original form uses :math:`\kappa_i=0.37464+1.54226\omega_i-0.26992\omega^2_i`, [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] da_alpha_dTs : list[float] First temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K)] d2a_alpha_dT2s : list[float] Second temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K^2)] Notes ----- Examples -------- >>> Tcs = [469.7, 507.4, 540.3] >>> ais = [2.0698956357716662, 2.7018068455659545, 3.3725793885832323] >>> kappas = [0.74192743008, 0.819919992, 0.8800122140799999] >>> PR_a_alpha_and_derivatives_vectorized(322.29, Tcs=Tcs, ais=ais, kappas=kappas) ([2.63068116797, 3.67615033489, 4.859328623453], [-0.0044497546430, -0.00638993749167, -0.0085372308846], [1.066668360e-05, 1.546687574587e-05, 2.07440632117e-05]) '''<line_sep>N=len(Tcs)<line_sep>x0_inv=1.0/sqrt(T)<line_sep>x0=T<times>x0_inv<line_sep>T_inv=x0_inv<times>x0_inv<line_sep>x0T_inv=x0_inv<times>T_inv<line_sep>x5,x6=0.5<times>T_inv 0.5<times>x0T_inv<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><if_stmt>da_alpha_dTs<is><none><block_start>da_alpha_dTs=[0.0]<times>N<block_end><if_stmt>d2a_alpha_dT2s<is><none><block_start>d2a_alpha_dT2s=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>x1=1.0/sqrt(Tcs[i])<line_sep>x2=kappas[i]<times>(x0<times>x1-1.)-1.<line_sep>x3=ais[i]<times>kappas[i]<line_sep>x4=x1<times>x2<line_sep>a_alphas[i]=ais[i]<times>x2<times>x2<line_sep>da_alpha_dTs[i]=x4<times>x3<times>x0_inv<line_sep>d2a_alpha_dT2s[i]=x3<times>(x5<times>x1<times>x1<times>kappas[i]-x4<times>x6)<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>SRK_a_alphas_vectorized T Tcs ais ms a_alphas=<none><block_start>r'''Calculates the `a_alpha` terms for the SRK equation of state given the critical temperatures `Tcs`, constants `ais`, and `kappas`. .. math:: a_i\alpha(T)_i = \left[1 + m_i\left(1 - \sqrt{\frac{T}{T_{c,i}}} \right)\right]^2 Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}}`, [Pa*m^6/mol^2] ms : list[float] `m` parameters of SRK EOS; formulas vary, but the original form uses :math:`m_i = 0.480 + 1.574\omega_i - 0.176\omega_i^2`, [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] Notes ----- Examples -------- >>> Tcs = [469.7, 507.4, 540.3] >>> ais = [1.9351940385541342, 2.525982668162287, 3.1531036708059315] >>> ms = [0.8610138239999999, 0.9436976, 1.007889024] >>> SRK_a_alphas_vectorized(322.29, Tcs=Tcs, ais=ais, ms=ms) [2.549485814512, 3.586598245260, 4.76614806648] '''<line_sep>sqrtT=sqrt(T)<line_sep>N=len(Tcs)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>x0=ms[i]<times>(1.-sqrtT/sqrt(Tcs[i]))+1.0<line_sep>a_alphas[i]=ais[i]<times>x0<times>x0<block_end><return>a_alphas<block_end><def_stmt>SRK_a_alpha_and_derivatives_vectorized T Tcs ais ms a_alphas=<none> da_alpha_dTs=<none> d2a_alpha_dT2s=<none><block_start>r'''Calculates the `a_alpha` terms and their first and second temperature derivatives for the SRK equation of state given the critical temperatures `Tcs`, constants `ais`, and `kappas`. .. math:: a_i\alpha(T)_i = \left[1 + m_i\left(1 - \sqrt{\frac{T}{T_{c,i}}} \right)\right]^2 .. math:: \frac{d a_i\alpha_i}{dT} = \frac{a_i m_i}{T} \sqrt{\frac{T}{T_{c,i}}} \left(m_i \left(\sqrt{\frac{T}{T{c,i}}} - 1\right) - 1\right) .. math:: \frac{d^2 a_i\alpha_i}{dT^2} = \frac{a_i m_i \sqrt{\frac{T}{T_{c,i}}}} {2 T^{2}} \left(m_i + 1\right) Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}}`, [Pa*m^6/mol^2] ms : list[float] `m` parameters of SRK EOS; formulas vary, but the original form uses :math:`m_i = 0.480 + 1.574\omega_i - 0.176\omega_i^2`, [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] da_alpha_dTs : list[float] First temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K)] d2a_alpha_dT2s : list[float] Second temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K^2)] Notes ----- Examples -------- >>> Tcs = [469.7, 507.4, 540.3] >>> ais = [1.9351940385541342, 2.525982668162287, 3.1531036708059315] >>> ms = [0.8610138239999999, 0.9436976, 1.007889024] >>> SRK_a_alpha_and_derivatives_vectorized(322.29, Tcs=Tcs, ais=ais, ms=ms) ([2.549485814512, 3.586598245260, 4.76614806648], [-0.004915469296196, -0.00702410108423, -0.00936320876945], [1.236441916324e-05, 1.77752796719e-05, 2.37231823137e-05]) '''<line_sep>N=len(Tcs)<line_sep>sqrtnT=1.0/sqrt(T)<line_sep>sqrtT=T<times>sqrtnT<line_sep>T_inv=sqrtnT<times>sqrtnT<line_sep>x10=0.5<times>T_inv<times>T_inv<line_sep>nT_inv=-T_inv<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><if_stmt>da_alpha_dTs<is><none><block_start>da_alpha_dTs=[0.0]<times>N<block_end><if_stmt>d2a_alpha_dT2s<is><none><block_start>d2a_alpha_dT2s=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>x1=sqrtT/sqrt(Tcs[i])<line_sep>x2=ais[i]<times>ms[i]<times>x1<line_sep>x3=ms[i]<times>(1.0-x1)+1.<line_sep>a_alphas[i]=ais[i]<times>x3<times>x3<line_sep>da_alpha_dTs[i]=x2<times>nT_inv<times>x3<line_sep>d2a_alpha_dT2s[i]=x2<times>x10<times>(ms[i]+1.)<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>RK_a_alphas_vectorized T Tcs ais a_alphas=<none><block_start>r'''Calculates the `a_alpha` terms for the RK equation of state given the critical temperatures `Tcs`, and `a` parameters `ais`. .. math:: a_i\alpha_i = \frac{a_i}{\sqrt{\frac{T}{T_{c,i}}}} Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}}`, [Pa*m^6/mol^2] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] Notes ----- Examples -------- >>> Tcs = [469.7, 507.4, 540.3] >>> ais = [1.9351940385541342, 2.525982668162287, 3.1531036708059315] >>> RK_a_alphas_vectorized(322.29, Tcs=Tcs, ais=ais) [2.3362073307, 3.16943743055, 4.0825575798] '''<line_sep>N=len(ais)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end>T_root_inv=1.0/sqrt(T)<for_stmt>i range(N)<block_start>a_alphas[i]=ais[i]<times>sqrt(Tcs[i])<times>T_root_inv<block_end><return>a_alphas<block_end><def_stmt>RK_a_alpha_and_derivatives_vectorized T Tcs ais a_alphas=<none> da_alpha_dTs=<none> d2a_alpha_dT2s=<none><block_start>r'''Calculates the `a_alpha` terms and their first and second temperature derivatives for the RK equation of state given the critical temperatures `Tcs`, and `a` parameters `ais`. .. math:: a_i\alpha_i = \frac{a_i}{\sqrt{\frac{T}{T_{c,i}}}} .. math:: \frac{d a_i\alpha_i}{dT} = - \frac{a_i}{2 T\sqrt{\frac{T}{T_{c,i}}}} .. math:: \frac{d^2 a_i\alpha_i}{dT^2} = \frac{3 a_i}{4 T^{2}\sqrt{\frac{T}{T_{c,i}}}} Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}}`, [Pa*m^6/mol^2] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] da_alpha_dTs : list[float] First temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K)] d2a_alpha_dT2s : list[float] Second temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K^2)] Notes ----- Examples -------- >>> Tcs = [469.7, 507.4, 540.3] >>> ais = [1.9351940385541342, 2.525982668162287, 3.1531036708059315] >>> RK_a_alpha_and_derivatives_vectorized(322.29, Tcs=Tcs, ais=ais) ([2.3362073307, 3.16943743055, 4.08255757984], [-0.00362438693525, -0.0049170582868, -0.00633367088622], [1.6868597855e-05, 2.28849403652e-05, 2.94781294155e-05]) '''<line_sep>N=len(ais)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><if_stmt>da_alpha_dTs<is><none><block_start>da_alpha_dTs=[0.0]<times>N<block_end><if_stmt>d2a_alpha_dT2s<is><none><block_start>d2a_alpha_dT2s=[0.0]<times>N<block_end>T_root_inv=1.0/sqrt(T)<line_sep>T_inv=T_root_inv<times>T_root_inv<line_sep>T_15_inv=T_inv<times>T_root_inv<line_sep>T_25_inv=T_inv<times>T_15_inv<line_sep>x0=-0.5<times>T_15_inv<line_sep>x1=0.75<times>T_25_inv<for_stmt>i range(N)<block_start>Tc_05=sqrt(Tcs[i])<line_sep>aiTc_05=ais[i]<times>Tc_05<line_sep>a_alphas[i]=aiTc_05<times>T_root_inv<line_sep>da_alpha_dTs[i]=aiTc_05<times>x0<line_sep>d2a_alpha_dT2s[i]=aiTc_05<times>x1<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>PRSV_a_alphas_vectorized T Tcs ais kappa0s kappa1s a_alphas=<none><block_start>r'''Calculates the `a_alpha` terms for the Peng-Robinson-Stryjek-Vera equation of state given the critical temperatures `Tcs`, constants `ais`, PRSV parameters `kappa0s` and `kappa1s`. .. math:: a_i\alpha_i = a_i \left(\left(\kappa_{0} + \kappa_{1} \left(\sqrt{\frac{ T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right) \right) \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) + 1\right)^{2} Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}}`, [Pa*m^6/mol^2] kappa0s : list[float] `kappa0` parameters of PRSV EOS; the original form uses :math:`\kappa_{0,i} = 0.378893 + 1.4897153\omega_i - 0.17131848\omega_i^2 + 0.0196554\omega_i^3`, [-] kappa1s : list[float] Fit parameters, can be set to 0 if unknown [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] Notes ----- Examples -------- >>> Tcs = [507.6] >>> ais = [2.6923169620277805] >>> kappa0s = [0.8074380841890093] >>> kappa1s = [0.05104] >>> PRSV_a_alphas_vectorized(299.0, Tcs=Tcs, ais=ais, kappa0s=kappa0s, kappa1s=kappa1s) [3.81298569831] '''<line_sep>sqrtT=sqrt(T)<line_sep>N=len(Tcs)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>Tc_inv_root=1.0/sqrt(Tcs[i])<line_sep>Tc_inv=Tc_inv_root<times>Tc_inv_root<line_sep>x0=Tc_inv_root<times>sqrtT<line_sep>x2=(1.0+(kappa0s[i]+kappa1s[i]<times>(x0+1.0)<times>(0.7-T<times>Tc_inv))<times>(1.0-x0))<line_sep>a_alphas[i]=ais[i]<times>x2<times>x2<block_end><return>a_alphas<block_end><def_stmt>PRSV_a_alpha_and_derivatives_vectorized T Tcs ais kappa0s kappa1s a_alphas=<none> da_alpha_dTs=<none> d2a_alpha_dT2s=<none><block_start>r'''Calculates the `a_alpha` terms and their first and second derivative for the Peng-Robinson-Stryjek-Vera equation of state given the critical temperatures `Tcs`, constants `ais`, PRSV parameters `kappa0s` and `kappa1s`. .. math:: a_i\alpha_i = a_i \left(\left(\kappa_{0} + \kappa_{1} \left(\sqrt{\frac{ T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right) \right) \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) + 1\right)^{2} .. math:: \frac{d a_i\alpha_i}{dT} =a_{i} \left(\left(1 - \sqrt{\frac{T}{T_{c,i}}} \right) \left(\kappa_{0,i} + \kappa_{1,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right)\right) + 1\right) \left(2 \left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left( - \frac{\kappa_{1,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right)}{T_{c,i}} + \frac{\kappa_{1,i} \sqrt{\frac{T}{T_{c,i}}} \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right)}{2 T}\right) - \frac{\sqrt{\frac{T}{T_{c,i}}} \left(\kappa_{0,i} + \kappa_{1,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right)\right)}{T} \right) .. math:: \frac{d^2 a_i\alpha_i}{dT^2} = \frac{a_{i} \left(\left(\kappa_{1,i} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\frac{20 \left(\sqrt{ \frac{T}{T_{c,i}}} + 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T}{T_{c,i}}} \left(\frac{10 T}{T_{c,i}} - 7\right)}{T}\right) - \frac{\sqrt{\frac{T} {T_{c,i}}} \left(10 \kappa_{0,i} - \kappa_{1,i} \left(\sqrt{\frac{T} {T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right)\right)}{T} \right)^{2} - \frac{\sqrt{\frac{T}{T_{c,i}}} \left(\left(10 \kappa_{0,i} - \kappa_{1,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right)\right) \left(\sqrt{\frac{T} {T_{c,i}}} - 1\right) - 10\right) \left(\kappa_{1,i} \left(\frac{40} {T_{c,i}} - \frac{\frac{10 T}{T_{c,i}} - 7}{T}\right) \left(\sqrt{ \frac{T}{T_{c,i}}} - 1\right) + 2 \kappa_{1,i} \left(\frac{20 \left( \sqrt{\frac{T}{T_{c,i}}} + 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T} {T_{c,i}}} \left(\frac{10 T}{T_{c,i}} - 7\right)}{T}\right) + \frac{10 \kappa_{0,i} - \kappa_{1,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right)}{T}\right)}{T}\right)}{200} Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}}`, [Pa*m^6/mol^2] kappa0s : list[float] `kappa0` parameters of PRSV EOS; the original form uses :math:`\kappa_{0,i} = 0.378893 + 1.4897153\omega_i - 0.17131848\omega_i^2 + 0.0196554\omega_i^3`, [-] kappa1s : list[float] Fit parameters, can be set to 0 if unknown [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] da_alpha_dTs : list[float] First temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K)] d2a_alpha_dT2s : list[float] Second temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K^2)] Notes ----- Examples -------- >>> Tcs = [507.6] >>> ais = [2.6923169620277805] >>> kappa0s = [0.8074380841890093] >>> kappa1s = [0.05104] >>> PRSV_a_alpha_and_derivatives_vectorized(299.0, Tcs=Tcs, ais=ais, kappa0s=kappa0s, kappa1s=kappa1s) ([3.8129856983], [-0.0069769034748], [2.00265608110e-05]) '''<line_sep>r''' Formula derived with: from sympy import * Tc = symbols('T_{c\,i}') T, a, kappa0, kappa1 = symbols('T, a_i, \kappa_{0\,i}, \kappa_{1\,i}') kappa = kappa0 + kappa1*(1 + sqrt(T/Tc))*(Rational(7, 10)-T/Tc) a_alpha = a*(1 + kappa*(1-sqrt(T/Tc)))**2 diff(a_alpha, T, 2) '''<line_sep>sqrtT=sqrt(T)<line_sep>T_inv=1.0/T<line_sep>N=len(Tcs)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><if_stmt>da_alpha_dTs<is><none><block_start>da_alpha_dTs=[0.0]<times>N<block_end><if_stmt>d2a_alpha_dT2s<is><none><block_start>d2a_alpha_dT2s=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>Tc_inv_root=1.0/sqrt(Tcs[i])<line_sep>Tc_inv=Tc_inv_root<times>Tc_inv_root<line_sep>x1=T<times>Tc_inv<line_sep>x2=sqrtT<times>Tc_inv_root<line_sep>x3=x2-1.<line_sep>x4=10.<times>x1-7.<line_sep>x5=x2+1.<line_sep>x6=10.<times>kappa0s[i]-kappa1s[i]<times>x4<times>x5<line_sep>x7=x3<times>x6<line_sep>x8=x7<times>0.1-1.<line_sep>x10=x6<times>T_inv<line_sep>x11=kappa1s[i]<times>x3<line_sep>x12=x4<times>T_inv<line_sep>x13=20.<times>Tc_inv<times>x5+x12<times>x2<line_sep>x14=-x10<times>x2+x11<times>x13<line_sep>a_alpha=ais[i]<times>x8<times>x8<line_sep>da_alpha_dT=-ais[i]<times>x14<times>x8<times>0.1<line_sep>d2a_alpha_dT2=ais[i]<times>0.005<times>(x14<times>x14-x2<times>T_inv<times>(x7-10.)<times>(2.<times>kappa1s[i]<times>x13+x10+x11<times>(40.<times>Tc_inv-x12)))<line_sep>a_alphas[i]=a_alpha<line_sep>da_alpha_dTs[i]=da_alpha_dT<line_sep>d2a_alpha_dT2s[i]=d2a_alpha_dT2<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>PRSV2_a_alphas_vectorized T Tcs ais kappa0s kappa1s kappa2s kappa3s a_alphas=<none><block_start>r'''Calculates the `a_alpha` terms for the Peng-Robinson-Stryjek-Vera 2 equation of state given the critical temperatures `Tcs`, constants `ais`, PRSV2 parameters `kappa0s, `kappa1s`, `kappa2s`, and `kappa3s`. .. math:: a_i\alpha_i = a_{i} \left(\left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(\kappa_{0,i} + \left(\kappa_{1,i} + \kappa_{2,i} \left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(- \frac{T}{T_{c,i}} + \kappa_{3,i}\right)\right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right)\right) + 1\right)^{2} Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}}`, [Pa*m^6/mol^2] kappa0s : list[float] `kappa0` parameters of PRSV EOS; the original form uses :math:`\kappa_{0,i} = 0.378893 + 1.4897153\omega_i - 0.17131848\omega_i^2 + 0.0196554\omega_i^3`, [-] kappa1s : list[float] Fit parameters, can be set to 0 if unknown [-] kappa2s : list[float] Fit parameters, can be set to 0 if unknown [-] kappa3s : list[float] Fit parameters, can be set to 0 if unknown [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] Notes ----- Examples -------- >>> PRSV2_a_alphas_vectorized(400.0, Tcs=[507.6], ais=[2.6923169620277805], kappa0s=[0.8074380841890093], kappa1s=[0.05104], kappa2s=[0.8634], kappa3s=[0.460]) [3.2005700986984] '''<line_sep>sqrtT=sqrt(T)<line_sep>N=len(Tcs)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>Tc_inv_root=1.0/sqrt(Tcs[i])<line_sep>Tr_sqrt=sqrtT<times>Tc_inv_root<line_sep>Tr=T<times>Tc_inv_root<times>Tc_inv_root<line_sep>kappa=(kappa0s[i]+((kappa1s[i]+kappa2s[i]<times>(kappa3s[i]-Tr)<times>(1.0-Tr_sqrt))<times>(1.0+Tr_sqrt)<times>(0.7-Tr)))<line_sep>x0=(1.0+kappa<times>(1.0-Tr_sqrt))<line_sep>a_alphas[i]=ais[i]<times>x0<times>x0<block_end><return>a_alphas<block_end><def_stmt>PRSV2_a_alpha_and_derivatives_vectorized T Tcs ais kappa0s kappa1s kappa2s kappa3s a_alphas=<none> da_alpha_dTs=<none> d2a_alpha_dT2s=<none><block_start>r'''Calculates the `a_alpha` terms and their first and second derivatives for the Peng-Robinson-Stryjek-Vera 2 equation of state given the critical temperatures `Tcs`, constants `ais`, PRSV2 parameters `kappa0s, `kappa1s`, `kappa2s`, and `kappa3s`. .. math:: a_i\alpha_i = a_{i} \left(\left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(\kappa_{0,i} + \left(\kappa_{1,i} + \kappa_{2,i} \left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(- \frac{T}{T_{c,i}} + \kappa_{3,i}\right)\right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right)\right) + 1\right)^{2} .. math:: \frac{d a_i\alpha_i}{dT} = a_{i} \left(\left(1 - \sqrt{\frac{T}{T_{c,i} }}\right) \left(\kappa_{0,i} + \left(\kappa_{1,i} + \kappa_{2,i} \left( 1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(- \frac{T}{T_{c,i}} + \kappa_{3,i}\right)\right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right)\right) + 1\right) \left(2 \left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(\left(\sqrt{ \frac{T}{T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10} \right) \left(- \frac{\kappa_{2,i} \left(1 - \sqrt{\frac{T}{T_{c,i}}} \right)}{T_{c,i}} - \frac{\kappa_{2,i} \sqrt{\frac{T}{T_{c,i}}} \left( - \frac{T}{T_{c,i}} + \kappa_{3,i}\right)}{2 T}\right) - \frac{\left( \kappa_{1,i} + \kappa_{2,i} \left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left(- \frac{T}{T_{c,i}} + \kappa_{3,i}\right)\right) \left(\sqrt{ \frac{T}{T_{c,i}}} + 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T}{T_{c,i} }} \left(\kappa_{1,i} + \kappa_{2,i} \left(1 - \sqrt{\frac{T}{T_{c,i}}} \right) \left(- \frac{T}{T_{c,i}} + \kappa_{3,i}\right)\right) \left( - \frac{T}{T_{c,i}} + \frac{7}{10}\right)}{2 T}\right) - \frac{\sqrt{ \frac{T}{T_{c,i}}} \left(\kappa_{0,i} + \left(\kappa_{1,i} + \kappa_{2,i} \left(1 - \sqrt{\frac{T}{T_{c,i}}}\right) \left( - \frac{T}{T_{c,i}} + \kappa_{3,i}\right)\right) \left(\sqrt{\frac{T} {T_{c,i}}} + 1\right) \left(- \frac{T}{T_{c,i}} + \frac{7}{10}\right) \right)}{T}\right) .. math:: \frac{d^2 a_i\alpha_i}{dT^2} = - \frac{a_{i} \left(\left(\left(10 \kappa_{0,i} - \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T} {T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right) \right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T} {T_{c,i}} - 7\right)\right) \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) - 10\right) \left(\left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left( \frac{40 \kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left( \frac{2 \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right)}{T_{c,i}} + \frac{ \sqrt{\frac{T}{T_{c,i}}} \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)} {T}\right)}{T_{c,i}} + \frac{\kappa_{2,i} \sqrt{\frac{T}{T_{c,i}}} \left(\frac{4}{T_{c,i}} - \frac{\frac{T}{T_{c,i}} - \kappa_{3,i}}{T} \right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T} {T_{c,i}} - 7\right)}{T} + \frac{2 \kappa_{2,i} \sqrt{\frac{T}{T_{c,i}}} \left(\frac{10 T}{T_{c,i}} - 7\right) \left(\frac{2 \left(\sqrt{\frac {T}{T_{c,i}}} - 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T}{T_{c,i}}} \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)}{T}\right)}{T} + \frac{40 \sqrt{\frac{T}{T_{c,i}}} \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{ \frac{T}{T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i} \right)\right)}{T T_{c,i}} - \frac{\sqrt{\frac{T}{T_{c,i}}} \left( \kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)\right) \left(\frac{10 T} {T_{c,i}} - 7\right)}{T^{2}}\right) + \frac{2 \sqrt{\frac{T}{T_{c,i}}} \left(\kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right) \left(\frac{2 \left(\sqrt{ \frac{T}{T_{c,i}}} - 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T} {T_{c,i}}} \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)}{T}\right) + \frac{20 \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T} {T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right) \right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T}{T_{c,i}}} \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)\right) \left(\frac{10 T}{T_{c,i}} - 7\right)} {T}\right)}{T} + \frac{\sqrt{\frac{T}{T_{c,i}}} \left(10 \kappa_{0,i} - \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)\right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right)\right)}{T^{2}}\right) - \left(\left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right) \left(\frac{2 \left(\sqrt{ \frac{T}{T_{c,i}}} - 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T}{T_{c,i}}} \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)}{T}\right) + \frac{20 \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right)\right) \left( \sqrt{\frac{T}{T_{c,i}}} + 1\right)}{T_{c,i}} + \frac{\sqrt{\frac{T} {T_{c,i}}} \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T} {T_{c,i}}} - 1\right) \left(\frac{T}{T_{c,i}} - \kappa_{3,i}\right) \right) \left(\frac{10 T}{T_{c,i}} - 7\right)}{T}\right) - \frac{ \sqrt{\frac{T}{T_{c,i}}} \left(10 \kappa_{0,i} - \left(\kappa_{1,i} + \kappa_{2,i} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) \left(\frac{T} {T_{c,i}} - \kappa_{3,i}\right)\right) \left(\sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{10 T}{T_{c,i}} - 7\right)\right)}{T}\right)^{2} \right)}{200} Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=0.45724\frac{R^2T_{c,i}^2}{P_{c,i}}`, [Pa*m^6/mol^2] kappa0s : list[float] `kappa0` parameters of PRSV EOS; the original form uses :math:`\kappa_{0,i} = 0.378893 + 1.4897153\omega_i - 0.17131848\omega_i^2 + 0.0196554\omega_i^3`, [-] kappa1s : list[float] Fit parameters, can be set to 0 if unknown [-] kappa2s : list[float] Fit parameters, can be set to 0 if unknown [-] kappa3s : list[float] Fit parameters, can be set to 0 if unknown [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] da_alpha_dTs : list[float] First temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K)] d2a_alpha_dT2s : list[float] Second temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K^2)] Notes ----- Examples -------- >>> PRSV2_a_alpha_and_derivatives_vectorized(400.0, Tcs=[507.6], ais=[2.6923169620277805], kappa0s=[0.8074380841890093], kappa1s=[0.05104], kappa2s=[0.8634], kappa3s=[0.460]) ([3.2005700986], [-0.005301195971], [1.11181477576e-05]) '''<line_sep>sqrtT=sqrt(T)<line_sep>T_inv=1.0/T<line_sep>N=len(Tcs)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><if_stmt>da_alpha_dTs<is><none><block_start>da_alpha_dTs=[0.0]<times>N<block_end><if_stmt>d2a_alpha_dT2s<is><none><block_start>d2a_alpha_dT2s=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>Tc_inv_root=1.0/sqrt(Tcs[i])<line_sep>Tc_inv=Tc_inv_root<times>Tc_inv_root<line_sep>x1=T<times>Tc_inv<line_sep>x2=sqrtT<times>Tc_inv_root<line_sep>x3=x2-1.<line_sep>x4=x2+1.<line_sep>x5=10.<times>x1-7.<line_sep>x6=-kappa3s[i]+x1<line_sep>x7=kappa1s[i]+kappa2s[i]<times>x3<times>x6<line_sep>x8=x5<times>x7<line_sep>x9=10.<times>kappa0s[i]-x4<times>x8<line_sep>x10=x3<times>x9<line_sep>x11=x10<times>0.1-1.0<line_sep>x13=x2<times>T_inv<line_sep>x14=x7<times>Tc_inv<line_sep>x15=kappa2s[i]<times>x4<times>x5<line_sep>x16=2.<times>(-x2+1.)<times>Tc_inv+x13<times>(kappa3s[i]-x1)<line_sep>x17=-x13<times>x8-x14<times>(20.<times>x2+20.)+x15<times>x16<line_sep>x18=x13<times>x9+x17<times>x3<line_sep>x19=x2<times>T_inv<times>T_inv<line_sep>x20=2.<times>x2<times>T_inv<line_sep>a_alpha=ais[i]<times>x11<times>x11<line_sep>da_alpha_dT=ais[i]<times>x11<times>x18<times>0.1<line_sep>d2a_alpha_dT2=ais[i]<times>(x18<times>x18+(x10-10.)<times>(x17<times>x20-x19<times>x9+x3<times>(40.<times>kappa2s[i]<times>Tc_inv<times>x16<times>x4+kappa2s[i]<times>x16<times>x20<times>x5-40.<times>T_inv<times>x14<times>x2-x15<times>T_inv<times>x2<times>(4.0<times>Tc_inv-x6<times>T_inv)+x19<times>x8)))<times>0.005<line_sep>a_alphas[i]=a_alpha<line_sep>da_alpha_dTs[i]=da_alpha_dT<line_sep>d2a_alpha_dT2s[i]=d2a_alpha_dT2<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>APISRK_a_alphas_vectorized T Tcs ais S1s S2s a_alphas=<none><block_start>r'''Calculates the `a_alpha` terms for the API SRK equation of state given the critical temperatures `Tcs`, constants `ais`, and API parameters `S1s` and `S2s`. .. math:: a_i\alpha(T)_i = a_i \left[1 + S_{1,i}\left(1-\sqrt{T_{r,i}}\right) + S_{2,i} \frac{1- \sqrt{T_{r,i}}}{\sqrt{T_{r,i}}}\right]^2 Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}}`, [Pa*m^6/mol^2] S1s : list[float] `S1` parameters of API SRK EOS; regressed or estimated with :math:`S_{1,i} = 0.48508 + 1.55171\omega_i - 0.15613\omega_i^2`, [-] S2s : list[float] `S2` parameters of API SRK EOS; regressed or set to zero, [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] Notes ----- Examples -------- >>> APISRK_a_alphas_vectorized(T=430.0, Tcs=[514.0], ais=[1.2721974560809934], S1s=[1.678665], S2s=[-0.216396]) [1.60465652994097] '''<line_sep>N=len(Tcs)<line_sep>sqrtT=sqrt(T)<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>rtTr=1.0/sqrt(Tcs[i])<line_sep>x0=(-rtTr<times>sqrtT+1.)<line_sep>x1=1.0/(rtTr<times>sqrtT)<line_sep>x2=(S1s[i]<times>x0+S2s[i]<times>(x0)<times>x1+1.0)<line_sep>a_alphas[i]=ais[i]<times>x2<times>x2<block_end><return>a_alphas<block_end><def_stmt>APISRK_a_alpha_and_derivatives_vectorized T Tcs ais S1s S2s a_alphas=<none> da_alpha_dTs=<none> d2a_alpha_dT2s=<none><block_start>r'''Calculates the `a_alpha` terms and their first two temperature derivatives for the API SRK equation of state given the critical temperatures `Tcs`, constants `ais`, and API parameters `S1s` and `S2s`. .. math:: a_i\alpha(T)_i = a_i \left[1 + S_{1,i}\left(1-\sqrt{T_{r,i}}\right) + S_{2,i} \frac{1- \sqrt{T_{r,i}}}{\sqrt{T_{r,i}}}\right]^2 .. math:: \frac{d a_i\alpha_i}{dT} = a_i\frac{T_{c,i}}{T^{2}} \left(- S_{2,i} \left(\sqrt{ \frac{T}{T_{c,i}}} - 1\right) + \sqrt{\frac{T}{T_{c,i}}} \left(S_{1,i} \sqrt{ \frac{T}{T_{c,i}}} + S_{2,i}\right)\right) \left(S_{2,i} \left(\sqrt{\frac{ T}{T_{c,i}}} - 1\right) + \sqrt{\frac{T}{T_{c,i}}} \left(S_{1,i} \left(\sqrt{ \frac{T}{T_{c,i}}} - 1\right) - 1\right)\right) .. math:: \frac{d^2 a_i\alpha_i}{dT^2} = a_i\frac{1}{2 T^{3}} \left(S_{1,i}^{2} T \sqrt{\frac{T}{T_{c,i}}} - S_{1,i} S_{2,i} T \sqrt{\frac{T}{T_{c,i}}} + 3 S_{1,i} S_{2,i} T_{c,i} \sqrt{\frac{T}{T_{c,i}}} + S_{1,i} T \sqrt{\frac{T}{T_{c,i}}} - 3 S_{2,i}^{2} T_{c,i} \sqrt{\frac{T}{T_{c,i}}} + 4 S_{2,i}^{2} T_{c,i} + 3 S_{2,i} T_{c,i} \sqrt{\frac{T}{T_{c,i}}}\right) Parameters ---------- T : float Temperature, [K] Tcs : list[float] Critical temperatures of components, [K] ais : list[float] `a` parameters of cubic EOS, :math:`a_i=\frac{0.42748\cdot R^2(T_{c,i})^{2}}{P_{c,i}}`, [Pa*m^6/mol^2] S1s : list[float] `S1` parameters of API SRK EOS; regressed or estimated with :math:`S_{1,i} = 0.48508 + 1.55171\omega_i - 0.15613\omega_i^2`, [-] S2s : list[float] `S2` parameters of API SRK EOS; regressed or set to zero, [-] Returns ------- a_alphas : list[float] Pure component `a_alpha` terms in the cubic EOS, [Pa*m^6/mol^2] da_alpha_dTs : list[float] First temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K)] d2a_alpha_dT2s : list[float] Second temperature derivative of pure component `a_alpha`, [Pa*m^6/(mol^2*K^2)] Notes ----- Examples -------- >>> APISRK_a_alpha_and_derivatives_vectorized(T=430.0, Tcs=[514.0], ais=[1.2721974560809934], S1s=[1.678665], S2s=[-0.216396]) ([1.60465652994], [-0.0043155855337], [8.9931026263e-06]) '''<line_sep>N=len(Tcs)<line_sep>T_inv=1.0/T<line_sep>c0=T_inv<times>T_inv<times>0.5<if_stmt>a_alphas<is><none><block_start>a_alphas=[0.0]<times>N<block_end><if_stmt>da_alpha_dTs<is><none><block_start>da_alpha_dTs=[0.0]<times>N<block_end><if_stmt>d2a_alpha_dT2s<is><none><block_start>d2a_alpha_dT2s=[0.0]<times>N<block_end><for_stmt>i range(N)<block_start>x0=sqrt(T/Tcs[i])<line_sep>x1=x0-1.<line_sep>x2=x1/x0<line_sep>x3=S2s[i]<times>x2<line_sep>x4=S1s[i]<times>x1+x3-1.<line_sep>x5=S1s[i]<times>x0<line_sep>x6=S2s[i]-x3+x5<line_sep>x7=3.<times>S2s[i]<line_sep>a_alphas[i]=ais[i]<times>x4<times>x4<line_sep>da_alpha_dTs[i]=ais[i]<times>x4<times>x6<times>T_inv<line_sep>d2a_alpha_dT2s[i]=ais[i]<times>(-x4<times>(-x2<times>x7+x5+x7)+x6<times>x6)<times>c0<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>TWU_a_alpha_common T Tc omega a full=<true> method='PR'<block_start>r'''Function to calculate `a_alpha` and optionally its first and second derivatives for the TWUPR or TWUSRK EOS. Returns 'a_alpha', and optionally 'da_alpha_dT' and 'd2a_alpha_dT2'. Used by `TWUPR` and `TWUSRK`; has little purpose on its own. See either class for the correct reference, and examples of using the EOS. Parameters ---------- T : float Temperature, [K] Tc : float Critical temperature, [K] omega : float Acentric factor, [-] a : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] full : float Whether or not to return its first and second derivatives method : str Either 'PR' or 'SRK' Notes ----- The derivatives are somewhat long and are not described here for brevity; they are obtainable from the following SymPy expression. >>> from sympy import * >>> T, Tc, omega, N1, N0, M1, M0, L1, L0 = symbols('T, Tc, omega, N1, N0, M1, M0, L1, L0') >>> Tr = T/Tc >>> alpha0 = Tr**(N0*(M0-1))*exp(L0*(1-Tr**(N0*M0))) >>> alpha1 = Tr**(N1*(M1-1))*exp(L1*(1-Tr**(N1*M1))) >>> alpha = alpha0 + omega*(alpha1-alpha0) >>> # diff(alpha, T) >>> # diff(alpha, T, T) '''<line_sep># e-10 works min_a_alpha=1e-3# There are a LOT of formulas, and they do not like having zeros Tr=T/Tc<if_stmt>Tr<l>5e-3# not enough: Tr from (x) 0 to 2e-4 to (y) 1e-4 2e-4 # trying: Tr from (x) 0 to 1e-3 to (y) 5e-4 1e-3 # Tr = 1e-3 + (Tr - 0.0)*(1e-3 - 5e-4)/1e-3 # Tr = 5e-4 + (Tr - 0.0)*(5e-4)/1e-3 <block_start>Tr=4e-3+(Tr-0.0)<times>(1e-3)/5e-3<line_sep>T=Tc<times>Tr<block_end><if_stmt>method<eq>'PR'<block_start><if_stmt>Tr<l>1.0<block_start>L0,M0,N0=0.125283 0.911807 1.948150<line_sep>L1,M1,N1=0.511614 0.784054 2.812520<block_end><else_stmt><block_start>L0,M0,N0=0.401219 4.963070 -0.2<line_sep>L1,M1,N1=0.024955 1.248089 -8.<block_end><block_end><elif_stmt>method<eq>'SRK'<block_start><if_stmt>Tr<l>1.0<block_start>L0,M0,N0=0.141599 0.919422 2.496441<line_sep>L1,M1,N1=0.500315 0.799457 3.291790<block_end><else_stmt><block_start>L0,M0,N0=0.441411 6.500018 -0.20<line_sep>L1,M1,N1=0.032580 1.289098 -8.0<block_end><block_end><else_stmt><block_start><raise>ValueError('Only `PR` and `SRK` are accepted as method')<block_end><if_stmt><not>full<block_start>alpha0=Tr<power>(N0<times>(M0-1.))<times>exp(L0<times>(1.-Tr<power>(N0<times>M0)))<line_sep>alpha1=Tr<power>(N1<times>(M1-1.))<times>exp(L1<times>(1.-Tr<power>(N1<times>M1)))<line_sep>alpha=alpha0+omega<times>(alpha1-alpha0)<line_sep>a_alpha=a<times>alpha<if_stmt>a_alpha<l>min_a_alpha<block_start>a_alpha=min_a_alpha<block_end><return>a_alpha<block_end><else_stmt><block_start>x0=Tr<line_sep>x1=M0-1<line_sep>x2=N0<times>x1<line_sep>x3=x0<power>x2<line_sep>x4=M0<times>N0<line_sep>x5=x0<power>x4<line_sep>x6=exp(-L0<times>(x5-1.))<line_sep>x7=x3<times>x6<line_sep>x8=M1-1.<line_sep>x9=N1<times>x8<line_sep>x10=x0<power>x9<line_sep>x11=M1<times>N1<line_sep>x12=x0<power>x11<line_sep>x13=x2<times>x7<line_sep>x14=L0<times>M0<times>N0<times>x3<times>x5<times>x6<line_sep>x15=x13-x14<line_sep>x16=exp(-L1<times>(x12-1))<line_sep>x17=-L1<times>M1<times>N1<times>x10<times>x12<times>x16+x10<times>x16<times>x9-x13+x14<line_sep>x18=N0<times>N0<line_sep>x19=x18<times>x3<times>x6<line_sep>x20=x1<power>2<times>x19<line_sep>x21=M0<power>2<line_sep>x22=L0<times>x18<times>x3<times>x5<times>x6<line_sep>x23=x21<times>x22<line_sep>x24=2<times>M0<times>x1<times>x22<line_sep>x25=L0<power>2<times>x0<power>(2<times>x4)<times>x19<times>x21<line_sep>x26=N1<power>2<line_sep>x27=x10<times>x16<times>x26<line_sep>x28=M1<power>2<line_sep>x29=L1<times>x10<times>x12<times>x16<times>x26<line_sep>a_alpha=a<times>(-omega<times>(-x10<times>exp(L1<times>(-x12+1))+x3<times>exp(L0<times>(-x5+1)))+x7)<line_sep>da_alpha_dT=a<times>(omega<times>x17+x15)/T<line_sep>d2a_alpha_dT2=a<times>(-(omega<times>(-L1<power>2<times>x0<power>(2.<times>x11)<times>x27<times>x28+2.<times>M1<times>x29<times>x8+x17+x20-x23-x24+x25-x27<times>x8<power>2+x28<times>x29)+x15-x20+x23+x24-x25)/T<power>2)<if_stmt>a_alpha<l>min_a_alpha<block_start>a_alpha=min_a_alpha<line_sep>da_alpha_dT=d2a_alpha_dT2=0.0<line_sep># Hydrogen at low T <block_end># a_alpha = da_alpha_dT = d2a_alpha_dT2 = 0.0 <return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><block_end><def_stmt>Twu91_alpha_pure T Tc c0 c1 c2<block_start>Tr=T/Tc<line_sep><return>(Tr<power>(c2<times>(c1-1.0))<times>exp(c0<times>(1.0-(Tr)<power>(c1<times>c2))))<block_end><def_stmt>Soave_1979_alpha_pure T Tc M N<block_start>Tr=T/Tc<line_sep><return>(1.0+(1.0-Tr)<times>(M+N/Tr))<block_end><def_stmt>Soave_1972_alpha_pure T Tc c0<block_start>Tr=T/Tc<line_sep><return>(c0<times>(-sqrt(T/Tc)+1)+1)<power>2<block_end><def_stmt>Heyen_alpha_pure T Tc c1 c2<block_start><return>exp(c1<times>(1.0-(T/Tc)<power>c2))<block_end><def_stmt>Harmens_Knapp_alpha_pure T Tc c1 c2<block_start><return>(c1<times>(-sqrt(T/Tc)+1)-c2<times>(1-Tc/T)+1)<power>2<block_end><def_stmt>Mathias_1983_alpha_pure T Tc c1 c2<block_start>Tr=T/Tc<line_sep><return>(1+c1<times>(1-sqrt(Tr))-c2<times>(1-Tr)<times>(0.7-Tr))<power>2<block_end><def_stmt>Mathias_Copeman_untruncated_alpha_pure T Tc c1 c2 c3<block_start><return>(c1<times>(-sqrt(T/Tc)+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2<block_end><def_stmt>Mathias_Copeman_original_alpha_pure T Tc c1 c2 c3<block_start><if_stmt>T<l>Tc<block_start><return>(c1<times>(-sqrt(T/Tc)+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2<block_end>rt=sqrt(T/Tc)<line_sep>tau=1.0-rt<line_sep>x=(1.0+c1<times>tau)<line_sep><return>x<times>x<block_end><def_stmt>Mathias_Copeman_alpha_pure T Tc *alpha_coeffs<block_start>rt=sqrt(T/Tc)<line_sep>tau=1.0-rt<if_stmt>T<l>Tc<block_start>x0=horner(alpha_coeffs tau)<line_sep><return>x0<times>x0<block_end><else_stmt><block_start>x=(1.0+alpha_coeffs[-2]<times>tau)<line_sep><return>x<times>x<block_end><block_end><def_stmt>Gibbons_Laughton_alpha_pure T Tc c1 c2<block_start><return>(c1<times>(T/Tc-1)+c2<times>(sqrt(T/Tc)-1)+1)<block_end><def_stmt>Soave_1984_alpha_pure T Tc c1 c2<block_start><return>(c1<times>(-T/Tc+1)+c2<times>(-1+Tc/T)+1)<block_end><def_stmt>Yu_Lu_alpha_pure T Tc c1 c2 c3 c4<block_start><return>10<power>(c4<times>(-T/Tc+1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1))<block_end><def_stmt>Trebble_Bishnoi_alpha_pure T Tc c1<block_start><return>exp(c1<times>(-T/Tc+1))<block_end><def_stmt>Melhem_alpha_pure T Tc c1 c2<block_start><return>exp(c1<times>(-T/Tc+1)+c2<times>(-sqrt(T/Tc)+1)<power>2)<block_end><def_stmt>Androulakis_alpha_pure T Tc c1 c2 c3<block_start><return>(c1<times>(-(T/Tc)<power>(2/3)+1)+c2<times>(-(T/Tc)<power>(2/3)+1)<power>2+c3<times>(-(T/Tc)<power>(2/3)+1)<power>3+1)<block_end><def_stmt>Schwartzentruber_alpha_pure T Tc c1 c2 c3 c4<block_start><return>((c4<times>(-sqrt(T/Tc)+1)-(-sqrt(T/Tc)+1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)+1)<power>2)<block_end><def_stmt>Almeida_alpha_pure T Tc c1 c2 c3<block_start><return>exp(c1<times>(-T/Tc+1)<times>abs(T/Tc-1)<power>(c2-1)+c3<times>(-1+Tc/T))<block_end><def_stmt>Soave_1993_alpha_pure T Tc c1 c2<block_start><return>(c1<times>(-T/Tc+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+1)<block_end><def_stmt>Gasem_alpha_pure T Tc c1 c2 c3<block_start><return>(exp((-(T/Tc)<power>c3+1)<times>(T<times>c2/Tc+c1)))<block_end><def_stmt>Coquelet_alpha_pure T Tc c1 c2 c3<block_start><return>(exp(c1<times>(-T/Tc+1)<times>(c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2))<block_end><def_stmt>Haghtalab_alpha_pure T Tc c1 c2 c3<block_start><return>exp((-c3<power>log(T/Tc)+1)<times>(-T<times>c2/Tc+c1))<block_end><def_stmt>Saffari_alpha_pure T Tc c1 c2 c3<block_start><return>(exp(T<times>c1/Tc+c2<times>log(T/Tc)+c3<times>(-sqrt(T/Tc)+1)))<block_end><def_stmt>Chen_Yang_alpha_pure T Tc omega c1 c2 c3 c4 c5 c6 c7<block_start><return>exp(c4<times>log((-sqrt(T/Tc)+1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)<power>2+(-T/Tc+1)<times>(c1+c2<times>omega+c3<times>omega<power>2))<block_end><class_stmt>a_alpha_base(object)<block_start><def_stmt>_init_test self Tc a alpha_coeffs **kwargs<block_start>self.Tc=Tc<line_sep>self.a=a<line_sep>self.alpha_coeffs=alpha_coeffs<line_sep>self.__dict__.update(kwargs)<block_end><block_end><class_stmt>Poly_a_alpha(object)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives given that there is a polynomial equation for :math:`\alpha`. .. math:: a \alpha = a\cdot \text{poly}(T) Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] '''<line_sep>res=horner_and_der2(self.alpha_coeffs T)<line_sep>a=self.a<line_sep><return>(a<times>res[0] a<times>res[1] a<times>res[2])<block_end><def_stmt>a_alpha_pure self T<block_start>r'''Method to calculate `a_alpha` given that there is a polynomial equation for :math:`\alpha`. .. math:: a \alpha = a\cdot \text{poly}(T) Parameters ---------- T : float Temperature, [K] Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] '''<line_sep><return>self.a<times>horner(self.alpha_coeffs T)<block_end><block_end><class_stmt>Soave_1972_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Soave (1972) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Same as `SRK.a_alpha_and_derivatives` but slower and requiring `alpha_coeffs` to be set. One coefficient needed. .. math:: \alpha = \left(c_{0} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) + 1\right)^{2} References ---------- .. [1] <NAME>. "Equilibrium Constants from a Modified Redlich- Kwong Equation of State." Chemical Engineering Science 27, no. 6 (June 1972): 1197-1203. doi:10.1016/0009-2509(72)80096-4. .. [2] Young, <NAME>., <NAME>, and <NAME>. "Comparison of 20 Alpha Functions Applied in the Peng–Robinson Equation of State for Vapor Pressure Estimation." Industrial & Engineering Chemistry Research 55, no. 22 (June 8, 2016): 6506-16. doi:10.1021/acs.iecr.6b00721. '''<line_sep>c0=self.alpha_coeffs[0]<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c0<times>(-sqrt(T/Tc)+1)+1)<power>2<line_sep>da_alpha_dT=-a<times>c0<times>sqrt(T/Tc)<times>(c0<times>(-sqrt(T/Tc)+1)+1)/T<line_sep>d2a_alpha_dT2=a<times>c0<times>(c0/Tc-sqrt(T/Tc)<times>(c0<times>(sqrt(T/Tc)-1)-1)/T)/(2<times>T)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c0=self.alpha_coeffs[0]<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Soave_1972_alpha_pure(T Tc c0)<block_end><block_end><class_stmt>Heyen_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Heyen (1980) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficients needed. .. math:: \alpha = e^{c_{1} \left(- \left(\frac{T}{T_{c,i}}\right)^{c_{2}} + 1\right)} References ---------- .. [1] <NAME>. Liquid and Vapor Properties from a Cubic Equation of State. In "Proceedings of the 2nd International Conference on Phase Equilibria and Fluid Properties in the Chemical Industry". DECHEMA: Frankfurt, 1980; p 9-13. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>exp(c1<times>(1-(T/Tc)<power>c2))<line_sep>da_alpha_dT=-a<times>c1<times>c2<times>(T/Tc)<power>c2<times>exp(c1<times>(-(T/Tc)<power>c2+1))/T<line_sep>d2a_alpha_dT2=a<times>c1<times>c2<times>(T/Tc)<power>c2<times>(c1<times>c2<times>(T/Tc)<power>c2-c2+1)<times>exp(-c1<times>((T/Tc)<power>c2-1))/T<power>2<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Heyen_alpha_pure(T Tc c1 c2)<block_end><block_end><class_stmt>Harmens_Knapp_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Harmens and Knapp (1980) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficients needed. .. math:: \alpha = \left(c_{1} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) - c_{2} \left(1 - \frac{T_{c,i}}{T}\right) + 1\right)^{2} References ---------- .. [1] <NAME>., and <NAME>. "Three-Parameter Cubic Equation of State for Normal Substances." Industrial & Engineering Chemistry Fundamentals 19, no. 3 (August 1, 1980): 291-94. doi:10.1021/i160075a010. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c1<times>(-sqrt(T/Tc)+1)-c2<times>(1-Tc/T)+1)<power>2<line_sep>da_alpha_dT=a<times>(-c1<times>sqrt(T/Tc)/T-2<times>Tc<times>c2/T<power>2)<times>(c1<times>(-sqrt(T/Tc)+1)-c2<times>(1-Tc/T)+1)<line_sep>d2a_alpha_dT2=a<times>((c1<times>sqrt(T/Tc)+2<times>Tc<times>c2/T)<power>2-(c1<times>sqrt(T/Tc)+8<times>Tc<times>c2/T)<times>(c1<times>(sqrt(T/Tc)-1)+c2<times>(1-Tc/T)-1))/(2<times>T<power>2)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Harmens_Knapp_alpha_pure(T Tc c1 c2)<block_end><block_end><class_stmt>Mathias_1983_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Mathias (1983) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficients needed. .. math:: \alpha = \left(c_{1} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) - c_{2} \left(- \frac{T}{T_{c,i}} + 0.7\right) \left(- \frac{T}{T_{c,i}} + 1\right) + 1\right)^{2} References ---------- .. [1] <NAME>. "A Versatile Phase Equilibrium Equation of State." Industrial & Engineering Chemistry Process Design and Development 22, no. 3 (July 1, 1983): 385-91. doi:10.1021/i200022a008. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>Tr=T/Tc<line_sep>a_alpha=a<times>(1+c1<times>(1-sqrt(Tr))-c2<times>(1-Tr)<times>(0.7-Tr))<power>2<line_sep>da_alpha_dT=a<times>(c1<times>(-sqrt(T/Tc)+1)-c2<times>(-T/Tc+0.7)<times>(-T/Tc+1)+1)<times>(2<times>c2<times>(-T/Tc+0.7)/Tc+2<times>c2<times>(-T/Tc+1)/Tc-c1<times>sqrt(T/Tc)/T)<line_sep>d2a_alpha_dT2=a<times>((8<times>c2/Tc<power>2-c1<times>sqrt(T/Tc)/T<power>2)<times>(c1<times>(sqrt(T/Tc)-1)+c2<times>(T/Tc-1)<times>(T/Tc-0.7)-1)+(2<times>c2<times>(T/Tc-1)/Tc+2<times>c2<times>(T/Tc-0.7)/Tc+c1<times>sqrt(T/Tc)/T)<power>2)/2<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>Tr=T/Tc<line_sep><return>a<times>Mathias_1983_alpha_pure(T Tc c1 c2)<block_end><block_end><class_stmt>Mathias_Copeman_untruncated_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Mathias and Copeman (1983) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = \left(c_{1} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) + c_{2} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{2} + c_{3} \left( - \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{3} + 1\right)^{2} References ---------- .. [1] Mathias, <NAME>., and <NAME>. "Extension of the Peng-Robinson Equation of State to Complex Mixtures: Evaluation of the Various Forms of the Local Composition Concept." Fluid Phase Equilibria 13 (January 1, 1983): 91-108. doi:10.1016/0378-3812(83)80084-3. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c1<times>(-sqrt(T/Tc)+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2<line_sep>da_alpha_dT=a<times>(-c1<times>sqrt(T/Tc)/T-2<times>c2<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)/T-3<times>c3<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)<power>2/T)<times>(c1<times>(-sqrt(T/Tc)+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<line_sep>d2a_alpha_dT2=a<times>(T<times>(c1-2<times>c2<times>(sqrt(T/Tc)-1)+3<times>c3<times>(sqrt(T/Tc)-1)<power>2)<power>2-(2<times>T<times>(c2-3<times>c3<times>(sqrt(T/Tc)-1))+Tc<times>sqrt(T/Tc)<times>(c1-2<times>c2<times>(sqrt(T/Tc)-1)+3<times>c3<times>(sqrt(T/Tc)-1)<power>2))<times>(c1<times>(sqrt(T/Tc)-1)-c2<times>(sqrt(T/Tc)-1)<power>2+c3<times>(sqrt(T/Tc)-1)<power>3-1))/(2<times>T<power>2<times>Tc)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Mathias_Copeman_untruncated_alpha_pure(T Tc c1 c2 c3)<block_end><block_end><class_stmt>Mathias_Copeman_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Mathias and Copeman (1983) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = \left(c_{1} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) + c_{2} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{2} + c_{3} \left( - \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{3} + 1\right)^{2} References ---------- .. [1] Mathias, <NAME>., and <NAME>. "Extension of the Peng-Robinson Equation of State to Complex Mixtures: Evaluation of the Various Forms of the Local Composition Concept." Fluid Phase Equilibria 13 (January 1, 1983): 91-108. doi:10.1016/0378-3812(83)80084-3. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>Tr=T/Tc<if_stmt>Tr<g>1<block_start>x0=1.0/T<line_sep>x1=1.0/Tc<line_sep>x2=sqrt(T<times>x1)<line_sep>x3=c1<times>(x2-1.0)-1.0<line_sep>x4=x0<times>x2<times>x3<line_sep>a_alpha=a<times>x3<times>x3<line_sep>da_alpha_dT=a<times>c1<times>x4<line_sep>d2a_alpha_dT2=0.5<times>a<times>c1<times>x0<times>(c1<times>x1-x4)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><else_stmt><block_start>a_alpha=a<times>(c1<times>(-sqrt(T/Tc)+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2<line_sep>da_alpha_dT=a<times>(-c1<times>sqrt(T/Tc)/T-2<times>c2<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)/T-3<times>c3<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)<power>2/T)<times>(c1<times>(-sqrt(T/Tc)+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<line_sep>d2a_alpha_dT2=a<times>(T<times>(c1-2<times>c2<times>(sqrt(T/Tc)-1)+3<times>c3<times>(sqrt(T/Tc)-1)<power>2)<power>2-(2<times>T<times>(c2-3<times>c3<times>(sqrt(T/Tc)-1))+Tc<times>sqrt(T/Tc)<times>(c1-2<times>c2<times>(sqrt(T/Tc)-1)+3<times>c3<times>(sqrt(T/Tc)-1)<power>2))<times>(c1<times>(sqrt(T/Tc)-1)-c2<times>(sqrt(T/Tc)-1)<power>2+c3<times>(sqrt(T/Tc)-1)<power>3-1))/(2<times>T<power>2<times>Tc)<block_end><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Mathias_Copeman_original_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Mathias_Copeman_poly_a_alpha(a_alpha_base)<block_start><def_stmt>a_alphas_vectorized self T<block_start>ais,alpha_coeffs,Tcs=self.ais self.alpha_coeffs self.Tcs<line_sep>a_alphas=[]<for_stmt>i range(self.N)<block_start>tau=1.0-(T/Tcs[i])<power>0.5<if_stmt>T<l>Tcs[i]<block_start>x0=horner(alpha_coeffs[i] tau)<line_sep>a_alpha=x0<times>x0<times>ais[i]<block_end><else_stmt><block_start>x=(1.0+alpha_coeffs[i][-2]<times>tau)<line_sep>a_alpha=ais[i]<times>x<times>x<block_end>a_alphas.append(a_alpha)<block_end><return>a_alphas<block_end><def_stmt>a_alpha_and_derivatives_vectorized self T<block_start>ais,alpha_coeffs,Tcs=self.ais self.alpha_coeffs self.Tcs<line_sep>a_alphas,da_alpha_dTs,d2a_alpha_dT2s=[] [] []<for_stmt>i range(self.N)<block_start>a=ais[i]<line_sep>Tc=Tcs[i]<line_sep>rt=(T/Tc)<power>0.5<line_sep>tau=1.0-rt<if_stmt>T<l>Tc<block_start>x0,x1,x2=horner_and_der2(alpha_coeffs[i] tau)<line_sep>a_alpha=x0<times>x0<times>a<line_sep>da_alpha_dT=-a<times>(rt<times>x0<times>x1/T)<line_sep>d2a_alpha_dT2=a<times>((x0<times>x2/Tc+x1<times>x1/Tc+rt<times>x0<times>x1/T)/(2.0<times>T))<block_end><else_stmt># [-2] is the index to get the second-last coefficient (c1)! Wasted time on this before. <block_start>c1=alpha_coeffs[i][-2]<line_sep>x0=1.0/T<line_sep>x1=1.0/Tc<line_sep>x2=rt#sqrt(T*x1) x3=c1<times>(x2-1.0)-1.0<line_sep>x4=x0<times>x2<times>x3<line_sep>a_alpha=a<times>x3<times>x3<line_sep>da_alpha_dT=a<times>c1<times>x4<line_sep>d2a_alpha_dT2=a<times>0.5<times>c1<times>x0<times>(c1<times>x1-x4)<block_end>a_alphas.append(a_alpha)<line_sep>da_alpha_dTs.append(da_alpha_dT)<line_sep>d2a_alpha_dT2s.append(d2a_alpha_dT2)<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><def_stmt>a_alpha_pure self T# alpha_coeffs [c3, c2, c1, 1] always # [-2] is the index to get the second-last coefficient (c1)! Wasted time on this before. # return self.a*Mathias_Copeman_alpha_pure(T, self.Tc, self.alpha_coeffs) <block_start>Tc=self.Tc<line_sep>a=self.a<line_sep>rt=sqrt(T/Tc)<line_sep>tau=1.0-rt<line_sep>alpha_coeffs=self.alpha_coeffs<if_stmt>T<l>Tc<block_start>x0=horner(alpha_coeffs tau)<line_sep>a_alpha=x0<times>x0<times>a<line_sep><return>a_alpha<block_end><else_stmt><block_start>x=(1.0+alpha_coeffs[-2]<times>tau)<line_sep><return>a<times>x<times>x<block_end><block_end><def_stmt>a_alpha_and_derivatives_pure self T<block_start>Tc=self.Tc<line_sep>a=self.a<line_sep>rt=(T/Tc)<power>0.5<line_sep>tau=1.0-rt<line_sep>alpha_coeffs=self.alpha_coeffs<if_stmt>T<l>Tc# Do not optimize until unit tests are in place <block_start>x0,x1,x2=horner_and_der2(alpha_coeffs tau)<line_sep>a_alpha=x0<times>x0<times>a<line_sep>da_alpha_dT=-a<times>(rt<times>x0<times>x1/T)<line_sep>d2a_alpha_dT2=a<times>((x0<times>x2/Tc+x1<times>x1/Tc+rt<times>x0<times>x1/T)/(2.0<times>T))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><else_stmt><block_start>''' from sympy import * T, Tc, c1 = symbols('T, Tc, c1') tau = 1 - sqrt(T/Tc) alpha = (1 + c1*tau)**2 cse([alpha, diff(alpha, T), diff(alpha, T, T)], optimizations='basic') '''<line_sep># [-2] is the index to get the second-last coefficient (c1)! Wasted time on this before. c1=alpha_coeffs[-2]<line_sep>x0=1.0/T<line_sep>x1=1.0/Tc<line_sep>x2=rt#sqrt(T*x1) x3=c1<times>(x2-1.0)-1.0<line_sep>x4=x0<times>x2<times>x3<line_sep>a_alpha=a<times>x3<times>x3<line_sep>da_alpha_dT=a<times>c1<times>x4<line_sep>d2a_alpha_dT2=0.5<times>a<times>c1<times>x0<times>(c1<times>x1-x4)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><block_end><block_end><class_stmt>Gibbons_Laughton_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Gibbons and Laughton (1984) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficients needed. .. math:: \alpha = c_{1} \left(\frac{T}{T_{c,i}} - 1\right) + c_{2} \left(\sqrt{\frac{T}{T_{c,i}}} - 1\right) + 1 References ---------- .. [1] Gibbons, <NAME>., and <NAME>. "An Equation of State for Polar and Non-Polar Substances and Mixtures" 80, no. 9 (January 1, 1984): 1019-38. doi:10.1039/F29848001019. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c1<times>(T/Tc-1)+c2<times>(sqrt(T/Tc)-1)+1)<line_sep>da_alpha_dT=a<times>(c1/Tc+c2<times>sqrt(T/Tc)/(2<times>T))<line_sep>d2a_alpha_dT2=a<times>(-c2<times>sqrt(T/Tc)/(4<times>T<power>2))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Gibbons_Laughton_alpha_pure(T Tc c1 c2)<block_end><block_end><class_stmt>Soave_1984_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Soave (1984) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficients needed. .. math:: \alpha = c_{1} \left(- \frac{T}{T_{c,i}} + 1\right) + c_{2} \left(-1 + \frac{T_{c,i}}{T}\right) + 1 References ---------- .. [1] <NAME>. "Improvement of the Van Der Waals Equation of State." Chemical Engineering Science 39, no. 2 (January 1, 1984): 357-69. doi:10.1016/0009-2509(84)80034-2. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c1<times>(-T/Tc+1)+c2<times>(-1+Tc/T)+1)<line_sep>da_alpha_dT=a<times>(-c1/Tc-Tc<times>c2/T<power>2)<line_sep>d2a_alpha_dT2=a<times>(2<times>Tc<times>c2/T<power>3)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Soave_1984_alpha_pure(T Tc c1 c2)<block_end><block_end><class_stmt>Yu_Lu_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Yu and Lu (1987) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Four coefficients needed. .. math:: \alpha = 10^{c_{4} \left(- \frac{T}{T_{c,i}} + 1\right) \left( \frac{T^{2} c_{3}}{Tc^{2}} + \frac{T c_{2}}{T_{c,i}} + c_{1}\right)} References ---------- .. [1] Yu, Jin-Min, and <NAME>. -<NAME>. "A Three-Parameter Cubic Equation of State for Asymmetric Mixture Density Calculations." Fluid Phase Equilibria 34, no. 1 (January 1, 1987): 1-19. doi:10.1016/0378-3812(87)85047-1. '''<line_sep>c1,c2,c3,c4=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>10<power>(c4<times>(-T/Tc+1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1))<line_sep>da_alpha_dT=a<times>(10<power>(c4<times>(-T/Tc+1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1))<times>(c4<times>(-T/Tc+1)<times>(2<times>T<times>c3/Tc<power>2+c2/Tc)-c4<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)/Tc)<times>log(10))<line_sep>d2a_alpha_dT2=a<times>(10<power>(-c4<times>(T/Tc-1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1))<times>c4<times>(-4<times>T<times>c3/Tc-2<times>c2-2<times>c3<times>(T/Tc-1)+c4<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1+(T/Tc-1)<times>(2<times>T<times>c3/Tc+c2))<power>2<times>log(10))<times>log(10)/Tc<power>2)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Yu_Lu_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Trebble_Bishnoi_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Trebble and Bishnoi (1987) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. One coefficient needed. .. math:: \alpha = e^{c_{1} \left(- \frac{T}{T_{c,i}} + 1\right)} References ---------- .. [1] <NAME>., and <NAME>. "Development of a New Four- Parameter Cubic Equation of State." Fluid Phase Equilibria 35, no. 1 (September 1, 1987): 1-18. doi:10.1016/0378-3812(87)80001-8. '''<line_sep>c1=self.alpha_coeffs[0]<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>exp(c1<times>(-T/Tc+1))<line_sep>da_alpha_dT=a<times>-c1<times>exp(c1<times>(-T/Tc+1))/Tc<line_sep>d2a_alpha_dT2=a<times>c1<power>2<times>exp(-c1<times>(T/Tc-1))/Tc<power>2<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Trebble_Bishnoi_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Melhem_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Melhem et al. (1989) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficients needed. .. math:: \alpha = e^{c_{1} \left(- \frac{T}{T_{c,i}} + 1\right) + c_{2} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{2}} References ---------- .. [1] Melhem, <NAME>., <NAME>, and <NAME>. "A Modified Peng-Robinson Equation of State." Fluid Phase Equilibria 47, no. 2 (August 1, 1989): 189-237. doi:10.1016/0378-3812(89)80176-1. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>exp(c1<times>(-T/Tc+1)+c2<times>(-sqrt(T/Tc)+1)<power>2)<line_sep>da_alpha_dT=a<times>((-c1/Tc-c2<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)/T)<times>exp(c1<times>(-T/Tc+1)+c2<times>(-sqrt(T/Tc)+1)<power>2))<line_sep>d2a_alpha_dT2=a<times>(((c1/Tc-c2<times>sqrt(T/Tc)<times>(sqrt(T/Tc)-1)/T)<power>2+c2<times>(1/Tc-sqrt(T/Tc)<times>(sqrt(T/Tc)-1)/T)/(2<times>T))<times>exp(-c1<times>(T/Tc-1)+c2<times>(sqrt(T/Tc)-1)<power>2))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Melhem_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Androulakis_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Androulakis et al. (1989) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = c_{1} \left(- \left(\frac{T}{T_{c,i}}\right)^{\frac{2}{3}} + 1\right) + c_{2} \left(- \left(\frac{T}{T_{c,i}}\right)^{\frac{2}{3}} + 1\right)^{2} + c_{3} \left(- \left(\frac{T}{T_{c,i}}\right)^{ \frac{2}{3}} + 1\right)^{3} + 1 References ---------- .. [1] Androulakis, <NAME>., <NAME>, and <NAME>. "Thermophysical Properties of Pure Polar and Nonpolar Compounds with a Modified VdW-711 Equation of State." Fluid Phase Equilibria 45, no. 2 (April 1, 1989): 135-63. doi:10.1016/0378-3812(89)80254-7. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c1<times>(-(T/Tc)<power>(2/3)+1)+c2<times>(-(T/Tc)<power>(2/3)+1)<power>2+c3<times>(-(T/Tc)<power>(2/3)+1)<power>3+1)<line_sep>da_alpha_dT=a<times>(-2<times>c1<times>(T/Tc)<power>(2/3)/(3<times>T)-4<times>c2<times>(T/Tc)<power>(2/3)<times>(-(T/Tc)<power>(2/3)+1)/(3<times>T)-2<times>c3<times>(T/Tc)<power>(2/3)<times>(-(T/Tc)<power>(2/3)+1)<power>2/T)<line_sep>d2a_alpha_dT2=a<times>(2<times>(T/Tc)<power>(2/3)<times>(c1+4<times>c2<times>(T/Tc)<power>(2/3)-2<times>c2<times>((T/Tc)<power>(2/3)-1)-12<times>c3<times>(T/Tc)<power>(2/3)<times>((T/Tc)<power>(2/3)-1)+3<times>c3<times>((T/Tc)<power>(2/3)-1)<power>2)/(9<times>T<power>2))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Androulakis_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Schwartzentruber_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Schwartzentruber et al. (1990) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = \left(c_{4} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) - \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right) \left(\frac{T^{2} c_{3}} {Tc^{2}} + \frac{T c_{2}}{T_{c,i}} + c_{1}\right) + 1\right)^{2} References ---------- .. [1] <NAME>, <NAME>, and <NAME>, "K-values for Non-Ideal Systems:An Easier Way," Chem. Eng., March 1990, 118-124. '''<line_sep>c1,c2,c3,c4=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>((c4<times>(-sqrt(T/Tc)+1)-(-sqrt(T/Tc)+1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)+1)<power>2)<line_sep>da_alpha_dT=a<times>((c4<times>(-sqrt(T/Tc)+1)-(-sqrt(T/Tc)+1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)+1)<times>(-2<times>(-sqrt(T/Tc)+1)<times>(2<times>T<times>c3/Tc<power>2+c2/Tc)-c4<times>sqrt(T/Tc)/T+sqrt(T/Tc)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)/T))<line_sep>d2a_alpha_dT2=a<times>(((-c4<times>(sqrt(T/Tc)-1)+(sqrt(T/Tc)-1)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)+1)<times>(8<times>c3<times>(sqrt(T/Tc)-1)/Tc<power>2+4<times>sqrt(T/Tc)<times>(2<times>T<times>c3/Tc+c2)/(T<times>Tc)+c4<times>sqrt(T/Tc)/T<power>2-sqrt(T/Tc)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)/T<power>2)+(2<times>(sqrt(T/Tc)-1)<times>(2<times>T<times>c3/Tc+c2)/Tc-c4<times>sqrt(T/Tc)/T+sqrt(T/Tc)<times>(T<power>2<times>c3/Tc<power>2+T<times>c2/Tc+c1)/T)<power>2)/2)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Schwartzentruber_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Almeida_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Almeida et al. (1991) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = e^{c_{1} \left(- \frac{T}{T_{c,i}} + 1\right) \left|{ \frac{T}{T_{c,i}} - 1}\right|^{c_{2} - 1} + c_{3} \left(-1 + \frac{T_{c,i}}{T}\right)} References ---------- .. [1] <NAME>., <NAME>, and <NAME>. "Uma Nova Forma de Dependência Com a Temperatura Do Termo Atrativo de Equações de Estado Cúbicas." RBE, Rev. Bras. Eng., Cad. Eng. Quim 8 (1991): 95. '''<line_sep># Note: Sympy didn't handle the derivative of the absolute value for # the second derivative, requires the use a CAS which can # handle the assumption that Tr-1 != 0. # A second pass on this function resulted in writting two functions: # one which works on Tr < 1, one which works on Tr > 1. c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>Tr=T/Tc<if_stmt>Tr<g>1<block_start>x0=c3<times>(1-Tc/T)<line_sep>x1=1/Tc<line_sep>x2=T<times>x1-1<line_sep>x3=c2-1<line_sep>x4=c1<times>x2<power>x3<line_sep>x5=x2<times>x4<line_sep>x6=exp(-x0-x5)<line_sep>x7=Tc<times>c3<line_sep>x8=x1<times>x4<line_sep>x9=x3<times>x8+x8+x7/T<power>2<line_sep>x10=x4/(Tc<power>2<times>x2)<line_sep>alpha,d_alpha_dT,d2_alpha_dT2=exp(-x0-x5) -x6<times>x9 x6<times>(-x10<times>x3<power>2-x10<times>x3+x9<power>2+2<times>x7/T<power>3)<block_end><else_stmt><block_start>x0=c3<times>(1-Tc/T)<line_sep>x1=1/Tc<line_sep>x2=T<times>x1<line_sep>x3=x2-1<line_sep>x4=c2-1<line_sep>x5=c1<times>(1-x2)<power>x4<line_sep>x6=x3<times>x5<line_sep>x7=exp(-x0-x6)<line_sep>x8=Tc<times>c3<line_sep>x9=x1<times>x5<line_sep>x10=x4<times>x9+x9+x8/T<power>2<line_sep>x11=x5/(Tc<power>2<times>x3)<line_sep>alpha,d_alpha_dT,d2_alpha_dT2=exp(-x0-x6) -x10<times>x7 x7<times>(x10<power>2-x11<times>x4<power>2-x11<times>x4+2<times>x8/T<power>3)<block_end><return>a<times>alpha a<times>d_alpha_dT a<times>d2_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Almeida_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Twu91_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Twu et al. (1991) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = \left(\frac{T}{T_{c,i}}\right)^{c_{3} \left(c_{2} - 1\right)} e^{c_{1} \left(- \left(\frac{T}{T_{c,i}} \right)^{c_{2} c_{3}} + 1\right)} References ---------- .. [1] Twu, <NAME>., <NAME>, <NAME>, and <NAME>. Coon. "A Cubic Equation of State with a New Alpha Function and a New Mixing Rule." Fluid Phase Equilibria 69 (December 10, 1991): 33-50. doi:10.1016/0378-3812(91)90024-2. '''<line_sep>c0,c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>Tr=T/Tc<line_sep>T_inv=1.0/T<line_sep>x1=c1-1.0<line_sep>x2=c2<times>x1<line_sep>x3=c1<times>c2<line_sep>x4=Tr<power>x3<line_sep>x5=a<times>Tr<power>x2<times>exp(-c0<times>(x4-1.0))<line_sep>x6=c0<times>x4<line_sep>x7=c1<times>x6<line_sep>x8=c2<times>x5<line_sep>x9=c1<times>c1<times>c2<line_sep>d2a_alpha_dT2=(x8<times>(c0<times>c0<times>x4<times>x4<times>x9-c1+c2<times>x1<times>x1-2.0<times>x2<times>x7-x6<times>x9+x7+1.0)<times>T_inv<times>T_inv)<line_sep><return>x5 x8<times>(x1-x7)<times>T_inv d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start>c0,c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Twu91_alpha_pure(T Tc c0 c1 c2)<block_end><def_stmt>a_alphas_vectorized self T<block_start>ais,alpha_coeffs,Tcs=self.ais self.alpha_coeffs self.Tcs<line_sep>a_alphas=[]<for_stmt>i range(self.N)<block_start>coeffs=alpha_coeffs[i]<line_sep>Tr=T/Tcs[i]<line_sep>a_alpha=ais[i]<times>(Tr<power>(coeffs[2]<times>(coeffs[1]-1.0))<times>exp(coeffs[0]<times>(1.0-(Tr)<power>(coeffs[1]<times>coeffs[2]))))<line_sep>a_alphas.append(a_alpha)<block_end><if_stmt>self.scalar<block_start><return>a_alphas<block_end><return>array(a_alphas)<block_end><def_stmt>a_alpha_and_derivatives_vectorized self T<block_start>r'''Method to calculate the pure-component `a_alphas` and their first and second derivatives for TWU91 alpha function EOS. This vectorized implementation is added for extra speed. .. math:: \alpha = \left(\frac{T}{T_{c,i}}\right)^{c_{3} \left(c_{2} - 1\right)} e^{c_{1} \left(- \left(\frac{T}{T_{c,i}} \right)^{c_{2} c_{3}} + 1\right)} Parameters ---------- T : float Temperature, [K] Returns ------- a_alphas : list[float] Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dTs : list[float] Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2s : list[float] Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] '''<line_sep>ais,alpha_coeffs,Tcs=self.ais self.alpha_coeffs self.Tcs<line_sep>N=len(ais)<line_sep>a_alphas=[0.0]<times>N<line_sep>da_alpha_dTs=[0.0]<times>N<line_sep>d2a_alpha_dT2s=[0.0]<times>N<line_sep>T_inv=1.0/T<for_stmt>i range(N)<block_start>coeffs=alpha_coeffs[i]<line_sep>c0,c1,c2=coeffs[0] coeffs[1] coeffs[2]<line_sep>Tr=T/Tcs[i]<line_sep>x1=c1-1.0<line_sep>x2=c2<times>x1<line_sep>x3=c1<times>c2<line_sep>x4=Tr<power>x3<line_sep>x5=ais[i]<times>Tr<power>x2<times>exp(-c0<times>(x4-1.0))<line_sep>x6=c0<times>x4<line_sep>x7=c1<times>x6<line_sep>x8=c2<times>x5<line_sep>x9=c1<times>c1<times>c2<line_sep>d2a_alpha_dT2=(x8<times>(c0<times>c0<times>x4<times>x4<times>x9-c1+c2<times>x1<times>x1-2.0<times>x2<times>x7-x6<times>x9+x7+1.0)<times>T_inv<times>T_inv)<line_sep>a_alphas[i]=x5<line_sep>da_alpha_dTs[i]=x8<times>(x1-x7)<times>T_inv<line_sep>d2a_alpha_dT2s[i]=d2a_alpha_dT2<block_end><if_stmt>self.scalar<block_start><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><return>array(a_alphas) array(da_alpha_dTs) array(d2a_alpha_dT2s)<block_end><block_end><class_stmt>Soave_1993_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Soave (1983) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Two coefficient needed. .. math:: \alpha = c_{1} \left(- \frac{T}{T_{c,i}} + 1\right) + c_{2} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{2} + 1 References ---------- .. [1] <NAME>. "Improving the Treatment of Heavy Hydrocarbons by the SRK EOS." Fluid Phase Equilibria 84 (April 1, 1993): 339-42. doi:10.1016/0378-3812(93)85131-5. '''<line_sep>c1,c2=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(c1<times>(-T/Tc+1)+c2<times>(-sqrt(T/Tc)+1)<power>2+1)<line_sep>da_alpha_dT=a<times>(-c1/Tc-c2<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)/T)<line_sep>d2a_alpha_dT2=a<times>(c2<times>(1/Tc-sqrt(T/Tc)<times>(sqrt(T/Tc)-1)/T)/(2<times>T))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Soave_1993_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Gasem_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Gasem (2001) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = e^{\left(- \left(\frac{T}{T_{c,i}}\right)^{c_{3}} + 1\right) \left(\frac{T c_{2}}{T_{c,i}} + c_{1}\right)} References ---------- .. [1] Gasem, <NAME>, <NAME>, <NAME>, and <NAME>. "A Modified Temperature Dependence for the Peng-Robinson Equation of State." Fluid Phase Equilibria 181, no. 1–2 (May 25, 2001): 113-25. doi:10.1016/S0378-3812(01)00488-5. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(exp((-(T/Tc)<power>c3+1)<times>(T<times>c2/Tc+c1)))<line_sep>da_alpha_dT=a<times>((c2<times>(-(T/Tc)<power>c3+1)/Tc-c3<times>(T/Tc)<power>c3<times>(T<times>c2/Tc+c1)/T)<times>exp((-(T/Tc)<power>c3+1)<times>(T<times>c2/Tc+c1)))<line_sep>d2a_alpha_dT2=a<times>(((c2<times>((T/Tc)<power>c3-1)/Tc+c3<times>(T/Tc)<power>c3<times>(T<times>c2/Tc+c1)/T)<power>2-c3<times>(T/Tc)<power>c3<times>(2<times>c2/Tc+c3<times>(T<times>c2/Tc+c1)/T-(T<times>c2/Tc+c1)/T)/T)<times>exp(-((T/Tc)<power>c3-1)<times>(T<times>c2/Tc+c1)))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Gasem_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Coquelet_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Coquelet et al. (2004) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = e^{c_{1} \left(- \frac{T}{T_{c,i}} + 1\right) \left(c_{2} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{2} + c_{3} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)^{3} + 1\right)^{2}} References ---------- .. [1] <NAME>., <NAME>, and <NAME>. "Development of a New Alpha Function for the Peng–Robinson Equation of State: Comparative Study of Alpha Function Models for Pure Gases (Natural Gas Components) and Water-Gas Systems." International Journal of Thermophysics 25, no. 1 (January 1, 2004): 133-58. doi:10.1023/B:IJOT.0000022331.46865.2f. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(exp(c1<times>(-T/Tc+1)<times>(c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2))<line_sep>da_alpha_dT=a<times>((c1<times>(-T/Tc+1)<times>(-2<times>c2<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)/T-3<times>c3<times>sqrt(T/Tc)<times>(-sqrt(T/Tc)+1)<power>2/T)<times>(c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)-c1<times>(c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2/Tc)<times>exp(c1<times>(-T/Tc+1)<times>(c2<times>(-sqrt(T/Tc)+1)<power>2+c3<times>(-sqrt(T/Tc)+1)<power>3+1)<power>2))<line_sep>d2a_alpha_dT2=a<times>(c1<times>(c1<times>(-(c2<times>(sqrt(T/Tc)-1)<power>2-c3<times>(sqrt(T/Tc)-1)<power>3+1)/Tc+sqrt(T/Tc)<times>(-2<times>c2+3<times>c3<times>(sqrt(T/Tc)-1))<times>(sqrt(T/Tc)-1)<times>(T/Tc-1)/T)<power>2<times>(c2<times>(sqrt(T/Tc)-1)<power>2-c3<times>(sqrt(T/Tc)-1)<power>3+1)<power>2-((T/Tc-1)<times>(c2<times>(sqrt(T/Tc)-1)<power>2-c3<times>(sqrt(T/Tc)-1)<power>3+1)<times>(2<times>c2/Tc-6<times>c3<times>(sqrt(T/Tc)-1)/Tc-2<times>c2<times>sqrt(T/Tc)<times>(sqrt(T/Tc)-1)/T+3<times>c3<times>sqrt(T/Tc)<times>(sqrt(T/Tc)-1)<power>2/T)+4<times>sqrt(T/Tc)<times>(2<times>c2-3<times>c3<times>(sqrt(T/Tc)-1))<times>(sqrt(T/Tc)-1)<times>(c2<times>(sqrt(T/Tc)-1)<power>2-c3<times>(sqrt(T/Tc)-1)<power>3+1)/Tc+(2<times>c2-3<times>c3<times>(sqrt(T/Tc)-1))<power>2<times>(sqrt(T/Tc)-1)<power>2<times>(T/Tc-1)/Tc)/(2<times>T))<times>exp(-c1<times>(T/Tc-1)<times>(c2<times>(sqrt(T/Tc)-1)<power>2-c3<times>(sqrt(T/Tc)-1)<power>3+1)<power>2))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Coquelet_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Haghtalab_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Haghtalab et al. (2010) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = e^{\left(- c_{3}^{\ln{\left (\frac{T}{T_{c,i}} \right )}} + 1\right) \left(- \frac{T c_{2}}{T_{c,i}} + c_{1}\right)} References ---------- .. [1] <NAME>., <NAME>, <NAME>, and <NAME>. "A New Three-Parameter Cubic Equation of State for Calculation Physical Properties and Vapor-liquid Equilibria." Fluid Phase Equilibria 293, no. 2 (June 25, 2010): 209-18. doi:10.1016/j.fluid.2010.03.029. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>exp((-c3<power>log(T/Tc)+1)<times>(-T<times>c2/Tc+c1))<line_sep>da_alpha_dT=a<times>((-c2<times>(-c3<power>log(T/Tc)+1)/Tc-c3<power>log(T/Tc)<times>(-T<times>c2/Tc+c1)<times>log(c3)/T)<times>exp((-c3<power>log(T/Tc)+1)<times>(-T<times>c2/Tc+c1)))<line_sep>d2a_alpha_dT2=a<times>(((c2<times>(c3<power>log(T/Tc)-1)/Tc+c3<power>log(T/Tc)<times>(T<times>c2/Tc-c1)<times>log(c3)/T)<power>2+c3<power>log(T/Tc)<times>(2<times>c2/Tc+(T<times>c2/Tc-c1)<times>log(c3)/T-(T<times>c2/Tc-c1)/T)<times>log(c3)/T)<times>exp((c3<power>log(T/Tc)-1)<times>(T<times>c2/Tc-c1)))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Haghtalab_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Saffari_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Saffari and Zahedi (2013) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Three coefficients needed. .. math:: \alpha = e^{\frac{T c_{1}}{T_{c,i}} + c_{2} \ln{\left (\frac{T}{T_{c,i}} \right )} + c_{3} \left(- \sqrt{\frac{T}{T_{c,i}}} + 1\right)} References ---------- .. [1] Saffari, Hamid, and <NAME>. "A New Alpha-Function for the Peng-Robinson Equation of State: Application to Natural Gas." Chinese Journal of Chemical Engineering 21, no. 10 (October 1, 2013): 1155-61. doi:10.1016/S1004-9541(13)60581-9. '''<line_sep>c1,c2,c3=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep>a_alpha=a<times>(exp(T<times>c1/Tc+c2<times>log(T/Tc)+c3<times>(-sqrt(T/Tc)+1)))<line_sep>da_alpha_dT=a<times>((c1/Tc+c2/T-c3<times>sqrt(T/Tc)/(2<times>T))<times>exp(T<times>c1/Tc+c2<times>log(T/Tc)+c3<times>(-sqrt(T/Tc)+1)))<line_sep>d2a_alpha_dT2=a<times>(((2<times>c1/Tc+2<times>c2/T-c3<times>sqrt(T/Tc)/T)<power>2-(4<times>c2-c3<times>sqrt(T/Tc))/T<power>2)<times>exp(T<times>c1/Tc+c2<times>log(T/Tc)-c3<times>(sqrt(T/Tc)-1))/4)<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Saffari_alpha_pure(T self.Tc *self.alpha_coeffs)<block_end><block_end><class_stmt>Chen_Yang_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Hamid and Yang (2017) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Seven coefficients needed. .. math:: \alpha = e^{\left(- c_{3}^{\ln{\left (\frac{T}{T_{c,i}} \right )}} + 1\right) \left(- \frac{T c_{2}}{T_{c,i}} + c_{1}\right)} References ---------- .. [1] Chen, Zehua, and <NAME>. "Optimization of the Reduced Temperature Associated with Peng–Robinson Equation of State and Soave-Redlich-Kwong Equation of State To Improve Vapor Pressure Prediction for Heavy Hydrocarbon Compounds." Journal of Chemical & Engineering Data, August 31, 2017. doi:10.1021/acs.jced.7b00496. '''<line_sep>c1,c2,c3,c4,c5,c6,c7=self.alpha_coeffs<line_sep>Tc,a,omega=self.Tc self.a self.omega<line_sep>a_alpha=a<times>exp(c4<times>log((-sqrt(T/Tc)+1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)<power>2+(-T/Tc+1)<times>(c1+c2<times>omega+c3<times>omega<power>2))<line_sep>da_alpha_dT=a<times>(-(c1+c2<times>omega+c3<times>omega<power>2)/Tc-c4<times>sqrt(T/Tc)<times>(c5+c6<times>omega+c7<times>omega<power>2)<times>log((-sqrt(T/Tc)+1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)/(T<times>((-sqrt(T/Tc)+1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)))<times>exp(c4<times>log((-sqrt(T/Tc)+1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)<power>2+(-T/Tc+1)<times>(c1+c2<times>omega+c3<times>omega<power>2))<line_sep>d2a_alpha_dT2=a<times>(((c1+c2<times>omega+c3<times>omega<power>2)/Tc-c4<times>sqrt(T/Tc)<times>(c5+c6<times>omega+c7<times>omega<power>2)<times>log(-(sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)/(T<times>((sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)-1)))<power>2-c4<times>(c5+c6<times>omega+c7<times>omega<power>2)<times>((c5+c6<times>omega+c7<times>omega<power>2)<times>log(-(sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)/(Tc<times>((sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)-1))-(c5+c6<times>omega+c7<times>omega<power>2)/(Tc<times>((sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)-1))+sqrt(T/Tc)<times>log(-(sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)/T)/(2<times>T<times>((sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)-1)))<times>exp(c4<times>log(-(sqrt(T/Tc)-1)<times>(c5+c6<times>omega+c7<times>omega<power>2)+1)<power>2-(T/Tc-1)<times>(c1+c2<times>omega+c3<times>omega<power>2))<line_sep><return>a_alpha da_alpha_dT d2a_alpha_dT2<block_end><def_stmt>a_alpha_pure self T<block_start><return>self.a<times>Chen_Yang_alpha_pure(T self.Tc self.omega *self.alpha_coeffs)<block_end><block_end><class_stmt>TwuSRK95_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate :math:`a \alpha` and its first and second derivatives for the Twu alpha function. Uses the set values of `Tc`, `omega` and `a`. .. math:: \alpha = \alpha^{(0)} + \omega(\alpha^{(1)}-\alpha^{(0)}) .. math:: \alpha^{(i)} = T_r^{N(M-1)}\exp[L(1-T_r^{NM})] For sub-critical conditions: L0, M0, N0 = 0.141599, 0.919422, 2.496441 L1, M1, N1 = 0.500315, 0.799457, 3.291790 For supercritical conditions: L0, M0, N0 = 0.441411, 6.500018, -0.20 L1, M1, N1 = 0.032580, 1.289098, -8.0 Parameters ---------- T : float Temperature at which to calculate the values, [-] Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dT : float Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2 : float Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K^2] Notes ----- This method does not alter the object's state and the temperature provided can be a different than that of the object. The derivatives are somewhat long and are not described here for brevity; they are obtainable from the following SymPy expression. >>> from sympy import * # doctest:+SKIP >>> T, Tc, omega, N1, N0, M1, M0, L1, L0 = symbols('T, Tc, omega, N1, N0, M1, M0, L1, L0') # doctest:+SKIP >>> Tr = T/Tc # doctest:+SKIP >>> alpha0 = Tr**(N0*(M0-1))*exp(L0*(1-Tr**(N0*M0))) # doctest:+SKIP >>> alpha1 = Tr**(N1*(M1-1))*exp(L1*(1-Tr**(N1*M1))) # doctest:+SKIP >>> alpha = alpha0 + omega*(alpha1-alpha0) # doctest:+SKIP >>> diff(alpha, T) # doctest:+SKIP >>> diff(alpha, T, T) # doctest:+SKIP '''<line_sep><return>TWU_a_alpha_common(T self.Tc self.omega self.a full=<true> method='SRK')<block_end><def_stmt>a_alpha_pure self T<block_start>r'''Method to calculate :math:`a \alpha` for the Twu alpha function. Uses the set values of `Tc`, `omega` and `a`. .. math:: \alpha = \alpha^{(0)} + \omega(\alpha^{(1)}-\alpha^{(0)}) .. math:: \alpha^{(i)} = T_r^{N(M-1)}\exp[L(1-T_r^{NM})] For sub-critical conditions: L0, M0, N0 = 0.141599, 0.919422, 2.496441 L1, M1, N1 = 0.500315, 0.799457, 3.291790 For supercritical conditions: L0, M0, N0 = 0.441411, 6.500018, -0.20 L1, M1, N1 = 0.032580, 1.289098, -8.0 Parameters ---------- T : float Temperature at which to calculate the value, [-] Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] Notes ----- This method does not alter the object's state and the temperature provided can be a different than that of the object. '''<line_sep><return>TWU_a_alpha_common(T self.Tc self.omega self.a full=<false> method='SRK')<block_end><def_stmt>a_alphas_vectorized self T<block_start>Tcs,omegas,ais=self.Tcs self.omegas self.ais<line_sep>a_alphas=[TWU_a_alpha_common(T Tcs[i] omegas[i] ais[i] full=<false> method='SRK')<for>i range(self.N)]<if_stmt>self.scalar<block_start><return>a_alphas<block_end><return>array(a_alphas)<block_end><def_stmt>a_alpha_and_derivatives_vectorized self T<block_start>Tcs,omegas,ais=self.Tcs self.omegas self.ais<line_sep>r0,r1,r2=[] [] []<for_stmt>i range(self.N)<block_start>v0,v1,v2=TWU_a_alpha_common(T Tcs[i] omegas[i] ais[i] full=<true> method='SRK')<line_sep>r0.append(v0)<line_sep>r1.append(v1)<line_sep>r2.append(v2)<block_end><if_stmt>self.scalar<block_start><return>r0 r1 r2<block_end><return>array(r0) array(r1) array(r2)<block_end><block_end><class_stmt>TwuPR95_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate :math:`a \alpha` and its first and second derivatives for the Twu alpha function. Uses the set values of `Tc`, `omega` and `a`. .. math:: \alpha = \alpha^{(0)} + \omega(\alpha^{(1)}-\alpha^{(0)}) .. math:: \alpha^{(i)} = T_r^{N(M-1)}\exp[L(1-T_r^{NM})] For sub-critical conditions: L0, M0, N0 = 0.125283, 0.911807, 1.948150; L1, M1, N1 = 0.511614, 0.784054, 2.812520 For supercritical conditions: L0, M0, N0 = 0.401219, 4.963070, -0.2; L1, M1, N1 = 0.024955, 1.248089, -8. Parameters ---------- T : float Temperature at which to calculate the values, [-] Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dT : float Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2 : float Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K^2] Notes ----- This method does not alter the object's state and the temperature provided can be a different than that of the object. The derivatives are somewhat long and are not described here for brevity; they are obtainable from the following SymPy expression. >>> from sympy import * # doctest:+SKIP >>> T, Tc, omega, N1, N0, M1, M0, L1, L0 = symbols('T, Tc, omega, N1, N0, M1, M0, L1, L0') # doctest:+SKIP >>> Tr = T/Tc # doctest:+SKIP >>> alpha0 = Tr**(N0*(M0-1))*exp(L0*(1-Tr**(N0*M0))) # doctest:+SKIP >>> alpha1 = Tr**(N1*(M1-1))*exp(L1*(1-Tr**(N1*M1))) # doctest:+SKIP >>> alpha = alpha0 + omega*(alpha1-alpha0) # doctest:+SKIP >>> diff(alpha, T) # doctest:+SKIP >>> diff(alpha, T, T) # doctest:+SKIP '''<line_sep><return>TWU_a_alpha_common(T self.Tc self.omega self.a full=<true> method='PR')<block_end><def_stmt>a_alpha_pure self T<block_start>r'''Method to calculate :math:`a \alpha` for the Twu alpha function. Uses the set values of `Tc`, `omega` and `a`. .. math:: \alpha = \alpha^{(0)} + \omega(\alpha^{(1)}-\alpha^{(0)}) .. math:: \alpha^{(i)} = T_r^{N(M-1)}\exp[L(1-T_r^{NM})] For sub-critical conditions: L0, M0, N0 = 0.125283, 0.911807, 1.948150; L1, M1, N1 = 0.511614, 0.784054, 2.812520 For supercritical conditions: L0, M0, N0 = 0.401219, 4.963070, -0.2; L1, M1, N1 = 0.024955, 1.248089, -8. Parameters ---------- T : float Temperature at which to calculate the value, [-] Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] Notes ----- This method does not alter the object's state and the temperature provided can be a different than that of the object. '''<line_sep><return>TWU_a_alpha_common(T self.Tc self.omega self.a full=<false> method='PR')<block_end><def_stmt>a_alphas_vectorized self T<block_start>Tcs,omegas,ais=self.Tcs self.omegas self.ais<line_sep>a_alphas=[TWU_a_alpha_common(T Tcs[i] omegas[i] ais[i] full=<false> method='PR')<for>i range(self.N)]<if_stmt>self.scalar<block_start><return>a_alphas<block_end><return>array(a_alphas)<block_end><def_stmt>a_alpha_and_derivatives_vectorized self T<block_start>Tcs,omegas,ais=self.Tcs self.omegas self.ais<line_sep>r0,r1,r2=[] [] []<for_stmt>i range(self.N)<block_start>v0,v1,v2=TWU_a_alpha_common(T Tcs[i] omegas[i] ais[i] full=<true> method='PR')<line_sep>r0.append(v0)<line_sep>r1.append(v1)<line_sep>r2.append(v2)<block_end><if_stmt>self.scalar<block_start><return>r0 r1 r2<block_end><return>array(r0) array(r1) array(r2)<block_end><block_end><class_stmt>Soave_1979_a_alpha(a_alpha_base)<block_start><def_stmt>a_alpha_and_derivatives_pure self T<block_start>r'''Method to calculate `a_alpha` and its first and second derivatives according to Soave (1979) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. Three coefficients are needed. .. math:: \alpha = 1 + (1 - T_r)(M + \frac{N}{T_r}) References ---------- .. [1] <NAME>. "Rigorous and Simplified Procedures for Determining the Pure-Component Parameters in the Redlich—Kwong—Soave Equation of State." Chemical Engineering Science 35, no. 8 (January 1, 1980): 1725-30. https://doi.org/10.1016/0009-2509(80)85007-X. '''<line_sep>M,N=self.alpha_coeffs#self.M, self.N Tc,a=self.Tc self.a<line_sep>T_inv=1.0/T<line_sep>x0=1.0/Tc<line_sep>x1=T<times>x0-1.0<line_sep>x2=Tc<times>T_inv<line_sep>x3=M+N<times>x2<line_sep>x4=N<times>T_inv<times>T_inv<line_sep><return>(a<times>(1.0-x1<times>x3) a<times>(Tc<times>x1<times>x4-x0<times>x3) a<times>(2.0<times>x4<times>(1.0-x1<times>x2)))<block_end><def_stmt>a_alpha_pure self T<block_start>M,N=self.alpha_coeffs<line_sep>Tc,a=self.Tc self.a<line_sep><return>a<times>Soave_1979_alpha_pure(T self.Tc M N)<block_end><def_stmt>a_alphas_vectorized self T<block_start>ais,alpha_coeffs,Tcs=self.ais self.alpha_coeffs self.Tcs<line_sep>a_alphas=[]<for_stmt>i range(self.N)<block_start>Tr=T/Tcs[i]<line_sep>M,N=alpha_coeffs[i]<line_sep>a_alphas.append(ais[i]<times>(1.0+(1.0-Tr)<times>(M+N/Tr)))<block_end><return>a_alphas<block_end><def_stmt>a_alpha_and_derivatives_vectorized self T<block_start>ais,alpha_coeffs,Tcs=self.ais self.alpha_coeffs self.Tcs<line_sep>T_inv=1.0/T<line_sep>a_alphas,da_alpha_dTs,d2a_alpha_dT2s=[] [] []<for_stmt>i range(self.N)<block_start>a=ais[i]<line_sep>M,N=alpha_coeffs[i]<line_sep>x0=1.0/Tcs[i]<line_sep>x1=T<times>x0-1.0<line_sep>x2=Tcs[i]<times>T_inv<line_sep>x3=M+N<times>x2<line_sep>x4=N<times>T_inv<times>T_inv<line_sep>a_alphas.append(a<times>(1.0-x1<times>x3))<line_sep>da_alpha_dTs.append(a<times>(Tcs[i]<times>x1<times>x4-x0<times>x3))<line_sep>d2a_alpha_dT2s.append(a<times>(2.0<times>x4<times>(1.0-x1<times>x2)))<block_end><return>a_alphas da_alpha_dTs d2a_alpha_dT2s<block_end><block_end>a_alpha_bases=[Soave_1972_a_alpha Heyen_a_alpha Harmens_Knapp_a_alpha Mathias_1983_a_alpha Mathias_Copeman_untruncated_a_alpha Gibbons_Laughton_a_alpha Soave_1984_a_alpha Yu_Lu_a_alpha Trebble_Bishnoi_a_alpha Melhem_a_alpha Androulakis_a_alpha Schwartzentruber_a_alpha Almeida_a_alpha Twu91_a_alpha Soave_1993_a_alpha Gasem_a_alpha Coquelet_a_alpha Haghtalab_a_alpha Saffari_a_alpha Chen_Yang_a_alpha Mathias_Copeman_poly_a_alpha TwuSRK95_a_alpha TwuPR95_a_alpha Soave_1979_a_alpha]<line_sep>
<import_stmt>tensorflow<as>tf<import_from_stmt>tensorflow.keras.layers Layer Conv3D LeakyReLU PReLU UpSampling3D MaxPooling3D Activation<import_from_stmt>tensorflow.keras.models Model<import_from_stmt>..utils.complex to_complex<import_from_stmt>..utils.fourier AdjNFFT<class_stmt>Conv(Layer)<block_start><def_stmt>__init__ self n_filters kernel_size=3 non_linearity='relu' **kwargs<block_start>super().__init__(**kwargs)<line_sep>self.n_filters=n_filters<line_sep>self.kernel_size=kernel_size<line_sep>self.non_linearity=non_linearity<line_sep>self.conv=Conv3D(filters=self.n_filters kernel_size=self.kernel_size padding='same' activation=<none> )<if_stmt>self.non_linearity<eq>'lrelu'<block_start>self.act=LeakyReLU(0.1)<block_end><elif_stmt>self.non_linearity<eq>'prelu'<block_start>self.act=PReLU(shared_axes=[1 2 3])<block_end><else_stmt><block_start>self.act=Activation(self.non_linearity)<block_end><block_end><def_stmt>call self inputs<block_start>outputs=self.conv(inputs)<line_sep>outputs=self.act(outputs)<line_sep><return>outputs<block_end><def_stmt>get_config self<block_start>config=super().get_config()<line_sep>config.update({'n_filters':self.n_filters 'kernel_size':self.kernel_size 'non_linearity':self.non_linearity })<line_sep><return>config<block_end><block_end><class_stmt>ConvBlock(Layer)<block_start><def_stmt>__init__ self n_filters kernel_size=3 non_linearity='relu' n_non_lins=2 **kwargs<block_start>super().__init__(**kwargs)<line_sep>self.n_filters=n_filters<line_sep>self.kernel_size=kernel_size<line_sep>self.non_linearity=non_linearity<line_sep>self.n_non_lins=n_non_lins<line_sep>self.convs=[Conv(n_filters=self.n_filters kernel_size=self.kernel_size non_linearity=self.non_linearity )<for>_ range(self.n_non_lins)]<block_end><def_stmt>call self inputs<block_start>outputs=inputs<for_stmt>conv self.convs<block_start>outputs=conv(outputs)<block_end><return>outputs<block_end><def_stmt>get_config self<block_start>config=super().get_config()<line_sep>config.update({'n_non_lins':self.n_non_lins 'n_filters':self.n_filters 'kernel_size':self.kernel_size 'non_linearity':self.non_linearity })<line_sep><return>config<block_end><block_end><class_stmt>UpConv(Layer)<block_start><def_stmt>__init__ self n_filters kernel_size=3 post_processing=<false> **kwargs<block_start>super().__init__(**kwargs)<line_sep>self.n_filters=n_filters<line_sep>self.kernel_size=kernel_size<line_sep>self.post_processing=post_processing<line_sep>self.conv=Conv3D(filters=self.n_filters kernel_size=self.kernel_size padding='same' activation=<none> )<line_sep>self.up=UpSampling3D(size=(1<if>self.post_processing<else>2 2 2))<block_end><def_stmt>call self inputs<block_start>outputs=self.up(inputs)<line_sep>outputs=self.conv(outputs)<line_sep><return>outputs<block_end><def_stmt>get_config self<block_start>config=super().get_config()<line_sep>config.update({'n_filters':self.n_filters 'kernel_size':self.kernel_size 'post_processing':self.post_processing })<line_sep><return>config<block_end><block_end><class_stmt>Vnet(Model)<block_start><def_stmt>__init__ self n_output_channels=1 kernel_size=3 layers_n_channels=[4] layers_n_non_lins=1 non_linearity='relu' post_processing=<false> res=<false> **kwargs <block_start>super().__init__(**kwargs)<line_sep>self.n_output_channels=n_output_channels<line_sep>self.kernel_size=kernel_size<line_sep>self.layers_n_channels=layers_n_channels<line_sep>self.n_layers=len(self.layers_n_channels)<line_sep>self.layers_n_non_lins=layers_n_non_lins<line_sep>self.non_linearity=non_linearity<line_sep>self.post_processing=post_processing<line_sep>self.res=res<line_sep>self.down_convs=[ConvBlock(n_filters=n_channels kernel_size=self.kernel_size non_linearity=self.non_linearity n_non_lins=self.layers_n_non_lins )<for>n_channels self.layers_n_channels[:-1]]<line_sep>self.down=MaxPooling3D(pool_size=(1<if>self.post_processing<else>2 2 2) padding='same' )<line_sep>self.bottom_conv=ConvBlock(n_filters=self.layers_n_channels[-1] kernel_size=self.kernel_size non_linearity=self.non_linearity n_non_lins=self.layers_n_non_lins )<line_sep>self.up_convs=[ConvBlock(n_filters=n_channels kernel_size=self.kernel_size non_linearity=self.non_linearity n_non_lins=self.layers_n_non_lins )<for>n_channels self.layers_n_channels[:-1]]<line_sep>self.ups=[UpConv(n_filters=n_channels kernel_size=self.kernel_size post_processing=self.post_processing )<for>n_channels self.layers_n_channels[:-1]]<line_sep>self.final_conv=Conv3D(filters=self.n_output_channels kernel_size=1 padding='same' activation=<none> )<block_end><def_stmt>call self inputs<block_start>scales=[]<line_sep>outputs=inputs<for_stmt>conv self.down_convs<block_start>outputs=conv(outputs)<line_sep>scales.append(outputs)<line_sep>outputs=self.down(outputs)<block_end>outputs=self.bottom_conv(outputs)<for_stmt>scale,conv,up zip(scales[::-1] self.up_convs[::-1] self.ups[::-1])<block_start>outputs=up(outputs)<line_sep>outputs=tf.concat([outputs scale] axis=-1)<line_sep>outputs=conv(outputs)<block_end>outputs=self.final_conv(outputs)<if_stmt>self.res<block_start>outputs=outputs+inputs<block_end><return>outputs<block_end><block_end><class_stmt>VnetComplex(Model)<block_start><def_stmt>__init__ self n_input_channels=1 n_output_channels=1 kernel_size=3 layers_n_channels=[4] layers_n_non_lins=1 res=<false> non_linearity='relu' dealiasing_nc=<false> im_size=<none> dcomp=<none> grad_traj=<false> **kwargs <block_start>super(VnetComplex self).__init__(**kwargs)<line_sep>self.n_input_channels=n_input_channels<line_sep>self.n_output_channels=n_output_channels<line_sep>self.kernel_size=kernel_size<line_sep>self.layers_n_channels=layers_n_channels<line_sep>self.layers_n_non_lins=layers_n_non_lins<line_sep>self.res=res<line_sep>self.non_linearity=non_linearity<line_sep>self.dealiasing_nc=dealiasing_nc<if_stmt>self.dealiasing_nc<block_start>self.adj_op=AdjNFFT(im_size=im_size multicoil=<false> density_compensation=dcomp grad_traj=grad_traj )<block_end>self.vnet=Vnet(n_output_channels=2<times>self.n_output_channels kernel_size=self.kernel_size layers_n_channels=self.layers_n_channels layers_n_non_lins=self.layers_n_non_lins non_linearity=self.non_linearity )<block_end><def_stmt>call self inputs<block_start><if_stmt>self.dealiasing_nc<block_start><if_stmt>len(inputs)<eq>2<block_start>original_kspace,mask=inputs<line_sep>op_args=()<block_end><else_stmt><block_start>original_kspace,mask,op_args=inputs<block_end>outputs=self.adj_op([original_kspace mask *op_args])<line_sep># we do this to match the residual part. inputs=outputs<block_end><else_stmt><block_start>outputs=inputs<block_end># NOTE: for now no padding in 3d case outputs=tf.concat([tf.math.real(outputs) tf.math.imag(outputs)] axis=-1)<line_sep>outputs=self.vnet(outputs)<line_sep>outputs=to_complex(outputs self.n_output_channels)<if_stmt>self.res<block_start>outputs=inputs[<ellipsis> :self.n_output_channels]+outputs<block_end><if_stmt>self.dealiasing_nc<block_start>outputs=tf.abs(outputs)<block_end><return>outputs<block_end><block_end>
<import_stmt>torch<import_stmt>numpy<as>np<import_from_stmt>onnx numpy_helper<import_from_stmt>thop.vision.basic_hooks zero_ops<import_from_stmt>.counter counter_matmul counter_zero_ops counter_conv counter_mul counter_norm counter_pow counter_sqrt counter_div counter_softmax counter_avgpool<def_stmt>onnx_counter_matmul diction node<block_start>input1=node.input[0]<line_sep>input2=node.input[1]<line_sep>input1_dim=diction[input1]<line_sep>input2_dim=diction[input2]<line_sep>out_size=np.append(input1_dim[0:-1] input2_dim[-1])<line_sep>output_name=node.output[0]<line_sep>macs=counter_matmul(input1_dim out_size[-2:])<line_sep><return>macs out_size output_name<block_end><def_stmt>onnx_counter_add diction node<block_start><if_stmt>np.array(diction[node.input[1]]).size<ge>np.array(diction[node.input[0]]).size<block_start>out_size=diction[node.input[1]]<block_end><else_stmt><block_start>out_size=diction[node.input[0]]<block_end>output_name=node.output[0]<line_sep>macs=counter_zero_ops()<line_sep># if '140' in diction: # print(diction['140'],output_name) <return>macs out_size output_name<block_end><def_stmt>onnx_counter_conv diction node# print(node) # bias,kernelsize,outputsize <block_start>dim_bias=0<line_sep>input_count=0<for_stmt>i node.input<block_start>input_count<augadd>1<block_end><if_stmt>(input_count<eq>3)<block_start>dim_bias=1<line_sep>dim_weight=diction[node.input[1]]<block_end><else_stmt><block_start>dim_weight=diction[node.input[1]]<block_end><for_stmt>attr node.attribute# print(attr) <block_start><if_stmt>(attr.name<eq>'kernel_shape')<block_start>dim_kernel=attr.ints# kw,kh <block_end><if_stmt>(attr.name<eq>'strides')<block_start>dim_stride=attr.ints<block_end><if_stmt>(attr.name<eq>'pads')<block_start>dim_pad=attr.ints<block_end><if_stmt>(attr.name<eq>'dilations')<block_start>dim_dil=attr.ints<block_end><if_stmt>(attr.name<eq>'group')<block_start>group=attr.i<line_sep># print(dim_dil) <block_end><block_end>dim_input=diction[node.input[0]]<line_sep>output_size=np.append(dim_input[0:-np.array(dim_kernel).size-1] dim_weight[0])<line_sep>hw=np.array(dim_input[-np.array(dim_kernel).size:])<for_stmt>i range(hw.size)<block_start>hw[i]=int((hw[i]+2<times>dim_pad[i]-dim_dil[i]<times>(dim_kernel[i]-1)-1)/dim_stride[i]+1)<block_end>output_size=np.append(output_size hw)<line_sep>macs=counter_conv(dim_bias np.prod(dim_kernel) np.prod(output_size) dim_weight[1] group)<line_sep>output_name=node.output[0]<line_sep># if '140' in diction: # print("conv",diction['140'],output_name) <return>macs output_size output_name<block_end><def_stmt>onnx_counter_constant diction node# print("constant",node) <block_start>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>output_size=[1]<line_sep>#print(macs, output_size, output_name) <return>macs output_size output_name<block_end><def_stmt>onnx_counter_mul diction node<block_start><if_stmt>np.array(diction[node.input[1]]).size<ge>np.array(diction[node.input[0]]).size<block_start>input_size=diction[node.input[1]]<block_end><else_stmt><block_start>input_size=diction[node.input[0]]<block_end>macs=counter_mul(np.prod(input_size))<line_sep>output_size=diction[node.input[0]]<line_sep>output_name=node.output[0]<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_bn diction node<block_start>input_size=diction[node.input[0]]<line_sep>macs=counter_norm(np.prod(input_size))<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_relu diction node<block_start>input_size=diction[node.input[0]]<line_sep>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep>#print(macs, output_size, output_name) # if '140' in diction: # print("relu",diction['140'],output_name) <return>macs output_size output_name<block_end><def_stmt>onnx_counter_reducemean diction node<block_start>keep_dim=0<for_stmt>attr node.attribute<block_start><if_stmt>('axes'<in>attr.name)<block_start>dim_axis=np.array(attr.ints)<block_end><elif_stmt>('keepdims'<in>attr.name)<block_start>keep_dim=attr.i<block_end><block_end>input_size=diction[node.input[0]]<line_sep>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<if_stmt>(keep_dim<eq>1)<block_start>output_size=input_size<block_end><else_stmt><block_start>output_size=np.delete(input_size dim_axis)<block_end>#output_size = input_size <return>macs output_size output_name<block_end><def_stmt>onnx_counter_sub diction node<block_start>input_size=diction[node.input[0]]<line_sep>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_pow diction node<block_start><if_stmt>np.array(diction[node.input[1]]).size<ge>np.array(diction[node.input[0]]).size<block_start>input_size=diction[node.input[1]]<block_end><else_stmt><block_start>input_size=diction[node.input[0]]<block_end>macs=counter_pow(np.prod(input_size))<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_sqrt diction node<block_start>input_size=diction[node.input[0]]<line_sep>macs=counter_sqrt(np.prod(input_size))<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_div diction node<block_start><if_stmt>np.array(diction[node.input[1]]).size<ge>np.array(diction[node.input[0]]).size<block_start>input_size=diction[node.input[1]]<block_end><else_stmt><block_start>input_size=diction[node.input[0]]<block_end>macs=counter_div(np.prod(input_size))<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_instance diction node<block_start>input_size=diction[node.input[0]]<line_sep>macs=counter_norm(np.prod(input_size))<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_softmax diction node<block_start>input_size=diction[node.input[0]]<line_sep>dim=node.attribute[0].i<line_sep>nfeatures=input_size[dim]<line_sep>batch_size=np.prod(input_size)/nfeatures<line_sep>macs=counter_softmax(nfeatures batch_size)<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_pad diction node# # TODO add constant name and output real vector # if # if (np.array(diction[node.input[1]]).size >= np.array(diction[node.input[0]]).size): # input_size = diction[node.input[1]] # else: # input_size = diction[node.input[0]] <block_start>input_size=diction[node.input[0]]<line_sep>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_averagepool diction node# TODO add support of ceil_mode and floor <block_start>macs=counter_avgpool(np.prod(diction[node.input[0]]))<line_sep>output_name=node.output[0]<line_sep>dim_pad=<none><for_stmt>attr node.attribute# print(attr) <block_start><if_stmt>(attr.name<eq>'kernel_shape')<block_start>dim_kernel=attr.ints# kw,kh <block_end><elif_stmt>(attr.name<eq>'strides')<block_start>dim_stride=attr.ints<block_end><elif_stmt>(attr.name<eq>'pads')<block_start>dim_pad=attr.ints<block_end><elif_stmt>(attr.name<eq>'dilations')<block_start>dim_dil=attr.ints<line_sep># print(dim_dil) <block_end><block_end>dim_input=diction[node.input[0]]<line_sep>hw=dim_input[-np.array(dim_kernel).size:]<if_stmt>dim_pad<is><not><none><block_start><for_stmt>i range(hw.size)<block_start>hw[i]=int((hw[i]+2<times>dim_pad[i]-dim_kernel[i])/dim_stride[i]+1)<block_end>output_size=np.append(dim_input[0:-np.array(dim_kernel).size] hw)<block_end><else_stmt><block_start><for_stmt>i range(hw.size)<block_start>hw[i]=int((hw[i]-dim_kernel[i])/dim_stride[i]+1)<block_end>output_size=np.append(dim_input[0:-np.array(dim_kernel).size] hw)<block_end>#print(macs, output_size, output_name) <return>macs output_size output_name<block_end><def_stmt>onnx_counter_flatten diction node# print(node) <block_start>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>axis=node.attribute[0].i<line_sep>input_size=diction[node.input[0]]<line_sep>output_size=np.append(input_size[axis-1] np.prod(input_size[axis:]))<line_sep># print("flatten",output_size) <return>macs output_size output_name<block_end><def_stmt>onnx_counter_gemm diction node# print(node) # Compute Y = alpha * A' * B' + beta * C <block_start>input_size=diction[node.input[0]]<line_sep>dim_weight=diction[node.input[1]]<line_sep># print(input_size,dim_weight) macs=np.prod(input_size)<times>dim_weight[1]+dim_weight[0]<line_sep>output_size=np.append(input_size[0:-1] dim_weight[0])<line_sep>output_name=node.output[0]<line_sep><return>macs output_size output_name<line_sep><pass><block_end><def_stmt>onnx_counter_maxpool diction node# TODO add support of ceil_mode and floor # print(node) <block_start>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>dim_pad=<none><for_stmt>attr node.attribute# print(attr) <block_start><if_stmt>(attr.name<eq>'kernel_shape')<block_start>dim_kernel=attr.ints# kw,kh <block_end><elif_stmt>(attr.name<eq>'strides')<block_start>dim_stride=attr.ints<block_end><elif_stmt>(attr.name<eq>'pads')<block_start>dim_pad=attr.ints<block_end><elif_stmt>(attr.name<eq>'dilations')<block_start>dim_dil=attr.ints<line_sep># print(dim_dil) <block_end><block_end>dim_input=diction[node.input[0]]<line_sep>hw=dim_input[-np.array(dim_kernel).size:]<if_stmt>dim_pad<is><not><none><block_start><for_stmt>i range(hw.size)<block_start>hw[i]=int((hw[i]+2<times>dim_pad[i]-dim_kernel[i])/dim_stride[i]+1)<block_end>output_size=np.append(dim_input[0:-np.array(dim_kernel).size] hw)<block_end><else_stmt><block_start><for_stmt>i range(hw.size)<block_start>hw[i]=int((hw[i]-dim_kernel[i])/dim_stride[i]+1)<block_end>output_size=np.append(dim_input[0:-np.array(dim_kernel).size] hw)<block_end>#print(macs, output_size, output_name) <return>macs output_size output_name<block_end><def_stmt>onnx_counter_globalaveragepool diction node<block_start>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>input_size=diction[node.input[0]]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_concat diction node# print(node) # print(diction[node.input[0]]) <block_start>axis=node.attribute[0].i<line_sep>input_size=diction[node.input[0]]<for_stmt>i node.input<block_start>dim_concat=diction[i][axis]<block_end>output_size=input_size<line_sep>output_size[axis]=dim_concat<line_sep>output_name=node.output[0]<line_sep>macs=counter_zero_ops()<line_sep><return>macs output_size output_name<block_end><def_stmt>onnx_counter_clip diction node<block_start>macs=counter_zero_ops()<line_sep>output_name=node.output[0]<line_sep>input_size=diction[node.input[0]]<line_sep>output_size=input_size<line_sep><return>macs output_size output_name<block_end>onnx_operators={'MatMul':onnx_counter_matmul 'Add':onnx_counter_add 'Conv':onnx_counter_conv 'Mul':onnx_counter_mul 'Constant':onnx_counter_constant 'BatchNormalization':onnx_counter_bn 'Relu':onnx_counter_relu 'ReduceMean':onnx_counter_reducemean 'Sub':onnx_counter_sub 'Pow':onnx_counter_pow 'Sqrt':onnx_counter_sqrt 'Div':onnx_counter_div 'InstanceNormalization':onnx_counter_instance 'Softmax':onnx_counter_softmax 'Pad':onnx_counter_pad 'AveragePool':onnx_counter_averagepool 'MaxPool':onnx_counter_maxpool 'Flatten':onnx_counter_flatten 'Gemm':onnx_counter_gemm 'GlobalAveragePool':onnx_counter_globalaveragepool 'Concat':onnx_counter_concat 'Clip':onnx_counter_clip <none>:<none> }<line_sep>
""" Predicts outputs of the MySQL 'rand' function. For example, mysql> CREATE TABLE t (i INT); mysql> INSERT INTO t VALUES(1),(2),(3); mysql> SELECT i, RAND() FROM t; +------+------------------+ | i | RAND() | +------+------------------+ | 1 | 0.61914388706828 | | 2 | 0.93845168309142 | | 3 | 0.83482678498591 | +------+------------------+ Given "0.61914388706828" and "0.93845168309142", this module `from_outputs` would yield "0.83482678498591". """<import_from_stmt>ctypes c_uint32<line_sep>__all__=["from_outputs" "from_seed"]<def_stmt>predict_state values<block_start>values=[int(round(v<times>0x3FFFFFFF 0))<for>v values]<line_sep>seed1=values[0]<line_sep>seed2=(values[1]-seed1<times>3)%0x3FFFFFFF<line_sep><return>[seed1 seed2]<block_end><def_stmt>generate_values state# from password.c # max_value = 0x3FFFFFFFL # max_value_dbl=(double) rand_st->max_value; # from my_rnd.cc # rand_st->seed1= (rand_st->seed1*3+rand_st->seed2) % rand_st->max_value; # rand_st->seed2= (rand_st->seed1+rand_st->seed2+33) % rand_st->max_value; # return (((double) rand_st->seed1) / rand_st->max_value_dbl); <block_start>seed1,seed2=state<while_stmt><true><block_start>seed1=(seed1<times>3+seed2)%0x3FFFFFFF<line_sep>seed2=(seed1+seed2+33)%0x3FFFFFFF<line_sep><yield>seed1/0x3FFFFFFF<block_end><block_end><def_stmt>from_outputs prev_values<block_start>state=predict_state(prev_values)<line_sep>gen=generate_values(state)<line_sep># only 2 values are needed, so advance past any others we were given <for_stmt>_ prev_values[1:]<block_start>next(gen)<block_end><yield><from>gen<block_end><def_stmt>from_seed seed<block_start>seed1=c_uint32(seed<times>0x10001+55555555).value<line_sep>seed2=c_uint32(seed<times>0x10000001).value<line_sep><yield><from>generate_values([seed1 seed2])<block_end>
<import_stmt>os<import_stmt>urllib.error<import_stmt>urllib.request<import_from_stmt>tempfile NamedTemporaryFile<import_stmt>pytest<import_stmt>genomepy.online<import_from_stmt>tests linux travis<def_stmt>test_download_file # HTTP <block_start>tmp=NamedTemporaryFile().name<assert_stmt><not>os.path.exists(tmp)<line_sep>url="http://hgdownload.soe.ucsc.edu/goldenPath/ailMel1/bigZips/md5sum.txt"<line_sep>genomepy.online.download_file(url tmp)<assert_stmt>os.path.exists(tmp)<line_sep># FTP (doesn't work on Travis-Linux) <if_stmt><not>(travis<and>linux)<block_start>tmp=NamedTemporaryFile().name<assert_stmt><not>os.path.exists(tmp)<line_sep>url="ftp://ftp.ncbi.nlm.nih.gov//genomes/all/GCF/000/027/325/GCF_000027325.1_ASM2732v1/README.txt"<line_sep>genomepy.online.download_file(url tmp)<assert_stmt>os.path.exists(tmp)<block_end><block_end><def_stmt>test_connect_ftp_link <block_start><if_stmt><not>(travis<and>linux)# (doesn't work on Travis-Linux) # good FTP host <block_start>ftp_link="ftp://ftp.ncbi.nlm.nih.gov/genomes/README.txt"<line_sep>ftp,target=genomepy.online.connect_ftp_link(ftp_link)<assert_stmt>target<eq>"/genomes/README.txt"<line_sep>result=ftp.nlst(target)<line_sep>ftp.quit()# logout <assert_stmt>result<eq>[target]<line_sep># bad FTP host <with_stmt>pytest.raises(genomepy.exceptions.GenomeDownloadError)<block_start>genomepy.online.connect_ftp_link("ftp://not.an.ftp/at/all")<block_end><block_end><block_end><def_stmt>test_read_url url="http://ftp.xenbase.org/pub/Genomics/JGI/README" expected="The data"<block_start>text=genomepy.online.read_url(url)<assert_stmt>text.startswith(expected)<block_end><def_stmt>test_retry capsys# runs passed function <block_start>txt="hello world"<line_sep>genomepy.online.retry(print 1 txt)<line_sep>captured=capsys.readouterr().out.strip()<assert_stmt>captured<eq>txt<line_sep># handles URLErrors <def_stmt>_offline_func <block_start><raise>urllib.error.URLError("this function is offline")<block_end><assert_stmt>genomepy.online.retry(_offline_func 1)<is><none><block_end><def_stmt>test_check_url # good URL <block_start><assert_stmt>genomepy.online.check_url("http://ftp.xenbase.org/pub/Genomics/JGI/README")<line_sep># bad URL: <assert_stmt><not>genomepy.online.check_url("https://www.thiswebsiteisoffline.nl/")<if_stmt><not>(travis<and>linux)# (doesn't work on Travis-Linux) # good FTP <block_start>ftp_link=("ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/027/325/"<concat>"GCF_000027325.1_ASM2732v1/GCF_000027325.1_ASM2732v1_genomic.gff.gz")<assert_stmt>genomepy.online.check_url(ftp_link)<line_sep># bad FTP target <assert_stmt><not>genomepy.online.check_url("ftp://ftp.ncbi.nlm.nih.gov/bad_target")<block_end><block_end>
<import_from_stmt>torch nn<class_stmt>FeedForwardNet(nn.Module)<block_start><def_stmt>__init__ self inp_dim hidden_dim outp_dim n_layers nonlinearity dropout=0<block_start>super().__init__()<line_sep>layers=[]<line_sep>d_in=inp_dim<for_stmt>i range(n_layers)<block_start>module=nn.Linear(d_in hidden_dim)<line_sep>self.reset_parameters(module)<line_sep>layers.append(module)<if_stmt>dropout<g>0<block_start>layers.append(nn.Dropout(dropout))<block_end><if_stmt>nonlinearity<eq>'relu'<block_start>nonlin=nn.ReLU(inplace=<true>)<block_end><elif_stmt>nonlinearity<eq>'tanh'<block_start>nonlin=nn.Tanh()<block_end><elif_stmt>nonlinearity<eq>'elu'<block_start>nonlin=nn.ELU(inplace=<true>)<block_end><elif_stmt>nonlinearity<ne>'none'<block_start><raise>NotImplementedError('only relu, tanh, and elu nonlinearities have been implemented')<block_end><if_stmt>nonlinearity<ne>'none'<block_start>layers.append(nonlin)<block_end>d_in=hidden_dim<block_end>module=nn.Linear(d_in outp_dim)<line_sep>self.reset_parameters(module)<line_sep>layers.append(module)<line_sep>self.network=nn.Sequential(*layers)<block_end><def_stmt>reset_parameters self module<block_start>init_range=0.07<line_sep>module.weight.data.uniform_(-init_range init_range)<line_sep>module.bias.data.zero_()<block_end><def_stmt>forward self x<block_start><return>self.network(x)<block_end><block_end>
<import_from_stmt>toga_winforms.libs WinForms<import_from_stmt>.base Widget<class_stmt>Tree(Widget)<block_start><def_stmt>create self<block_start>self.native=WinForms.TreeView()<block_end><def_stmt>row_data self item<block_start>self.interface.factory.not_implemented('Tree.row_data()')<block_end><def_stmt>on_select self selection<block_start>self.interface.factory.not_implemented('Tree.on_select()')<block_end><def_stmt>change_source self source<block_start>self.interface.factory.not_implemented('Tree.change_source()')<block_end><def_stmt>insert self parent index item<block_start>self.interface.factory.not_implemented('Tree.insert()')<block_end><def_stmt>change self item<block_start>self.interface.factory.not_implemented('Tree.change()')<block_end><def_stmt>remove self parent index item<block_start>self.interface.factory.not_implemented('Tree.remove()')<block_end><def_stmt>clear self<block_start>self.interface.factory.not_implemented('Tree.clear()')<block_end><def_stmt>get_selection self<block_start>self.interface.factory.not_implemented('Tree.get_selection()')<block_end><def_stmt>set_on_select self handler<block_start>self.interface.factory.not_implemented('Tree.set_on_select()')<block_end><def_stmt>set_on_double_click self handler<block_start>self.interface.factory.not_implemented('Table.set_on_double_click()')<block_end><def_stmt>scroll_to_node self node<block_start>self.interface.factory.not_implemented('Tree.scroll_to_node()')<block_end><block_end>
# -*- coding:utf-8 -*- # # Tencent is pleased to support the open source community by making QTA available. # Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); you may not use this # file except in compliance with the License. You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific language # governing permissions and limitations under the License. # '''RPC Server Host Driver '''<import_from_future_stmt> absolute_import print_function<import_stmt>os<import_stmt>base64<import_stmt>six<import_from_stmt>qt4i.driver.rpc rpc_method<import_from_stmt>qt4i.driver.rpc RPCEndpoint<import_from_stmt>qt4i.driver.tools.dt DT<import_from_stmt>qt4i.driver.xctest.agent XCUITestAgentManager<line_sep>BUFFER_SIZE=1024<times>1024<times>100<class_stmt>RPCServerHost(RPCEndpoint)<block_start>"""RPC Server Host API """<line_sep>agent_manager=XCUITestAgentManager()<def_stmt>__init__ self rpc_server<block_start>self.rpc_server=rpc_server<line_sep>RPCEndpoint.__init__(self)<block_end>@rpc_method<def_stmt>pull_file_data self filepath seek_index buffer_size=BUFFER_SIZE<block_start>'''copy file from rpc server :param filepath: file path of rpc server :type filename: str :returns: six.xmlrpc_client.Binary '''<if_stmt>os.path.exists(filepath)<block_start><with_stmt>open(filepath "rb")<as>fd<block_start>seek=seek_index<times>buffer_size<if_stmt>seek<le>os.path.getsize(filepath)<block_start>fd.seek(seek)<line_sep>data=base64.b64encode(fd.read(buffer_size))<line_sep><return>data<block_end><return><none><block_end><block_end><else_stmt><block_start><raise>Exception('file(%s) does not exist'%filepath)<block_end><block_end>@rpc_method<def_stmt>push_file_data self data file_path override=<true><block_start>'''push file to rpc server :param data: str :param file_path: str :param override: boolean :return: boolean '''<if_stmt>os.path.exists(file_path)<and>override<block_start>os.remove(file_path)<block_end><with_stmt>open(file_path "ab")<as>fd<block_start><if_stmt>six.PY3<and>isinstance(data six.string_types)<block_start>data=data.encode('utf-8')<line_sep>fd.write(base64.decodebytes(data))<block_end><else_stmt><block_start>fd.write(base64.decodestring(data))<block_end><block_end><return>os.path.isfile(file_path)<block_end>@rpc_method<def_stmt>list_devices self<block_start>'''list all devices of rpc server host :return: list '''<line_sep><return>DT().get_devices()<block_end>@rpc_method<def_stmt>list_real_devices self<block_start>'''list all real iOS devices of rpc server host :returns: list '''<line_sep><return>DT().get_real_devices()<block_end>@rpc_method<def_stmt>list_simulators self<block_start>'''list all iOS simulators of rpc server host :returns: list '''<line_sep><return>DT().get_simulators()<block_end>@rpc_method<def_stmt>start_simulator self udid=<none><block_start>'''start iOS simulator of rpc server host :param udid: udid of iOS simulator :type udid: str :returns: boolean '''<line_sep><return>DT().start_simulator(udid)<block_end>@rpc_method<def_stmt>get_device_by_udid self udid<block_start>'''inquire device by udid :param udid: udid of device :type udid: str :returns: dict or None '''<line_sep><return>DT().get_device_by_udid(udid)<block_end>@rpc_method<def_stmt>echo self<block_start>'''test xmlrpc server started :returns: boolean '''<line_sep><return><true><block_end>@rpc_method<def_stmt>stop_all_agents self<block_start>''' stop all agents '''<line_sep>XCUITestAgentManager.stop_all_agents()<block_end><block_end>
<import_from_stmt>math isnan<import_from_stmt>datetime datetime<import_stmt>sys<import_stmt>accelerator<import_from_stmt>accelerator.test_methods test_data<line_sep>options=dict(n=int now=datetime)<line_sep>jobs=('source' )<line_sep>nanmarker=object()<def_stmt>nanfix values<block_start><def_stmt>fix v<block_start><if_stmt>isinstance(v float)<and>isnan(v)<block_start><return>nanmarker<block_end><else_stmt><block_start><return>v<block_end><block_end><return>list(map(fix values))<block_end><def_stmt>prepare <block_start>data=jobs.source.load()<assert_stmt>data['now']<eq>options.now<if_stmt>data['py_version']<eq>2<block_start><assert_stmt>data['blaa']<eq>u'bl\xe5'.encode('utf-8')<block_end><else_stmt><block_start><assert_stmt>data['blaa']<eq>u'bl\xe5'<block_end><block_end><def_stmt>analysis sliceno<block_start>good=test_data.sort_data_for_slice(sliceno)<for_stmt>lineno,got enumerate(jobs.source.dataset().iterate(sliceno))<block_start>want=next(good)<assert_stmt>nanfix(want)<eq>nanfix(got) "Wanted:\n%r\nbut got:\n%r\non line %d in slice %d of %s"%(want got lineno sliceno jobs.source)<block_end>left_over=len(list(good))<assert_stmt>left_over<eq>0 "Slice %d of %s missing %d lines"%(sliceno jobs.source left_over )<if_stmt>jobs.source.load()['py_version']<g>2<and>sys.version_info[0]<g>2<block_start><assert_stmt>list(jobs.source.dataset('pickle').iterate(sliceno 'p'))<eq>[{'sliceno':sliceno}]<block_end><block_end><def_stmt>synthesis job<block_start>p=jobs.source.params<assert_stmt>p.versions.accelerator<eq>accelerator.__version__<with_stmt>job.open_input('proj/accelerator.conf')<as>fh<block_start><for_stmt>line fh<block_start><if_stmt>line.startswith('interpreters: p%d '%(options.n ))<block_start>path=line.split(' ' 2)[2].strip()[1:-1]<line_sep><break><block_end><block_end><else_stmt><block_start><raise>Exception('Failed to find interpreter #%d in accelerator.conf'%(options.n ))<block_end><block_end><assert_stmt>p.versions.python_path<eq>path<block_end>
''' Spam predictor pip install -U scikit-learn X are the data features y are the labels [ 0, 0, 1 ...] Download the enron database for testing http://www2.aueb.gr/users/ion/data/enron-spam/ Should work on any of the datasets: seq 1 6 | parallel -j 1 wget -q -nc http://www.aueb.gr/users/ion/data/enron-spam/preprocessed/enron{}.tar.gz '''<import_stmt>logging<import_stmt>sys os<import_stmt>plac<import_from_stmt>joblib dump load<line_sep>logger=logging.getLogger("engine")<try_stmt><block_start><import_from_stmt>sklearn.feature_extraction.text CountVectorizer<import_from_stmt>sklearn.metrics classification_report<import_from_stmt>sklearn.model_selection train_test_split<import_from_stmt>sklearn.naive_bayes MultinomialNB<import_from_stmt>sklearn.pipeline make_pipeline<line_sep>has_sklearn=<true><block_end><except_stmt>ImportError<as>exc<block_start>logger.error("sklearn not installed, no predictions are generated")<line_sep>has_sklearn=<false><block_end><def_stmt>load_model model="spam.model"<block_start>nb=load(model)<line_sep><return>nb<block_end><def_stmt>classify_content content model<block_start>""" Classify content """<if_stmt><not>has_sklearn<block_start><return>0<block_end><try_stmt><block_start>nb=load_model(model)<line_sep>y_pred=nb.predict([content])<block_end><except_stmt>Exception<as>exc<block_start>logger.error(exc)<line_sep>y_pred=[0]<block_end><return>y_pred[0]<block_end><def_stmt>fit_model X y<block_start>nb=make_pipeline(CountVectorizer() MultinomialNB() # LinearSVC(), # RandomForestClassifier(), )<line_sep>nb.fit(X y)<line_sep><return>nb<block_end><def_stmt>evaluate_model fname model<block_start>X,y=parse_file(fname=fname)<line_sep>X_train,X_test,y_train,y_test=train_test_split(X y)<if_stmt>model<block_start>nb=load_model(model)<block_end><else_stmt><block_start>nb=fit_model(X_train y_train)<block_end>y_pred=nb.predict(X_test)<line_sep>rep=classification_report(y_test y_pred)<line_sep>print(rep)<block_end><def_stmt>parse_file fname<block_start><import_stmt>tarfile<line_sep># Take filename from command line tar=tarfile.open(name=fname mode='r:gz' fileobj=<none>)<line_sep>elems=filter(<lambda>t:t.isreg() tar)<line_sep>X,y=[] []<for_stmt>info elems# Fill in the labels <block_start>y.append(int("spam"<in>info.name))<line_sep>stream=tar.extractfile(info)<line_sep>content=stream.read().decode("utf-8" errors="ignore")<line_sep>X.append(content)<block_end>spam_count=sum(filter(<none> y))<line_sep>ham_count=len(y)-spam_count<line_sep>logger.info(f"parsed: {ham_count} ham, {spam_count} spam")<line_sep><return>X y<block_end><def_stmt>build_model fname model<block_start>''' wget -nc http://www.aueb.gr/users/ion/data/enron-spam/preprocessed/enron1.tar.gz '''<line_sep># Generate features. X,y=parse_file(fname)<line_sep># Fits the model. nb=fit_model(X y)<line_sep>logger.info(f"fitted model to: {fname}")<line_sep># Save the model. <if_stmt>model<block_start>logger.info(f"saving model to: {model}")<line_sep>dump(nb model)<block_end><return>nb<line_sep># evaluate_model(X, y, model=model) <block_end>@plac.pos('fname')@plac.flg('build')@plac.flg('eval_' help="evaluate model ")@plac.opt('model')@plac.flg('classify')<def_stmt>main classify build model eval_ fname<block_start><if_stmt>build<block_start>build_model(fname=fname model=model)<block_end><if_stmt>eval_<block_start>evaluate_model(fname=fname model=model)<block_end><if_stmt>classify<block_start>content=open(fname 'rt').read()<line_sep>res=classify_content(content=content model=model)<line_sep>print("spam"<if>res<else>"ham")<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>logging.basicConfig(level=logging.DEBUG)<line_sep>plac.call(main)<block_end>
# -*- coding: utf-8 -*- """Falcon request argument parsing module. """<import_stmt>falcon<import_from_stmt>webargs core<line_sep>HTTP_422='422 Unprocessable entity'<def_stmt>parse_json_body req<block_start><if_stmt>req.content_length<in>(<none> 0)# Nothing to do <block_start><return>{}<block_end>content_type=req.get_header('Content-Type')<if_stmt>content_type<and>'application/json'<in>content_type<block_start>body=req.stream.read()<if_stmt>body<block_start><try_stmt><block_start><return>core.parse_json(body)<block_end><except_stmt>(TypeError ValueError)<block_start><pass><block_end><block_end><block_end><return>{}<block_end><class_stmt>HTTPError(falcon.HTTPError)<block_start>"""HTTPError that stores a dictionary of validation error messages. """<def_stmt>__init__ self status errors *args **kwargs<block_start>self.errors=errors<line_sep>super(HTTPError self).__init__(status *args **kwargs)<block_end><def_stmt>to_dict self *args **kwargs<block_start>"""Override `falcon.HTTPError` to include error messages in responses."""<line_sep>ret=super(HTTPError self).to_dict(*args **kwargs)<if_stmt>self.errors<is><not><none><block_start>ret['errors']=self.errors<block_end><return>ret<block_end><block_end><class_stmt>FalconParser(core.Parser)<block_start>"""Falcon request argument parser."""<def_stmt>parse_querystring self req name field<block_start>"""Pull a querystring value from the request."""<line_sep><return>core.get_value(req.params name field)<block_end><def_stmt>parse_form self req name field<block_start>"""Pull a form value from the request."""<line_sep><return>core.get_value(req.params name field)<block_end><def_stmt>parse_json self req name field<block_start>"""Pull a JSON body value from the request."""<line_sep>json_body=self._cache.get('json')<if_stmt>json_body<is><none><block_start>self._cache['json']=json_body=parse_json_body(req)<block_end><return>core.get_value(json_body name field)<block_end><def_stmt>parse_headers self req name field<block_start>"""Pull a header value from the request."""<line_sep># Use req.get_headers rather than req.headers for performance <return>req.get_header(name required=<false>)<or>core.missing<block_end><def_stmt>parse_cookies self req name field<block_start>"""Pull a cookie value from the request."""<line_sep>cookies=self._cache.get('cookies')<if_stmt>cookies<is><none><block_start>self._cache['cookies']=cookies=req.cookies<block_end><return>core.get_value(cookies name field)<block_end><def_stmt>get_request_from_view_args self view args kwargs<block_start>"""Get request from a resource method's arguments. Assumes that request is the second argument. """<line_sep>req=args[1]<assert_stmt>isinstance(req falcon.Request) 'Argument is not a falcon.Request'<line_sep><return>req<block_end><def_stmt>parse_files self req name field<block_start><raise>NotImplementedError('Parsing files not yet supported by {0}'.format(self.__class__.__name__))<block_end><def_stmt>handle_error self error<block_start>"""Handles errors during parsing."""<line_sep><raise>HTTPError(HTTP_422 errors=error.messages)<block_end><block_end>parser=FalconParser()<line_sep>use_args=parser.use_args<line_sep>use_kwargs=parser.use_kwargs<line_sep>
# generated by generate-protocol-files <import_from_stmt>.airbyte_protocol *<line_sep>
<import_from_stmt>dataclasses dataclass<import_from_stmt>apischema.json_schema deserialization_schema<line_sep>@dataclass<class_stmt>Bar<block_start>baz:str<block_end>@dataclass<class_stmt>Foo<block_start>bar1:Bar<line_sep>bar2:Bar<block_end><assert_stmt>deserialization_schema(Foo all_refs=<false>)<eq>{"$schema":"http://json-schema.org/draft/2020-12/schema#" "$defs":{"Bar":{"additionalProperties":<false> "properties":{"baz":{"type":"string"}} "required":["baz"] "type":"object" }} "additionalProperties":<false> "properties":{"bar1":{"$ref":"#/$defs/Bar"} "bar2":{"$ref":"#/$defs/Bar"}} "required":["bar1" "bar2"] "type":"object" }<assert_stmt>deserialization_schema(Foo all_refs=<true>)<eq>{"$schema":"http://json-schema.org/draft/2020-12/schema#" "$defs":{"Bar":{"additionalProperties":<false> "properties":{"baz":{"type":"string"}} "required":["baz"] "type":"object" } "Foo":{"additionalProperties":<false> "properties":{"bar1":{"$ref":"#/$defs/Bar"} "bar2":{"$ref":"#/$defs/Bar"} } "required":["bar1" "bar2"] "type":"object" } } "$ref":"#/$defs/Foo" }<line_sep>
<import_stmt>numpy<as>np<def_stmt>prefix_search mat:np.ndarray chars:str<arrow>str<block_start>"""Prefix search decoding. See dissertation of Graves, p63-66. Args: mat: Output of neural network of shape TxC. chars: The set of characters the neural network can recognize, excluding the CTC-blank. Returns: The decoded text. """<line_sep>blank_idx=len(chars)<line_sep>max_T,max_C=mat.shape<line_sep># g_n and g_b: gamma in paper g_n=[]<line_sep>g_b=[]<line_sep># p(y|x) and p(y...|x), where y is a prefix (not p as in paper to avoid confusion with probability) prob={}<line_sep>prob_ext={}<line_sep># Init: 1-6 <for_stmt>t range(max_T)<block_start>g_n.append({'':0})<line_sep>last=g_b[t-1]['']<if>t<g>0<else>1<line_sep>g_b.append({'':last<times>mat[t blank_idx]})<block_end># init for empty prefix prob['']=g_b[max_T-1]['']<line_sep>prob_ext['']=1-prob['']<line_sep>l_star=y_star=''<line_sep>Y={''}<line_sep># Algorithm: 8-31 <while_stmt>prob_ext[y_star]<g>prob[l_star]<block_start>prob_remaining=prob_ext[y_star]<line_sep># for all chars <for_stmt>k range(max_C-1)<block_start>y=y_star+chars[k]<line_sep>g_n[0][y]=mat[0 k]<if>len(y_star)<eq>0<else>0<line_sep>g_b[0][y]=0<line_sep>prefix_prob=g_n[0][y]<line_sep># for all time steps <for_stmt>t range(1 max_T)<block_start>new_label_prob=g_b[t-1][y_star]+(0<if>y_star<ne>''<and>y_star[-1]<eq>chars[k]<else>g_n[t-1][y_star])<line_sep>g_n[t][y]=mat[t k]<times>(new_label_prob+g_n[t-1][y])<line_sep>g_b[t][y]=mat[t blank_idx]<times>(g_b[t-1][y]+g_n[t-1][y])<line_sep>prefix_prob<augadd>mat[t k]<times>new_label_prob<block_end>prob[y]=g_n[max_T-1][y]+g_b[max_T-1][y]<line_sep>prob_ext[y]=prefix_prob-prob[y]<line_sep>prob_remaining<augsub>prob_ext[y]<if_stmt>prob[y]<g>prob[l_star]<block_start>l_star=y<block_end><if_stmt>prob_ext[y]<g>prob[l_star]<block_start>Y.add(y)<block_end><if_stmt>prob_remaining<le>prob[l_star]<block_start><break><block_end><block_end># 30 Y.remove(y_star)<line_sep># 31 best_y=<none><line_sep>best_prob_ext=0<for_stmt>y Y<block_start><if_stmt>prob_ext[y]<g>best_prob_ext<block_start>best_prob_ext=prob_ext[y]<line_sep>best_y=y<block_end><block_end>y_star=best_y<line_sep># terminate if no more prefix exists <if_stmt>best_y<is><none><block_start><break><block_end><block_end># Termination: 33-34 <return>l_star<block_end><def_stmt>prefix_search_heuristic_split mat:np.ndarray chars:str<arrow>str<block_start>"""Prefix search decoding with heuristic to speed up the algorithm. Speed up prefix computation by splitting sequence into subsequences as described by Graves (p66). Args: mat: Output of neural network of shape TxC. chars: The set of characters the neural network can recognize, excluding the CTC-blank. Returns: The decoded text. """<line_sep>blank_idx=len(chars)<line_sep>max_T,_=mat.shape<line_sep># split sequence into 3 subsequences, splitting points should be roughly placed at 1/3 and 2/3 split_targets=[int(max_T<times>1/3) int(max_T<times>2/3)]<line_sep>best=[{'target':s 'bestDist':max_T 'bestIdx':s}<for>s split_targets]<line_sep># find good splitting points (blanks above threshold) thres=0.9<for_stmt>t range(max_T)<block_start><for_stmt>b best<block_start><if_stmt>mat[t blank_idx]<g>thres<and>abs(t-b['target'])<l>b['bestDist']<block_start>b['bestDist']=abs(t-b['target'])<line_sep>b['bestIdx']=t<line_sep><break><block_end><block_end><block_end># splitting points plus begin and end of sequence ranges=[0]+[b['bestIdx']<for>b best]+[max_T]<line_sep># do prefix search for each subsequence and concatenate results res=''<for_stmt>i range(len(ranges)-1)<block_start>beg=ranges[i]<line_sep>end=ranges[i+1]<line_sep>res<augadd>prefix_search(mat[beg:end :] chars)<block_end><return>res<block_end>
# Copyright 2022 Google. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Summarization datasets."""<import_stmt>functools<import_from_stmt>prompt_tuning.spot.data preprocessors<as>spot_preprocessors<import_stmt>seqio<import_from_stmt>t5.data tasks<as>t5_tasks<import_from_stmt>t5.evaluation metrics<as>t5_metrics<line_sep>TaskRegistry=seqio.TaskRegistry<line_sep>MixtureRegistry=seqio.MixtureRegistry<line_sep>DATASETS={'anli_r1':{'tfds_name':'anli/r1:0.1.0' 'text_a_key':'hypothesis' 'text_b_key':'context' 'label_names':['entailment' 'neutral' 'contradiction'] } 'anli_r2':{'tfds_name':'anli/r2:0.1.0' 'text_a_key':'hypothesis' 'text_b_key':'context' 'label_names':['entailment' 'neutral' 'contradiction'] } 'anli_r3':{'tfds_name':'anli/r3:0.1.0' 'text_a_key':'hypothesis' 'text_b_key':'context' 'label_names':['entailment' 'neutral' 'contradiction'] } 'doc_nli':{'tfds_name':'doc_nli:1.0.0' 'text_a_key':'hypothesis' 'text_b_key':'premise' 'label_names':['not_entailment' 'entailment'] } 'snli':{'tfds_name':'snli:1.1.0' 'text_a_key':'hypothesis' 'text_b_key':'premise' 'label_names':['entailment' 'neutral' 'contradiction'] } }<line_sep># Register datasets <for_stmt>dataset DATASETS<block_start>version=f"v{DATASETS[dataset]['tfds_name'].split(':')[-1].replace('.' '')}"<line_sep>TaskRegistry.add(f'spot_{dataset.lower()}_{version}' source=seqio.TfdsDataSource(tfds_name=DATASETS[dataset]['tfds_name']) preprocessors=[functools.partial(spot_preprocessors.preprocess_text_classification text_a_key=DATASETS[dataset]['text_a_key'] text_b_key=DATASETS[dataset]['text_b_key'] task_name=dataset label_names=DATASETS[dataset]['label_names']) seqio.preprocessors.tokenize seqio.CacheDatasetPlaceholder() seqio.preprocessors.append_eos_after_trim ] metric_fns=[t5_metrics.accuracy] output_features=t5_tasks.DEFAULT_OUTPUT_FEATURES)<block_end>
"""Blockly Games: Legacy Reddit to Turtle/Movie router. Copyright 2014 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """<line_sep>"""Blockly Games used to use Reddit as a gallery. These URLs still exist. """<line_sep>__author__="<EMAIL> (<NAME>)"<import_stmt>os<import_stmt>re<line_sep>app=re.search(r"(\w+)-reddit$" os.environ.get('PATH_INFO' '')).group(1)<line_sep>uuid=os.environ.get('QUERY_STRING' '')<line_sep>print("Status: 301 Moved Permanently")<line_sep>print("Location: /%s?level=10#%s\n"%(app uuid))<line_sep>
<import_stmt>logging<import_from_stmt>os path<import_stmt>tornado.web<import_from_stmt>tornado.escape url_escape url_unescape<import_from_stmt>temboardui.web Blueprint HTTPError Redirect TemplateRenderer <line_sep>PLUGIN_NAME='pgconf'<line_sep>logger=logging.getLogger(__name__)<line_sep>blueprint=Blueprint()<line_sep>blueprint.generic_proxy("/pgconf/configuration" methods=["POST"])<line_sep>plugin_path=path.dirname(path.realpath(__file__))<line_sep>render_template=TemplateRenderer(plugin_path+"/templates")<def_stmt>configuration config<block_start><return>{}<block_end><def_stmt>get_routes config<block_start>routes=blueprint.rules+[(r"/js/pgconf/(.*)" tornado.web.StaticFileHandler {'path':plugin_path+"/static/js"}) (r"/css/pgconf/(.*)" tornado.web.StaticFileHandler {'path':plugin_path+"/static/css"}) ]<line_sep><return>routes<block_end>@blueprint.instance_route("/pgconf/configuration(?:/category/(.+))?" methods=["GET" "POST"])<def_stmt>configuration_handler request category=<none><block_start>request.instance.check_active_plugin(PLUGIN_NAME)<line_sep>profile=request.instance.get_profile()<line_sep>agent_username=profile['username']<line_sep>template_vars={}<line_sep># Deduplicate HTTP prefix of plugin on agent. prefix="/pgconf/configuration"<line_sep>query_filter=request.handler.get_argument('filter' <none> strip=<true>)<line_sep>status=request.instance.get(prefix+"/status")<line_sep>categories=request.instance.get(prefix+"/categories")<if_stmt>category<block_start>category=url_unescape(category)<block_end><else_stmt><block_start>category=categories['categories'][0]<block_end>logger.debug("category=%s" category)<if_stmt>query_filter<block_start>query={'filter':query_filter}<line_sep>configuration_url=prefix<block_end><else_stmt><block_start>query={}<line_sep>configuration_url=prefix+"/category/"+url_escape(category)<block_end>configuration=request.instance.get(configuration_url query=query)<if_stmt>"POST"<eq>request.method<block_start>settings={'settings':[{'name':name 'setting':value[0]}<for>name,value request.arguments.iteritems()# 'filter' is not a setting, just ignore it. <if>name<ne>'filter']}<try_stmt><block_start>request.instance.post(prefix body=settings)<line_sep># Redirect to GET page, same URI. <return>Redirect(request.uri)<block_end><except_stmt>HTTPError<as>e# Rerender HTML page with errors. <block_start>template_vars['error_code']=e<line_sep>template_vars['error_message']=e.log_message<block_end><block_end><return>render_template('configuration.html' nav=<true> role=request.current_user instance=request.instance agent_username=agent_username plugin=PLUGIN_NAME xsession=request.instance.xsession current_cat=category configuration_categories=categories configuration_status=status data=configuration query_filter=query_filter **template_vars)<block_end>
# # Copyright 1993-2017 NVIDIA Corporation. All rights reserved. # # NOTICE TO LICENSEE: # # This source code and/or documentation ("Licensed Deliverables") are # subject to NVIDIA intellectual property rights under U.S. and # international Copyright laws. # # These Licensed Deliverables contained herein is PROPRIETARY and # CONFIDENTIAL to NVIDIA and is being provided under the terms and # conditions of a form of NVIDIA software license agreement by and # between NVIDIA and Licensee ("License Agreement") or electronically # accepted by Licensee. Notwithstanding any terms or conditions to # the contrary in the License Agreement, reproduction or disclosure # of the Licensed Deliverables to any third party without the express # written consent of NVIDIA is prohibited. # # NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE # LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE # SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS # PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. # NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED # DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, # NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. # NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE # LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY # SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THESE LICENSED DELIVERABLES. # # U.S. Government End Users. These Licensed Deliverables are a # "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT # 1995), consisting of "commercial computer software" and "commercial # computer software documentation" as such terms are used in 48 # C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government # only as a commercial end item. Consistent with 48 C.F.R.12.212 and # 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all # U.S. Government End Users acquire the Licensed Deliverables with # only those rights set forth herein. # # Any use of the Licensed Deliverables in individual and commercial # software must include, in the user documentation and internal # comments to the code, the above Disclaimer and U.S. Government End # Users Notice. # #!/usr/bin/python <import_from_future_stmt> division<import_from_future_stmt> print_function<import_stmt>os<import_stmt>sys<import_from_stmt>random randint<import_stmt>numpy<as>np<import_stmt>lenet5<try_stmt><block_start><import_from_stmt>PIL Image<import_stmt>pycuda.driver<as>cuda<import_stmt>pycuda.autoinit<import_stmt>argparse<block_end><except_stmt>ImportError<as>err<block_start>sys.stderr.write("""ERROR: failed to import module ({}) Please make sure you have pycuda and the example dependencies installed. https://wiki.tiker.net/PyCuda/Installation/Linux pip(3) install tensorrt[examples] """.format(err))<line_sep>exit(1)<block_end><try_stmt><block_start><import_stmt>uff<block_end><except_stmt>ImportError<block_start><raise>ImportError("""Please install the UFF Toolkit""")<block_end><try_stmt><block_start><import_stmt>tensorrt<as>trt<import_from_stmt>tensorrt.parsers uffparser<block_end><except_stmt>ImportError<as>err<block_start>sys.stderr.write("""ERROR: failed to import module ({}) Please make sure you have the TensorRT Library installed and accessible in your LD_LIBRARY_PATH """.format(err))<line_sep>exit(1)<block_end>MAX_WORKSPACE=1<lshift>30<line_sep>G_LOGGER=trt.infer.ConsoleLogger(trt.infer.LogSeverity.INFO)<line_sep>INPUT_W=28<line_sep>INPUT_H=28<line_sep>OUTPUT_SIZE=10<line_sep>MAX_BATCHSIZE=1<line_sep>ITERATIONS=10<line_sep># API CHANGE: Try to generalize into a utils function #Run inference on device <def_stmt>infer context input_img batch_size#load engine <block_start>engine=context.get_engine()<assert_stmt>(engine.get_nb_bindings()<eq>2)<line_sep>#create output array to receive data dims=engine.get_binding_dimensions(1).to_DimsCHW()<line_sep>elt_count=dims.C()<times>dims.H()<times>dims.W()<times>batch_size<line_sep>#convert input data to Float32 input_img=input_img.astype(np.float32)<line_sep>#Allocate pagelocked memory output=cuda.pagelocked_empty(elt_count dtype=np.float32)<line_sep>#alocate device memory d_input=cuda.mem_alloc(batch_size<times>input_img.size<times>input_img.dtype.itemsize)<line_sep>d_output=cuda.mem_alloc(batch_size<times>output.size<times>output.dtype.itemsize)<line_sep>bindings=[int(d_input) int(d_output)]<line_sep>stream=cuda.Stream()<line_sep>#transfer input data to device cuda.memcpy_htod_async(d_input input_img stream)<line_sep>#execute model context.enqueue(batch_size bindings stream.handle <none>)<line_sep>#transfer predictions back cuda.memcpy_dtoh_async(output d_output stream)<line_sep>#return predictions <return>output<block_end><def_stmt>main <block_start>path=os.path.dirname(os.path.realpath(__file__))<line_sep>tf_model=lenet5.learn()<line_sep>uff_model=uff.from_tensorflow(tf_model ["fc2/Relu"])<line_sep>#Convert Tensorflow model to TensorRT model parser=uffparser.create_uff_parser()<line_sep>parser.register_input("Placeholder" (1 28 28) 0)<line_sep>parser.register_output("fc2/Relu")<line_sep>engine=trt.utils.uff_to_trt_engine(G_LOGGER uff_model parser MAX_BATCHSIZE MAX_WORKSPACE)<assert_stmt>(engine)<line_sep># parser.destroy() context=engine.create_execution_context()<line_sep>print("\n| TEST CASE | PREDICTION |")<for_stmt>i range(ITERATIONS)<block_start>img,label=lenet5.get_testcase()<line_sep>img=img[0]<line_sep>label=label[0]<line_sep>out=infer(context img 1)<line_sep>print("|-----------|------------|")<line_sep>print("| "+str(label)+" | "+str(np.argmax(out))+" |")<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>main()<block_end>
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Multitask base trainer implementation. The trainer derives from the Orbit `StandardTrainer` class. """<import_from_stmt>typing Union<import_stmt>gin<import_stmt>orbit<import_stmt>tensorflow<as>tf<import_from_stmt>official.modeling.multitask base_model<import_from_stmt>official.modeling.multitask multitask<line_sep>@gin.configurable<class_stmt>MultiTaskBaseTrainer(orbit.StandardTrainer)<block_start>"""Multitask base trainer."""<def_stmt>__init__ self multi_task:multitask.MultiTask multi_task_model:Union[tf.keras.Model base_model.MultiTaskBaseModel] optimizer:tf.optimizers.Optimizer trainer_options=<none> train_datasets=<none><block_start>self._strategy=tf.distribute.get_strategy()<line_sep>self._multi_task=multi_task<line_sep>self._multi_task_model=multi_task_model<line_sep>self._optimizer=optimizer<line_sep>self._training_losses=<none><line_sep>self._training_metrics=<none><line_sep>self._global_step=orbit.utils.create_global_step()<if_stmt>hasattr(self.multi_task_model "checkpoint_items")<block_start>checkpoint_items=self.multi_task_model.checkpoint_items<block_end><else_stmt><block_start>checkpoint_items={}<block_end>self._checkpoint=tf.train.Checkpoint(model=self.multi_task_model optimizer=self.optimizer global_step=self.global_step **checkpoint_items)<if_stmt>train_datasets<is><none><block_start>train_datasets={}<for_stmt>name,task self.multi_task.tasks.items()<block_start>train_datasets[name]=orbit.utils.make_distributed_dataset(self.strategy task.build_inputs task.task_config.train_data)<block_end><block_end>super().__init__(train_dataset=train_datasets options=trainer_options<or>orbit.StandardTrainerOptions())<block_end><def_stmt>train_loop_begin self<block_start>"""Clean up states that hold losses and metrics."""<for_stmt>_,train_loss_metric self.training_losses.items()<block_start>train_loss_metric.reset_states()<block_end><for_stmt>_,metrics self.training_metrics.items()<block_start><for_stmt>metric metrics<block_start>metric.reset_states()<block_end><block_end><block_end><def_stmt>train_loop_end self<block_start>"""Record loss and metric values per task."""<line_sep>result={}<for_stmt>task_name,loss self.training_losses.items()<block_start>result[task_name]={loss.name:loss.result()}<block_end><for_stmt>task_name,task_metrics self.training_metrics.items()<block_start>result[task_name].update({metric.name:metric.result()<for>metric task_metrics})<block_end># Note that, the learning rate schedule is managed by the keras optimizer # internally, which respects the number of backward pass as `iterations`. # The learning rate schedule does not follow the trainer logical global # step of multiple tasks. <if_stmt>callable(self.optimizer.learning_rate)<block_start>result["learning_rate"]=self.optimizer.learning_rate(self.optimizer.iterations)<block_end><else_stmt><block_start>result["learning_rate"]=self.optimizer.learning_rate<block_end><return>result<block_end>@property<def_stmt>checkpoint self<block_start>"""Accesses the training checkpoint."""<line_sep><return>self._checkpoint<block_end>@property<def_stmt>training_losses self<block_start>"""Access training loss metric objects for all tasks."""<if_stmt>self._training_losses<is><none># Builds the per-task metrics and losses. # This the total summed training loss of tasks in the joint training. <block_start>self._training_losses=dict(total_loss=tf.keras.metrics.Mean("training_loss" dtype=tf.float32))<for_stmt>name self.multi_task.tasks<block_start>self._training_losses[name]=tf.keras.metrics.Mean("training_loss" dtype=tf.float32)<block_end><block_end><return>self._training_losses<block_end>@property<def_stmt>training_metrics self<block_start>"""Access training metric metric objects for all tasks."""<if_stmt>self._training_metrics<is><none># Builds the per-task metrics and losses. <block_start>self._training_metrics={}<for_stmt>name,task self.multi_task.tasks.items()<block_start>self._training_metrics[name]=task.build_metrics(training=<true>)<block_end><block_end><return>self._training_metrics<block_end>@property<def_stmt>strategy self<block_start><return>self._strategy<block_end>@property<def_stmt>multi_task self<block_start><return>self._multi_task<block_end>@property<def_stmt>multi_task_model self<block_start><return>self._multi_task_model<block_end>@property<def_stmt>optimizer self<block_start><return>self._optimizer<block_end>@property<def_stmt>global_step self<block_start><return>self._global_step<block_end><def_stmt>train_step self iterator_map<block_start>"""The default train step calling the multi-task train step. Args: iterator_map: a dictionary of task names and per-task dataset iterators. """<def_stmt>step_fn inputs<block_start>losses=self.multi_task.joint_train_step(inputs multi_task_model=self.multi_task_model optimizer=self.optimizer task_metrics=self.training_metrics)<for_stmt>key,loss losses.items()<block_start>self.training_losses[key].update_state(loss)<block_end><block_end>self.strategy.run(step_fn args=(tf.nest.map_structure(next iterator_map) ))<line_sep>self.global_step.assign_add(1)<block_end><block_end>
<import_from_stmt>typing Dict List Tuple<import_from_stmt>lib.metastore.base_metastore_loader BaseMetastoreLoader DataTable DataColumn <import_from_stmt>lib.query_executor.executor_template.templates sqlalchemy_template<import_from_stmt>lib.query_executor.connection_string.sqlalchemy create_sqlalchemy_engine<class_stmt>SqlAlchemyMetastoreLoader(BaseMetastoreLoader)<block_start><def_stmt>__init__ self metastore_dict:Dict<block_start>self._engine,self._inspect,self._conn=self._get_sqlalchemy(metastore_dict)<line_sep>super(SqlAlchemyMetastoreLoader self).__init__(metastore_dict)<block_end><def_stmt>__del__ self<block_start>self._conn.close()<del_stmt>self._inspect<line_sep>self._engine.dispose()<block_end>@classmethod<def_stmt>get_metastore_params_template cls<block_start><return>sqlalchemy_template<block_end><def_stmt>get_all_schema_names self<arrow>List[str]<block_start><return>self._inspect.get_schema_names()<block_end><def_stmt>get_all_table_names_in_schema self schema_name:str<arrow>List[str]<block_start><return>self._inspect.get_table_names(schema=schema_name)<block_end><def_stmt>get_table_and_columns self schema_name table_name<arrow>Tuple[DataTable List[DataColumn]]<block_start><if_stmt><not>self._engine.dialect.has_table(self._conn table_name=table_name schema=schema_name)<block_start><return><none> []<block_end>table=DataTable(name=table_name type=<none> owner=<none> table_created_at=<none> table_updated_by=<none> table_updated_at=<none> data_size_bytes=<none> location=<none> partitions=<none> raw_description="" )<line_sep>raw_columns=self._inspect.get_columns(table_name=table_name schema=schema_name)<line_sep>columns=list(map(<lambda>col:DataColumn(name=col["name"] type=str(col["type"]) comment=f"Default:{col['default']} Nullable:{col['nullable']}" ) raw_columns ))<line_sep><return>table columns<block_end><def_stmt>_get_sqlalchemy self metastore_dict<block_start><import_from_stmt>sqlalchemy.engine reflection<line_sep>engine=create_sqlalchemy_engine(metastore_dict["metastore_params"])<line_sep>inspect=reflection.Inspector.from_engine(engine)<line_sep>conn=engine.connect()<line_sep><return>engine inspect conn<block_end><block_end>
""" ================== Time Series Forest ================== This example illustrates which information is considered important by the algorithm in order to classify time series. The index of the most important window is retrieved via the ``feature_importance_`` and ``indices_`` attributes. The first time series for both classes are plotted and the most important window is highlighted with a larger line width. It is implemented as :class:`pyts.classification.TimeSeriesForest`. """<line_sep># Author: <NAME> <<EMAIL>> # License: BSD-3-Clause <import_stmt>numpy<as>np<import_from_stmt>pyts.datasets load_gunpoint<import_from_stmt>pyts.classification TimeSeriesForest<import_stmt>matplotlib.pyplot<as>plt<line_sep>X_train,X_test,y_train,y_test=load_gunpoint(return_X_y=<true>)<line_sep>clf=TimeSeriesForest(random_state=43)<line_sep>clf.fit(X_train y_train)<line_sep>start_idxmax,end_idxmax=clf.indices_[np.argmax(clf.feature_importances_)<floordiv>3]<line_sep>plt.figure(figsize=(12 5))<line_sep>plt.plot(X_train[y_train<eq>1][0] label='First sample in class 1')<line_sep>plt.plot(np.arange(start_idxmax end_idxmax) X_train[y_train<eq>1][0 start_idxmax:end_idxmax] color='C0' lw=4)<line_sep>plt.plot(X_train[y_train<eq>2][0] label='First sample in class 2')<line_sep>plt.plot(np.arange(start_idxmax end_idxmax) X_train[y_train<eq>2][0 start_idxmax:end_idxmax] color='C1' lw=4)<line_sep>plt.legend(loc='best' fontsize=14)<line_sep>plt.title('The most important window according to the feature importance '<concat>'scores' fontsize=16)<line_sep>plt.tight_layout()<line_sep>plt.show()<line_sep>
"""Collection of helpers."""<import_from_stmt>homeassistant.components.coinbase.const CONF_CURRENCIES CONF_EXCHANGE_RATES DOMAIN <import_from_stmt>homeassistant.const CONF_API_KEY CONF_API_TOKEN<import_from_stmt>.const GOOD_EXCHANGE_RATE GOOD_EXCHANGE_RATE_2 MOCK_ACCOUNTS_RESPONSE<import_from_stmt>tests.common MockConfigEntry<class_stmt>MockPagination<block_start>"""Mock pagination result."""<def_stmt>__init__ self value=<none><block_start>"""Load simple pagination for tests."""<line_sep>self.next_starting_after=value<block_end><block_end><class_stmt>MockGetAccounts<block_start>"""Mock accounts with pagination."""<def_stmt>__init__ self starting_after=0<block_start>"""Init mocked object, forced to return two at a time."""<if_stmt>(target_end:=starting_after+2)<ge>(max_end:=len(MOCK_ACCOUNTS_RESPONSE))<block_start>end=max_end<line_sep>self.pagination=MockPagination(value=<none>)<block_end><else_stmt><block_start>end=target_end<line_sep>self.pagination=MockPagination(value=target_end)<block_end>self.accounts={"data":MOCK_ACCOUNTS_RESPONSE[starting_after:end] }<line_sep>self.started_at=starting_after<block_end><def_stmt>__getitem__ self item<block_start>"""Handle subscript request."""<line_sep><return>self.accounts[item]<block_end><block_end><def_stmt>mocked_get_accounts _ **kwargs<block_start>"""Return simplified accounts using mock."""<line_sep><return>MockGetAccounts(**kwargs)<block_end><def_stmt>mock_get_current_user <block_start>"""Return a simplified mock user."""<line_sep><return>{"id":"123456-abcdef" "name":"Test User" }<block_end><def_stmt>mock_get_exchange_rates <block_start>"""Return a heavily reduced mock list of exchange rates for testing."""<line_sep><return>{"currency":"USD" "rates":{GOOD_EXCHANGE_RATE_2:"0.109" GOOD_EXCHANGE_RATE:"0.00002"} }<block_end><async_keyword><def_stmt>init_mock_coinbase hass currencies=<none> rates=<none><block_start>"""Init Coinbase integration for testing."""<line_sep>config_entry=MockConfigEntry(domain=DOMAIN unique_id=<none> title="Test User" data={CONF_API_KEY:"123456" CONF_API_TOKEN:"AbCDeF"} options={CONF_CURRENCIES:currencies<or>[] CONF_EXCHANGE_RATES:rates<or>[] } )<line_sep>config_entry.add_to_hass(hass)<line_sep><await>hass.config_entries.async_setup(config_entry.entry_id)<line_sep><await>hass.async_block_till_done()<line_sep><return>config_entry<block_end>
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. <import_stmt>os sys<import_stmt>time<import_stmt>json<import_stmt>torch<import_stmt>torch.distributed<as>dist<import_from_stmt>tutel system<import_from_stmt>tutel net<as>C<def_stmt>warp_bwd_allreduce data is_param<block_start><if_stmt>is_param<block_start>fusable_params.add(id(data))<line_sep><return>C.allreduce_backward(data group=parallel_env.global_group)<block_end><return>C.allreduce_backward(data group=parallel_env.model_group)<block_end><def_stmt>sharded_randn shape dim dtype requires_grad=<false> is_param=<false> device=<none><block_start><if_stmt>device<is><none><block_start>device=parallel_env.local_device<block_end>torch.manual_seed(1)<line_sep>complete_tensor=torch.tensor(torch.randn(shape dtype=dtype device='cpu').numpy() device=device requires_grad=requires_grad)<if_stmt>dim<ge>0<block_start>result=torch.chunk(complete_tensor chunks=parallel_env.model_size dim=dim)[parallel_env.model_rank].contiguous()<block_end><elif_stmt>dim<eq>-2<block_start>numel=complete_tensor.numel()<assert_stmt>numel%parallel_env.model_size<eq>0<line_sep>result=complete_tensor.view(parallel_env.model_size -1)[parallel_env.model_rank].contiguous()<block_end><else_stmt><block_start>result=complete_tensor.contiguous()<block_end><if_stmt>is_param<block_start>result=torch.nn.Parameter(result<times>1e-3)<line_sep>result.is_param=<true><block_end><if_stmt>dim<eq>-2<block_start>result._full_shape=shape<line_sep>result.is_param=<true><block_end>result.dim_state=dim<line_sep><return>result<block_end><def_stmt>init_session group_size group_count=1 device_type='cuda'<block_start><global>parallel_env fusable_params<line_sep>parallel_env=system.init_data_model_parallel(group_count=group_count backend='nccl'<if>device_type<eq>'cuda'<else>'gloo')<line_sep>fusable_params=set()<assert_stmt>parallel_env.model_size<eq>group_size f"This codegen is designed for distributed parallelism = {group_size}, while current session only activates {parallel_env.model_size} device.\n\nPlease retry with command: mpiexec --allow-run-as-root -host localhost -x MASTER_ADDR=localhost -x LOCAL_SIZE={group_size} {sys.executable} -m tutel.launcher.run {sys.executable} {' '.join(sys.argv)}"<block_end><def_stmt>model_executor module is_training=<true><block_start>name=module.compute_name<line_sep>model=module().to(parallel_env.local_device)<line_sep>inputs=module.synthetic_inputs()<line_sep>output=model(**inputs)<line_sep>params=model.parameters()<line_sep>verbose=int(os.environ.get('VERBOSE' '0'))<line_sep>is_cuda=(parallel_env.local_device.type<eq>'cuda')<line_sep>is_training=is_training<and>isinstance(output torch.Tensor)<line_sep>start_result=output.contiguous().view(-1)[0]<if>isinstance(output torch.Tensor)<else>-1<if_stmt>verbose<block_start>sys.stderr.write('[%d] %g %g .. %g (%s)\n'%(parallel_env.model_rank output.flatten()[0] output.flatten()[1] output.flatten()[-1] output.shape))<block_end><if_stmt>is_training<block_start>torch.manual_seed(1)<line_sep>label=torch.LongTensor(output.size(0)).random_(1).to(output.device)<if_stmt>params<block_start>optimizer=torch.optim.SGD(params lr=1e-5)<block_end><else_stmt><block_start>optimizer=model_executor<line_sep>optimizer.zero_grad=optimizer.step=<lambda>*x:<none><block_end><block_end><def_stmt>next_step <block_start><if_stmt>parallel_env.group_count<g>1<block_start>dist.barrier()<block_end><if_stmt>is_cuda<block_start>torch.cuda.synchronize(parallel_env.local_device)<block_end>t_start=time.time()<if_stmt>is_training<block_start>optimizer.zero_grad()<line_sep>result=model(**inputs).contiguous()<line_sep>result=torch.nn.functional.log_softmax(result.view(result.size(0) -1) dim=1)<line_sep>result=torch.nn.functional.nll_loss(result label)<if_stmt>parallel_env.model_rank<eq>0<and>verbose<block_start>sys.stderr.write(f' Loss = {result} ({output.shape}, {label.shape})\n')<block_end>result.backward(retain_graph=<true>)<if_stmt>parallel_env.group_count<g>1<block_start><for_stmt>p params<block_start><if_stmt>id(p)<not><in>fusable_params<block_start>p.grad=simple_all_reduce(p.grad group=parallel_env.data_group)<block_end><block_end><block_end>optimizer.step()<block_end><else_stmt><block_start>result=model(**inputs)<line_sep>result=result.contiguous().view(-1)[0]<if>isinstance(result torch.Tensor)<else>-1<block_end><if_stmt>parallel_env.group_count<g>1<block_start>dist.barrier()<block_end><if_stmt>is_cuda<block_start>torch.cuda.synchronize(parallel_env.local_device)<block_end>t_stop=time.time()<line_sep>step_time=t_stop-t_start<if_stmt>parallel_env.model_rank<eq>0<and>verbose<block_start>sys.stderr.write('Result(is_training=%s) = %g, cost = %s\n'%(is_training result step_time))<block_end><return>step_time<block_end><for_stmt>i range(5)<block_start>next_step()<block_end>average_step_time=sum([next_step()<for>_ range(5)])/5<if_stmt>parallel_env.model_rank<eq>0<block_start>sys.stderr.write(' [%s] digest = %g .., time = %g\n'%(name start_result average_step_time))<line_sep>result=json.dumps({'name':name 'step_time':average_step_time})<if_stmt>'CONFIG_STORE_PATH'<in>os.environ<block_start><with_stmt>open(os.environ['CONFIG_STORE_PATH'] 'w')<as>fp<block_start>fp.write(result)<block_end><block_end>print(result)<block_end><block_end>
<import_stmt>math<import_from_stmt>OpenGL.GL *<import_from_stmt>OpenGL.GLUT *<import_from_stmt>OpenGL.GLU *<line_sep>""" Turtle drawings Once the functions reset(), turn(), turnTo() and forw() there is a possibility to program a path. In essence this is very similar to using polar coordinates relative to the last set point. Meaning you define the angle and the length over which a line should be drawn. First an example will be given containing the full source, next will will only focus on the display function since the same primitives will be used. http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLTurtle """<line_sep>curX=0.0<line_sep>curY=0.0<line_sep>angle=0.0<def_stmt>reset <block_start>""" Reset the position to the origin """<line_sep><global>curX<line_sep><global>curY<line_sep><global>angle<line_sep>curX=0.0<line_sep>curY=0.0<line_sep>angle=0.0<block_end><def_stmt>turnTo deg<block_start>""" Turn to a certain angle """<line_sep><global>angle<line_sep>angle=deg<block_end><def_stmt>turn deg<block_start>""" Turn a certain number of degrees """<line_sep><global>angle<line_sep>angle<augadd>deg<block_end><def_stmt>forw len visible<block_start>""" Move forward over a certain distance """<line_sep><global>curX<line_sep><global>curY<line_sep>tmpX=curX<line_sep>tmpY=curY<line_sep>curX=curX+len<times>math.cos(math.radians(angle))<line_sep>curY=curY+len<times>math.sin(math.radians(angle))<if_stmt>visible<block_start>glBegin(GL_LINE_STRIP)<line_sep>glVertex2f(tmpX tmpY)<line_sep>glVertex2f(curX curY)<line_sep>glEnd()<block_end><block_end><def_stmt>initFun <block_start>glClearColor(1.0 1.0 1.0 0.0)<line_sep>glColor3f(0.0 0.0 0.0)<line_sep>glMatrixMode(GL_PROJECTION)<line_sep>glLoadIdentity()<line_sep>gluOrtho2D(-100 100 -100 100)<block_end><def_stmt>reshapeFun w h<block_start>glViewport(0 0 w h)<line_sep># if w > h: # glViewport((w-h)/2,0,h,h) # else: # glViewport(0,(h-w)/2,w,w) <block_end><def_stmt>turtle_1 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>reset()<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>L=30<line_sep>turnTo(0)<for_stmt>i range(0 4)<block_start>forw(3<times>L <true>)<line_sep>turn(90)<line_sep>forw(L <true>)<line_sep>turn(90)<line_sep>forw(L <true>)<line_sep>turn(90)<block_end>glFlush()<block_end><def_stmt>turtle_2 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>length=0<line_sep>increment=1<for_stmt>i range(0 100)<block_start>forw(length <true>)<line_sep>turn(60)<line_sep>length<augadd>increment<block_end>glFlush()<block_end><def_stmt>turtle_3 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>length=0<line_sep>increment=1<for_stmt>i range(0 200)<block_start>forw(length <true>)<line_sep>turn(89.5)<line_sep>length<augadd>increment<block_end>glFlush()<block_end><def_stmt>turtle_4 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>length=0<line_sep>increment=1<for_stmt>i range(0 200)<block_start>forw(length <true>)<line_sep>turn(-144)<line_sep>length<augadd>increment<block_end>glFlush()<block_end><def_stmt>turtle_5 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>length=0<line_sep>increment=1<for_stmt>i range(0 200)<block_start>forw(length <true>)<line_sep>turn(170)<line_sep>length<augadd>increment<block_end>glFlush()<block_end><def_stmt>turtle_6 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>L=10<line_sep>length=L<for_stmt>i range(0 10)<block_start><for_stmt>j range(0 4)<block_start>forw(length <true>)<line_sep>turn(90)<block_end>length<augadd>L<block_end>glFlush()<block_end><def_stmt>turtle_7 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>L=3<line_sep>length=L<for_stmt>i range(0 100)<block_start>forw(length <true>)<line_sep>turn(90)<line_sep>length<augadd>L<block_end>glFlush()<block_end><def_stmt>turtle_8 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>forw(100 <true>)<line_sep>turn(120)<line_sep>forw(100 <true>)<line_sep>turn(120)<line_sep>forw(50 <true>)<line_sep>turn(120)<line_sep>forw(50 <true>)<line_sep>turn(-120)<line_sep>forw(50 <true>)<line_sep>turn(-120)<line_sep>forw(50 <true>)<line_sep>turn(120)<line_sep>forw(50 <true>)<line_sep>glFlush()<block_end><def_stmt>turtle_9 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>L=50<for_stmt>i range(0 3)<block_start>forw(L <true>)<line_sep>turn(-60)<line_sep>forw(L <true>)<line_sep>turn(-120)<line_sep>forw(L <true>)<line_sep>turn(-60)<line_sep>forw(L <true>)<block_end>glFlush()<block_end><def_stmt>turtle_10 <block_start>glClear(GL_COLOR_BUFFER_BIT)<line_sep>glColor3f(0.0 0.0 1.0)<line_sep>reset()<line_sep>L=30<for_stmt>i range(0 3)<block_start>forw(L <true>)<line_sep>turn(60)<line_sep>forw(L <true>)<line_sep>turn(60)<line_sep>forw(L <true>)<line_sep>turn(60)<line_sep>forw(L <true>)<line_sep>turn(-60)<block_end>glFlush()<block_end><if_stmt>__name__<eq>'__main__'<block_start>glutInit()<line_sep>glutInitWindowSize(400 400)<line_sep>glutCreateWindow(b"Turtle")<line_sep>glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB)<line_sep>glutDisplayFunc(turtle_1)<line_sep># glutDisplayFunc(turtle_2) # glutDisplayFunc(turtle_3) # glutDisplayFunc(turtle_4) # glutDisplayFunc(turtle_5) # glutDisplayFunc(turtle_6) # glutDisplayFunc(turtle_7) # glutDisplayFunc(turtle_8) # glutDisplayFunc(turtle_9) # glutDisplayFunc(turtle_10) glutReshapeFunc(reshapeFun)<line_sep>initFun()<line_sep>glutMainLoop()<block_end>
<import_stmt>pytest<import_stmt>numpy<as>np<import_stmt>dice_ml<import_from_stmt>sklearn.ensemble RandomForestClassifier RandomForestRegressor<import_from_stmt>dice_ml.utils.exception SystemException<class_stmt>TestModelClassification<block_start><def_stmt>create_sklearn_random_forest_classifier self X y<block_start>rfc=RandomForestClassifier(n_estimators=10 max_depth=4 random_state=777)<line_sep>model=rfc.fit(X y)<line_sep><return>model<block_end><def_stmt>test_base_model_classification self create_iris_data<block_start>x_train,x_test,y_train,y_test,feature_names,classes=create_iris_data<line_sep>trained_model=self.create_sklearn_random_forest_classifier(x_train y_train)<line_sep>diceml_model=dice_ml.Model(model=trained_model backend='sklearn')<line_sep>diceml_model.transformer.initialize_transform_func()<assert_stmt>diceml_model<is><not><none><line_sep>prediction_probabilities=diceml_model.get_output(x_test)<assert_stmt>prediction_probabilities.shape[0]<eq>x_test.shape[0]<assert_stmt>prediction_probabilities.shape[1]<eq>len(classes)<line_sep>predictions=diceml_model.get_output(x_test model_score=<false>).reshape(-1 1)<assert_stmt>predictions.shape[0]<eq>x_test.shape[0]<assert_stmt>predictions.shape[1]<eq>1<assert_stmt>np.all(np.unique(predictions)<eq>np.unique(y_test))<with_stmt>pytest.raises(NotImplementedError)<block_start>diceml_model.get_gradient()<block_end><assert_stmt>diceml_model.get_num_output_nodes2(x_test)<eq>len(classes)<block_end><block_end><class_stmt>TestModelRegression<block_start><def_stmt>create_sklearn_random_forest_regressor self X y<block_start>rfc=RandomForestRegressor(n_estimators=10 max_depth=4 random_state=777)<line_sep>model=rfc.fit(X y)<line_sep><return>model<block_end><def_stmt>test_base_model_regression self create_boston_data<block_start>x_train,x_test,y_train,y_test,feature_names=create_boston_data<line_sep>trained_model=self.create_sklearn_random_forest_regressor(x_train y_train)<line_sep>diceml_model=dice_ml.Model(model=trained_model model_type='regressor' backend='sklearn')<line_sep>diceml_model.transformer.initialize_transform_func()<assert_stmt>diceml_model<is><not><none><line_sep>prediction_probabilities=diceml_model.get_output(x_test).reshape(-1 1)<assert_stmt>prediction_probabilities.shape[0]<eq>x_test.shape[0]<assert_stmt>prediction_probabilities.shape[1]<eq>1<line_sep>predictions=diceml_model.get_output(x_test model_score=<false>).reshape(-1 1)<assert_stmt>predictions.shape[0]<eq>x_test.shape[0]<assert_stmt>predictions.shape[1]<eq>1<with_stmt>pytest.raises(NotImplementedError)<block_start>diceml_model.get_gradient()<block_end><with_stmt>pytest.raises(SystemException)<block_start>diceml_model.get_num_output_nodes2(x_test)<block_end><block_end><block_end>
""" Utilities for starting up a test slapd server and talking to it with ldapsearch/ldapadd. """<import_stmt>sys os socket time subprocess logging<line_sep>_log=logging.getLogger("slapd")<def_stmt>quote s<block_start>'''Quotes the '"' and '\' characters in a string and surrounds with "..."'''<line_sep><return>'"'+s.replace('\\' '\\\\').replace('"' '\\"')+'"'<block_end><def_stmt>mkdirs path<block_start>"""Creates the directory path unless it already exists"""<if_stmt><not>os.access(os.path.join(path os.path.curdir) os.F_OK)<block_start>_log.debug("creating temp directory %s" path)<line_sep>os.mkdir(path)<block_end><return>path<block_end><def_stmt>delete_directory_content path<block_start><for_stmt>dirpath,dirnames,filenames os.walk(path topdown=<false>)<block_start><for_stmt>n filenames<block_start>_log.info("remove %s" os.path.join(dirpath n))<line_sep>os.remove(os.path.join(dirpath n))<block_end><for_stmt>n dirnames<block_start>_log.info("rmdir %s" os.path.join(dirpath n))<line_sep>os.rmdir(os.path.join(dirpath n))<block_end><block_end><block_end>LOCALHOST='127.0.0.1'<def_stmt>find_available_tcp_port host=LOCALHOST<block_start>s=socket.socket()<line_sep>s.bind((host 0))<line_sep>port=s.getsockname()[1]<line_sep>s.close()<line_sep>_log.info("Found available port %d" port)<line_sep><return>port<block_end><class_stmt>Slapd<block_start>""" Controller class for a slapd instance, OpenLDAP's server. This class creates a temporary data store for slapd, runs it on a private port, and initialises it with a top-level dc and the root user. When a reference to an instance of this class is lost, the slapd server is shut down. """<line_sep>_log=logging.getLogger("Slapd")<line_sep># Use /var/tmp to placate apparmour on Ubuntu: PATH_TMPDIR="/var/tmp/python-ldap-test"<line_sep>PATH_SBINDIR="/usr/sbin"<line_sep>PATH_BINDIR="/usr/bin"<line_sep>PATH_SCHEMA_CORE="/etc/ldap/schema/core.schema"<line_sep>PATH_LDAPADD=os.path.join(PATH_BINDIR "ldapadd")<line_sep>PATH_LDAPSEARCH=os.path.join(PATH_BINDIR "ldapsearch")<line_sep>PATH_SLAPD=os.path.join(PATH_SBINDIR "slapd")<line_sep>PATH_SLAPTEST=os.path.join(PATH_SBINDIR "slaptest")<line_sep># TODO add paths for other OSs <def_stmt>check_paths cls<block_start>""" Checks that the configured executable paths look valid. If they don't, then logs warning messages (not errors). """<for_stmt>name,path (("slapd" cls.PATH_SLAPD) ("ldapadd" cls.PATH_LDAPADD) ("ldapsearch" cls.PATH_LDAPSEARCH) )<block_start>cls._log.debug("checking %s executable at %s" name path)<if_stmt><not>os.access(path os.X_OK)<block_start>cls._log.warn("cannot find %s executable at %s" name path)<block_end><block_end><block_end>check_paths=classmethod(check_paths)<def_stmt>__init__ self<block_start>self._config=[]<line_sep>self._proc=<none><line_sep>self._port=0<line_sep>self._tmpdir=self.PATH_TMPDIR<line_sep>self._dn_suffix="dc=python-ldap,dc=org"<line_sep>self._root_cn="Manager"<line_sep>self._root_password="password"<line_sep>self._slapd_debug_level=0<block_end># Setters <def_stmt>set_port self port<block_start>self._port=port<block_end><def_stmt>set_dn_suffix self dn<block_start>self._dn_suffix=dn<block_end><def_stmt>set_root_cn self cn<block_start>self._root_cn=cn<block_end><def_stmt>set_root_password self pw<block_start>self._root_password=pw<block_end><def_stmt>set_tmpdir self path<block_start>self._tmpdir=path<block_end><def_stmt>set_slapd_debug_level self level<block_start>self._slapd_debug_level=level<block_end><def_stmt>set_debug self<block_start>self._log.setLevel(logging.DEBUG)<line_sep>self.set_slapd_debug_level('Any')<block_end># getters <def_stmt>get_url self<block_start><return>"ldap://%s:%d/"%self.get_address()<block_end><def_stmt>get_address self<block_start><if_stmt>self._port<eq>0<block_start>self._port=find_available_tcp_port(LOCALHOST)<block_end><return>(LOCALHOST self._port)<block_end><def_stmt>get_dn_suffix self<block_start><return>self._dn_suffix<block_end><def_stmt>get_root_dn self<block_start><return>"cn="+self._root_cn+","+self.get_dn_suffix()<block_end><def_stmt>get_root_password self<block_start><return>self._root_password<block_end><def_stmt>get_tmpdir self<block_start><return>self._tmpdir<block_end><def_stmt>__del__ self<block_start>self.stop()<block_end><def_stmt>configure self cfg<block_start>""" Appends slapd.conf configuration lines to cfg. Also re-initializes any backing storage. Feel free to subclass and override this method. """<line_sep># Global cfg.append("include "+quote(self.PATH_SCHEMA_CORE))<line_sep>cfg.append("allow bind_v2")<line_sep># Database ldif_dir=mkdirs(os.path.join(self.get_tmpdir() "ldif-data"))<line_sep>delete_directory_content(ldif_dir)# clear it out cfg.append("database ldif")<line_sep>cfg.append("directory "+quote(ldif_dir))<line_sep>cfg.append("suffix "+quote(self.get_dn_suffix()))<line_sep>cfg.append("rootdn "+quote(self.get_root_dn()))<line_sep>cfg.append("rootpw "+quote(self.get_root_password()))<block_end><def_stmt>_write_config self<block_start>"""Writes the slapd.conf file out, and returns the path to it."""<line_sep>path=os.path.join(self._tmpdir "slapd.conf")<line_sep>ldif_dir=mkdirs(self._tmpdir)<if_stmt>os.access(path os.F_OK)<block_start>self._log.debug("deleting existing %s" path)<line_sep>os.remove(path)<block_end>self._log.debug("writing config to %s" path)<line_sep>file(path "w").writelines([line+"\n"<for>line self._config])<line_sep><return>path<block_end><def_stmt>start self<block_start>""" Starts the slapd server process running, and waits for it to come up. """<if_stmt>self._proc<is><none><block_start>ok=<false><line_sep>config_path=<none><try_stmt><block_start>self.configure(self._config)<line_sep>self._test_configuration()<line_sep>self._start_slapd()<line_sep>self._wait_for_slapd()<line_sep>ok=<true><line_sep>self._log.debug("slapd ready at %s" self.get_url())<line_sep>self.started()<block_end><finally_stmt><block_start><if_stmt><not>ok<block_start><if_stmt>config_path<block_start><try_stmt><block_start>os.remove(config_path)<block_end><except_stmt>os.error<block_start><pass><block_end><block_end><if_stmt>self._proc<block_start>self.stop()<block_end><block_end><block_end><block_end><block_end><def_stmt>_start_slapd self# Spawns/forks the slapd process <block_start>config_path=self._write_config()<line_sep>self._log.info("starting slapd")<line_sep>self._proc=subprocess.Popen([self.PATH_SLAPD "-f" config_path "-h" self.get_url() "-d" str(self._slapd_debug_level) ])<line_sep>self._proc_config=config_path<block_end><def_stmt>_wait_for_slapd self# Waits until the LDAP server socket is open, or slapd crashed <block_start>s=socket.socket()<while_stmt>1<block_start><if_stmt>self._proc.poll()<is><not><none><block_start>self._stopped()<line_sep><raise>RuntimeError("slapd exited before opening port")<block_end><try_stmt><block_start>self._log.debug("Connecting to %s" repr(self.get_address()))<line_sep>s.connect(self.get_address())<line_sep>s.close()<line_sep><return><block_end><except_stmt>socket.error<block_start>time.sleep(1)<block_end><block_end><block_end><def_stmt>stop self<block_start>"""Stops the slapd server, and waits for it to terminate"""<if_stmt>self._proc<is><not><none><block_start>self._log.debug("stopping slapd")<if_stmt>hasattr(self._proc 'terminate')<block_start>self._proc.terminate()<block_end><else_stmt><block_start><import_stmt>posix signal<line_sep>posix.kill(self._proc.pid signal.SIGHUP)<line_sep>#time.sleep(1) #posix.kill(self._proc.pid, signal.SIGTERM) #posix.kill(self._proc.pid, signal.SIGKILL) <block_end>self.wait()<block_end><block_end><def_stmt>restart self<block_start>""" Restarts the slapd server; ERASING previous content. Starts the server even it if isn't already running. """<line_sep>self.stop()<line_sep>self.start()<block_end><def_stmt>wait self<block_start>"""Waits for the slapd process to terminate by itself."""<if_stmt>self._proc<block_start>self._proc.wait()<line_sep>self._stopped()<block_end><block_end><def_stmt>_stopped self<block_start>"""Called when the slapd server is known to have terminated"""<if_stmt>self._proc<is><not><none><block_start>self._log.info("slapd terminated")<line_sep>self._proc=<none><try_stmt><block_start>os.remove(self._proc_config)<block_end><except_stmt>os.error<block_start>self._log.debug("could not remove %s" self._proc_config)<block_end><block_end><block_end><def_stmt>_test_configuration self<block_start>config_path=self._write_config()<try_stmt><block_start>self._log.debug("testing configuration")<line_sep>verboseflag="-Q"<if_stmt>self._log.isEnabledFor(logging.DEBUG)<block_start>verboseflag="-v"<block_end>p=subprocess.Popen([self.PATH_SLAPTEST verboseflag "-f" config_path])<if_stmt>p.wait()<ne>0<block_start><raise>RuntimeError("configuration test failed")<block_end>self._log.debug("configuration seems ok")<block_end><finally_stmt><block_start>os.remove(config_path)<block_end><block_end><def_stmt>ldapadd self ldif extra_args=[]<block_start>"""Runs ldapadd on this slapd instance, passing it the ldif content"""<line_sep>self._log.debug("adding %s" repr(ldif))<line_sep>p=subprocess.Popen([self.PATH_LDAPADD "-x" "-D" self.get_root_dn() "-w" self.get_root_password() "-H" self.get_url()]+extra_args stdin=subprocess.PIPE stdout=subprocess.PIPE)<line_sep>p.communicate(ldif)<if_stmt>p.wait()<ne>0<block_start><raise>RuntimeError("ldapadd process failed")<block_end><block_end><def_stmt>ldapsearch self base=<none> filter='(objectClass=*)' attrs=[] scope='sub' extra_args=[]<block_start><if_stmt>base<is><none><block_start>base=self.get_dn_suffix()<block_end>self._log.debug("ldapsearch filter=%s" repr(filter))<line_sep>p=subprocess.Popen([self.PATH_LDAPSEARCH "-x" "-D" self.get_root_dn() "-w" self.get_root_password() "-H" self.get_url() "-b" base "-s" scope "-LL" ]+extra_args+[filter]+attrs stdout=subprocess.PIPE)<line_sep>output=p.communicate()[0]<if_stmt>p.wait()<ne>0<block_start><raise>RuntimeError("ldapadd process failed")<block_end># RFC 2849: LDIF format # unfold lines=[]<for_stmt>l output.split('\n')<block_start><if_stmt>l.startswith(' ')<block_start>lines[-1]=lines[-1]+l[1:]<block_end><elif_stmt>l<eq>''<and>lines<and>lines[-1]<eq>''<block_start><pass># ignore multiple blank lines <block_end><else_stmt><block_start>lines.append(l)<block_end><block_end># Remove comments lines=[l<for>l lines<if><not>l.startswith("#")]<line_sep># Remove leading version and blank line(s) <if_stmt>lines<and>lines[0]<eq>''<block_start><del_stmt>lines[0]<block_end><if_stmt><not>lines<or>lines[0]<ne>'version: 1'<block_start><raise>RuntimeError("expected 'version: 1', got "+repr(lines[:1]))<block_end><del_stmt>lines[0]<if_stmt>lines<and>lines[0]<eq>''<block_start><del_stmt>lines[0]<block_end># ensure the ldif ends with a blank line (unless it is just blank) <if_stmt>lines<and>lines[-1]<ne>''<block_start>lines.append('')<block_end>objects=[]<line_sep>obj=[]<for_stmt>line lines<block_start><if_stmt>line<eq>''# end of an object <block_start><if_stmt>obj[0][0]<ne>'dn'<block_start><raise>RuntimeError("first line not dn" repr(obj))<block_end>objects.append((obj[0][1] obj[1:]))<line_sep>obj=[]<block_end><else_stmt><block_start>attr,value=line.split(':' 2)<if_stmt>value.startswith(': ')<block_start>value=base64.decodestring(value[2:])<block_end><elif_stmt>value.startswith(' ')<block_start>value=value[1:]<block_end><else_stmt><block_start><raise>RuntimeError("bad line: "+repr(line))<block_end>obj.append((attr value))<block_end><block_end><assert_stmt>obj<eq>[]<line_sep><return>objects<block_end><def_stmt>started self<block_start>""" This method is called when the LDAP server has started up and is empty. By default, this method adds the two initial objects, the domain object and the root user object. """<assert_stmt>self.get_dn_suffix().startswith("dc=")<line_sep>suffix_dc=self.get_dn_suffix().split(',')[0][3:]<assert_stmt>self.get_root_dn().startswith("cn=")<assert_stmt>self.get_root_dn().endswith(","+self.get_dn_suffix())<line_sep>root_cn=self.get_root_dn().split(',')[0][3:]<line_sep>self._log.debug("adding %s and %s" self.get_dn_suffix() self.get_root_dn())<line_sep>self.ldapadd("\n".join(['dn: '+self.get_dn_suffix() 'objectClass: dcObject' 'objectClass: organization' 'dc: '+suffix_dc 'o: '+suffix_dc '' 'dn: '+self.get_root_dn() 'objectClass: organizationalRole' 'cn: '+root_cn '']))<block_end><block_end>Slapd.check_paths()<if_stmt>__name__<eq>'__main__'<and>sys.argv<eq>['run']<block_start>logging.basicConfig(level=logging.DEBUG)<line_sep>slapd=Slapd()<line_sep>print("Starting slapd...")<line_sep>slapd.start()<line_sep>print("Contents of LDAP server follow:\n")<for_stmt>dn,attrs slapd.ldapsearch()<block_start>print("dn: "+dn)<for_stmt>name,val attrs<block_start>print(name+": "+val)<block_end>print("")<block_end>print(slapd.get_url())<line_sep>slapd.wait()<block_end>
<import_from_stmt>joerd.util BoundingBox<import_stmt>joerd.download<as>download<import_stmt>joerd.check<as>check<import_stmt>joerd.srs<as>srs<import_stmt>joerd.mask<as>mask<import_from_stmt>joerd.mkdir_p mkdir_p<import_from_stmt>shutil copyfileobj<import_stmt>os.path<import_stmt>os<import_stmt>requests<import_stmt>logging<import_stmt>re<import_stmt>tempfile<import_stmt>sys<import_stmt>traceback<import_stmt>subprocess<import_stmt>glob<import_from_stmt>osgeo gdal<class_stmt>GMTEDTile(object)<block_start><def_stmt>__init__ self parent x y<block_start>self.url=parent.url<line_sep>self.download_options=parent.download_options<line_sep>self.base_dir=parent.base_dir<line_sep>self.x=x<line_sep>self.y=y<block_end><def_stmt>__key self<block_start><return>(self.x self.y)<block_end><def_stmt>__eq__ a b<block_start><return>isinstance(b type(a))<and>a.__key()<eq>b.__key()<block_end><def_stmt>__hash__ self<block_start><return>hash(self.__key())<block_end><def_stmt>_res self<block_start><return>'300'<if>self.y<eq>-90<else>'075'<block_end><def_stmt>_file_name self<block_start>res=self._res()<line_sep>xname="%03d%s"%(abs(self.x) "E"<if>self.x<ge>0<else>"W")<line_sep>yname="%02d%s"%(abs(self.y) "N"<if>self.y<ge>0<else>"S")<line_sep><return>"%(y)s%(x)s_20101117_gmted_mea%(res)s.tif"%dict(res=res x=xname y=yname)<block_end><def_stmt>urls self<block_start>dir="%s%03d"%("E"<if>self.x<ge>0<else>"W" abs(self.x))<line_sep>res=self._res()<line_sep>dname="/%(res)sdarcsec/mea/%(dir)s/"%dict(res=res dir=dir)<line_sep><return>[self.url+dname+self._file_name()]<block_end><def_stmt>verifier self<block_start><return>check.is_gdal<block_end><def_stmt>options self<block_start><return>self.download_options<block_end><def_stmt>output_file self<block_start>fname=self._file_name()<line_sep><return>os.path.join(self.base_dir fname)<block_end><def_stmt>unpack self store tmp<block_start><with_stmt>store.upload_dir()<as>target<block_start>mkdir_p(os.path.join(target self.base_dir))<line_sep>output_file=os.path.join(target self.output_file())<line_sep>mask.negative(tmp.name "GTiff" output_file)<block_end><block_end><def_stmt>freeze_dry self<block_start><return>dict(type='gmted' x=self.x y=self.y)<block_end><block_end><class_stmt>GMTED(object)<block_start><def_stmt>__init__ self options={}<block_start>self.num_download_threads=options.get('num_download_threads')<line_sep>self.base_dir=options.get('base_dir' 'gmted')<line_sep>self.url=options['url']<line_sep>self.xs=options['xs']<line_sep>self.ys=options['ys']<line_sep>self.download_options=options<block_end><def_stmt>get_index self# GMTED is a static set of files - there's no need for an index, but we # do need a directory to store stuff in. <block_start><if_stmt><not>os.path.isdir(self.base_dir)<block_start>os.makedirs(self.base_dir)<block_end><block_end><def_stmt>existing_files self<block_start><for_stmt>base,dirs,files os.walk(self.base_dir)<block_start><for_stmt>f files<block_start><if_stmt>f.endswith('tif')<block_start><yield>os.path.join(base f)<block_end><block_end><block_end><block_end><def_stmt>rehydrate self data<block_start><assert_stmt>data.get('type')<eq>'gmted' "Unable to rehydrate %r from GMTED."%data<line_sep><return>GMTEDTile(self data['x'] data['y'])<block_end><def_stmt>downloads_for self tile<block_start>tiles=set()<line_sep># if the tile scale is greater than 20x the GMTED scale, then there's no # point in including GMTED, it'll be far too fine to make a difference. # GMTED is 7.5 arc seconds at best (30 at the poles). <if_stmt>tile.max_resolution()<g>20<times>7.5/3600<block_start><return>tiles<block_end># buffer by 0.1 degrees (48px) to grab neighbouring tiles to ensure # that there's no tile edge artefacts. tile_bbox=tile.latlon_bbox().buffer(0.1)<for_stmt>y self.ys<block_start><for_stmt>x self.xs<block_start>bbox=BoundingBox(x y x+30 y+20)<if_stmt>tile_bbox.intersects(bbox)<block_start>tiles.add(GMTEDTile(self x y))<block_end><block_end><block_end><return>tiles<block_end><def_stmt>vrts_for self tile<block_start>""" Returns a list of sets of tiles, with each list element intended as a separate VRT for use in GDAL. The reason for this is that GDAL doesn't do any compositing _within_ a single VRT, so if there are multiple overlapping source rasters in the VRT, only one will be chosen. This isn't often the case - most raster datasets are non-overlapping apart from deliberately duplicated margins. """<line_sep><return>[self.downloads_for(tile)]<block_end><def_stmt>srs self<block_start><return>srs.wgs84()<block_end><def_stmt>filter_type self src_res dst_res# seems like GRA_Lanczos has trouble with nodata, which is causing # "ringing" near the edges of the data. <block_start><return>gdal.GRA_Bilinear<if>src_res<g>dst_res<else>gdal.GRA_Cubic<block_end><def_stmt>_parse_bbox self ns_deg is_ns ew_deg is_ew res<block_start>bottom=int(ns_deg)<line_sep>left=int(ew_deg)<if_stmt>is_ns<eq>'S'<block_start>bottom=-bottom<block_end><if_stmt>is_ew<eq>'W'<block_start>left=-left<block_end>b=BoundingBox(left bottom left+30 bottom+20)<line_sep><return>b<block_end><block_end><def_stmt>create options<block_start><return>GMTED(options)<block_end>
<import_stmt>datetime<import_stmt>os<import_stmt>random<try_stmt><block_start><import_stmt>binutil# required to import from dreamcoder modules <block_end><except_stmt>ModuleNotFoundError<block_start><import_stmt>bin.binutil<block_end># alt import if called as module <import_from_stmt>dreamcoder.dreamcoder explorationCompression commandlineArguments<import_from_stmt>dreamcoder.domains.arithmetic.arithmeticPrimitives real real_division real_addition real_multiplication<import_from_stmt>dreamcoder.grammar Grammar<import_from_stmt>dreamcoder.program Primitive Abstraction Application<import_from_stmt>dreamcoder.recognition ImageFeatureExtractor<import_from_stmt>dreamcoder.task DifferentiableTask squaredErrorLoss<import_from_stmt>dreamcoder.type arrow treal<import_from_stmt>dreamcoder.utilities testTrainSplit eprint numberOfCPUs<def_stmt>makeTask name f actualParameters<block_start>xs=[x/100.<for>x range(-500 500)]<line_sep>maximum=10<line_sep>N=50<line_sep>inputs=[]<line_sep>outputs=[]<for_stmt>x xs<block_start><try_stmt><block_start>y=f(x)<block_end><except_stmt>BaseException<block_start><continue><block_end><if_stmt>abs(y)<l>maximum<block_start>inputs.append(float(x))<line_sep>outputs.append(float(y))<block_end><block_end><if_stmt>len(inputs)<ge>N<block_start>ex=list(zip(inputs outputs))<line_sep>ex=ex[::int(len(ex)/N)][:N]<line_sep>t=DifferentiableTask(name arrow(treal treal) [((x ) y)<for>x,y ex] BIC=1. restarts=360 steps=50 likelihoodThreshold=-0.05 temperature=0.1 actualParameters=actualParameters maxParameters=6 loss=squaredErrorLoss)<line_sep>t.f=f<line_sep><return>t<block_end><return><none><block_end><def_stmt>randomCoefficient m=5<block_start>t=0.3<line_sep>f=t+(random.random()<times>(m-t))<if_stmt>random.random()<g>0.5<block_start>f=-f<block_end>f=float("%0.1f"%f)<line_sep><return>f<block_end><def_stmt>randomOffset <block_start>c=randomCoefficient(m=2.5)<def_stmt>f x<block_start><return>x+c<block_end>name="x + %0.1f"%c<line_sep><return>name f<block_end><def_stmt>randomPolynomial order<block_start>coefficients=[randomCoefficient(m=2.5)<for>_ range(order+1)]<def_stmt>f x<block_start><return>sum(c<times>(x<power>(order-j))<for>j,c enumerate(coefficients))<block_end>name=""<for_stmt>j,c enumerate(coefficients)<block_start>e=order-j<if_stmt>e<eq>0<block_start>monomial=""<block_end><elif_stmt>e<eq>1<block_start>monomial="x"<block_end><else_stmt><block_start>monomial="x^%d"%e<block_end><if_stmt>j<eq>0<block_start>coefficient="%0.1f"%c<block_end><else_stmt><block_start><if_stmt>c<l>0<block_start>coefficient=" - %.01f"%(abs(c))<block_end><else_stmt><block_start>coefficient=" + %.01f"%c<block_end><block_end>name=name+coefficient+monomial<block_end><return>name f<block_end><def_stmt>randomFactored order<block_start>offsets=[randomCoefficient(m=5)<for>_ range(order)]<def_stmt>f x<block_start>p=1.<for_stmt>o offsets<block_start>p=p<times>(x+o)<block_end><return>p<block_end>name=""<for_stmt>c offsets<block_start><if_stmt>c<g>0<block_start>name<augadd>"(x + %0.1f)"%c<block_end><else_stmt><block_start>name<augadd>"(x - %0.1f)"%(abs(c))<block_end><block_end><return>name f<block_end><def_stmt>randomRational <block_start>no=random.choice([0 1])<line_sep>nn,n=randomPolynomial(no)<line_sep>nf=random.choice([1 2])<line_sep>dn,d=randomFactored(nf)<def_stmt>f x<block_start><return>n(x)/d(x)<block_end><if_stmt>no<eq>0<block_start>name="%s/[%s]"%(nn dn)<block_end><else_stmt><block_start>name="(%s)/[%s]"%(nn dn)<block_end><return>name f no+1+nf<block_end><def_stmt>randomPower <block_start>e=random.choice([1 2 3])<line_sep>c=randomCoefficient()<def_stmt>f x<block_start><return>c<times>(x<power>(-e))<block_end><if_stmt>e<eq>1<block_start>name="%0.1f/x"%c<block_end><else_stmt><block_start>name="%0.1f/x^%d"%(c e)<block_end><return>name f<block_end><def_stmt>prettyFunction f export<block_start><import_stmt>numpy<as>np<line_sep>n=200<line_sep>dx=10.<import_stmt>matplotlib<line_sep>#matplotlib.use('Agg') <import_stmt>matplotlib.pyplot<as>plot<line_sep>figure=plot.figure()<line_sep>plot.plot(np.arange(-dx dx 0.05) [0.5<times>f(x/2)<for>x np.arange(-dx dx 0.05)] linewidth=15 color='c')<line_sep>plot.ylim([-dx dx])<line_sep>plot.gca().set_xticklabels([])<line_sep>plot.gca().set_yticklabels([])<for_stmt>tic plot.gca().xaxis.get_major_ticks()<block_start>tic.tick1On=tic.tick2On=<false><block_end># plot.xlabel([]) #plot.yticks([]) #plot.axis('off') plot.grid(color='k' linewidth=2)<line_sep>plot.savefig(export)<line_sep>print(export)<line_sep>plot.close(figure)<block_end><def_stmt>drawFunction n dx f resolution=64<block_start><import_stmt>numpy<as>np<import_stmt>matplotlib<line_sep>matplotlib.use('Agg')<import_stmt>matplotlib.pyplot<as>plot<import_from_stmt>PIL Image<line_sep>figure=plot.figure()<line_sep>plot.plot(np.arange(-dx dx 0.05) [f(x)<for>x np.arange(-dx dx 0.05)] linewidth=20)<line_sep>plot.ylim([-10 10])<line_sep>plot.axis('off')<line_sep>figure.canvas.draw()<line_sep>data=np.frombuffer(figure.canvas.tostring_rgb() dtype=np.uint8)<line_sep>data=data.reshape(figure.canvas.get_width_height()[::-1]+(3 ))<line_sep>data=data[: : 0]<line_sep>data=255-data<line_sep>data=data/255.<line_sep># print "upper and lower bounds before # resizing",np.max(data),np.min(data),data.dtype data=np.array(Image.fromarray(data).resize(size=(resolution resolution) resample=Image.BICUBIC).getdata()).reshape((resolution resolution))<line_sep># print "upper and lower bounds after # resizing",np.max(data),np.min(data),data.dtype plot.close(figure)<line_sep><return>data<block_end><def_stmt>makeTasks <block_start>tasks=[]<line_sep>tasksPerType=35<line_sep>ts=[]<while_stmt>len(ts)<l>tasksPerType<block_start>n,f=randomOffset()<if_stmt>makeTask(n f 1)<is><none><block_start><continue><block_end>ts.append(makeTask(n f 1))<block_end>tasks<augadd>ts<for_stmt>o range(1 5)<block_start>ts=[]<while_stmt>len(ts)<l>tasksPerType<block_start>n,f=randomPolynomial(o)<if_stmt>makeTask(n f o+1)<is><none><block_start><continue><block_end>ts.append(makeTask(n f o+1))<block_end>tasks<augadd>ts<block_end>ts=[]<while_stmt>len(ts)<l>tasksPerType<times>3<block_start>n,f,df=randomRational()<if_stmt>makeTask(n f df)<is><none><block_start><continue><block_end>ts.append(makeTask(n f df))<block_end>tasks<augadd>ts<line_sep>ts=[]<while_stmt>len(ts)<l>tasksPerType<block_start>n,f=randomPower()<if_stmt>makeTask(n f 1)<is><none><block_start><continue><block_end>ts.append(makeTask(n f 1))<block_end>tasks<augadd>ts<line_sep><return>tasks<block_end><class_stmt>RandomParameterization(object)<block_start><def_stmt>primitive self e<block_start><if_stmt>e.name<eq>'REAL'<block_start><return>Primitive(str(e) e.tp randomCoefficient())<block_end><return>e<block_end><def_stmt>invented self e<block_start><return>e.body.visit(self)<block_end><def_stmt>abstraction self e<block_start><return>Abstraction(e.body.visit(self))<block_end><def_stmt>application self e<block_start><return>Application(e.f.visit(self) e.x.visit(self))<block_end><def_stmt>index self e<block_start><return>e<block_end><block_end>RandomParameterization.single=RandomParameterization()<class_stmt>FeatureExtractor(ImageFeatureExtractor)<block_start>special='differentiable'<def_stmt>__init__ self tasks testingTasks=[] cuda=<false> H=64<block_start>self.recomputeTasks=<true><line_sep>super(FeatureExtractor self).__init__(inputImageDimension=64 channels=1)<line_sep>self.tasks=tasks<block_end><def_stmt>featuresOfTask self t<block_start><return>self(t.features)<block_end><def_stmt>taskOfProgram self p t<block_start>p=p.visit(RandomParameterization.single)<def_stmt>f x<block_start><return>p.runWithArguments([x])<block_end>t=makeTask(str(p) f <none>)<if_stmt>t<is><none><block_start><return><none><block_end>t.features=drawFunction(200 5. t.f)<line_sep>delattr(t 'f')<line_sep><return>t<block_end><block_end><def_stmt>demo <block_start><import_from_stmt>PIL Image<line_sep>os.system("mkdir -p /tmp/rational_demo")<for_stmt>j,t enumerate(makeTasks())# range(100): <block_start>name,f=t.name t.f<line_sep>prettyFunction(f f"/tmp/rational_demo/{name.replace('/' '$')}.png")<line_sep>print(j "\n" name)<line_sep>a=drawFunction(200 5. f resolution=32)<times>255<line_sep>Image.fromarray(a).convert('RGB').save("/tmp/rational_demo/%d.png"%j)<block_end><assert_stmt><false><block_end>#demo() <def_stmt>rational_options p<block_start>p.add_argument("--smooth" action="store_true" default=<false> help="smooth likelihood model")<block_end><if_stmt>__name__<eq>"__main__"<block_start><import_stmt>time<line_sep>arguments=commandlineArguments(featureExtractor=FeatureExtractor iterations=6 CPUs=numberOfCPUs() structurePenalty=1. recognitionTimeout=7200 helmholtzRatio=0.5 activation="tanh" maximumFrontier=5 a=3 topK=2 pseudoCounts=30.0 extras=rational_options)<line_sep>primitives=[real # f1, real_division real_addition real_multiplication]<line_sep>baseGrammar=Grammar.uniform(primitives)<line_sep>random.seed(42)<line_sep>tasks=makeTasks()<line_sep>smooth=arguments.pop('smooth')<for_stmt>t tasks<block_start>t.features=drawFunction(200 10. t.f)<line_sep>delattr(t 'f')<if_stmt>smooth<block_start>t.likelihoodThreshold=<none><block_end><block_end>eprint("Got %d tasks..."%len(tasks))<line_sep>test,train=testTrainSplit(tasks 100)<line_sep>random.shuffle(test)<line_sep>test=test[:100]<line_sep>eprint("Training on" len(train) "tasks")<if_stmt><false><block_start>hardTasks=[t<for>t train<if>'/'<in>t.name<and>'['<in>t.name]<for_stmt>clamp [<true> <false>]<block_start><for_stmt>lr [0.1 0.05 0.5 1.]<block_start><for_stmt>steps [50 100 200]<block_start><for_stmt>attempts [10 50 100 200]<block_start><for_stmt>s [0.1 0.5 1 3]<block_start>start=time.time()<line_sep>losses=callCompiled(debugMany hardTasks clamp lr steps attempts s)<line_sep>losses=dict(zip(hardTasks losses))<line_sep>failures=0<for_stmt>t,l sorted(losses.items() key=<lambda>t_l:t_l[1])# print t,l <block_start><if_stmt>l<g>-t.likelihoodThreshold<block_start>failures<augadd>1<block_end><block_end>eprint("clamp,lr,steps, attempts,std" clamp lr steps attempts s)<line_sep>eprint("%d/%d failures"%(failures len(hardTasks)))<line_sep>eprint("dt=" time.time()-start)<line_sep>eprint()<line_sep>eprint()<block_end><block_end><block_end><block_end><block_end><assert_stmt><false><block_end>timestamp=datetime.datetime.now().isoformat()<line_sep>outputDirectory="experimentOutputs/rational/%s"%timestamp<line_sep>os.system("mkdir -p %s"%outputDirectory)<line_sep>explorationCompression(baseGrammar train outputPrefix="%s/rational"%outputDirectory evaluationTimeout=0.1 testingTasks=test **arguments)<block_end>
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """DiffWave architecture. Ported from PyTorch to JAX from https://github.com/philsyn/DiffWave-unconditional/blob/master/WaveNet.py """<import_from_stmt>typing Any Callable Iterable Optional Tuple<import_from_stmt>flax linen<as>nn<import_stmt>jax<import_from_stmt>jax numpy<as>jnp<import_stmt>numpy<as>np<import_from_stmt>autoregressive_diffusion.model.architecture_components input_embedding<import_from_stmt>autoregressive_diffusion.model.architecture_components layers<line_sep>Array=jnp.ndarray<line_sep>Shape=Iterable[int]<line_sep>Dtype=Any<line_sep>PRNGKey=Array<line_sep>InitializerFn=Callable[[PRNGKey Shape Dtype] Array]<class_stmt>ResBlock(nn.Module)<block_start>"""Step-conditioned Residual block."""<line_sep>features:int<line_sep>kernel_size:Tuple[int]=(3 )<line_sep>kernel_dilation:Tuple[int]=(1 )<line_sep>skip_features:Optional[int]=<none><line_sep>kernel_init:InitializerFn=nn.initializers.kaiming_normal()<line_sep>activation:Callable[[Array] Array]=jax.nn.swish<line_sep>is_causal:bool=<false><line_sep>@nn.compact<def_stmt>__call__ self x t_embed<block_start>"""Apply the residual block. Args: x: Inputs of shape [batch, <spatial>, features]. t_embed: Embedded time steps of shape [batch, dim]. Returns: Mapped inputs of shape [batch, <spatial>, features] for the output and skip connections. """<line_sep>in_features=x.shape[-1]<if_stmt>in_features<ne>self.features<block_start><raise>ValueError(f'DiffWave ResBlock requires the same number of input ({in_features})'<concat>f'and output ({self.features}) features.')<block_end>h=x<if_stmt>t_embed<is><not><none># Project time step embedding. <block_start>t_embed=nn.Dense(in_features name='step_proj')(self.activation(t_embed))<line_sep># Reshape to [batch, 1, ..., 1, in_features] for broadcast. t_embed=jnp.reshape(t_embed (-1 )+(1 )<times>len(self.kernel_size)+(in_features ))<line_sep>h<augadd>t_embed<block_end># Dilated gated conv. u=layers.CausalConv(self.features self.kernel_size kernel_dilation=self.kernel_dilation kernel_init=self.kernel_init padding='VALID'<if>self.is_causal<else>'SAME' is_causal=self.is_causal name='dilated_tanh')(h)<line_sep>v=layers.CausalConv(self.features self.kernel_size kernel_dilation=self.kernel_dilation kernel_init=self.kernel_init padding='VALID'<if>self.is_causal<else>'SAME' is_causal=self.is_causal name='dilated_sigmoid')(h)<line_sep>y=jax.nn.tanh(u)<times>jax.nn.sigmoid(v)<line_sep># Residual and skip convs. residual=nn.Conv(self.features (1 )<times>len(self.kernel_size) kernel_init=self.kernel_init name='residual')(y)<line_sep>skip=nn.Conv(self.skip_features<or>self.features (1 )<times>len(self.kernel_size) kernel_init=self.kernel_init name='skip')(y)<line_sep><return>(x+residual)/np.sqrt(2.) skip<block_end><block_end><class_stmt>ResGroup(nn.Module)<block_start>"""Residual group with skip connection aggregation and dilation cycling. Attributes: num_blocks: Number of residual blocks. features: Number of ResBlock features. skip_features: Number of ResBlock skip connection features. kernel_size: Kernel size for ResBlock-s. kernel_init: Convolutional kernel initializer. dilation_cycle: Dilation cycling length. is_causal: Whether to use a causal architecture. """<line_sep>num_blocks:int<line_sep>features:int<line_sep>skip_features:Optional[int]=<none><line_sep>kernel_size:Tuple[int]=(3 )<line_sep>kernel_init:InitializerFn=nn.initializers.kaiming_normal()<line_sep>dilation_cycle:int=12# Max dilation is 2 ** 11 = 2048. is_causal:bool=<false><line_sep>@nn.compact<def_stmt>__call__ self x t_embed<block_start>"""Apply a residual group. Args: x: Inputs of shape [batch, <spatial>, features]. t_embed: Embedded time steps of shape [batch, dim]. Returns: Mapped inputs of shape [batch, <spatial>, skip_features] """<line_sep>y=0.<for_stmt>i range(self.num_blocks)<block_start>x,skip=ResBlock(features=self.features skip_features=self.skip_features kernel_size=self.kernel_size kernel_dilation=(2<power>(i%self.dilation_cycle) ) kernel_init=self.kernel_init is_causal=self.is_causal)(x t_embed)<line_sep>y<augadd>skip<block_end>y<augdiv>np.sqrt(self.num_blocks)<line_sep><return>y<block_end><block_end><class_stmt>DiffWave(nn.Module)<block_start>"""DiffWave network architecture. Attributes: num_blocks: Number of residual blocks. features: Number of ResBlock features. max_time: Number of generation steps (i.e. data dimensionality). num_classes: Number of output classes. output_features: Number of output features. skip_features: Number of ResBlock skip connection features. kernel_size: Kernel size for ResBlock-s. kernel_init: Convolutional kernel initializer. dilation_cycle: ResGroup dilation cycling length. is_causal: Whether to use the causal architecture. """<line_sep>num_blocks:int<line_sep>features:int<line_sep>max_time:int<line_sep>num_classes:int<line_sep>output_features:Optional[int]=1<line_sep>skip_features:Optional[int]=<none><line_sep>kernel_size:Tuple[int]=(3 )<line_sep>kernel_init:InitializerFn=nn.initializers.kaiming_normal()<line_sep>dilation_cycle:int=12<line_sep>is_causal:bool=<false><line_sep>@nn.compact<def_stmt>__call__ self x t mask train context=<none><block_start>"""Apply the WaveDiff network. Args: x: Inputs of shape [batch, <spatial>, features]. t: Time steps of shape [batch]. mask: Array of the same shape as `x` giving the auto-regressive mask. train: If True, the model is ran in training. *Not* used in this architecture. context: Unused. Returns: Mapped inputs of shape [batch, <spatial>, skip_features] """<assert_stmt>context<is><none><line_sep># Sinusoidal features + MLP for time step embedding. # Note: this differs from the DiffWave embedding in several ways: # * Time embeddings have different dimensionality: 128-512-512 # vs 256-1024-1024. # * First convlution has kernel size 3 instead of 1. h,t_embed=input_embedding.InputProcessingAudio(num_classes=self.num_classes num_channels=self.features max_time=self.max_time is_causal=self.is_causal)(x t mask train)<del_stmt>x t mask<line_sep>h=nn.relu(h)<line_sep>h=ResGroup(num_blocks=self.num_blocks features=self.features skip_features=self.skip_features kernel_size=self.kernel_size dilation_cycle=self.dilation_cycle kernel_init=self.kernel_init is_causal=self.is_causal name='res_group')(h t_embed)<line_sep># Final convolution. h=nn.Conv(features=self.skip_features<or>self.features kernel_size=(1 )<times>len(self.kernel_size) kernel_init=self.kernel_init name='flower_conv')(h)<line_sep>h=nn.relu(h)<if_stmt>self.output_features<block_start>h=nn.Conv(features=self.output_features kernel_size=(1 )<times>len(self.kernel_size) kernel_init=nn.initializers.zeros name='class_conv')(h)<block_end><return>h<block_end><block_end>
<import_from_stmt>lyrebird application<import_from_stmt>.. checker<class_stmt>CustomDecoder<block_start><def_stmt>__call__ self rules=<none> *args **kw<block_start><def_stmt>func origin_func<block_start>func_type=checker.TYPE_DECODER<if_stmt><not>checker.scripts_tmp_storage.get(func_type)<block_start>checker.scripts_tmp_storage[func_type]=[]<block_end>checker.scripts_tmp_storage[func_type].append({'name':origin_func.__name__ 'func':origin_func 'rules':rules})<line_sep><return>origin_func<block_end><return>func<block_end>@staticmethod<def_stmt>register func_info<block_start>application.decoder.append(func_info)<block_end>@staticmethod<def_stmt>unregister func_info<block_start><if_stmt>func_info<in>application.decoder<block_start>application.decoder.remove(func_info)<block_end><block_end><block_end>decoder=CustomDecoder()<line_sep>
<import_stmt>typing<import_from_stmt>typing Optional List Union Tuple<import_from_stmt>labml.internal.util.colors StyleCode<import_from_stmt>.iterator Iterator<import_from_stmt>.loop Loop<import_from_stmt>.mix Mix<import_from_stmt>.sections Section OuterSection<import_from_stmt>..logger logger_singleton<as>logger<import_from_stmt>..logger.types LogPart<import_from_stmt>..tracker tracker_singleton<as>tracker<import_from_stmt>...logger Text<import_from_stmt>...utils.notice labml_notice<class_stmt>Monitor<block_start>__loop_indicators:List[Union[str Tuple[str Optional[StyleCode]]]]<line_sep>__is_looping:bool<def_stmt>__init__ self<block_start>self.__loop:Optional[Loop]=<none><line_sep>self.__sections:List[Section]=[]<line_sep>self.__is_looping=<false><line_sep>self.__loop_indicators=[]<line_sep>self.__is_silent=<false><block_end><def_stmt>clear self<block_start>self.__loop:Optional[Loop]=<none><line_sep>self.__sections:List[Section]=[]<line_sep>self.__is_looping=<false><line_sep>self.__loop_indicators=[]<block_end><def_stmt>silent self is_silent:bool=<true><block_start>self.__is_silent=is_silent<block_end><def_stmt>mix self total_iterations iterators:List[Tuple[str typing.Sized]] is_monit:bool<block_start><return>Mix(total_iterations=total_iterations iterators=iterators is_monit=is_monit logger=self)<block_end><def_stmt>iterate self name iterable:Union[typing.Iterable typing.Sized int] total_steps:Optional[int] * is_silent:bool is_children_silent:bool is_timed:bool section:Optional[Section]<block_start><return>Iterator(logger=self name=name iterable=iterable is_silent=is_silent is_timed=is_timed total_steps=total_steps is_children_silent=is_children_silent is_enumerate=<false> section=section)<block_end><def_stmt>enum self name iterable:typing.Sized * is_silent:bool is_children_silent:bool is_timed:bool section:Optional[Section]<block_start><return>Iterator(logger=self name=name iterable=iterable is_silent=is_silent is_timed=is_timed total_steps=<none> is_children_silent=is_children_silent is_enumerate=<true> section=section)<block_end><def_stmt>section self name * is_silent:bool is_timed:bool is_partial:bool is_new_line:bool is_children_silent:bool total_steps:float<arrow>Section<block_start><if_stmt>self.__is_looping<block_start><if_stmt>len(self.__sections)<ne>0<block_start>is_silent=<true><block_end>section=self.__loop.get_section(name=name is_silent=is_silent is_timed=is_timed is_partial=is_partial total_steps=total_steps parents=[s.name<for>s self.__sections])<line_sep>self.__sections.append(section)<block_end><else_stmt><block_start><if_stmt>len(self.__sections)<g>0<block_start><if_stmt>self.__sections[-1].is_silent<or>self.__sections[-1].is_children_silent<block_start>is_silent=<true><line_sep>is_children_silent=<true><block_end><block_end>self.__sections.append(OuterSection(monitor=self name=name is_silent=is_silent is_timed=is_timed is_partial=is_partial is_new_line=is_new_line is_children_silent=is_children_silent total_steps=total_steps level=len(self.__sections)))<block_end><return>self.__sections[-1]<block_end><def_stmt>progress self steps:float<block_start><if_stmt>len(self.__sections)<eq>0<block_start><raise>RuntimeError("You must be within a section to report progress")<block_end><if_stmt>self.__sections[-1].progress(steps)<block_start>self.__log_line()<block_end><block_end><def_stmt>set_successful self is_successful=<true><block_start><if_stmt>len(self.__sections)<eq>0<block_start><raise>RuntimeError("You must be within a section to report success")<block_end>self.__sections[-1].is_successful=is_successful<line_sep>self.__log_line()<block_end><def_stmt>loop self iterator_:typing.Collection * is_track:bool is_print_iteration_time:bool<block_start><if_stmt>len(self.__sections)<ne>0<block_start>labml_notice(['LabML Loop: ' ('Starting loop inside sections' Text.key) '\n' ('This could be because some iterators crashed in a previous cell in a notebook.' Text.meta)] is_danger=<false>)<line_sep>err=RuntimeError('Section outside loop')<for_stmt>s reversed(self.__sections)<block_start>s.__exit__(type(err) err err.__traceback__)<block_end># raise RuntimeError("Cannot start a loop within a section") <block_end>self.__loop=Loop(iterator=iterator_ monitor=self is_track=is_track is_print_iteration_time=is_print_iteration_time)<line_sep><return>self.__loop<block_end><def_stmt>start_loop self<block_start>self.__is_looping=<true><line_sep>tracker().start_loop(self.set_looping_indicators)<block_end><def_stmt>finish_loop self<block_start><if_stmt>len(self.__sections)<ne>0<block_start><raise>RuntimeError("Cannot be within a section when finishing the loop")<block_end>tracker().finish_loop()<line_sep>self.__loop=<none><line_sep>self.__is_looping=<false><block_end><def_stmt>section_enter self section<block_start><if_stmt>len(self.__sections)<eq>0<block_start><raise>RuntimeError("Entering a section without creating a section.\n"<concat>"Always use logger.section to create a section")<block_end><if_stmt>section<is><not>self.__sections[-1]<block_start><raise>RuntimeError("Entering a section other than the one last_created\n"<concat>"Always user with logger.section(...):")<block_end><if_stmt>len(self.__sections)<g>1<and><not>self.__sections[-2].is_parented<block_start>self.__sections[-2].make_parent()<if_stmt><not>self.__is_silent<and><not>self.__sections[-1].is_silent<block_start>logger().log([])<block_end><block_end>self.__log_line()<block_end><def_stmt>__log_looping_line self<block_start>parts=[(f"{tracker().global_step:8,}: " Text.highlight)]<line_sep>parts<augadd>self.__loop.log_sections()<line_sep>parts<augadd>self.__loop_indicators<line_sep>parts<augadd>self.__loop.log_progress()<if_stmt><not>self.__is_silent<block_start>logger().log(parts is_new_line=<false>)<block_end><block_end><def_stmt>__log_line self<block_start><if_stmt>self.__is_looping<block_start>self.__log_looping_line()<line_sep><return><block_end><if_stmt>len(self.__sections)<eq>0<block_start><return><block_end>parts=self.__sections[-1].log()<if_stmt>parts<is><none><block_start><return><block_end><if_stmt><not>self.__is_silent<block_start>logger().log(parts is_new_line=<false>)<block_end><block_end><def_stmt>set_looping_indicators self indicators:List[LogPart]<block_start>self.__loop_indicators=indicators<line_sep>self.__log_looping_line()<block_end><def_stmt>section_exit self section<block_start><if_stmt>len(self.__sections)<eq>0<block_start><raise>RuntimeError("Impossible")<block_end><if_stmt>section<is><not>self.__sections[-1]<block_start><raise>RuntimeError("Impossible")<block_end>self.__log_line()<line_sep>self.__sections.pop(-1)<block_end><block_end>_internal:Optional[Monitor]=<none><def_stmt>monitor_singleton <arrow>Monitor<block_start><global>_internal<if_stmt>_internal<is><none><block_start>_internal=Monitor()<block_end><return>_internal<block_end>
<import_stmt>esphome.codegen<as>cg<import_stmt>esphome.config_validation<as>cv<import_from_stmt>esphome.components mqtt sensor<import_from_stmt>esphome.const CONF_QOS CONF_TOPIC <import_from_stmt>.. mqtt_subscribe_ns<line_sep>DEPENDENCIES=["mqtt"]<line_sep>CONF_MQTT_PARENT_ID="mqtt_parent_id"<line_sep>MQTTSubscribeSensor=mqtt_subscribe_ns.class_("MQTTSubscribeSensor" sensor.Sensor cg.Component)<line_sep>CONFIG_SCHEMA=(sensor.sensor_schema(MQTTSubscribeSensor accuracy_decimals=1 ).extend({cv.GenerateID(CONF_MQTT_PARENT_ID):cv.use_id(mqtt.MQTTClientComponent) cv.Required(CONF_TOPIC):cv.subscribe_topic cv.Optional(CONF_QOS default=0):cv.mqtt_qos }).extend(cv.COMPONENT_SCHEMA))<async_keyword><def_stmt>to_code config<block_start>var=<await>sensor.new_sensor(config)<line_sep><await>cg.register_component(var config)<line_sep>parent=<await>cg.get_variable(config[CONF_MQTT_PARENT_ID])<line_sep>cg.add(var.set_parent(parent))<line_sep>cg.add(var.set_topic(config[CONF_TOPIC]))<line_sep>cg.add(var.set_qos(config[CONF_QOS]))<block_end>
<import_stmt>copy<import_stmt>functools<import_stmt>numpy<as>np<import_from_stmt>federatedml.statistic.data_overview get_header<import_from_stmt>federatedml.statistic.statics MultivariateStatisticalSummary<import_from_stmt>federatedml.util consts<import_from_stmt>federatedml.util LOGGER<import_from_stmt>federatedml.statistic data_overview<class_stmt>Imputer(object)<block_start>""" This class provides basic strategies for values replacement. It can be used as missing filled or outlier replace. You can use the statistics such as mean, median or max of each column to fill the missing value or replace outlier. """<def_stmt>__init__ self missing_value_list=<none><block_start>""" Parameters ---------- missing_value_list: list of str, the value to be replaced. Default None, if is None, it will be set to list of blank, none, null and na, which regarded as missing filled. If not, it can be outlier replace, and missing_value_list includes the outlier values """<if_stmt>missing_value_list<is><none><block_start>self.missing_value_list=['' 'none' 'null' 'na']<block_end><else_stmt><block_start>self.missing_value_list=missing_value_list<block_end>self.support_replace_method=['min' 'max' 'mean' 'median' 'quantile' 'designated']<line_sep>self.support_output_format={'str':str 'float':float 'int':int 'origin':<none>}<line_sep>self.support_replace_area={'min':'col' 'max':'col' 'mean':'col' 'median':'col' 'quantile':'col' 'designated':'col'}<line_sep>self.cols_fit_impute_rate=[]<line_sep>self.cols_transform_impute_rate=[]<block_end><def_stmt>get_missing_value_list self<block_start><return>self.missing_value_list<block_end><def_stmt>get_impute_rate self mode="fit"<block_start><if_stmt>mode<eq>"fit"<block_start><return>list(self.cols_fit_impute_rate)<block_end><elif_stmt>mode<eq>"transform"<block_start><return>list(self.cols_transform_impute_rate)<block_end><else_stmt><block_start><raise>ValueError("Unknown mode of {}".format(mode))<block_end><block_end>@staticmethod<def_stmt>__replace_missing_value_with_cols_transform_value_format data transform_list missing_value_list output_format<block_start>_data=copy.deepcopy(data)<line_sep>replace_cols_index_list=[]<for_stmt>i,v enumerate(_data)<block_start><if_stmt>str(v)<in>missing_value_list<block_start>_data[i]=output_format(transform_list[i])<line_sep>replace_cols_index_list.append(i)<block_end><else_stmt><block_start>_data[i]=output_format(v)<block_end><block_end><return>_data replace_cols_index_list<block_end>@staticmethod<def_stmt>__replace_missing_value_with_cols_transform_value data transform_list missing_value_list<block_start>_data=copy.deepcopy(data)<line_sep>replace_cols_index_list=[]<for_stmt>i,v enumerate(_data)<block_start><if_stmt>str(v)<in>missing_value_list<block_start>_data[i]=str(transform_list[i])<line_sep>replace_cols_index_list.append(i)<block_end><block_end><return>_data replace_cols_index_list<block_end>@staticmethod<def_stmt>__replace_missing_value_with_replace_value_format data replace_value missing_value_list output_format<block_start>_data=copy.deepcopy(data)<line_sep>replace_cols_index_list=[]<for_stmt>i,v enumerate(_data)<block_start><if_stmt>str(v)<in>missing_value_list<block_start>_data[i]=output_format(replace_value)<line_sep>replace_cols_index_list.append(i)<block_end><else_stmt><block_start>_data[i]=output_format(_data[i])<block_end><block_end><return>_data replace_cols_index_list<block_end>@staticmethod<def_stmt>__replace_missing_value_with_replace_value data replace_value missing_value_list<block_start>_data=copy.deepcopy(data)<line_sep>replace_cols_index_list=[]<for_stmt>i,v enumerate(_data)<block_start><if_stmt>str(v)<in>missing_value_list<block_start>_data[i]=str(replace_value)<line_sep>replace_cols_index_list.append(i)<block_end><block_end><return>_data replace_cols_index_list<block_end><def_stmt>__get_cols_transform_value self data replace_method quantile=<none><block_start>summary_obj=MultivariateStatisticalSummary(data -1 abnormal_list=self.missing_value_list)<line_sep>header=get_header(data)<if_stmt>replace_method<eq>consts.MIN<block_start>cols_transform_value=summary_obj.get_min()<block_end><elif_stmt>replace_method<eq>consts.MAX<block_start>cols_transform_value=summary_obj.get_max()<block_end><elif_stmt>replace_method<eq>consts.MEAN<block_start>cols_transform_value=summary_obj.get_mean()<block_end><elif_stmt>replace_method<eq>consts.MEDIAN<block_start>cols_transform_value=summary_obj.get_median()<block_end><elif_stmt>replace_method<eq>consts.QUANTILE<block_start><if_stmt>quantile<g>1<or>quantile<l>0<block_start><raise>ValueError("quantile should between 0 and 1, but get:{}".format(quantile))<block_end>cols_transform_value=summary_obj.get_quantile_point(quantile)<block_end><else_stmt><block_start><raise>ValueError("Unknown replace method:{}".format(replace_method))<block_end>cols_transform_value=[round(cols_transform_value[key] 6)<for>key header]<line_sep><return>cols_transform_value<block_end><def_stmt>__fit_replace self data replace_method replace_value=<none> output_format=<none> quantile=<none><block_start><if_stmt>replace_method<is><not><none><and>replace_method<ne>consts.DESIGNATED<block_start>cols_transform_value=self.__get_cols_transform_value(data replace_method quantile=quantile)<if_stmt>output_format<is><not><none><block_start>f=functools.partial(Imputer.__replace_missing_value_with_cols_transform_value_format transform_list=cols_transform_value missing_value_list=self.missing_value_list output_format=output_format)<block_end><else_stmt><block_start>f=functools.partial(Imputer.__replace_missing_value_with_cols_transform_value transform_list=cols_transform_value missing_value_list=self.missing_value_list)<block_end>transform_data=data.mapValues(f)<line_sep>LOGGER.info("finish replace missing value with cols transform value, replace method is {}".format(replace_method))<line_sep><return>transform_data cols_transform_value<block_end><else_stmt><block_start><if_stmt>replace_value<is><none><block_start><raise>ValueError("Replace value should not be None")<block_end><if_stmt>output_format<is><not><none><block_start>f=functools.partial(Imputer.__replace_missing_value_with_replace_value_format replace_value=replace_value missing_value_list=self.missing_value_list output_format=output_format)<block_end><else_stmt><block_start>f=functools.partial(Imputer.__replace_missing_value_with_replace_value replace_value=replace_value missing_value_list=self.missing_value_list)<block_end>transform_data=data.mapValues(f)<line_sep>LOGGER.info("finish replace missing value with replace value {}, replace method is:{}".format(replace_value replace_method))<line_sep>shape=data_overview.get_data_shape(data)<line_sep>replace_value=[replace_value<for>_ range(shape)]<line_sep><return>transform_data replace_value<block_end><block_end><def_stmt>__transform_replace self data transform_value replace_area output_format<block_start><if_stmt>replace_area<eq>'all'<block_start><if_stmt>output_format<is><not><none><block_start>f=functools.partial(Imputer.__replace_missing_value_with_replace_value_format replace_value=transform_value missing_value_list=self.missing_value_list output_format=output_format)<block_end><else_stmt><block_start>f=functools.partial(Imputer.__replace_missing_value_with_replace_value replace_value=transform_value missing_value_list=self.missing_value_list)<block_end><block_end><elif_stmt>replace_area<eq>'col'<block_start><if_stmt>output_format<is><not><none><block_start>f=functools.partial(Imputer.__replace_missing_value_with_cols_transform_value_format transform_list=transform_value missing_value_list=self.missing_value_list output_format=output_format)<block_end><else_stmt><block_start>f=functools.partial(Imputer.__replace_missing_value_with_cols_transform_value transform_list=transform_value missing_value_list=self.missing_value_list)<block_end><block_end><else_stmt><block_start><raise>ValueError("Unknown replace area {} in Imputer".format(replace_area))<block_end><return>data.mapValues(f)<block_end>@staticmethod<def_stmt>__get_impute_number some_data<block_start>impute_num_list=<none><line_sep>data_size=<none><for_stmt>line some_data<block_start>processed_data=line[1][0]<line_sep>index_list=line[1][1]<if_stmt><not>data_size<block_start>data_size=len(processed_data)<line_sep># data_size + 1, the last element of impute_num_list used to count the number of "some_data" impute_num_list=[0<for>_ range(data_size+1)]<block_end>impute_num_list[data_size]<augadd>1<for_stmt>index index_list<block_start>impute_num_list[index]<augadd>1<block_end><block_end><return>np.array(impute_num_list)<block_end><def_stmt>__get_impute_rate_from_replace_data self data<block_start>impute_number_statics=data.applyPartitions(self.__get_impute_number).reduce(<lambda>x y:x+y)<line_sep>cols_impute_rate=impute_number_statics[:-1]/impute_number_statics[-1]<line_sep><return>cols_impute_rate<block_end><def_stmt>fit self data replace_method=<none> replace_value=<none> output_format=consts.ORIGIN quantile=<none><block_start>""" Apply imputer for input data Parameters ---------- data: DTable, each data's value should be list replace_method: str, the strategy of imputer, like min, max, mean or designated and so on. Default None replace_value: str, if replace_method is designated, you should assign the replace_value which will be used to replace the value in imputer_value_list output_format: str, the output data format. The output data can be 'str', 'int', 'float'. Default origin, the original format as input data Returns ---------- fit_data:data_instance, data after imputer cols_transform_value: list, the replace value in each column """<if_stmt>output_format<not><in>self.support_output_format<block_start><raise>ValueError("Unsupport output_format:{}".format(output_format))<block_end>output_format=self.support_output_format[output_format]<if_stmt>isinstance(replace_method str)<block_start>replace_method=replace_method.lower()<if_stmt>replace_method<not><in>self.support_replace_method<block_start><raise>ValueError("Unknown replace method:{}".format(replace_method))<block_end><block_end><elif_stmt>replace_method<is><none><block_start>replace_value='0'<block_end><else_stmt><block_start><raise>ValueError("parameter replace_method should be str or None only")<block_end>process_data,cols_transform_value=self.__fit_replace(data replace_method replace_value output_format quantile=quantile)<line_sep>self.cols_fit_impute_rate=self.__get_impute_rate_from_replace_data(process_data)<line_sep>process_data=process_data.mapValues(<lambda>v:v[0])<line_sep>process_data.schema=data.schema<line_sep><return>process_data cols_transform_value<block_end><def_stmt>transform self data transform_value output_format=consts.ORIGIN<block_start>""" Transform input data using Imputer with fit results Parameters ---------- data: DTable, each data's value should be list transform_value: output_format: str, the output data format. The output data can be 'str', 'int', 'float'. Default origin, the original format as input data Returns ---------- transform_data:data_instance, data after transform """<if_stmt>output_format<not><in>self.support_output_format<block_start><raise>ValueError("Unsupport output_format:{}".format(output_format))<block_end>output_format=self.support_output_format[output_format]<line_sep># Now all of replace_method is "col", remain replace_area temporarily # replace_area = self.support_replace_area[replace_method] replace_area="col"<line_sep>process_data=self.__transform_replace(data transform_value replace_area output_format)<line_sep>self.cols_transform_impute_rate=self.__get_impute_rate_from_replace_data(process_data)<line_sep>process_data=process_data.mapValues(<lambda>v:v[0])<line_sep>process_data.schema=data.schema<line_sep><return>process_data<block_end><block_end>
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2012 California Institute of Technology. ALL RIGHTS RESERVED. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # United States Government Sponsorship acknowledged. This software is subject to # U.S. export control laws and regulations and has been classified as 'EAR99 NLR' # (No [Export] License Required except when exporting to an embargoed country, # end user, or in support of a prohibited end use). By downloading this software, # the user agrees to comply with all applicable U.S. export laws and regulations. # The user has the responsibility to obtain export licenses, or other export # authority as may be required before exporting this software to any 'EAR99' # embargoed foreign country or citizen of those countries. # # Author: <NAME> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <import_stmt>isceobj<import_stmt>stdproc<import_from_stmt>iscesys.ImageUtil.ImageUtil ImageUtil<as>IU<import_from_stmt>isceobj.Util.Polynomial Polynomial<import_from_stmt>isceobj.Util.Poly2D Poly2D<import_from_stmt>isceobj.Constants SPEED_OF_LIGHT<import_stmt>logging<import_stmt>numpy<as>np<import_stmt>datetime<import_stmt>os<line_sep>logger=logging.getLogger('isce.insar.runGeo2rdr')<def_stmt>runGeo2rdr self<block_start><import_from_stmt>zerodop.geo2rdr createGeo2rdr<import_from_stmt>isceobj.Planet.Planet Planet<line_sep>logger.info("Running geo2rdr")<line_sep>info=self._insar.loadProduct(self._insar.secondarySlcCropProduct)<line_sep>offsetsDir=self.insar.offsetsDirname<line_sep>os.makedirs(offsetsDir exist_ok=<true>)<line_sep>grdr=createGeo2rdr()<line_sep>grdr.configure()<line_sep>planet=info.getInstrument().getPlatform().getPlanet()<line_sep>grdr.slantRangePixelSpacing=info.getInstrument().getRangePixelSize()<line_sep>grdr.prf=info.PRF#info.getInstrument().getPulseRepetitionFrequency() grdr.radarWavelength=info.getInstrument().getRadarWavelength()<line_sep>grdr.orbit=info.getOrbit()<line_sep>grdr.width=info.getImage().getWidth()<line_sep>grdr.length=info.getImage().getLength()<line_sep>grdr.wireInputPort(name='planet' object=planet)<line_sep>grdr.lookSide=info.instrument.platform.pointingDirection<line_sep>grdr.setSensingStart(info.getSensingStart())<line_sep>grdr.rangeFirstSample=info.startingRange<line_sep>grdr.numberRangeLooks=1<line_sep>grdr.numberAzimuthLooks=1<if_stmt>self.insar.secondaryGeometrySystem.lower().startswith('native')<block_start>p=[x/info.PRF<for>x info._dopplerVsPixel]<block_end><else_stmt><block_start>p=[0.]<block_end>grdr.dopplerCentroidCoeffs=p<line_sep>grdr.fmrateCoeffs=[0.]<line_sep>###Input and output files grdr.rangeOffsetImageName=os.path.join(offsetsDir self.insar.rangeOffsetFilename)<line_sep>grdr.azimuthOffsetImageName=os.path.join(offsetsDir self.insar.azimuthOffsetFilename)<line_sep>latFilename=os.path.join(self.insar.geometryDirname self.insar.latFilename+'.full')<line_sep>lonFilename=os.path.join(self.insar.geometryDirname self.insar.lonFilename+'.full')<line_sep>heightFilename=os.path.join(self.insar.geometryDirname self.insar.heightFilename+'.full')<line_sep>demImg=isceobj.createImage()<line_sep>demImg.load(heightFilename+'.xml')<line_sep>demImg.setAccessMode('READ')<line_sep>grdr.demImage=demImg<line_sep>latImg=isceobj.createImage()<line_sep>latImg.load(latFilename+'.xml')<line_sep>latImg.setAccessMode('READ')<line_sep>grdr.latImage=latImg<line_sep>lonImg=isceobj.createImage()<line_sep>lonImg.load(lonFilename+'.xml')<line_sep>lonImg.setAccessMode('READ')<line_sep>grdr.lonImage=lonImg<line_sep>grdr.outputPrecision='DOUBLE'<line_sep>grdr.geo2rdr()<line_sep><return><block_end>
# Generated by Django 2.2.16 on 2021-02-16 20:27 <import_stmt>awx.main.fields<import_from_stmt>django.db migrations<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('main' '0128_organiaztion_read_roles_ee_admin') ]<line_sep>operations=[migrations.AddField(model_name='unifiedjob' name='installed_collections' field=awx.main.fields.JSONBField(blank=<true> default=dict editable=<false> help_text='The Collections names and versions installed in the execution environment.') ) ]<block_end>
# Implementation based on pytorch 1.6.0 <import_from_stmt>.lane_seg_loss *<import_from_stmt>.hungarian_loss *<line_sep>
# See LICENSE for licensing information. # # Copyright (c) 2016-2021 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # <import_stmt>debug<import_stmt>pgate<import_from_stmt>vector vector<import_from_stmt>sram_factory factory<import_from_stmt>tech layer<class_stmt>pinvbuf(pgate.pgate)<block_start>""" This is a simple inverter/buffer used for driving loads. It is used in the column decoder for 1:2 decoding and as the clock buffer. """<def_stmt>__init__ self name size=4 height=<none><block_start>debug.info(1 "creating pinvbuf {}".format(name))<line_sep>self.add_comment("size: {}".format(size))<line_sep>self.stage_effort=4<line_sep>self.row_height=height<line_sep># FIXME: Change the number of stages to support high drives. # stage effort of 4 or less # The pinvbuf has a FO of 2 for the first stage, so the second stage # should be sized "half" to prevent loading of the first stage self.size=size<line_sep>self.predriver_size=max(int(self.size/(self.stage_effort/2)) 1)<line_sep># Creates the netlist and layout super().__init__(name)<block_end><def_stmt>create_netlist self<block_start>self.add_pins()<line_sep>self.add_modules()<line_sep>self.create_insts()<block_end><def_stmt>create_layout self<block_start>self.width=2<times>self.inv1.width+self.inv2.width<line_sep>self.height=2<times>self.inv1.height<line_sep>self.place_modules()<line_sep>self.route_wires()<line_sep>self.add_layout_pins()<line_sep>self.add_boundary()<line_sep>self.offset_all_coordinates()<block_end><def_stmt>add_pins self<block_start>self.add_pin("A")<line_sep>self.add_pin("Zb")<line_sep>self.add_pin("Z")<line_sep>self.add_pin("vdd")<line_sep>self.add_pin("gnd")<block_end><def_stmt>add_modules self# Shield the cap, but have at least a stage effort of 4 <block_start>input_size=max(1 int(self.predriver_size/self.stage_effort))<line_sep>self.inv=factory.create(module_type="pinv" size=input_size height=self.row_height)<line_sep>self.add_mod(self.inv)<line_sep>self.inv1=factory.create(module_type="pinv" size=self.predriver_size height=self.row_height)<line_sep>self.add_mod(self.inv1)<line_sep>self.inv2=factory.create(module_type="pinv" size=self.size height=self.row_height)<line_sep>self.add_mod(self.inv2)<block_end><def_stmt>create_insts self# Create INV1 (capacitance shield) <block_start>self.inv1_inst=self.add_inst(name="buf_inv1" mod=self.inv)<line_sep>self.connect_inst(["A" "zb_int" "vdd" "gnd"])<line_sep>self.inv2_inst=self.add_inst(name="buf_inv2" mod=self.inv1)<line_sep>self.connect_inst(["zb_int" "z_int" "vdd" "gnd"])<line_sep>self.inv3_inst=self.add_inst(name="buf_inv3" mod=self.inv2)<line_sep>self.connect_inst(["z_int" "Zb" "vdd" "gnd"])<line_sep>self.inv4_inst=self.add_inst(name="buf_inv4" mod=self.inv2)<line_sep>self.connect_inst(["zb_int" "Z" "vdd" "gnd"])<block_end><def_stmt>place_modules self# Add INV1 to the left (capacitance shield) <block_start>self.inv1_inst.place(vector(0 0))<line_sep># Add INV2 to the right of INV1 self.inv2_inst.place(vector(self.inv1_inst.rx() 0))<line_sep># Add INV3 to the right of INV2 self.inv3_inst.place(vector(self.inv2_inst.rx() 0))<line_sep># Add INV4 flipped to the bottom aligned with INV2 self.inv4_inst.place(offset=vector(self.inv2_inst.rx() 2<times>self.inv2.height) mirror="MX")<block_end><def_stmt>route_wires self<block_start><if_stmt>"li"<in>layer<block_start>route_stack=self.li_stack<block_end><else_stmt><block_start>route_stack=self.m1_stack<block_end># inv1 Z to inv2 A z1_pin=self.inv1_inst.get_pin("Z")<line_sep>a2_pin=self.inv2_inst.get_pin("A")<line_sep>mid_point=vector(z1_pin.cx() a2_pin.cy())<line_sep>self.add_path(z1_pin.layer [z1_pin.center() mid_point a2_pin.center()])<line_sep>self.add_via_stack_center(from_layer=z1_pin.layer to_layer=a2_pin.layer offset=a2_pin.center())<line_sep># inv2 Z to inv3 A z2_pin=self.inv2_inst.get_pin("Z")<line_sep>a3_pin=self.inv3_inst.get_pin("A")<line_sep>mid_point=vector(z2_pin.cx() a3_pin.cy())<line_sep>self.add_path(z2_pin.layer [z2_pin.center() mid_point a3_pin.center()])<line_sep>self.add_via_stack_center(from_layer=z2_pin.layer to_layer=a3_pin.layer offset=a3_pin.center())<line_sep># inv1 Z to inv4 A (up and over) z1_pin=self.inv1_inst.get_pin("Z")<line_sep>a4_pin=self.inv4_inst.get_pin("A")<line_sep>mid_point=vector(z1_pin.cx() a4_pin.cy())<line_sep>self.add_wire(route_stack [z1_pin.center() mid_point a4_pin.center()])<line_sep>self.add_via_stack_center(from_layer=z1_pin.layer to_layer=route_stack[2] offset=z1_pin.center())<block_end><def_stmt>add_layout_pins self# Continous vdd rail along with label. <block_start>vdd_pin=self.inv1_inst.get_pin("vdd")<line_sep>self.add_layout_pin(text="vdd" layer=vdd_pin.layer offset=vdd_pin.ll().scale(0 1) width=self.width height=vdd_pin.height())<line_sep># Continous vdd rail along with label. gnd_pin=self.inv4_inst.get_pin("gnd")<line_sep>self.add_layout_pin(text="gnd" layer=gnd_pin.layer offset=gnd_pin.ll().scale(0 1) width=self.width height=gnd_pin.height())<line_sep># Continous gnd rail along with label. gnd_pin=self.inv1_inst.get_pin("gnd")<line_sep>self.add_layout_pin(text="gnd" layer=gnd_pin.layer offset=gnd_pin.ll().scale(0 1) width=self.width height=vdd_pin.height())<line_sep>z_pin=self.inv4_inst.get_pin("Z")<line_sep>self.add_layout_pin_rect_center(text="Z" layer=z_pin.layer offset=z_pin.center())<line_sep>zb_pin=self.inv3_inst.get_pin("Z")<line_sep>self.add_layout_pin_rect_center(text="Zb" layer=zb_pin.layer offset=zb_pin.center())<line_sep>a_pin=self.inv1_inst.get_pin("A")<line_sep>self.add_layout_pin_rect_center(text="A" layer=a_pin.layer offset=a_pin.center())<block_end><block_end>
<class_stmt>IndexingError(Exception)<block_start>"""Exception raised for errors in the indexing flow. Attributes: type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists' blocknumber -- block number of error blockhash -- block hash of error txhash -- transaction hash of error message -- error message """<def_stmt>__init__ self type blocknumber blockhash txhash message<block_start>super().__init__(message)<line_sep>self.type=type<line_sep>self.blocknumber=blocknumber<line_sep>self.blockhash=blockhash<line_sep>self.txhash=txhash<line_sep>self.message=message<block_end><block_end>
<import_stmt>pytest<import_from_stmt>.. rank retrieve<def_stmt>cherche_retrievers on:str k:int=<none><block_start>"""List of retrievers available in cherche."""<line_sep><yield><from>[retrieve.TfIdf(key="title" on=on documents=documents() k=k) retrieve.BM25Okapi(key="title" on=on documents=documents() k=k) retrieve.BM25L(key="title" on=on documents=documents() k=k) retrieve.Lunr(key="title" on=on documents=documents() k=k) ]<block_end><def_stmt>documents <block_start><return>[{"title":"Paris" "article":"This town is the capital of France" "author":"Wikipedia"} {"title":"Eiffel tower" "article":"Eiffel tower is based in Paris" "author":"Wikipedia" } {"title":"Montreal" "article":"Montreal is in Canada." "author":"Wikipedia"} ]<block_end>@pytest.mark.parametrize("retriever, documents, k" [pytest.param(retriever documents() k id=f"retriever: {retriever.__class__.__name__}, k: {k}" )<for>k [<none> 0 2 4]<for>retriever cherche_retrievers(on="article" k=k)] )<def_stmt>test_retriever retriever documents:list k:int<block_start>"""Test retriever. Test if the number of retrieved documents is coherent. Check for unknown tokens in the corpus, should returns an empty list. """<line_sep>retriever=retriever+documents<line_sep>retriever.add(documents)<line_sep># A single document contains town. answers=retriever(q="town")<if_stmt>k<is><none><or>k<ge>1<block_start><assert_stmt>len(answers)<eq>1<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>0<block_end><for_stmt>sample answers<block_start><for_stmt>key ["title" "article" "author"]<block_start><assert_stmt>key<in>sample<block_end><block_end># Unknown token. answers=retriever(q="Unknown")<assert_stmt>len(answers)<eq>0<line_sep># All documents contains "Montreal Eiffel France" answers=retriever(q="Montreal Eiffel France")<if_stmt>k<is><none><or>k<ge>len(documents)<block_start><assert_stmt>len(answers)<eq>len(documents)<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>k<block_end><block_end>@pytest.mark.parametrize("retriever, documents, k" [pytest.param(retriever documents() k id=f"Multiple fields retriever: {retriever.__class__.__name__}, k: {k}" )<for>k [<none> 0 2 4]<for>retriever cherche_retrievers(on=["article" "title" "author"] k=k)] )<def_stmt>test_fields_retriever retriever documents:list k:int<block_start>"""Test retriever when providing multiples fields."""<line_sep>retriever=retriever+documents<line_sep># All documents have Wikipedia as author. answers=retriever(q="Wikipedia")<if_stmt>k<is><none><or>k<ge>len(documents)<block_start><assert_stmt>len(answers)<eq>len(documents)<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>max(k 0)<block_end><for_stmt>sample answers<block_start><for_stmt>key ["title" "article" "author"]<block_start><assert_stmt>key<in>sample<block_end><block_end># Unknown token. answers=retriever(q="Unknown")<assert_stmt>len(answers)<eq>0<line_sep># Two documents contains paris answers=retriever(q="Paris")<if_stmt>k<is><none><or>k<ge>2<block_start><assert_stmt>len(answers)<eq>2<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>max(k 0)<block_end><block_end>@pytest.mark.parametrize("documents, k" [pytest.param(documents() k id=f"retriever: Flash, k: {k}" )<for>k [<none> 0 2 4]] )<def_stmt>test_flash documents:list k:int<block_start>"""Test Flash retriever."""<line_sep># Reset retriever retriever=retrieve.Flash(key="title" k=k on="title")+documents<line_sep>retriever.add(documents)<line_sep># A single document contains town. answers=retriever(q="Paris")<if_stmt>k<is><none><or>k<ge>1<block_start><assert_stmt>len(answers)<eq>1<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>0<block_end><for_stmt>sample answers<block_start><for_stmt>key ["title" "article" "author"]<block_start><assert_stmt>key<in>sample<block_end><block_end># Unknown token. answers=retriever(q="Unknown")<assert_stmt>len(answers)<eq>0<line_sep># All documents contains is answers=retriever(q="<NAME>")<if_stmt>k<is><none><or>k<ge>len(documents)<block_start><assert_stmt>len(answers)<eq>len(documents)<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>k<block_end><block_end>@pytest.mark.parametrize("documents, k" [pytest.param(documents() k id=f"retriever: ElasticSearch, k: {k}" )<for>k [<none> 0 2 4]] )<def_stmt>test_elastic documents k<block_start>"""Test Elasticsearch if elastic server is running. Test elasticsearch as a retriever for a single field and multiple fields. Test if storing"""<import_from_stmt>elasticsearch Elasticsearch<import_from_stmt>sentence_transformers SentenceTransformer<line_sep>es=Elasticsearch()<if_stmt>es.ping()<block_start>ranker=rank.Encoder(key="title" encoder=SentenceTransformer("sentence-transformers/all-mpnet-base-v2" ).encode on=["title" "article" "author"] k=k )<line_sep>retriever=retrieve.Elastic(key="title" on="article" k=k es=es index="test_cherche")<line_sep>retriever.reset()<line_sep>retriever.add(documents)<line_sep>test_retriever(retriever=retriever documents=documents k=k)<line_sep>retriever=retrieve.Elastic(key="title" on=["title" "article" "author"] k=k es=es index="test_cherche")<line_sep>retriever.reset()<line_sep>retriever.add(documents)<line_sep>test_fields_retriever(retriever documents=documents k=k)<line_sep># Store embeddings using Elasticsearch retriever.reset()<line_sep>retriever.add_embeddings(documents=documents ranker=ranker)<line_sep>pipeline=retriever+ranker<line_sep>answers=pipeline("Paris")<if_stmt>k<is><none><or>k<ge>2<block_start><assert_stmt>len(answers)<eq>2<block_end><else_stmt><block_start><assert_stmt>len(answers)<eq>max(k 0)<block_end><block_end><block_end>
""" l_system_plugin """<import_from_future_stmt> absolute_import division print_function<import_stmt>logging<import_from_stmt>mcedit2.editortools.generate GeneratePlugin<import_from_stmt>mcedit2.synth.l_system renderBlocks renderSceneNodes applyReplacementsIterated<import_from_stmt>mcedit2.util.showprogress showProgress<import_from_stmt>mcedit2.widgets.spinslider SpinSlider<line_sep>log=logging.getLogger(__name__)<class_stmt>LSystemPlugin(GeneratePlugin)<block_start>""" A GeneratePlugin subclass intended for driving an L-system. Most of the GeneratePlugin methods are already implemented. To use an LSystemPlugin, you need to implement `getOptionsWidget` and `createInitialSymbol` - after that, previewing and generating the L-System is taken care of by LSystemPlugin. In your implementation of `getOptionsWidget`, you should add `self.iterationsSlider` to your widget to control the iteration depth. A `recursive` attribute is also available. If your L-System is not recursively defined - that is, a finite number of iterations will result in a symbol list that has no further `replace` methods defined, you may set the `recursive` attribute of the LSystemPlugin to False. Setting `recursive` to False will cause the block and schematic renderer to run the replacement rules until no further replacements occur (or until MAX_ITERATIONS iterations), and the value of `iterationsSlider` will be ignored for the final generation. The `iterationsSlider` will still affect the GL rendering, which is useful for inspecting the system's state after every iteration. """<line_sep>recursive=<true><line_sep>MAX_ITERATIONS=50<def_stmt>__init__ self editorSession<block_start>super(LSystemPlugin self).__init__(editorSession)<line_sep>self.optionsWidget=<none><line_sep>self.iterationsSlider=SpinSlider()<line_sep>self.iterationsSlider.setMinimum(1)<line_sep>self.iterationsSlider.setMaximum(50)<line_sep>self.iterationsSlider.setValue(3)<line_sep>self.iterationsSlider.valueChanged.connect(self.updatePreview)<block_end><def_stmt>createInitialSymbol self bounds<block_start>""" Create and return the initial Symbol for the L-System. The symbol is typically initialized using values input by the user via the options widget. :param bounds: The bounding box selected with the Generate tool, in world coordinates. :type bounds: BoundingBox :return: The initial Symbol for this L-System :rtype: Symbol """<line_sep><raise>NotImplementedError<block_end><def_stmt>createSymbolList self bounds indefinite=<false><block_start>system=self.createInitialSymbol(bounds)<line_sep>symbol_list=[system]<if_stmt>indefinite<block_start>max_iterations=self.MAX_ITERATIONS<block_end><else_stmt><block_start>max_iterations=self.iterationsSlider.value()<block_end><def_stmt>process _symbol_list<block_start><for_stmt>iteration,_symbol_list applyReplacementsIterated(_symbol_list max_iterations)<block_start><yield>iteration max_iterations<block_end><yield>_symbol_list<block_end>symbol_list=showProgress("Generating..." process(symbol_list) cancel=<true>)<if_stmt>symbol_list<is><false><block_start><return><none><block_end><return>symbol_list<block_end><def_stmt>getPreviewNode self bounds<block_start>symbol_list=self.createSymbolList(bounds)<if_stmt>symbol_list<is><none><block_start><return><none><block_end>log.info("Rendering symbols to OpenGL")<line_sep>sceneNodes=self.renderSceneNodes(symbol_list)<line_sep><return>sceneNodes<block_end><def_stmt>renderSceneNodes self symbol_list<block_start><return>renderSceneNodes(symbol_list)<block_end><def_stmt>generateInSchematic self dimension originalBounds<block_start>symbol_list=self.createSymbolList(originalBounds)<if_stmt>symbol_list<is><none><block_start><return><none><block_end>log.info("Rendering symbols to blocks")<line_sep>rendering=self.renderBlocks(symbol_list)<line_sep>log.info("Editing %d blocks"%len(rendering))<for_stmt>x,y,z,blockType rendering<block_start>x<augsub>originalBounds.minx<line_sep>y<augsub>originalBounds.miny<line_sep>z<augsub>originalBounds.minz<line_sep>dimension.setBlock(x y z blockType)<block_end><block_end><def_stmt>renderBlocks self symbol_list<block_start><return>renderBlocks(symbol_list)<block_end><block_end>
<import_stmt>math<def_stmt>isOn S j<block_start><return>(S&(1<lshift>j))<block_end><def_stmt>setBit S j<block_start><return>(S|(1<lshift>j))<block_end><def_stmt>clearBit S j<block_start><return>(S&(~(1<lshift>j)))<block_end><def_stmt>toggleBit S j<block_start><return>(S^(1<lshift>j))<block_end><def_stmt>lowBit S<block_start><return>(S&(-S))<block_end><def_stmt>setAll n<block_start><return>((1<lshift>n)-1)<block_end><def_stmt>modulo S N# returns S % N, where N is a power of 2 <block_start><return>((S)&(N-1))<block_end><def_stmt>isPowerOfTwo S<block_start><return>(<not>(S&(S-1)))<block_end><def_stmt>nearestPowerOfTwo S<block_start><return>1<lshift>round(math.log2(S))<block_end><def_stmt>turnOffLastBit S<block_start><return>(S&(S-1))<block_end><def_stmt>turnOnLastZero S<block_start><return>((S)|(S+1))<block_end><def_stmt>turnOffLastConsecutiveBits S<block_start><return>((S)&(S+1))<block_end><def_stmt>turnOnLastConsecutiveZeroes S<block_start><return>((S)|(S-1))<block_end><def_stmt>printSet vS# in binary representation <block_start>print("S = {} = {:b}".format(vS vS))<block_end><def_stmt>main <block_start>print("1. Representation (all indexing are 0-based and counted from right)")<line_sep>S=34<line_sep>printSet(S)<line_sep>print()<line_sep>print("2. Multiply S by 2, then divide S by 4 (2x2), then by 2")<line_sep>S=34<line_sep>printSet(S)<line_sep>S=S<lshift>1<line_sep>printSet(S)<line_sep>S=S<rshift>2<line_sep>printSet(S)<line_sep>S=S<rshift>1<line_sep>printSet(S)<line_sep>print()<line_sep>print("3. Set/turn on the 3-rd item of the set")<line_sep>S=34<line_sep>printSet(S)<line_sep>S=setBit(S 3)<line_sep>printSet(S)<line_sep>print()<line_sep>print("4. Check if the 3-rd and then 2-nd item of the set is on?")<line_sep>S=42<line_sep>printSet(S)<line_sep>T=isOn(S 3)<line_sep>print("T = {}, {}".format(T "ON"<if>T<else>"OFF"))<line_sep>T=isOn(S 2)<line_sep>print("T = {}, {}".format(T "ON"<if>T<else>"OFF"))<line_sep>print()<line_sep>print("5. Clear/turn off the 1-st item of the set")<line_sep>S=42<line_sep>printSet(S)<line_sep>S=clearBit(S 1)<line_sep>printSet(S)<line_sep>print()<line_sep>print("6. Toggle the 2-nd item and then 3-rd item of the set")<line_sep>S=40<line_sep>printSet(S)<line_sep>S=toggleBit(S 2)<line_sep>printSet(S)<line_sep>S=toggleBit(S 3)<line_sep>printSet(S)<line_sep>print()<line_sep>print("7. Check the first bit from right that is on")<line_sep>S=40<line_sep>printSet(S)<line_sep>T=lowBit(S)<line_sep>print("T = {} (this is always a power of 2)".format(T))<line_sep>S=52<line_sep>printSet(S)<line_sep>T=lowBit(S)<line_sep>print("T = {} (this is always a power of 2)".format(T))<line_sep>print()<line_sep>print("8. Turn on all bits in a set of size n = 6")<line_sep>S=setAll(6)<line_sep>printSet(S)<line_sep>print()<line_sep>print("9. Other tricks (not shown in the book)")<line_sep>print("8 % 4 = {}".format(modulo(8 4)))<line_sep>print("7 % 4 = {}".format(modulo(7 4)))<line_sep>print("6 % 4 = {}".format(modulo(6 4)))<line_sep>print("5 % 4 = {}".format(modulo(5 4)))<line_sep>print("is {} power of two? {}".format(9 isPowerOfTwo(9)))<line_sep>print("is {} power of two? {}".format(8 isPowerOfTwo(8)))<line_sep>print("is {} power of two? {}".format(7 isPowerOfTwo(7)))<for_stmt>i range(1 17)<block_start>print("Nearest power of two of {} is {}".format(i nearestPowerOfTwo(i)))<block_end>print("S = {}, turn off last bit in S, S = {}".format(40 turnOffLastBit(40)))<line_sep>print("S = {}, turn on last zero in S, S = {}".format(41 turnOnLastZero(41)))<line_sep>print("S = {}, turn off last consecutive bits in S, S = {}".format(39 turnOffLastConsecutiveBits(39)))<line_sep>print("S = {}, turn on last consecutive zeroes in S, S = {}".format(36 turnOnLastConsecutiveZeroes(36)))<block_end>main()<line_sep>
<import_from_stmt>graphics *<line_sep># --- constants --- WIDTH=300<line_sep>HEIGHT=300<line_sep># --- functions --- <def_stmt>moves # move figure 1 <block_start>s=win.itemcget(fig1 'start')<line_sep>win.itemconfig(fig1 start=float(s)+5)<line_sep># move figure 2 s=win.itemcget(fig2 'start')<line_sep>win.itemconfig(fig2 start=float(s)+5)<line_sep># move figure 3 s=win.itemcget(fig3 'start')<line_sep>win.itemconfig(fig3 start=float(s)+5)<line_sep># run again after 100ms (0.1s) win.after(100 moves)<block_end># --- main ---- win=GraphWin("Patch" WIDTH HEIGHT)<line_sep>bbox=(5 5 WIDTH-5 HEIGHT-5)<line_sep>fig1=win.create_arc(bbox fill="red" outline='green' width=3 start=0 extent=90 style='arc')<line_sep>fig2=win.create_arc(bbox fill="red" outline='green' width=3 start=95 extent=90 style='chord')<line_sep>fig3=win.create_arc(bbox fill="red" outline='green' width=3 start=190 extent=90 style='pieslice')<line_sep># run first time - to start animation moves()<line_sep>#win.getKey() win.getMouse()<line_sep>win.close()<line_sep>
# -*- coding: utf-8 -*- """ Created on Thu Apr 05 19:00:19 2018 @author: juherask """<line_sep># Written in Python 2.7, but try to maintain Python 3+ compatibility <import_from_future_stmt> print_function<import_from_future_stmt> division<import_stmt>sys<import_stmt>unittest<import_from_stmt>time time<import_stmt>numpy<as>np<import_from_stmt>local_search LSOPT do_local_search<import_from_stmt>local_search.solution_operators do_3optstar_move<import_from_stmt>classic_heuristics.nearest_neighbor nearest_neighbor_init<import_from_stmt>cvrp_io generate_CVRP<import_from_stmt>cvrp_ops check_solution_feasibility calculate_objective<import_from_stmt>util sol2routes routes2sol<import_from_stmt>test_intra_route_local_search_operation Test3Opt<line_sep>PRINT_ONLY_FINAL_RESULT=<true><def_stmt>_intra_route_3optstar_call sol D strategy=LSOPT.FIRST_ACCEPT<block_start><return>do_3optstar_move(sol D [1.0]<times>len(D) len(D) <none> strategy)<block_end><class_stmt>TestIntraRouteMoves3OptStarSolutionOperator(Test3Opt)<block_start>""" This tests all the move operators on a single route. The test reuses the test_local_search_operation.Test3Opt unit test. """<def_stmt>setUp self<block_start>super(TestIntraRouteMoves3OptStarSolutionOperator self).setUp()<line_sep>self.move_op=_intra_route_3optstar_call<block_end><block_end>#TODO: write this #class TestInterRouteMoves3OptStarSolutionOperator(unittest.TestCase): # e.g. 6 nodes on a circular formation, depot at the center but tad closer to one <def_stmt>_strategy_to_str strategy<block_start><if_stmt>LSOPT.FIRST_ACCEPT<block_start><return>"FIRST_ACCEPT"<block_end><elif_stmt>LSOPT.BEST_ACCEPT<block_start><return>"BEST_ACCEPT"<block_end><else_stmt><block_start><return>"N/A"<block_end><block_end><class_stmt>TestSmoke3OptStarSolutionOperator(unittest.TestCase)<block_start><def_stmt>setUp self<block_start>self.D=np.array([[0 195 168 293 236 276] [195 0 223 225 226 434] [168 223 0 158 377 236] [293 225 158 0 440 380] [236 226 377 440 0 507] [276 434 236 380 507 0]])<line_sep>self.d=[0 14 1 24 50 13]<line_sep>self.C=50<line_sep>self.initial_sol=[0 5 3 0 4 0 1 2 0]<block_end><def_stmt>test_smoke self<block_start>print("in" self.initial_sol)<line_sep>smoke_sol=do_local_search([do_3optstar_move] self.initial_sol self.D self.d self.C)<line_sep>print("out" smoke_sol)<block_end><block_end><class_stmt>TestRandomStressOn3OptStarSolutionOperator(unittest.TestCase)# abuse class variable to repeat with different problem sizes <block_start>problem_size=5<def_stmt>setUp self<block_start>N=TestRandomStressOn3OptStarSolutionOperator.problem_size<line_sep>problem=generate_CVRP(N 50 10 5)<line_sep>aN,pts,d,D,C=(problem.size problem.coordinate_points problem.customer_demands problem.distance_matrix problem.capacity_constraint)<line_sep>pts=<none><line_sep>d=[int(dv)<for>dv d]<line_sep>D=D.astype(int)<line_sep>problem=aN pts d D C<line_sep>self.naive_sol=routes2sol([[n]<for>n range(1 aN+1)])<line_sep>self.nn_sol=nearest_neighbor_init(D d C)<line_sep>self.L=max(calculate_objective(r D)<for>r sol2routes(self.nn_sol))<line_sep>self.N=aN<line_sep>self.problem=(aN pts d D C)<block_end><def_stmt>_improve_with_3opt_star self problem solution strategy<block_start><if_stmt>len(problem)<eq>5<block_start>N,pts,d,D,C=problem<line_sep>L=<none><block_end><else_stmt><block_start>N,pts,d,D,C,L=problem<block_end>sol=list(solution)<if_stmt><not>PRINT_ONLY_FINAL_RESULT<block_start>print("\nin" sol)<block_end>total_t=0<while_stmt><true><block_start>start_t=time()<line_sep>out_sol=do_3optstar_move(sol D d C L strategy)<line_sep>elapsed_t=time()-start_t<line_sep>total_t<augadd>elapsed_t<if_stmt><not>PRINT_ONLY_FINAL_RESULT<block_start>print("elapsed %.2f s"%elapsed_t)<line_sep>print("out (%s)\n"%_strategy_to_str(strategy))<block_end><if_stmt>out_sol[1]<eq><none><block_start>print("no more improvements found")<if_stmt>PRINT_ONLY_FINAL_RESULT<block_start>print("final (%s)"%_strategy_to_str(strategy) sol calculate_objective(sol D))<block_end>print("total elapsed %.2f s"%total_t)<line_sep><break><block_end><if_stmt><not>PRINT_ONLY_FINAL_RESULT<block_start>print(out_sol calculate_objective(out_sol[0] D))<block_end>sol=out_sol[0]<line_sep>self.assertTrue(all(check_solution_feasibility(sol D d C L)) "must be feasible")<block_end><block_end><def_stmt>test_random_problems_with_C_constraints_first_accept_from_naive_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>self._improve_with_3opt_star(self.problem self.naive_sol strategy=LSOPT.FIRST_ACCEPT)<block_end><def_stmt>test_random_problems_with_C_constraints_best_accept_from_naive_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>self._improve_with_3opt_star(self.problem self.naive_sol strategy=LSOPT.BEST_ACCEPT)<block_end><def_stmt>test_random_problems_with_L_constraints_first_accept_from_naive_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>problem_with_L=tuple(list(self.problem)+[self.L])<line_sep>self._improve_with_3opt_star(problem_with_L self.naive_sol strategy=LSOPT.FIRST_ACCEPT)<block_end><def_stmt>test_random_problems_with_L_constraints_best_accept_from_naive_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>problem_with_L=tuple(list(self.problem)+[self.L])<line_sep>self._improve_with_3opt_star(problem_with_L self.naive_sol strategy=LSOPT.BEST_ACCEPT)<block_end><def_stmt>test_random_problems_with_C_constraints_first_accept_from_nn_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>self._improve_with_3opt_star(self.problem self.nn_sol strategy=LSOPT.FIRST_ACCEPT)<block_end><def_stmt>test_random_problems_with_C_constraints_best_accept_from_nn_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>self._improve_with_3opt_star(self.problem self.nn_sol strategy=LSOPT.BEST_ACCEPT)<block_end><def_stmt>test_random_problems_with_L_constraints_first_accept_from_nn_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>problem_with_L=tuple(list(self.problem)+[self.L])<line_sep>self._improve_with_3opt_star(problem_with_L self.nn_sol strategy=LSOPT.FIRST_ACCEPT)<block_end><def_stmt>test_random_problems_with_L_constraints_best_accept_from_nn_sol self<block_start>print("\n\nTEST RANDOM PROBLEM WITH %d CUSTOMERS, NAIVE INITIAL SOLUTION"%self.N)<line_sep>problem_with_L=tuple(list(self.problem)+[self.L])<line_sep>self._improve_with_3opt_star(problem_with_L self.nn_sol strategy=LSOPT.BEST_ACCEPT)<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>unittest.main()<if_stmt>len(sys.argv)<le>1<or>"TestRandomStressOn3OptStarSolutionOperator"<in>sys.argv#for N in range(70,101,10): <block_start><for_stmt>N range(5 15)<block_start>TestRandomStressOn3OptStarSolutionOperator.problem_size=N<line_sep>wasSuccessful=unittest.main(exit=<false> argv=["TestRandomStressOn3OptStarSolutionOperator"]).result.wasSuccessful()<if_stmt><not>wasSuccessful<block_start>sys.exit(1)<block_end><block_end><block_end><block_end>
<import_from_stmt>dataclasses dataclass<import_from_stmt>typing Tuple<import_from_stmt>manim config<import_from_stmt>manim DEFAULT_MOBJECT_TO_EDGE_BUFFER<import_from_stmt>manim DEFAULT_MOBJECT_TO_MOBJECT_BUFFER<import_from_stmt>manim DOWN<import_from_stmt>manim LEFT<import_from_stmt>manim Mobject<import_from_stmt>manim np<import_from_stmt>manim ORIGIN<import_from_stmt>manim Polygon<import_from_stmt>manim RIGHT<import_from_stmt>manim UP<import_from_stmt>wrapt ObjectProxy<line_sep>WIDTH_THIRD=(config["frame_x_radius"]<times>2)/3<line_sep>@dataclass<class_stmt>Bounds<block_start>ul:Tuple[float float float]=<none><line_sep>ur:Tuple[float float float]=<none><line_sep>dr:Tuple[float float float]=<none><line_sep>dl:Tuple[float float float]=<none><line_sep>@property<def_stmt>width self<block_start><return>abs(self.ul[0]-self.ur[0])<block_end>@property<def_stmt>height self<block_start><return>abs(self.ur[1]-self.dr[1])<block_end><def_stmt>as_mobject self<arrow>Polygon<block_start><return>Polygon(self.ul self.ur self.dr self.dl)<block_end><block_end><class_stmt>AutoScaled(ObjectProxy)<block_start>""" Autoscales whatever it wraps on changes in placement including: * `next_to` * `to_edge` * `set_x` * `set_y` * `move_to` """<def_stmt>__init__ self delegate:Mobject rescale:bool=<true><block_start>""" Args: delegate: The object to scale rescale: Whether to rescale the object immediately or not """<line_sep>super().__init__(delegate)<line_sep>self._overall_scale_factor:float=1<line_sep>self._bounds=Bounds()<line_sep>self.reset_bounds()<if_stmt>rescale<block_start>self.autoscale(ORIGIN)<block_end><block_end><def_stmt>scale self scale_factor **kwargs<block_start>self._overall_scale_factor<augmul>scale_factor<line_sep>self.__wrapped__.scale(scale_factor **kwargs)<line_sep><return>self<block_end><def_stmt>copy self<block_start>result=self.__wrapped__.copy()<line_sep>wrapper=AutoScaled(result <false>)<line_sep>wrapper._bounds=self._bounds<line_sep>wrapper._overall_scale_factor=self._overall_scale_factor<line_sep><return>wrapper<block_end><def_stmt>next_to self mobject_or_point direction=RIGHT **kwargs<block_start>self.__wrapped__.next_to(mobject_or_point direction **kwargs)<line_sep>self._update_bounds_to_direction(direction<times>-1)<line_sep>self.autoscale(direction<times>-1)<line_sep><return>self<block_end><def_stmt>move_to self point_or_mobject aligned_edge=ORIGIN coor_mask=np.array([1 1 1])<block_start>self.__wrapped__.move_to(point_or_mobject aligned_edge coor_mask)<line_sep>self._update_bounds_to_direction(aligned_edge)<line_sep>self.autoscale(aligned_edge)<line_sep><return>self<block_end><def_stmt>set_x self x direction=ORIGIN<block_start>self.__wrapped__.set_x(x direction)<line_sep>self._update_bounds_to_direction(direction)<line_sep>self.autoscale(direction)<line_sep><return>self<block_end><def_stmt>fill_between_x self x_left:float x_right:float<block_start>""" Autoscales between two X values """<line_sep>self._bounds.ur=np.array((x_right self._bounds.ur[1] self._bounds.ur[2]))<line_sep>self._bounds.dr=np.array((x_right self._bounds.dr[1] self._bounds.dr[2]))<line_sep>self.set_x(x_left LEFT)<line_sep>self._update_bounds_to_direction(LEFT)<line_sep>self.autoscale(LEFT)<line_sep><return>self<block_end><def_stmt>set_y self y direction=ORIGIN<block_start>self.__wrapped__.set_y(y)<line_sep>self._update_bounds_to_direction(direction)<line_sep>self.autoscale(direction)<line_sep><return>self<block_end><def_stmt>full_size self<block_start>""" Resets the scaling to full screen """<line_sep>self.reset_bounds()<line_sep>self.__wrapped__.center()<line_sep>self.autoscale(ORIGIN)<line_sep><return>self<block_end><def_stmt>reset_bounds self<block_start>x_rad=config["frame_x_radius"]<line_sep>y_rad=config["frame_y_radius"]<line_sep>buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER<line_sep>self._bounds.ul=np.array((x_rad<times>-1+buff y_rad-buff 0))<line_sep>self._bounds.ur=np.array((x_rad-buff y_rad-buff 0))<line_sep>self._bounds.dr=np.array((x_rad-buff y_rad<times>-1+buff 0))<line_sep>self._bounds.dl=np.array((x_rad<times>-1+buff y_rad<times>-1+buff 0))<line_sep><return>self<block_end><def_stmt>to_edge self edge=LEFT buff=DEFAULT_MOBJECT_TO_EDGE_BUFFER<block_start>self.__wrapped__.to_edge(edge buff)<line_sep>self._update_bounds_to_direction(edge)<line_sep>self.autoscale(edge)<line_sep><return>self<block_end><def_stmt>autoscale self direction:np.array<block_start>""" Manually autoscales in a given direction Args: direction: The direction to scale in """<if_stmt><not>self.__wrapped__.get_width()<or><not>self.__wrapped__.get_height()<block_start><return><block_end>x_scale=self._bounds.width/self.__wrapped__.get_width()<line_sep>y_scale=self._bounds.height/self.__wrapped__.get_height()<line_sep>self.scale(min(x_scale y_scale) about_point=self._bounds.as_mobject().get_critical_point(direction))<block_end><def_stmt>_update_bounds_to_direction self direction:np.array<block_start><if_stmt>direction[0]<eq>-1<block_start>new_x=self.__wrapped__.get_x(LEFT)<line_sep>self._bounds.ul=np.array((new_x self._bounds.ul[1] self._bounds.ul[2]))<line_sep>self._bounds.dl=np.array((new_x self._bounds.dl[1] self._bounds.dl[2]))<block_end><elif_stmt>direction[0]<eq>1<block_start>new_x=self.__wrapped__.get_x(RIGHT)<line_sep>self._bounds.ur=np.array((new_x self._bounds.ur[1] self._bounds.ur[2]))<line_sep>self._bounds.dr=np.array((new_x self._bounds.dr[1] self._bounds.dr[2]))<block_end><if_stmt>direction[1]<eq>-1<block_start>new_y=self.__wrapped__.get_y(DOWN)<line_sep>self._bounds.dr=np.array((self._bounds.dr[0] new_y self._bounds.dr[2]))<line_sep>self._bounds.dl=np.array((self._bounds.dl[0] new_y self._bounds.dl[2]))<block_end><elif_stmt>direction[1]<eq>1<block_start>new_y=self.__wrapped__.get_y(UP)<line_sep>self._bounds.ur=np.array((self._bounds.ur[0] new_y self._bounds.ur[2]))<line_sep>self._bounds.ul=np.array((self._bounds.ul[0] new_y self._bounds.ul[2]))<block_end><block_end><block_end>
<import_stmt>unittest<import_stmt>numpy<as>np<import_from_stmt>audiomentations.augmentations.transforms Mp3Compression<import_from_stmt>audiomentations.core.composition Compose<class_stmt>TestMp3Compression(unittest.TestCase)<block_start><def_stmt>test_apply_mp3_compression_pydub self<block_start>sample_len=44100<line_sep>samples_in=np.random.normal(0 1 size=sample_len).astype(np.float32)<line_sep>sample_rate=44100<line_sep>augmenter=Compose([Mp3Compression(p=1.0 min_bitrate=48 max_bitrate=48 backend="pydub")])<line_sep>samples_out=augmenter(samples=samples_in sample_rate=sample_rate)<line_sep>self.assertEqual(samples_out.dtype np.float32)<line_sep>self.assertGreaterEqual(len(samples_out) sample_len)<line_sep>self.assertLess(len(samples_out) sample_len+2500)<block_end><def_stmt>test_apply_mp3_compression_lameenc self<block_start>sample_len=44100<line_sep>samples_in=np.random.normal(0 1 size=sample_len).astype(np.float32)<line_sep>sample_rate=44100<line_sep>augmenter=Compose([Mp3Compression(p=1.0 min_bitrate=48 max_bitrate=48 backend="lameenc")])<line_sep>samples_out=augmenter(samples=samples_in sample_rate=sample_rate)<line_sep>self.assertEqual(samples_out.dtype np.float32)<line_sep>self.assertGreaterEqual(len(samples_out) sample_len)<line_sep>self.assertLess(len(samples_out) sample_len+2500)<block_end><def_stmt>test_apply_mp3_compression_low_bitrate_pydub self<block_start>sample_len=16000<line_sep>samples_in=np.random.normal(0 1 size=sample_len).astype(np.float32)<line_sep>sample_rate=16000<line_sep>augmenter=Compose([Mp3Compression(p=1.0 min_bitrate=8 max_bitrate=8 backend="pydub")])<line_sep>samples_out=augmenter(samples=samples_in sample_rate=sample_rate)<line_sep>self.assertEqual(samples_out.dtype np.float32)<line_sep>self.assertGreaterEqual(len(samples_out) sample_len)<line_sep>self.assertLess(len(samples_out) sample_len+2500)<block_end><def_stmt>test_apply_mp3_compression_low_bitrate_lameenc self<block_start>sample_len=16000<line_sep>samples_in=np.random.normal(0 1 size=sample_len).astype(np.float32)<line_sep>sample_rate=16000<line_sep>augmenter=Compose([Mp3Compression(p=1.0 min_bitrate=8 max_bitrate=8 backend="lameenc")])<line_sep>samples_out=augmenter(samples=samples_in sample_rate=sample_rate)<line_sep>self.assertEqual(samples_out.dtype np.float32)<line_sep>self.assertGreaterEqual(len(samples_out) sample_len)<line_sep>self.assertLess(len(samples_out) sample_len+2500)<block_end><def_stmt>test_invalid_argument_combination self<block_start><with_stmt>self.assertRaises(AssertionError)<block_start>_=Mp3Compression(min_bitrate=400 max_bitrate=800)<block_end><with_stmt>self.assertRaises(AssertionError)<block_start>_=Mp3Compression(min_bitrate=2 max_bitrate=4)<block_end><with_stmt>self.assertRaises(AssertionError)<block_start>_=Mp3Compression(min_bitrate=64 max_bitrate=8)<block_end><block_end><block_end>
<import_from_stmt>. mysqldb<import_from_stmt>physical.models Instance<class_stmt>MySQLPercona(mysqldb.MySQL)<block_start><def_stmt>get_default_instance_type self<block_start><return>Instance.MYSQL_PERCONA<block_end>@classmethod<def_stmt>topology_name cls<block_start><return>['mysql_percona_single']<block_end><block_end><class_stmt>MySQLPerconaFOXHA(mysqldb.MySQLFOXHA)<block_start><def_stmt>get_default_instance_type self<block_start><return>Instance.MYSQL_PERCONA<block_end>@classmethod<def_stmt>topology_name cls<block_start><return>['mysql_percona_foxha']<block_end><block_end>
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. <class_stmt>OperationResult(object)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none><block_start>self.result_status=result_status<if_stmt>result_reason<is><not><none><block_start>self.result_reason=result_reason<block_end><else_stmt><block_start>self.result_reason=<none><block_end><if_stmt>result_message<is><not><none><block_start>self.result_message=result_message<block_end><else_stmt><block_start>self.result_message=<none><block_end><block_end><block_end><class_stmt>CreateResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> object_type=<none> uuid=<none> template_attribute=<none><block_start>super(CreateResult self).__init__(result_status result_reason result_message)<if_stmt>object_type<is><not><none><block_start>self.object_type=object_type<block_end><else_stmt><block_start>self.object_type=<none><block_end><if_stmt>uuid<is><not><none><block_start>self.uuid=uuid<block_end><else_stmt><block_start>self.uuid=<none><block_end><if_stmt>template_attribute<is><not><none><block_start>self.template_attribute=template_attribute<block_end><else_stmt><block_start>self.template_attribute=<none><block_end><block_end><block_end><class_stmt>CreateKeyPairResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> private_key_uuid=<none> public_key_uuid=<none> private_key_template_attribute=<none> public_key_template_attribute=<none><block_start>super(CreateKeyPairResult self).__init__(result_status result_reason result_message)<line_sep>self.private_key_uuid=private_key_uuid<line_sep>self.public_key_uuid=public_key_uuid<line_sep>self.private_key_template_attribute=private_key_template_attribute<line_sep>self.public_key_template_attribute=public_key_template_attribute<block_end><block_end><class_stmt>ActivateResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uuid=<none><block_start>super(ActivateResult self).__init__(result_status result_reason result_message)<if_stmt>uuid<is><not><none><block_start>self.uuid=uuid<block_end><else_stmt><block_start>self.uuid=<none><block_end><block_end><block_end><class_stmt>RegisterResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uuid=<none> template_attribute=<none><block_start>super(RegisterResult self).__init__(result_status result_reason result_message)<if_stmt>uuid<is><not><none><block_start>self.uuid=uuid<block_end><else_stmt><block_start>self.uuid=<none><block_end><if_stmt>template_attribute<is><not><none><block_start>self.template_attribute=template_attribute<block_end><else_stmt><block_start>self.template_attribute=<none><block_end><block_end><block_end><class_stmt>RekeyKeyPairResult(CreateKeyPairResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> private_key_uuid=<none> public_key_uuid=<none> private_key_template_attribute=<none> public_key_template_attribute=<none><block_start>super(RekeyKeyPairResult self).__init__(result_status result_reason result_message private_key_uuid public_key_uuid private_key_template_attribute public_key_template_attribute)<block_end><block_end><class_stmt>GetResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> object_type=<none> uuid=<none> secret=<none><block_start>super(GetResult self).__init__(result_status result_reason result_message)<if_stmt>object_type<is><not><none><block_start>self.object_type=object_type<block_end><else_stmt><block_start>self.object_type=<none><block_end><if_stmt>uuid<is><not><none><block_start>self.uuid=uuid<block_end><else_stmt><block_start>self.uuid=<none><block_end><if_stmt>secret<is><not><none><block_start>self.secret=secret<block_end><else_stmt><block_start>self.secret=<none><block_end><block_end><block_end><class_stmt>GetAttributesResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uuid=<none> attributes=<none><block_start>super(GetAttributesResult self).__init__(result_status result_reason result_message)<line_sep>self.uuid=uuid<line_sep>self.attributes=attributes<block_end><block_end><class_stmt>GetAttributeListResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uid=<none> names=<none><block_start>super(GetAttributeListResult self).__init__(result_status result_reason result_message)<line_sep>self.uid=uid<line_sep>self.names=names<block_end><block_end><class_stmt>DestroyResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uuid=<none><block_start>super(DestroyResult self).__init__(result_status result_reason result_message)<if_stmt>uuid<is><not><none><block_start>self.uuid=uuid<block_end><else_stmt><block_start>self.uuid=<none><block_end><block_end><block_end><class_stmt>LocateResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uuids=<none><block_start>super(LocateResult self).__init__(result_status result_reason result_message)<line_sep>self.uuids=uuids<block_end><block_end><class_stmt>QueryResult(OperationResult)<block_start>""" A container for the results of a Query operation. Attributes: result_status: The status of the Query operation (e.g., success or failure). result_reason: The reason for the operation status. result_message: Extra information pertaining to the status reason. operations: A list of Operations supported by the server. object_types: A list of Object Types supported by the server. vendor_identification: server_information: application_namespaces: A list of namespaces supported by the server. extension_information: A list of extensions supported by the server. """<def_stmt>__init__ self result_status result_reason=<none> result_message=<none> operations=<none> object_types=<none> vendor_identification=<none> server_information=<none> application_namespaces=<none> extension_information=<none><block_start>super(QueryResult self).__init__(result_status result_reason result_message)<if_stmt>operations<is><none><block_start>self.operations=list()<block_end><else_stmt><block_start>self.operations=operations<block_end><if_stmt>object_types<is><none><block_start>self.object_types=list()<block_end><else_stmt><block_start>self.object_types=object_types<block_end>self.vendor_identification=vendor_identification<line_sep>self.server_information=server_information<if_stmt>application_namespaces<is><none><block_start>self.application_namespaces=list()<block_end><else_stmt><block_start>self.application_namespaces=application_namespaces<block_end><if_stmt>extension_information<is><none><block_start>self.extension_information=list()<block_end><else_stmt><block_start>self.extension_information=extension_information<block_end><block_end><block_end><class_stmt>DiscoverVersionsResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> protocol_versions=<none><block_start>super(DiscoverVersionsResult self).__init__(result_status result_reason result_message)<line_sep>self.protocol_versions=protocol_versions<block_end><block_end><class_stmt>RevokeResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> unique_identifier=<none><block_start>super(RevokeResult self).__init__(result_status result_reason result_message)<line_sep>self.unique_identifier=unique_identifier<block_end><block_end><class_stmt>MACResult(OperationResult)<block_start><def_stmt>__init__ self result_status result_reason=<none> result_message=<none> uuid=<none> mac_data=<none><block_start>super(MACResult self).__init__(result_status result_reason result_message)<line_sep>self.uuid=uuid<line_sep>self.mac_data=mac_data<block_end><block_end>
# Author : <NAME> # Date : July 1st, 2010 # last update: $Date: 2010/03/17 18:17:34 $ by $Author: mussgill $ <import_stmt>FWCore.ParameterSet.Config<as>cms<line_sep>#_________________________________HLT bits___________________________________________ <import_stmt>HLTrigger.HLTfilters.hltHighLevel_cfi<line_sep>ALCARECOTkAlCosmicsInCollisionsHLT=HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone(andOr=<true> ## choose logical OR between Triggerbits eventSetupPathsKey='TkAlCosmicsInCollisions' throw=<false># tolerate triggers not available )<line_sep># DCS partitions # "EBp","EBm","EEp","EEm","HBHEa","HBHEb","HBHEc","HF","HO","RPC" # "DT0","DTp","DTm","CSCp","CSCm","CASTOR","TIBTID","TOB","TECp","TECm" # "BPIX","FPIX","ESp","ESm" <import_stmt>DPGAnalysis.Skims.skim_detstatus_cfi<line_sep>ALCARECOTkAlCosmicsInCollisionsDCSFilter=DPGAnalysis.Skims.skim_detstatus_cfi.dcsstatus.clone(DetectorType=cms.vstring('TIBTID' 'TOB' 'TECp' 'TECm' 'BPIX' 'FPIX') ApplyFilter=cms.bool(<true>) AndOr=cms.bool(<true>) DebugOn=cms.untracked.bool(<false>))<line_sep>#_________________________ Cosmic During Collisions__________________________________ <import_from_stmt>RecoTracker.SpecialSeedGenerators.cosmicDC_cff *<line_sep>#________________________________Track selection____________________________________ # AlCaReco for track based alignment using Cosmic muons reconstructed by Cosmics during collisions <import_stmt>Alignment.CommonAlignmentProducer.AlignmentTrackSelector_cfi<line_sep>ALCARECOTkAlCosmicsInCollisions=Alignment.CommonAlignmentProducer.AlignmentTrackSelector_cfi.AlignmentTrackSelector.clone(src='cosmicDCTracks' filter=<true> applyBasicCuts=<true> ptMin=0. ##10 ptMax=99999. pMin=4. ##10 pMax=99999. etaMin=-99. ##-2.4 keep also what is going through... etaMax=99. ## 2.4 ...both TEC with flat slope nHitMin=7 nHitMin2D=2 chi2nMax=999999. applyMultiplicityFilter=<false> applyNHighestPt=<true> ## select only highest pT track nHighestPt=1)<line_sep>#________________________________Sequences____________________________________ seqALCARECOTkAlCosmicsInCollisions=cms.Sequence(cosmicDCTracksSeq<times>ALCARECOTkAlCosmicsInCollisionsHLT+ALCARECOTkAlCosmicsInCollisionsDCSFilter+ALCARECOTkAlCosmicsInCollisions)<line_sep>
# -*- coding: utf-8 -*- <import_from_stmt>django.db DatabaseError<import_from_stmt>django.http HttpResponse<import_from_stmt>explorer.exporters get_exporter_class<import_from_stmt>explorer.utils url_get_params<def_stmt>_export request query download=<true><block_start>_fmt=request.GET.get('format' 'csv')<line_sep>exporter_class=get_exporter_class(_fmt)<line_sep>query.params=url_get_params(request)<line_sep>delim=request.GET.get('delim')<line_sep>exporter=exporter_class(query)<try_stmt><block_start>output=exporter.get_output(delim=delim)<block_end><except_stmt>DatabaseError<as>e<block_start>msg=f"Error executing query {query.title}: {e}"<line_sep><return>HttpResponse(msg status=500)<block_end>response=HttpResponse(output content_type=exporter.content_type)<if_stmt>download<block_start>response['Content-Disposition']=f'attachment; filename="{exporter.get_filename()}"'<block_end><return>response<block_end>
<import_from_stmt>rpython.rtyper.lltypesystem lltype rffi<import_from_stmt>rpython.rtyper rclass<line_sep>Size2Type=[<none>]<times>100<line_sep>Type2Size={}<def_stmt>get_size TYPE<block_start><try_stmt><block_start><return>Type2Size[TYPE]<block_end><except_stmt>KeyError<block_start>size=len(Size2Type)<line_sep>Size2Type.append(TYPE)<line_sep>Type2Size[TYPE]=size<line_sep><return>size<block_end><block_end>TokenToField=[<none>]<times>100<line_sep>FieldToToken={}<def_stmt>get_field_token STRUCT fieldname<block_start><try_stmt><block_start><return>FieldToToken[STRUCT fieldname]<block_end><except_stmt>KeyError<block_start>token=(len(TokenToField) get_size(getattr(STRUCT fieldname)))<line_sep>TokenToField.append((STRUCT fieldname))<line_sep>FieldToToken[STRUCT fieldname]=token<line_sep><return>token<block_end><block_end>get_field_token(rclass.OBJECT 'typeptr')# force the index 1 for this
<import_stmt>multiprocessing<as>mp<import_from_stmt>typing Dict<import_from_stmt>typing List<import_from_stmt>typing NoReturn<import_stmt>pytricia<import_stmt>redis<import_stmt>requests<import_stmt>ujson<as>json<import_from_stmt>artemis_utils flatten<import_from_stmt>artemis_utils get_ip_version<import_from_stmt>artemis_utils get_logger<import_from_stmt>artemis_utils search_worst_prefix<import_from_stmt>artemis_utils.constants CONFIGURATION_HOST<import_from_stmt>artemis_utils.envvars RABBITMQ_URI<import_from_stmt>artemis_utils.envvars REDIS_HOST<import_from_stmt>artemis_utils.envvars REDIS_PORT<import_from_stmt>artemis_utils.envvars REST_PORT<import_from_stmt>artemis_utils.rabbitmq create_exchange<import_from_stmt>artemis_utils.rabbitmq create_queue<import_from_stmt>artemis_utils.redis ping_redis<import_from_stmt>artemis_utils.translations translate_asn_range<import_from_stmt>artemis_utils.translations translate_rfc2622<import_from_stmt>kombu Connection<import_from_stmt>kombu Consumer<import_from_stmt>kombu Producer<import_from_stmt>kombu serialization<import_from_stmt>kombu uuid<import_from_stmt>kombu.mixins ConsumerProducerMixin<import_from_stmt>tornado.ioloop IOLoop<import_from_stmt>tornado.web Application<import_from_stmt>tornado.web RequestHandler<line_sep># logger log=get_logger()<line_sep># additional serializer for pg-amqp messages serialization.register("txtjson" json.dumps json.loads content_type="text" content_encoding="utf-8")<line_sep># shared memory object locks shared_memory_locks={"data_worker":mp.Lock() "prefix_tree":mp.Lock() "autoignore":mp.Lock() "monitored_prefixes":mp.Lock() "configured_prefix_count":mp.Lock() "config_timestamp":mp.Lock() "service_reconfiguring":mp.Lock() }<line_sep># global vars SERVICE_NAME="prefixtree"<def_stmt>pytricia_to_dict pyt_tree<block_start>pyt_dict={}<for_stmt>prefix pyt_tree<block_start>pyt_dict[prefix]=pyt_tree[prefix]<block_end><return>pyt_dict<block_end><def_stmt>dict_to_pytricia dict_tree size=32<block_start>pyt_tree=pytricia.PyTricia(size)<for_stmt>prefix dict_tree<block_start>pyt_tree.insert(prefix dict_tree[prefix])<block_end><return>pyt_tree<block_end><def_stmt>configure_prefixtree msg shared_memory_manager_dict<block_start>config=msg<try_stmt># check newer config <block_start>config_timestamp=shared_memory_manager_dict["config_timestamp"]<if_stmt>config["timestamp"]<g>config_timestamp<block_start>shared_memory_locks["service_reconfiguring"].acquire()<line_sep>shared_memory_manager_dict["service_reconfiguring"]=<true><line_sep>shared_memory_locks["service_reconfiguring"].release()<line_sep># calculate prefix tree prefix_tree={"v4":pytricia.PyTricia(32) "v6":pytricia.PyTricia(128)}<line_sep>rules=config.get("rules" [])<for_stmt>rule rules<block_start>rule_translated_origin_asn_set=set()<for_stmt>asn rule["origin_asns"]<block_start>this_translated_asn_list=flatten(translate_asn_range(asn))<line_sep>rule_translated_origin_asn_set.update(set(this_translated_asn_list))<block_end>rule["origin_asns"]=list(rule_translated_origin_asn_set)<line_sep>rule_translated_neighbor_set=set()<for_stmt>asn rule["neighbors"]<block_start>this_translated_asn_list=flatten(translate_asn_range(asn))<line_sep>rule_translated_neighbor_set.update(set(this_translated_asn_list))<block_end>rule["neighbors"]=list(rule_translated_neighbor_set)<line_sep>conf_obj={"origin_asns":rule["origin_asns"] "neighbors":rule["neighbors"] "prepend_seq":rule.get("prepend_seq" []) "policies":list(set(rule.get("policies" []))) "community_annotations":rule.get("community_annotations" []) "mitigation":rule.get("mitigation" "manual") }<for_stmt>prefix rule["prefixes"]<block_start><for_stmt>translated_prefix translate_rfc2622(prefix)<block_start>ip_version=get_ip_version(translated_prefix)<if_stmt>prefix_tree[ip_version].has_key(translated_prefix)<block_start>node=prefix_tree[ip_version][translated_prefix]<block_end><else_stmt><block_start>node={"prefix":translated_prefix "data":{"confs":[]} "timestamp":config["timestamp"] }<line_sep>prefix_tree[ip_version].insert(translated_prefix node)<block_end>node["data"]["confs"].append(conf_obj)<block_end><block_end><block_end># calculate the monitored and configured prefixes configured_prefix_count=0<line_sep>monitored_prefixes=set()<for_stmt>ip_version prefix_tree<block_start><for_stmt>prefix prefix_tree[ip_version]<block_start>configured_prefix_count<augadd>1<line_sep>monitored_prefix=search_worst_prefix(prefix prefix_tree[ip_version])<if_stmt>monitored_prefix<block_start>monitored_prefixes.add(monitored_prefix)<block_end><block_end><block_end># extract autoignore rules autoignore_rules=config.get("autoignore" {})<line_sep># calculate autoignore prefix tree autoignore_prefix_tree={"v4":pytricia.PyTricia(32) "v6":pytricia.PyTricia(128) }<for_stmt>key autoignore_rules<block_start>rule=autoignore_rules[key]<for_stmt>prefix rule["prefixes"]<block_start><for_stmt>translated_prefix translate_rfc2622(prefix)<block_start>ip_version=get_ip_version(translated_prefix)<if_stmt><not>autoignore_prefix_tree[ip_version].has_key(translated_prefix)<block_start>node={"prefix":translated_prefix "rule_key":key}<line_sep>autoignore_prefix_tree[ip_version].insert(translated_prefix node)<block_end><block_end><block_end><block_end># note that the object should be picklable (e.g., dict instead of pytricia tree, # see also: https://github.com/jsommers/pytricia/issues/20) shared_memory_locks["prefix_tree"].acquire()<line_sep>dict_prefix_tree={"v4":pytricia_to_dict(prefix_tree["v4"]) "v6":pytricia_to_dict(prefix_tree["v6"]) }<line_sep>shared_memory_manager_dict["prefix_tree"]=dict_prefix_tree<line_sep>shared_memory_manager_dict["prefix_tree_recalculate"]=<true><line_sep>shared_memory_locks["prefix_tree"].release()<line_sep>shared_memory_locks["monitored_prefixes"].acquire()<line_sep>shared_memory_manager_dict["monitored_prefixes"]=list(monitored_prefixes)<line_sep>shared_memory_locks["monitored_prefixes"].release()<line_sep>shared_memory_locks["configured_prefix_count"].acquire()<line_sep>shared_memory_manager_dict["configured_prefix_count"]=configured_prefix_count<line_sep>shared_memory_locks["configured_prefix_count"].release()<line_sep># note that the object should be picklable (e.g., dict instead of pytricia tree, # see also: https://github.com/jsommers/pytricia/issues/20) dict_autoignore_prefix_tree={"v4":pytricia_to_dict(autoignore_prefix_tree["v4"]) "v6":pytricia_to_dict(autoignore_prefix_tree["v6"]) }<line_sep>shared_memory_locks["autoignore"].acquire()<line_sep>shared_memory_manager_dict["autoignore_rules"]=autoignore_rules<line_sep>shared_memory_manager_dict["autoignore_prefix_tree"]=dict_autoignore_prefix_tree<line_sep>shared_memory_manager_dict["autoignore_recalculate"]=<true><line_sep>shared_memory_locks["autoignore"].release()<line_sep>shared_memory_locks["config_timestamp"].acquire()<line_sep>shared_memory_manager_dict["config_timestamp"]=config["timestamp"]<line_sep>shared_memory_locks["config_timestamp"].release()<block_end>shared_memory_locks["service_reconfiguring"].acquire()<line_sep>shared_memory_manager_dict["service_reconfiguring"]=<false><line_sep>shared_memory_locks["service_reconfiguring"].release()<line_sep><return>{"success":<true> "message":"configured"}<block_end><except_stmt>Exception<block_start>log.exception("exception")<line_sep>shared_memory_locks["service_reconfiguring"].acquire()<line_sep>shared_memory_manager_dict["service_reconfiguring"]=<false><line_sep>shared_memory_locks["service_reconfiguring"].release()<line_sep><return>{"success":<false> "message":"error during service configuration"}<block_end><block_end><class_stmt>ConfigHandler(RequestHandler)<block_start>""" REST request handler for configuration. """<def_stmt>initialize self shared_memory_manager_dict<block_start>self.shared_memory_manager_dict=shared_memory_manager_dict<block_end><def_stmt>get self<block_start>""" Provides current configuration primitives (in the form of a JSON dict) to the requester. Format: { "prefix_tree": { "v4": <dict>, "v6": <dict> }, "prefix_tree_recalculate": <bool>, "monitored_prefixes": <list>, "configured_prefix_count": <int>, "autoignore_rules": <dict>, "autoignore_prefix_tree": { "v4": <dict>, "v6": <dict> }, "autoignore_recalculate": <bool>, "config_timestamp": <timestamp> } """<line_sep>ret_dict={}<line_sep>ret_dict["prefix_tree"]=self.shared_memory_manager_dict["prefix_tree"]<line_sep>ret_dict["prefix_tree_recalculate"]=self.shared_memory_manager_dict["prefix_tree_recalculate"]<line_sep>ret_dict["monitored_prefixes"]=self.shared_memory_manager_dict["monitored_prefixes"]<line_sep>ret_dict["configured_prefix_count"]=self.shared_memory_manager_dict["configured_prefix_count"]<line_sep>ret_dict["autoignore_rules"]=self.shared_memory_manager_dict["autoignore_rules"]<line_sep>ret_dict["autoignore_prefix_tree"]=self.shared_memory_manager_dict["autoignore_prefix_tree"]<line_sep>ret_dict["autoignore_recalculate"]=self.shared_memory_manager_dict["autoignore_recalculate"]<line_sep>ret_dict["config_timestamp"]=self.shared_memory_manager_dict["config_timestamp"]<line_sep>self.write(ret_dict)<block_end><def_stmt>post self<block_start>""" Configures prefix tree and responds with a success message. :return: {"success": True | False, "message": < message >} """<try_stmt><block_start>msg=json.loads(self.request.body)<line_sep>self.write(configure_prefixtree(msg self.shared_memory_manager_dict))<block_end><except_stmt>Exception<block_start>self.write({"success":<false> "message":"error during service configuration"})<block_end><block_end><block_end><class_stmt>HealthHandler(RequestHandler)<block_start>""" REST request handler for health checks. """<def_stmt>initialize self shared_memory_manager_dict<block_start>self.shared_memory_manager_dict=shared_memory_manager_dict<block_end><def_stmt>get self<block_start>""" Extract the status of a service via a GET request. :return: {"status" : <unconfigured|running|stopped><,reconfiguring>} """<line_sep>status="stopped"<line_sep>shared_memory_locks["data_worker"].acquire()<if_stmt>self.shared_memory_manager_dict["data_worker_running"]<block_start>status="running"<block_end>shared_memory_locks["data_worker"].release()<if_stmt>self.shared_memory_manager_dict["service_reconfiguring"]<block_start>status<augadd>",reconfiguring"<block_end>self.write({"status":status})<block_end><block_end><class_stmt>ControlHandler(RequestHandler)<block_start>""" REST request handler for control commands. """<def_stmt>initialize self shared_memory_manager_dict<block_start>self.shared_memory_manager_dict=shared_memory_manager_dict<block_end><def_stmt>start_data_worker self<block_start>shared_memory_locks["data_worker"].acquire()<if_stmt>self.shared_memory_manager_dict["data_worker_running"]<block_start>log.info("data worker already running")<line_sep>shared_memory_locks["data_worker"].release()<line_sep><return>"already running"<block_end>shared_memory_locks["data_worker"].release()<line_sep>mp.Process(target=self.run_data_worker_process).start()<line_sep><return>"instructed to start"<block_end><def_stmt>run_data_worker_process self<block_start><try_stmt><block_start><with_stmt>Connection(RABBITMQ_URI)<as>connection<block_start>shared_memory_locks["data_worker"].acquire()<line_sep>data_worker=PrefixTreeDataWorker(connection self.shared_memory_manager_dict)<line_sep>self.shared_memory_manager_dict["data_worker_running"]=<true><line_sep>shared_memory_locks["data_worker"].release()<line_sep>log.info("data worker started")<line_sep>data_worker.run()<block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><finally_stmt><block_start>shared_memory_locks["data_worker"].acquire()<line_sep>self.shared_memory_manager_dict["data_worker_running"]=<false><line_sep>shared_memory_locks["data_worker"].release()<line_sep>log.info("data worker stopped")<block_end><block_end>@staticmethod<def_stmt>stop_data_worker <block_start>shared_memory_locks["data_worker"].acquire()<try_stmt><block_start><with_stmt>Connection(RABBITMQ_URI)<as>connection<block_start><with_stmt>Producer(connection)<as>producer<block_start>command_exchange=create_exchange("command" connection)<line_sep>producer.publish("" exchange=command_exchange routing_key="stop-{}".format(SERVICE_NAME) serializer="ujson" )<block_end><block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><finally_stmt><block_start>shared_memory_locks["data_worker"].release()<block_end>message="instructed to stop"<line_sep><return>message<block_end><def_stmt>post self<block_start>""" Instruct a service to start or stop by posting a command. Sample request body { "command": <start|stop> } :return: {"success": True|False, "message": <message>} """<try_stmt><block_start>msg=json.loads(self.request.body)<line_sep>command=msg["command"]<line_sep># start/stop data_worker <if_stmt>command<eq>"start"<block_start>message=self.start_data_worker()<line_sep>self.write({"success":<true> "message":message})<block_end><elif_stmt>command<eq>"stop"<block_start>message=self.stop_data_worker()<line_sep>self.write({"success":<true> "message":message})<block_end><else_stmt><block_start>self.write({"success":<false> "message":"unknown command"})<block_end><block_end><except_stmt>Exception<block_start>log.exception("Exception")<line_sep>self.write({"success":<false> "message":"error during control"})<block_end><block_end><block_end><class_stmt>ConfiguredPrefixCountHandler(RequestHandler)<block_start>""" REST request handler for configured prefix count information. """<def_stmt>initialize self shared_memory_manager_dict<block_start>self.shared_memory_manager_dict=shared_memory_manager_dict<block_end><def_stmt>get self<block_start>""" Simply provides the configured prefix count (in the form of a JSON dict) to the requester """<line_sep>self.write({"configured_prefix_count":self.shared_memory_manager_dict["configured_prefix_count"]})<block_end><block_end><class_stmt>MonitoredPrefixesHandler(RequestHandler)<block_start>""" REST request handler for monitored prefixes information. """<def_stmt>initialize self shared_memory_manager_dict<block_start>self.shared_memory_manager_dict=shared_memory_manager_dict<block_end><def_stmt>get self<block_start>""" Simply provides the monitored prefixes (in the form of a JSON dict) to the requester """<line_sep>self.write({"monitored_prefixes":self.shared_memory_manager_dict["monitored_prefixes"]})<block_end><block_end><class_stmt>PrefixTree<block_start>""" Prefix Tree Service. """<def_stmt>__init__ self# initialize shared memory <block_start>shared_memory_manager=mp.Manager()<line_sep>self.shared_memory_manager_dict=shared_memory_manager.dict()<line_sep>self.shared_memory_manager_dict["data_worker_running"]=<false><line_sep>self.shared_memory_manager_dict["service_reconfiguring"]=<false><line_sep>self.shared_memory_manager_dict["prefix_tree"]={"v4":{} "v6":{}}<line_sep>self.shared_memory_manager_dict["prefix_tree_recalculate"]=<true><line_sep>self.shared_memory_manager_dict["monitored_prefixes"]=list()<line_sep>self.shared_memory_manager_dict["configured_prefix_count"]=0<line_sep>self.shared_memory_manager_dict["autoignore_rules"]={}<line_sep>self.shared_memory_manager_dict["autoignore_prefix_tree"]={"v4":{} "v6":{}}<line_sep>self.shared_memory_manager_dict["autoignore_recalculate"]=<true><line_sep>self.shared_memory_manager_dict["config_timestamp"]=-1<line_sep>log.info("service initiated")<block_end><def_stmt>make_rest_app self<block_start><return>Application([("/config" ConfigHandler dict(shared_memory_manager_dict=self.shared_memory_manager_dict) ) ("/control" ControlHandler dict(shared_memory_manager_dict=self.shared_memory_manager_dict) ) ("/health" HealthHandler dict(shared_memory_manager_dict=self.shared_memory_manager_dict) ) ("/configuredPrefixCount" ConfiguredPrefixCountHandler dict(shared_memory_manager_dict=self.shared_memory_manager_dict) ) ("/monitoredPrefixes" MonitoredPrefixesHandler dict(shared_memory_manager_dict=self.shared_memory_manager_dict) ) ])<block_end><def_stmt>start_rest_app self<block_start>app=self.make_rest_app()<line_sep>app.listen(REST_PORT)<line_sep>log.info("REST worker started and listening to port {}".format(REST_PORT))<line_sep>IOLoop.current().start()<block_end><block_end><class_stmt>PrefixTreeDataWorker(ConsumerProducerMixin)<block_start>""" RabbitMQ Consumer/Producer for the prefix tree Service. """<def_stmt>__init__ self connection:Connection shared_memory_manager_dict:Dict<arrow>NoReturn<block_start>self.connection=connection<line_sep>self.redis=redis.Redis(host=REDIS_HOST port=REDIS_PORT)<line_sep>ping_redis(self.redis)<line_sep>self.shared_memory_manager_dict=shared_memory_manager_dict<line_sep>self.prefix_tree={"v4":pytricia.PyTricia(32) "v6":pytricia.PyTricia(128)}<line_sep>shared_memory_locks["prefix_tree"].acquire()<if_stmt>self.shared_memory_manager_dict["prefix_tree_recalculate"]<block_start><for_stmt>ip_version ["v4" "v6"]<block_start><if_stmt>ip_version<eq>"v4"<block_start>size=32<block_end><else_stmt><block_start>size=128<block_end>self.prefix_tree[ip_version]=dict_to_pytricia(self.shared_memory_manager_dict["prefix_tree"][ip_version] size)<line_sep>log.info("{} pytricia tree parsed from configuration".format(ip_version))<line_sep>self.shared_memory_manager_dict["prefix_tree_recalculate"]=<false><block_end><block_end>shared_memory_locks["prefix_tree"].release()<line_sep>self.autoignore_prefix_tree={"v4":pytricia.PyTricia(32) "v6":pytricia.PyTricia(128) }<line_sep>shared_memory_locks["autoignore"].acquire()<if_stmt>self.shared_memory_manager_dict["autoignore_recalculate"]<block_start><for_stmt>ip_version ["v4" "v6"]<block_start><if_stmt>ip_version<eq>"v4"<block_start>size=32<block_end><else_stmt><block_start>size=128<block_end>self.autoignore_prefix_tree[ip_version]=dict_to_pytricia(self.shared_memory_manager_dict["autoignore_prefix_tree"][ip_version] size )<line_sep>log.info("{} pytricia tree parsed from configuration".format(ip_version))<line_sep>self.shared_memory_manager_dict["autoignore_recalculate"]=<false><block_end><block_end>shared_memory_locks["autoignore"].release()<line_sep># EXCHANGES self.update_exchange=create_exchange("bgp-update" connection declare=<true>)<line_sep>self.hijack_exchange=create_exchange("hijack-update" connection declare=<true>)<line_sep>self.autoconf_exchange=create_exchange("autoconf" connection declare=<true>)<line_sep>self.pg_amq_bridge=create_exchange("amq.direct" connection)<line_sep>self.mitigation_exchange=create_exchange("mitigation" connection declare=<true>)<line_sep>self.autoignore_exchange=create_exchange("autoignore" connection declare=<true>)<line_sep>self.command_exchange=create_exchange("command" connection declare=<true>)<line_sep># QUEUES self.update_queue=create_queue(SERVICE_NAME exchange=self.update_exchange routing_key="update" priority=1 )<line_sep>self.hijack_ongoing_queue=create_queue(SERVICE_NAME exchange=self.hijack_exchange routing_key="ongoing" priority=1 )<line_sep>self.pg_amq_update_queue=create_queue(SERVICE_NAME exchange=self.pg_amq_bridge routing_key="update-insert" priority=1 )<line_sep>self.mitigation_request_queue=create_queue(SERVICE_NAME exchange=self.mitigation_exchange routing_key="mitigate" priority=2 )<line_sep>self.unmitigation_request_queue=create_queue(SERVICE_NAME exchange=self.mitigation_exchange routing_key="unmitigate" priority=2 )<line_sep>self.stop_queue=create_queue("{}-{}".format(SERVICE_NAME uuid()) exchange=self.command_exchange routing_key="stop-{}".format(SERVICE_NAME) priority=1 )<line_sep>self.autoconf_update_queue=create_queue(SERVICE_NAME exchange=self.autoconf_exchange routing_key="update" priority=4 random=<true> )<line_sep>self.ongoing_hijack_prefixes_queue=create_queue(SERVICE_NAME exchange=self.autoignore_exchange routing_key="ongoing-hijack-prefixes" priority=1 random=<true> )<line_sep>log.info("data worker initiated")<block_end><def_stmt>get_consumers self Consumer:Consumer channel:Connection<arrow>List[Consumer]<block_start><return>[Consumer(queues=[self.update_queue] on_message=self.annotate_bgp_update prefetch_count=100 accept=["ujson"] ) Consumer(queues=[self.hijack_ongoing_queue] on_message=self.annotate_ongoing_hijack_updates prefetch_count=100 accept=["ujson"] ) Consumer(queues=[self.mitigation_request_queue] on_message=self.annotate_mitigation_request prefetch_count=100 accept=["ujson" "json"] ) Consumer(queues=[self.unmitigation_request_queue] on_message=self.annotate_unmitigation_request prefetch_count=100 accept=["ujson" "json"] ) Consumer(queues=[self.pg_amq_update_queue] on_message=self.annotate_stored_bgp_update prefetch_count=100 accept=["ujson" "txtjson"] ) Consumer(queues=[self.stop_queue] on_message=self.stop_consumer_loop prefetch_count=100 accept=["ujson"] ) Consumer(queues=[self.autoconf_update_queue] on_message=self.handle_autoconf_updates prefetch_count=100 accept=["ujson"] ) Consumer(queues=[self.ongoing_hijack_prefixes_queue] on_message=self.handle_ongoing_hijack_prefixes prefetch_count=100 accept=["ujson"] ) ]<block_end><def_stmt>find_prefix_node self prefix<block_start>ip_version=get_ip_version(prefix)<line_sep>prefix_node=<none><line_sep>shared_memory_locks["prefix_tree"].acquire()<if_stmt>ip_version<eq>"v4"<block_start>size=32<block_end><else_stmt><block_start>size=128<block_end># need to turn to pytricia tree since this means that the tree has changed due to re-configuration <if_stmt>self.shared_memory_manager_dict["prefix_tree_recalculate"]<block_start>self.prefix_tree[ip_version]=dict_to_pytricia(self.shared_memory_manager_dict["prefix_tree"][ip_version] size)<line_sep>log.info("{} pytricia tree re-parsed from configuration".format(ip_version))<line_sep>self.shared_memory_manager_dict["prefix_tree_recalculate"]=<false><block_end><if_stmt>prefix<in>self.prefix_tree[ip_version]<block_start>prefix_node=self.prefix_tree[ip_version][prefix]<block_end>shared_memory_locks["prefix_tree"].release()<line_sep><return>prefix_node<block_end><def_stmt>find_autoignore_prefix_node self prefix<block_start>ip_version=get_ip_version(prefix)<line_sep>prefix_node=<none><line_sep>shared_memory_locks["autoignore"].acquire()<if_stmt>ip_version<eq>"v4"<block_start>size=32<block_end><else_stmt><block_start>size=128<block_end># need to turn to pytricia tree since this means that the tree has changed due to re-configuration <if_stmt>self.shared_memory_manager_dict["autoignore_recalculate"]<block_start>self.autoignore_prefix_tree[ip_version]=dict_to_pytricia(self.shared_memory_manager_dict["autoignore_prefix_tree"][ip_version] size )<line_sep>log.info("{} autoignore pytricia tree re-parsed from configuration".format(ip_version))<line_sep>self.shared_memory_manager_dict["autoignore_recalculate"]=<false><block_end><if_stmt>prefix<in>self.autoignore_prefix_tree[ip_version]<block_start>prefix_node=self.autoignore_prefix_tree[ip_version][prefix]<block_end>shared_memory_locks["autoignore"].release()<line_sep><return>prefix_node<block_end><def_stmt>annotate_bgp_update self message:Dict<arrow>NoReturn<block_start>""" Callback function that annotates an incoming bgp update with the associated configuration node (otherwise it discards it). """<line_sep>message.ack()<line_sep>bgp_update=message.payload<try_stmt><block_start>prefix_node=self.find_prefix_node(bgp_update["prefix"])<if_stmt>prefix_node<block_start>bgp_update["prefix_node"]=prefix_node<line_sep>self.producer.publish(bgp_update exchange=self.update_exchange routing_key="update-with-prefix-node" serializer="ujson" )<block_end># else: # log.warning("unconfigured BGP update received '{}'".format(bgp_update)) <block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><block_end><def_stmt>annotate_stored_bgp_update self message:Dict<arrow>NoReturn<block_start>""" Callback function that annotates an incoming (stored) bgp update with the associated configuration node (otherwise it discards it). """<line_sep>message.ack()<line_sep>bgp_update=message.payload<try_stmt><block_start>prefix_node=self.find_prefix_node(bgp_update["prefix"])<if_stmt>prefix_node<block_start>bgp_update["prefix_node"]=prefix_node<line_sep>self.producer.publish(bgp_update exchange=self.update_exchange routing_key="stored-update-with-prefix-node" serializer="ujson" )<block_end><else_stmt><block_start>log.warning("unconfigured stored BGP update received '{}'".format(bgp_update))<block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><block_end><def_stmt>annotate_ongoing_hijack_updates self message:Dict<arrow>NoReturn<block_start>""" Callback function that annotates incoming ongoing hijack updates with the associated configuration nodes (otherwise it discards them). """<line_sep>message.ack()<line_sep>bgp_updates=[]<for_stmt>bgp_update message.payload<block_start><try_stmt><block_start>prefix_node=self.find_prefix_node(bgp_update["prefix"])<if_stmt>prefix_node<block_start>bgp_update["prefix_node"]=prefix_node<block_end>bgp_updates.append(bgp_update)<block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><block_end>self.producer.publish(bgp_updates exchange=self.hijack_exchange routing_key="ongoing-with-prefix-node" serializer="ujson" )<block_end><def_stmt>annotate_mitigation_request self message:Dict<arrow>NoReturn<block_start>""" Callback function that annotates incoming hijack mitigation requests with the associated mitigation action/instruction (otherwise it discards them). """<line_sep>message.ack()<line_sep>mit_request=message.payload<try_stmt><block_start>prefix_node=self.find_prefix_node(mit_request["prefix"])<if_stmt>prefix_node<block_start>annotated_mit_request={}<line_sep># use the first best matching rule mitigation action; # a prefix should not have different mitigation actions anyway annotated_mit_request["hijack_info"]=mit_request<line_sep>annotated_mit_request["mitigation_action"]=prefix_node["data"]["confs"][0]["mitigation"]<line_sep>self.producer.publish(annotated_mit_request exchange=self.mitigation_exchange routing_key="mitigate-with-action" serializer="ujson" )<block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><block_end><def_stmt>annotate_unmitigation_request self message:Dict<arrow>NoReturn<block_start>""" Callback function that annotates incoming hijack unmitigation requests with the associated unmitigation action/instruction (otherwise it discards them). """<line_sep>message.ack()<line_sep>unmit_request=message.payload<try_stmt><block_start>prefix_node=self.find_prefix_node(unmit_request["prefix"])<if_stmt>prefix_node<block_start>annotated_unmit_request={}<line_sep># use the first best matching rule mitigation action; # a prefix should not have different mitigation actions anyway annotated_unmit_request["hijack_info"]=unmit_request<line_sep>annotated_unmit_request["mitigation_action"]=prefix_node["data"]["confs"][0]["mitigation"]<line_sep>self.producer.publish(annotated_unmit_request exchange=self.mitigation_exchange routing_key="unmitigate-with-action" serializer="ujson" )<block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><block_end><def_stmt>handle_autoconf_updates self message:List<arrow>NoReturn<block_start>""" Callback function that filters incoming autoconf updates based on whether their encoded information already exists in the configuration (prefixtree). """<line_sep>message.ack()<line_sep>bgp_updates=message.payload<if_stmt><not>isinstance(bgp_updates list)<block_start>bgp_updates=[bgp_updates]<block_end>bgp_updates_to_send_to_conf=list()<line_sep>delete_from_redis_without_sending_to_autoconf=set()<for_stmt>bgp_update bgp_updates# if you have seen the exact same update before, do nothing <block_start><if_stmt>self.redis.get(bgp_update["key"])<block_start><return><block_end><if_stmt>self.redis.exists("autoconf-update-keys-to-process")<and><not>self.redis.sismember("autoconf-update-keys-to-process" bgp_update["key"])<block_start><return><block_end>prefix_node=self.find_prefix_node(bgp_update["prefix"])<line_sep>add_update=<true><line_sep># small optimization: if prefix exist in prefix tree and we have an update for existing origin, discard it # attention: subprefixes belong to existing prefix nodes, so the check should also account # for exact prefix equality if it is to be deleted from the cache <if_stmt>(prefix_node<and>bgp_update["prefix"]<eq>prefix_node["prefix"]<and>bgp_update["type"]<eq>"A")<block_start><try_stmt><block_start>as_path=bgp_update["path"]<line_sep>origin=as_path[-1]<for_stmt>conf prefix_node["data"]["confs"]<block_start><if_stmt>origin<in>conf["origin_asns"]<block_start>add_update=<false><line_sep><break><block_end><block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<line_sep>add_update=<false><block_end><block_end><if_stmt><not>add_update<block_start>delete_from_redis_without_sending_to_autoconf.add(bgp_update["key"])<block_end><else_stmt><block_start>bgp_updates_to_send_to_conf.append(bgp_update)<block_end><block_end><if_stmt>self.redis.exists("autoconf-update-keys-to-process")<block_start>redis_pipeline=self.redis.pipeline()<for_stmt>bgp_update_key delete_from_redis_without_sending_to_autoconf<block_start>redis_pipeline.srem("autoconf-update-keys-to-process" bgp_update_key)<block_end>redis_pipeline.execute()<block_end>self.producer.publish(bgp_updates_to_send_to_conf exchange=self.autoconf_exchange routing_key="filtered-update" retry=<true> priority=4 serializer="ujson" )<block_end><def_stmt>handle_ongoing_hijack_prefixes self message:Dict<arrow>NoReturn<block_start>""" Callback function that checks whether ongoing hijack prefixes match an autoignore rule (included in the message). """<line_sep>message.ack()<line_sep>ongoing_hijacks_to_prefixes=message.payload["ongoing_hijacks_to_prefixes"]<line_sep>autoignore_rule_key=message.payload["rule_key"]<line_sep>hijacks_matching_rule=set()<for_stmt>hijack_key ongoing_hijacks_to_prefixes<block_start><try_stmt><block_start>autoignore_prefix_node=self.find_autoignore_prefix_node(ongoing_hijacks_to_prefixes[hijack_key])<if_stmt>(autoignore_prefix_node<and>autoignore_prefix_node["rule_key"]<eq>autoignore_rule_key)<block_start>hijacks_matching_rule.add(hijack_key)<block_end><block_end><except_stmt>Exception<block_start>log.exception("exception")<block_end><block_end>self.producer.publish({"hijacks_matching_rule":list(hijacks_matching_rule) "rule_key":autoignore_rule_key } exchange=self.autoignore_exchange routing_key="hijacks-matching-rule" retry=<true> priority=1 serializer="ujson" )<block_end><def_stmt>stop_consumer_loop self message:Dict<arrow>NoReturn<block_start>""" Callback function that stop the current consumer loop """<line_sep>message.ack()<line_sep>self.should_stop=<true><block_end><block_end><def_stmt>main # initiate prefix tree service with REST <block_start>prefixTreeService=PrefixTree()<line_sep># try to get configuration upon start (it is OK if it fails, will get it from POST) # (this is needed because service may restart while configuration is running) <try_stmt><block_start>r=requests.get("http://{}:{}/config".format(CONFIGURATION_HOST REST_PORT))<line_sep>conf_res=configure_prefixtree(r.json() prefixTreeService.shared_memory_manager_dict)<if_stmt><not>conf_res["success"]<block_start>log.info("could not get configuration upon startup, will get via POST later")<block_end><block_end><except_stmt>Exception<block_start>log.info("could not get configuration upon startup, will get via POST later")<block_end># start REST within main process prefixTreeService.start_rest_app()<block_end><if_stmt>__name__<eq>"__main__"<block_start>main()<block_end>
<import_stmt>numpy<as>np<import_from_stmt>numpy cos sin pi<line_sep>Ho=5000# ocean depth in meters nx=62# number of gridpoints in x-direction ny=62# number of gridpoints in y-direction xo=0# origin in x,y for ocean domain yo=0# (i.e. southwestern corner of ocean domain) dx=20# grid spacing in x (km) dy=20# grid spacing in y (km) xeast=xo+(nx-2)<times>dx# eastern extent of ocean domain ynorth=yo+(ny-2)<times>dy# northern extent of ocean domain # Flat bottom at z=-Ho h=-Ho<times>np.ones((ny nx))<line_sep># Walls (surrounding domain); generate bathymetry file h[: [0 -1]]=0# set ocean depth to zero at east and west walls h[[0 -1] :]=0# set ocean depth to zero at south and north walls # save as single-precision (float32) with big-endian byte ordering h.astype('>f4').tofile('bathy.bin')<line_sep># Ocean domain extends from (xo,yo) to (xeast,ynorth) # (i.e. the ocean spans nx-2, ny-2 grid cells) # out-of-box-config: xo=yo=0, dx=dy=20 km, ocean extent (0,0)-(1200,1200) km # model domain includes a land cell surrounding the ocean domain # The full model domain cell centers are located at: # XC[0,:] = -10, +10, ..., +1210 (km) # YC[:,0] = -10, +10, ..., +1210 (km) # and full model domain cell corners are located at: # XG[0,:] = -20, 0, ..., 1200 [, 1220] (km) # YG[:,0] = -20, 0, ..., 1200 [, 1220] (km) # where the last value in brackets is not included in the MITgcm grid variable # and reflects the eastern and northern edge of the model domain respectively. # See section 2.11.4 of the MITgcm users manual. # Zonal wind-stress, located at u-points (see section 2.11.4) # here we non-dimensionalize: 0 at southern and western ocean boundary # to 1.0 at eastern and northern ocean boundary # for the purpose of applying sinusoidal-shaped wind stress curve tauMax=0.1# wind stress maximum x=(np.arange(nx)-1)/(nx-2)# x-coordinate, located at XG points y=(np.arange(ny)-.5)/(ny-2)# y-coordinate, located at YC points Y,X=np.meshgrid(y x indexing='ij')<line_sep>tau=-tauMax<times>cos(Y<times>pi)# generate file for -cos(y) profile between 0-1200km tau.astype('>f4').tofile('windx_cosy.bin')<line_sep>tau=tauMax<times>sin(Y<times>pi)# generate file for +sin(y) profile between 0-1200km tau.astype('>f4').tofile('windx_siny.bin')<line_sep># Meridional wind-stress, if desired, would be located at v-points (XC, YG)
<import_stmt>base64<import_stmt>urllib2<import_stmt>json<import_stmt>os<import_stmt>logging<import_from_stmt>celery task<import_from_stmt>django.conf settings<import_from_stmt>django.utils.timezone now<import_from_stmt>github.GithubObject NotSet<import_from_stmt>github Github GithubException InputGitTreeElement<import_from_stmt>ide.git git_auth_check get_github<import_from_stmt>ide.models.build BuildResult<import_from_stmt>ide.models.project Project<import_from_stmt>ide.tasks do_import_archive run_compile<import_from_stmt>ide.utils.git git_sha git_blob<import_from_stmt>ide.utils.project find_project_root_and_manifest BaseProjectItem InvalidProjectArchiveException<import_from_stmt>ide.utils.sdk generate_manifest_dict generate_manifest generate_wscript_file manifest_name_for_project<import_from_stmt>utils.td_helper send_td_event<line_sep>__author__='katharine'<line_sep>logger=logging.getLogger(__name__)<line_sep>@task(acks_late=<true>)<def_stmt>do_import_github project_id github_user github_project github_branch delete_project=<false><block_start><try_stmt><block_start>url="https://github.com/%s/%s/archive/%s.zip"%(github_user github_project github_branch)<if_stmt>file_exists(url)<block_start>u=urllib2.urlopen(url)<line_sep><return>do_import_archive(project_id u.read())<block_end><else_stmt><block_start><raise>Exception("The branch '%s' does not exist."%github_branch)<block_end><block_end><except_stmt>Exception<as>e<block_start><try_stmt><block_start>project=Project.objects.get(pk=project_id)<line_sep>user=project.owner<block_end><except_stmt><block_start>project=<none><line_sep>user=<none><block_end><if_stmt>delete_project<and>project<is><not><none><block_start><try_stmt><block_start>project.delete()<block_end><except_stmt><block_start><pass><block_end><block_end>send_td_event('cloudpebble_github_import_failed' data={'data':{'reason':e.message 'github_user':github_user 'github_project':github_project 'github_branch':github_branch}} user=user)<line_sep><raise><block_end><block_end><def_stmt>file_exists url<block_start>request=urllib2.Request(url)<line_sep>request.get_method=<lambda>:'HEAD'<try_stmt><block_start>urllib2.urlopen(request)<block_end><except_stmt><block_start><return><false><block_end><else_stmt><block_start><return><true><block_end><block_end>@git_auth_check<def_stmt>github_push user commit_message repo_name project<block_start>g=Github(user.github.token client_id=settings.GITHUB_CLIENT_ID client_secret=settings.GITHUB_CLIENT_SECRET)<line_sep>repo=g.get_repo(repo_name)<try_stmt><block_start>branch=repo.get_branch(project.github_branch<or>repo.master_branch)<block_end><except_stmt>GithubException<block_start><raise>Exception("Unable to get branch.")<block_end>commit=repo.get_git_commit(branch.commit.sha)<line_sep>tree=repo.get_git_tree(commit.tree.sha recursive=<true>)<line_sep>next_tree={x.path:InputGitTreeElement(path=x.path mode=x.mode type=x.type sha=x.sha)<for>x tree.tree}<try_stmt><block_start>root,manifest_item=find_project_root_and_manifest([GitProjectItem(repo x)<for>x tree.tree])<block_end><except_stmt>InvalidProjectArchiveException<block_start>root=''<line_sep>manifest_item=<none><block_end>expected_paths=set()<def_stmt>update_expected_paths new_path# This adds the path *and* its parent directories to the list of expected paths. # The parent directories are already keys in next_tree, so if they aren't present in expected_paths # then, when iterating over next_tree to see which files have been deleted, we would have to treat # directories as special cases. <block_start>split_path=new_path.split('/')<line_sep>expected_paths.update('/'.join(split_path[:p])<for>p range(2 len(split_path)+1))<block_end>project_sources=project.source_files.all()<line_sep>has_changed=<false><for_stmt>source project_sources<block_start>repo_path=os.path.join(root source.project_path)<line_sep>update_expected_paths(repo_path)<if_stmt>repo_path<not><in>next_tree<block_start>has_changed=<true><line_sep>next_tree[repo_path]=InputGitTreeElement(path=repo_path mode='100644' type='blob' content=source.get_contents())<line_sep>logger.debug("New file: %s" repo_path)<block_end><else_stmt><block_start>sha=next_tree[repo_path]._InputGitTreeElement__sha<line_sep>our_content=source.get_contents()<line_sep>expected_sha=git_sha(our_content)<if_stmt>expected_sha<ne>sha<block_start>logger.debug("Updated file: %s" repo_path)<line_sep>next_tree[repo_path]._InputGitTreeElement__sha=NotSet<line_sep>next_tree[repo_path]._InputGitTreeElement__content=our_content<line_sep>has_changed=<true><block_end><block_end><block_end># Now try handling resource files. resources=project.resources.all()<line_sep>resource_root=project.resources_path<for_stmt>res resources<block_start><for_stmt>variant res.variants.all()<block_start>repo_path=os.path.join(resource_root variant.path)<line_sep>update_expected_paths(repo_path)<if_stmt>repo_path<in>next_tree<block_start>content=variant.get_contents()<if_stmt>git_sha(content)<ne>next_tree[repo_path]._InputGitTreeElement__sha<block_start>logger.debug("Changed resource: %s" repo_path)<line_sep>has_changed=<true><line_sep>blob=repo.create_git_blob(base64.b64encode(content) 'base64')<line_sep>logger.debug("Created blob %s" blob.sha)<line_sep>next_tree[repo_path]._InputGitTreeElement__sha=blob.sha<block_end><block_end><else_stmt><block_start>logger.debug("New resource: %s" repo_path)<line_sep>has_changed=<true><line_sep>blob=repo.create_git_blob(base64.b64encode(variant.get_contents()) 'base64')<line_sep>logger.debug("Created blob %s" blob.sha)<line_sep>next_tree[repo_path]=InputGitTreeElement(path=repo_path mode='100644' type='blob' sha=blob.sha)<block_end><block_end><block_end># Manage deleted files src_root=os.path.join(root 'src')<line_sep>worker_src_root=os.path.join(root 'worker_src')<for_stmt>path next_tree.keys()<block_start><if_stmt><not>(any(path.startswith(root+'/')<for>root (src_root resource_root worker_src_root)))<block_start><continue><block_end><if_stmt>path<not><in>expected_paths<block_start><del_stmt>next_tree[path]<line_sep>logger.debug("Deleted file: %s" path)<line_sep>has_changed=<true><block_end><block_end># Compare the resource dicts remote_manifest_path=root+manifest_name_for_project(project)<line_sep>remote_wscript_path=root+'wscript'<if_stmt>manifest_item<block_start>their_manifest_dict=json.loads(manifest_item.read())<line_sep>their_res_dict=their_manifest_dict.get('resources' their_manifest_dict.get('pebble' their_manifest_dict).get('resources' {'media':[]}))<line_sep># If the manifest needs a new path (e.g. it is now package.json), delete the old one <if_stmt>manifest_item.path<ne>remote_manifest_path<block_start><del_stmt>next_tree[manifest_item.path]<block_end><block_end><else_stmt><block_start>their_manifest_dict={}<line_sep>their_res_dict={'media':[]}<block_end>our_manifest_dict=generate_manifest_dict(project resources)<line_sep>our_res_dict=our_manifest_dict.get('resources' our_manifest_dict.get('pebble' our_manifest_dict).get('resources' {'media':[]}))<if_stmt>our_res_dict<ne>their_res_dict<block_start>logger.debug("Resources mismatch.")<line_sep>has_changed=<true><line_sep># Try removing things that we've deleted, if any to_remove=set(x['file']<for>x their_res_dict['media'])-set(x['file']<for>x our_res_dict['media'])<for_stmt>path to_remove<block_start>repo_path=resource_root+path<if_stmt>repo_path<in>next_tree<block_start>logger.debug("Deleted resource: %s" repo_path)<del_stmt>next_tree[repo_path]<block_end><block_end><block_end># This one is separate because there's more than just the resource map changing. <if_stmt>their_manifest_dict<ne>our_manifest_dict<block_start>has_changed=<true><if_stmt>remote_manifest_path<in>next_tree<block_start>next_tree[remote_manifest_path]._InputGitTreeElement__sha=NotSet<line_sep>next_tree[remote_manifest_path]._InputGitTreeElement__content=generate_manifest(project resources)<block_end><else_stmt><block_start>next_tree[remote_manifest_path]=InputGitTreeElement(path=remote_manifest_path mode='100644' type='blob' content=generate_manifest(project resources))<block_end><block_end><if_stmt>project.project_type<eq>'native'<and>remote_wscript_path<not><in>next_tree<block_start>next_tree[remote_wscript_path]=InputGitTreeElement(path=remote_wscript_path mode='100644' type='blob' content=generate_wscript_file(project <true>))<line_sep>has_changed=<true><block_end># Commit the new tree. <if_stmt>has_changed<block_start>logger.debug("Has changed; committing")<line_sep># GitHub seems to choke if we pass the raw directory nodes off to it, # so we delete those. <for_stmt>x next_tree.keys()<block_start><if_stmt>next_tree[x]._InputGitTreeElement__mode<eq>'040000'<block_start><del_stmt>next_tree[x]<line_sep>logger.debug("removing subtree node %s" x)<block_end><block_end>logger.debug([x._InputGitTreeElement__mode<for>x next_tree.values()])<line_sep>git_tree=repo.create_git_tree(next_tree.values())<line_sep>logger.debug("Created tree %s" git_tree.sha)<line_sep>git_commit=repo.create_git_commit(commit_message git_tree [commit])<line_sep>logger.debug("Created commit %s" git_commit.sha)<line_sep>git_ref=repo.get_git_ref('heads/%s'%(project.github_branch<or>repo.master_branch))<line_sep>git_ref.edit(git_commit.sha)<line_sep>logger.debug("Updated ref %s" git_ref.ref)<line_sep>project.github_last_commit=git_commit.sha<line_sep>project.github_last_sync=now()<line_sep>project.save()<line_sep><return><true><block_end>send_td_event('cloudpebble_github_push' data={'data':{'repo':project.github_repo}} user=user)<line_sep><return><false><block_end><def_stmt>get_root_path path<block_start>path,extension=os.path.splitext(path)<line_sep><return>path.split('~' 1)[0]+extension<block_end><class_stmt>GitProjectItem(BaseProjectItem)<block_start><def_stmt>__init__ self repo tree_item<block_start>self.repo=repo<line_sep>self.git_item=tree_item<block_end><def_stmt>read self<block_start><return>git_blob(self.repo self.git_item.sha)<block_end>@property<def_stmt>path self<block_start><return>self.git_item.path<block_end><block_end>@git_auth_check<def_stmt>github_pull user project<block_start>g=get_github(user)<line_sep>repo_name=project.github_repo<if_stmt>repo_name<is><none><block_start><raise>Exception("No GitHub repo defined.")<block_end>repo=g.get_repo(repo_name)<line_sep># If somehow we don't have a branch set, this will use the "master_branch" branch_name=project.github_branch<or>repo.master_branch<try_stmt><block_start>branch=repo.get_branch(branch_name)<block_end><except_stmt>GithubException<block_start><raise>Exception("Unable to get the branch.")<block_end><if_stmt>project.github_last_commit<eq>branch.commit.sha# Nothing to do. <block_start><return><false><block_end>commit=repo.get_git_commit(branch.commit.sha)<line_sep>tree=repo.get_git_tree(commit.tree.sha recursive=<true>)<line_sep>paths={x.path:x<for>x tree.tree}<line_sep>paths_notags={get_root_path(x)<for>x paths}<line_sep># First try finding the resource map so we don't fail out part-done later. <try_stmt><block_start>root,manifest_item=find_project_root_and_manifest([GitProjectItem(repo x)<for>x tree.tree])<block_end><except_stmt>ValueError<as>e<block_start><raise>ValueError("In manifest file: %s"%str(e))<block_end>resource_root=root+project.resources_path+'/'<line_sep>manifest=json.loads(manifest_item.read())<line_sep>media=manifest.get('resources' {}).get('media' [])<line_sep>project_type=manifest.get('projectType' 'native')<for_stmt>resource media<block_start>path=resource_root+resource['file']<if_stmt>project_type<eq>'pebblejs'<and>resource['name']<in>{'MONO_FONT_14' 'IMAGE_MENU_ICON' 'IMAGE_LOGO_SPLASH' 'IMAGE_TILE_SPLASH'}<block_start><continue><block_end><if_stmt>path<not><in>paths_notags<block_start><raise>Exception("Resource %s not found in repo."%path)<block_end><block_end># Now we grab the zip. zip_url=repo.get_archive_link('zipball' branch_name)<line_sep>u=urllib2.urlopen(zip_url)<line_sep># And wipe the project! # TODO: transaction support for file contents would be nice... project.source_files.all().delete()<line_sep>project.resources.all().delete()<line_sep># This must happen before do_import_archive or we'll stamp on its results. project.github_last_commit=branch.commit.sha<line_sep>project.github_last_sync=now()<line_sep>project.save()<line_sep>import_result=do_import_archive(project.id u.read())<line_sep>send_td_event('cloudpebble_github_pull' data={'data':{'repo':project.github_repo}} user=user)<line_sep><return>import_result<block_end>@task<def_stmt>do_github_push project_id commit_message<block_start>project=Project.objects.select_related('owner__github').get(pk=project_id)<line_sep><return>github_push(project.owner commit_message project.github_repo project)<block_end>@task<def_stmt>do_github_pull project_id<block_start>project=Project.objects.select_related('owner__github').get(pk=project_id)<line_sep><return>github_pull(project.owner project)<block_end>@task<def_stmt>hooked_commit project_id target_commit<block_start>project=Project.objects.select_related('owner__github').get(pk=project_id)<line_sep>did_something=<false><line_sep>logger.debug("Comparing %s versus %s" project.github_last_commit target_commit)<if_stmt>project.github_last_commit<ne>target_commit<block_start>github_pull(project.owner project)<line_sep>did_something=<true><block_end><if_stmt>project.github_hook_build<block_start>build=BuildResult.objects.create(project=project)<line_sep>run_compile(build.id)<line_sep>did_something=<true><block_end><return>did_something<block_end>
# Copyright 2021 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implements Longformer's attention (https://arxiv.org/abs/2004.05150). Like the current (8/28/20) Huggingface version, we do not support dilated and autoregressive attention patterns as they require custom CUDA kernels to be efficient. "Sliding window" and "global" attention patterns are supported, however. """<import_from_stmt>flax nn<import_from_stmt>jax lax<import_stmt>jax.numpy<as>jnp<import_stmt>numpy<as>np<def_stmt>_build_global_mask mask<block_start>"""Builds mask for global attention pattern. Args: mask: boolean jax array of shape `[batch_size, seq_len]`. Returns: mask, boolean jax array of shape `[batch_size, 1 (n_heads), seq_len, seq_len]`. """<line_sep><return>jnp.logical_or(mask[: jnp.newaxis : jnp.newaxis] mask[: jnp.newaxis jnp.newaxis :])<block_end><def_stmt>_build_sliding_window_mask window_size global_mask<block_start>"""Builds mask for sliding window pattern. Args: window_size: int, size of sliding window. global_mask: boolean jax array of shape `[batch_size, seq_len]`. Returns: mask, boolean jax array of shape `[batch_size, 1 (n_heads), seq_len, seq_len]`. If `window_size` is odd, both left and right sides have the same receptive field. Otherwise, the left side gets one more. Note - we need global mask because due to the symmetry requirement, non-global positions can still attend to global positions. """<line_sep>seq_len=global_mask.shape[1]<line_sep>right_size=window_size<floordiv>2<line_sep>left_size=window_size-right_size<line_sep>left_mask=sum(np.eye(seq_len k=-i)<for>i range(left_size))<line_sep>right_mask=sum(np.eye(seq_len k=i)<for>i range(1 right_size+1))<line_sep>mask=left_mask+right_mask<line_sep>mask=jnp.array(mask[np.newaxis np.newaxis : :]).astype(jnp.bool_)<line_sep><return>jnp.logical_or(mask _build_global_mask(global_mask))<block_end><def_stmt>_get_attention_result query key value dtype precision dropout_rng dropout_rate broadcast_dropout deterministic mask=<none> padding_mask=<none> key_padding_mask=<none> segmentation=<none> key_segmentation=<none> apply_causal_mask=<false><block_start>"""Helper function returning `[batch_size, seq_len, heads, features]` output."""<line_sep># assumes query/key/value has shape `[batch_size, seq_len, heads, features]`. mask_components=[]<if>mask<is><none><else>[mask]<line_sep>seq_len=query.shape[1]<if_stmt>apply_causal_mask<block_start>causal_mask=jnp.array(np.reshape(np.tri(seq_len k=0) [1 1 seq_len seq_len])).astype(jnp.bool_)<line_sep>mask_components.append(causal_mask)<block_end><if_stmt>padding_mask<is><not><none><block_start><if_stmt>key_padding_mask<is><none><block_start>key_padding_mask=padding_mask<block_end>padding_mask=nn.attention.make_padding_mask(padding_mask_query=padding_mask padding_mask_key=key_padding_mask query_shape=query.shape key_shape=key.shape attention_axis=(1 ))<line_sep>mask_components.append(padding_mask)<block_end><if_stmt>segmentation<is><not><none><block_start><if_stmt>key_segmentation<is><none><block_start>key_segmentation=segmentation<block_end>segmentation_mask=nn.attention.make_padding_mask(padding_mask_query=segmentation padding_mask_key=key_segmentation query_shape=query.shape key_shape=key.shape attention_axis=(1 ) segmentation_mask=<true>)<line_sep>mask_components.append(segmentation_mask)<block_end><if_stmt>mask_components<block_start>attention_mask=mask_components[0]<for_stmt>component mask_components[1:]<block_start>attention_mask=jnp.logical_and(attention_mask component)<block_end># attention mask in the form of attention bias attention_bias=lax.select(attention_mask<g>0 jnp.full(attention_mask.shape 0.).astype(dtype) jnp.full(attention_mask.shape -1e10).astype(dtype))<block_end><else_stmt><block_start>attention_bias=<none><block_end><return>nn.attention.dot_product_attention(query key value dtype=dtype axis=1 bias=attention_bias precision=precision dropout_rng=dropout_rng dropout_rate=dropout_rate broadcast_dropout=broadcast_dropout deterministic=deterministic)<block_end><class_stmt>LongformerAttention(nn.Module)<block_start>"""Module implementing Longformer attention."""<def_stmt>apply self inputs_q inputs_kv num_heads sliding_window_size=512 global_mask=<none> causal_mask=<false> dtype=jnp.float32 qkv_features=<none> out_features=<none> padding_mask=<none> key_padding_mask=<none> segmentation=<none> key_segmentation=<none> broadcast_dropout=<true> dropout_rng=<none> dropout_rate=0. deterministic=<false> precision=<none> kernel_init=nn.linear.default_kernel_init bias_init=nn.initializers.zeros bias=<true><block_start>"""Applies longformer multi-head dot product attention on the input data. Args: inputs_q: input queries of shape `[bs, seq_len, features]`. inputs_kv: key/values of shape `[bs, seq_len, features]` or `None` for self-attention, in which case key/values will be derived from inputs_q. num_heads: number of attention heads (should divide number of features). sliding_window_size: size of sliding window attention to use. global_mask: boolean matrix of shape `[bs, seq_len]`, where `True` indicates that the position is globally attended. By default, no global attention is used. causal_mask: If true, apply causal attention masking. dtype: the dtype of the computation (default: float32). qkv_features: dimension of the key, query, and value. out_features: dimension of the last projection. padding_mask: boolean specifying query tokens that are pad token. key_padding_mask: boolean specifying key-value tokens that are pad token. segmentation: segment indices for packed inputs_q data. key_segmentation: segment indices for packed inputs_kv data. broadcast_dropout: use a broadcasted dropout along batch dims. dropout_rng: JAX PRNGKey to be use for dropout. dropout_rate: dropout rate. deterministic: if true, apply dropout, else don't. precision: numerical precision of the computation. kernel_init: initializer for the kernel of the Dense layers. bias_init: initializer for the bias of the Dense layers. bias: whether pointwise QKVO dense transforms use bias. query, key, value, and returns output of shape `[bs, seq_len, num_heads, value_channels]`. Returns: output of shape `[bs, seq_len, features]`. """<if_stmt>inputs_kv<is><none><block_start>inputs_kv=inputs_q<block_end>batch_size=inputs_q.shape[0]<line_sep>features=out_features<or>inputs_q.shape[-1]<line_sep>qkv_features=qkv_features<or>inputs_q.shape[-1]<line_sep>seq_len=inputs_q.shape[1]<assert_stmt>qkv_features%num_heads<eq>0 ('Memory dimension must be divisible by number of heads.')<line_sep>head_dim=qkv_features<floordiv>num_heads<line_sep>dense=nn.DenseGeneral.partial(axis=-1 features=(num_heads head_dim) kernel_init=kernel_init bias_init=bias_init bias=bias precision=precision)<line_sep>query_sw=dense(inputs_q dtype=dtype name='query_sliding_window')<line_sep>key_sw=dense(inputs_kv dtype=dtype name='key_sliding_window')<line_sep>value_sw=dense(inputs_kv dtype=dtype name='value_sliding_window')<line_sep>query_global=dense(inputs_q dtype=dtype name='query_global')<line_sep>key_global=dense(inputs_kv dtype=dtype name='key_global')<line_sep>value_global=dense(inputs_kv dtype=dtype name='value_global')<if_stmt>global_mask<is><none><block_start>global_mask=jnp.full((batch_size seq_len) <false>)<block_end>full_global_mask=_build_global_mask(global_mask)<line_sep>sliding_window_mask=_build_sliding_window_mask(window_size=sliding_window_size global_mask=global_mask)<line_sep>x_sw=_get_attention_result(query=query_sw key=key_sw value=value_sw dtype=dtype precision=precision dropout_rng=dropout_rng dropout_rate=dropout_rate broadcast_dropout=broadcast_dropout deterministic=deterministic mask=sliding_window_mask padding_mask=padding_mask key_padding_mask=key_padding_mask segmentation=segmentation key_segmentation=key_segmentation apply_causal_mask=causal_mask)<line_sep>x_global=_get_attention_result(query=query_global key=key_global value=value_global dtype=dtype precision=precision dropout_rng=dropout_rng dropout_rate=dropout_rate broadcast_dropout=broadcast_dropout deterministic=deterministic mask=full_global_mask padding_mask=padding_mask key_padding_mask=key_padding_mask segmentation=segmentation key_segmentation=key_segmentation apply_causal_mask=causal_mask)<line_sep>x=jnp.where(global_mask[: : jnp.newaxis jnp.newaxis] x_global x_sw)<line_sep># back to the original inputs dimensions out=nn.DenseGeneral(x features=features axis=(-2 -1) kernel_init=kernel_init bias_init=bias_init bias=bias dtype=dtype precision=precision name='out')<line_sep><return>out<block_end><block_end>LongformerSelfAttention=LongformerAttention.partial(inputs_kv=<none>)<line_sep>
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """<import_from_stmt>typing Any<import_from_stmt>sims4communitylib.events.build_buy.events.build_buy_enter S4CLBuildBuyEnterEvent<import_from_stmt>sims4communitylib.events.build_buy.events.build_buy_exit S4CLBuildBuyExitEvent<import_from_stmt>sims4communitylib.events.event_handling.common_event_registry CommonEventRegistry<import_from_stmt>sims4communitylib.modinfo ModInfo<import_from_stmt>sims4communitylib.services.common_service CommonService<import_from_stmt>sims4communitylib.utils.common_injection_utils CommonInjectionUtils<import_from_stmt>zone Zone<class_stmt>CommonBuildBuyEventDispatcherService(CommonService)<block_start>"""A service that dispatches Build/Buy events. .. warning:: Do not use this service directly to listen for events!\ Use the :class:`.CommonEventRegistry` to listen for dispatched events. """<def_stmt>_on_build_buy_enter self zone:Zone *_ **__<block_start><return>CommonEventRegistry.get().dispatch(S4CLBuildBuyEnterEvent(zone))<block_end><def_stmt>_on_build_buy_exit self zone:Zone *_ **__<block_start><return>CommonEventRegistry.get().dispatch(S4CLBuildBuyExitEvent(zone))<block_end><block_end>@CommonInjectionUtils.inject_safely_into(ModInfo.get_identity() Zone Zone.on_build_buy_enter.__name__)<def_stmt>_common_build_buy_enter original self *args **kwargs<arrow>Any<block_start>result=original(self *args **kwargs)<line_sep>CommonBuildBuyEventDispatcherService.get()._on_build_buy_enter(self *args **kwargs)<line_sep><return>result<block_end>@CommonInjectionUtils.inject_safely_into(ModInfo.get_identity() Zone Zone.on_build_buy_exit.__name__)<def_stmt>_common_build_buy_exit original self *args **kwargs<arrow>Any<block_start>result=original(self *args **kwargs)<line_sep>CommonBuildBuyEventDispatcherService.get()._on_build_buy_exit(self *args **kwargs)<line_sep><return>result<block_end>
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Author: ryanss <<EMAIL>> (c) 2014-2017 # dr-prodigy <<EMAIL>> (c) 2017-2021 # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) <import_from_stmt>datetime date<import_from_stmt>dateutil.relativedelta relativedelta<as>rd MO<import_from_stmt>holidays.constants FRI SAT SUN<import_from_stmt>holidays.constants JAN FEB MAR MAY SEP NOV DEC<import_from_stmt>holidays.holiday_base HolidayBase<class_stmt>Mexico(HolidayBase)<block_start><def_stmt>__init__ self **kwargs<block_start>self.country="MX"<line_sep>HolidayBase.__init__(self **kwargs)<block_end><def_stmt>_populate self year# New Year's Day <block_start>name="Año Nuevo [New Year's Day]"<line_sep>self[date(year JAN 1)]=name<if_stmt>self.observed<and>date(year JAN 1).weekday()<eq>SUN<block_start>self[date(year JAN 1)+rd(days=+1)]=name+" (Observed)"<block_end># The next year's observed New Year's Day can be in this year # when it falls on a Friday (Jan 1st is a Saturday) <if_stmt>self.observed<and>date(year DEC 31).weekday()<eq>FRI<block_start>self[date(year DEC 31)]=name+" (Observed)"<block_end># Constitution Day name="Día de la Constitución [Constitution Day]"<if_stmt>self.observed<and>year<ge>2007<block_start>self[date(year FEB 1)+rd(weekday=MO(+1))]=(name+" (Observed)")<block_end><if_stmt>year<ge>1917<block_start>self[date(year FEB 5)]=name<block_end># Benito Juárez's birthday name="<NAME> [Benito Juárez's birthday]"<if_stmt>self.observed<and>year<ge>2007<block_start>self[date(year MAR 1)+rd(weekday=MO(+3))]=(name+" (Observed)")<block_end><if_stmt>year<ge>1917<block_start>self[date(year MAR 21)]=name<block_end># Labor Day <if_stmt>year<ge>1923<block_start>name="Día del Trabajo [Labour Day]"<line_sep>self[date(year MAY 1)]=name<if_stmt>self.observed<and>date(year MAY 1).weekday()<eq>SAT<block_start>self[date(year MAY 1)+rd(days=-1)]=name+" (Observed)"<block_end><elif_stmt>self.observed<and>date(year MAY 1).weekday()<eq>SUN<block_start>self[date(year MAY 1)+rd(days=+1)]=name+" (Observed)"<block_end><block_end># Independence Day name="Día de la Independencia [Independence Day]"<line_sep>self[date(year SEP 16)]=name<if_stmt>self.observed<and>date(year SEP 16).weekday()<eq>SAT<block_start>self[date(year SEP 16)+rd(days=-1)]=name+" (Observed)"<block_end><elif_stmt>self.observed<and>date(year SEP 16).weekday()<eq>SUN<block_start>self[date(year SEP 16)+rd(days=+1)]=name+" (Observed)"<block_end># Revolution Day name="Día de la Revolución [Revolution Day]"<if_stmt>self.observed<and>year<ge>2007<block_start>self[date(year NOV 1)+rd(weekday=MO(+3))]=(name+" (Observed)")<block_end><if_stmt>year<ge>1917<block_start>self[date(year NOV 20)]=name<block_end># Change of Federal Government # Every six years--next observance 2018 name="Transmisión del Poder Ejecutivo Federal"<line_sep>name<augadd>" [Change of Federal Government]"<if_stmt>year<ge>1970<and>(2096-year)%6<eq>0<block_start>self[date(year DEC 1)]=name<if_stmt>self.observed<and>date(year DEC 1).weekday()<eq>SAT<block_start>self[date(year DEC 1)+rd(days=-1)]=name+" (Observed)"<block_end><elif_stmt>self.observed<and>date(year DEC 1).weekday()<eq>SUN<block_start>self[date(year DEC 1)+rd(days=+1)]=name+" (Observed)"<block_end><block_end># Christmas self[date(year DEC 25)]="Navidad [Christmas]"<if_stmt>self.observed<and>date(year DEC 25).weekday()<eq>SAT<block_start>self[date(year DEC 25)+rd(days=-1)]=name+" (Observed)"<block_end><elif_stmt>self.observed<and>date(year DEC 25).weekday()<eq>SUN<block_start>self[date(year DEC 25)+rd(days=+1)]=name+" (Observed)"<block_end><block_end><block_end><class_stmt>MX(Mexico)<block_start><pass><block_end><class_stmt>MEX(Mexico)<block_start><pass><block_end>
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # <NAME> (<EMAIL>), Blue Yonder Gmbh, 2016 <import_stmt>warnings<import_from_stmt>builtins range<import_from_stmt>unittest TestCase<import_stmt>numpy<as>np<import_stmt>numpy.testing<as>npt<import_stmt>pandas<as>pd<import_stmt>pandas.testing<as>pdt<import_from_stmt>sklearn.exceptions NotFittedError<import_from_stmt>tsfresh.transformers.per_column_imputer PerColumnImputer<class_stmt>PerColumnImputerTestCase(TestCase)<block_start><def_stmt>setUp self<block_start>np.random.seed(0)<block_end><def_stmt>test_not_fitted self<block_start>imputer=PerColumnImputer()<line_sep>X=pd.DataFrame()<line_sep>self.assertRaises(NotFittedError imputer.transform X)<block_end><def_stmt>test_only_nans_and_infs self<block_start>imputer=PerColumnImputer()<line_sep>X=pd.DataFrame(index=list(range(100)))<line_sep>X["NaNs"]=np.nan<times>np.ones(100)<line_sep>X["PINF"]=np.PINF<times>np.ones(100)<line_sep>X["NINF"]=np.NINF<times>np.ones(100)<with_stmt>warnings.catch_warnings(record=<true>)<as>w<block_start>imputer.fit(X)<line_sep>self.assertEqual(len(w) 1)<line_sep>self.assertEqual("The columns ['NaNs' 'PINF' 'NINF'] did not have any finite values. Filling with zeros." str(w[0].message) )<block_end>selected_X=imputer.transform(X)<line_sep>self.assertTrue((selected_X.values<eq>0).all())<block_end><def_stmt>test_with_numpy_array self<block_start>imputer=PerColumnImputer()<line_sep>X=pd.DataFrame(index=list(range(100)))<line_sep>X["NaNs"]=np.nan<times>np.ones(100)<line_sep>X["PINF"]=np.PINF<times>np.ones(100)<line_sep>X["NINF"]=np.NINF<times>np.ones(100)<line_sep>X_numpy=X.values.copy()<with_stmt>warnings.catch_warnings(record=<true>)<as>w<block_start>imputer.fit(X)<line_sep>self.assertEqual(len(w) 1)<line_sep>self.assertEqual("The columns ['NaNs' 'PINF' 'NINF'] did not have any finite values. Filling with zeros." str(w[0].message) )<block_end>selected_X=imputer.transform(X)<line_sep># re-initialize for new dicts imputer=PerColumnImputer()<with_stmt>warnings.catch_warnings(record=<true>)<as>w<block_start>imputer.fit(X_numpy)<line_sep>self.assertEqual(len(w) 1)<line_sep>self.assertEqual("The columns [0 1 2] did not have any finite values. Filling with zeros." str(w[0].message) )<block_end>selected_X_numpy=imputer.transform(X_numpy)<line_sep>npt.assert_array_equal(selected_X.values selected_X_numpy.values)<line_sep>self.assertTrue(selected_X_numpy.shape (1 100))<block_end><def_stmt>test_standard_replacement_behavior self<block_start>imputer=PerColumnImputer()<line_sep>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>truth=[-100.0 100.0 1.0 100.0 -100.0 1.0 1.0]<line_sep>X=pd.DataFrame({"a":data})<line_sep>true_X=pd.DataFrame({"a":truth})<line_sep>imputer.fit(X)<line_sep>selected_X=imputer.transform(X)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_partial_preset_col_to_NINF_given self<block_start>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>truth=[-100.0 100.0 1.0 100.0 -100.0 1.0 1.0]<line_sep>X=pd.DataFrame({"a":data})<line_sep>true_X=pd.DataFrame({"a":truth})<line_sep>col_to_min={"a":-100}<line_sep>imputer=PerColumnImputer(col_to_NINF_repl_preset=col_to_min)<line_sep>imputer.fit(X)<line_sep>selected_X=imputer.transform(X)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_partial_preset_col_to_PINF_given self<block_start>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>truth=[-100.0 100.0 1.0 100.0 -100.0 1.0 1.0]<line_sep>X=pd.DataFrame({"a":data})<line_sep>true_X=pd.DataFrame({"a":truth})<line_sep>col_to_max={"a":100}<line_sep>imputer=PerColumnImputer(col_to_PINF_repl_preset=col_to_max)<line_sep>imputer.fit(X)<line_sep>selected_X=imputer.transform(X)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_partial_preset_col_to_NAN_given self<block_start>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>truth=[-100.0 100.0 1.0 100.0 -100.0 1.0 1.0]<line_sep>X=pd.DataFrame({"a":data})<line_sep>true_X=pd.DataFrame({"a":truth})<line_sep>col_to_median={"a":1}<line_sep>imputer=PerColumnImputer(col_to_NAN_repl_preset=col_to_median)<line_sep>imputer.fit(X)<line_sep>selected_X=imputer.transform(X)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_different_shapes_fitted_and_transformed self<block_start>imputer=PerColumnImputer()<line_sep>X=pd.DataFrame(index=list(range(10)))<line_sep>X["a"]=np.ones(10)<line_sep>imputer.fit(X)<line_sep>X["b"]=np.ones(10)<line_sep>self.assertRaises(ValueError imputer.transform X)<block_end><def_stmt>test_preset_has_higher_priority_than_fit self<block_start>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>truth=[-100.0 100.0 0.0 100.0 -100.0 1.0 1.0]<line_sep>X=pd.DataFrame({"a":data})<line_sep>true_X=pd.DataFrame({"a":truth})<line_sep>col_to_median={"a":0}<line_sep>imputer=PerColumnImputer(col_to_NAN_repl_preset=col_to_median)<line_sep>imputer.fit(X)<line_sep>selected_X=imputer.transform(X)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_only_parameters_of_last_fit_count self<block_start>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>data_2=[np.NINF np.PINF np.nan 10.0 -10.0 3.0 3.0]<line_sep>truth_a=[-10.0 10.0 3.0 10.0 -10.0 3.0 3.0]<line_sep>truth_b=[-10.0 10.0 3.0 10.0 -10.0 3.0 3.0]<line_sep>X=pd.DataFrame({"a":data "b":data})<line_sep>X_2=pd.DataFrame({"a":data_2 "b":data_2})<line_sep>true_X=pd.DataFrame({"a":truth_a "b":truth_b})<line_sep>imputer=PerColumnImputer()<line_sep>imputer.fit(X)<line_sep>imputer.fit(X_2)<line_sep>selected_X=imputer.transform(X_2)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_only_subset_of_columns_given self<block_start>data=[np.NINF np.PINF np.nan 100.0 -100.0 1.0 1.0]<line_sep>truth_a=[-100.0 100.0 0.0 100.0 -100.0 1.0 1.0]<line_sep>truth_b=[-100.0 100.0 1.0 100.0 -100.0 1.0 1.0]<line_sep>X=pd.DataFrame({"a":data "b":data})<line_sep>true_X=pd.DataFrame({"a":truth_a "b":truth_b})<line_sep>col_to_median={"a":0}<line_sep>imputer=PerColumnImputer(col_to_NAN_repl_preset=col_to_median)<line_sep>imputer.fit(X)<line_sep>selected_X=imputer.transform(X)<line_sep>pdt.assert_frame_equal(selected_X true_X)<block_end><def_stmt>test_NINF_preset_contains_more_columns_than_dataframe_to_fit self<block_start>X=pd.DataFrame(index=list(range(10)))<line_sep>X["a"]=np.ones(10)<line_sep>col_to_min={"a":0 "b":0}<line_sep>imputer=PerColumnImputer(col_to_NINF_repl_preset=col_to_min)<line_sep>self.assertRaises(ValueError imputer.fit X)<block_end><def_stmt>test_PINF_preset_contains_more_columns_than_dataframe_to_fit self<block_start>X=pd.DataFrame(index=list(range(10)))<line_sep>X["a"]=np.ones(10)<line_sep>col_to_max={"a":0 "b":0}<line_sep>imputer=PerColumnImputer(col_to_PINF_repl_preset=col_to_max)<line_sep>self.assertRaises(ValueError imputer.fit X)<block_end><def_stmt>test_NAN_preset_contains_more_columns_than_dataframe_to_fit self<block_start>X=pd.DataFrame(index=list(range(10)))<line_sep>X["a"]=np.ones(10)<line_sep>col_to_median={"a":0 "b":0}<line_sep>imputer=PerColumnImputer(col_to_NAN_repl_preset=col_to_median)<line_sep>self.assertRaises(ValueError imputer.fit X)<block_end><block_end>
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Baidu, Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Python Implementation of Flume Entity. Entity is """<import_stmt>copy<import_stmt>pickle<import_stmt>threading<import_stmt>os<import_stmt>uuid<import_stmt>atexit<import_stmt>subprocess<import_from_stmt>bigflow error<import_from_stmt>bigflow pcollection ptable pobject<import_from_stmt>bigflow.core.serde cloudpickle<import_from_stmt>bigflow.util.log logger<line_sep>_mutex=threading.Lock()<line_sep>_entity_id=0<line_sep>ENTITY_FOLDER_BASE="entity-"+str(uuid.uuid1())<line_sep>ENTITY_FOLDER=os.path.normpath(os.path.join(os.getcwd() ENTITY_FOLDER_BASE))<line_sep>FLUME_WORKER_ENTITY_FOLDER=ENTITY_FOLDER_BASE<line_sep>ONE_MEGA_BYTES=1024<times>1024<line_sep>ENTITY_PROTO_SIZE_LIMIT=ONE_MEGA_BYTES<def_stmt>_to_proto_message_wrapper func<block_start>"""wraps to_proto_message funcs 1. increase global counter 2. size > 1M, output config to a file """<def_stmt>_wrapper self *args **kwargs<block_start>"""inner wrapper"""<import_stmt>sys<import_stmt>os<line_sep>proto=func(self *args **kwargs)<with_stmt>_mutex<block_start>proto.id=sys.modules[__name__]._entity_id<line_sep>sys.modules[__name__]._entity_id<augadd>1<block_end><if_stmt>(proto.ByteSize()<g>ENTITY_PROTO_SIZE_LIMIT)# output to a file <block_start><if_stmt>hasattr(self "get_entity_name")<block_start>name=self.get_entity_name()<block_end><else_stmt><block_start>name=self.__class__.__name__<block_end>folder=sys.modules[__name__].ENTITY_FOLDER<line_sep>file=os.path.join(folder "_".join([name str(uuid.uuid1())]))<with_stmt>open(file 'wb')<as>fd<block_start>fd.write(proto.config)<block_end># clear config filed proto.ClearField('config')<line_sep>proto.config_file=(os.path.join(FLUME_WORKER_ENTITY_FOLDER os.path.basename(file)))<block_end><return>proto<block_end><return>_wrapper<block_end><class_stmt>EntitiedBySelf(object)<block_start>""" An entity that returns given entity_name and entity_config """<def_stmt>__init__ self<block_start><pass><block_end><def_stmt>get_entity_name self<block_start>""" Get entity_name of this entity Raises: NotImplementedError: if not implemented """<line_sep><raise>NotImplementedError<block_end><def_stmt>get_entity_config self<block_start>""" Get entity_config of this entity Raises: NotImplementedError: if not implemented """<line_sep><raise>NotImplementedError<block_end><block_end><class_stmt>Entity(object)<block_start>""" A wrapper of serializable operators of Flume. """<line_sep>loader="PythonLoaderDelegator"<line_sep>processor="PythonProcessorDelegator"<line_sep>objector="PythonObjectorDelegator"<line_sep>sinker="PythonSinkerDelegator"<line_sep>key_reader="PythonKeyReaderDelegator"<line_sep>partitioner="PythonPartitionerDelegator"<line_sep>sort_key_reader="StrKeyReaderDelegator"<line_sep>window="PythonWindowFnDelegator"<line_sep>trigger="PythonTriggerDelegator"<line_sep>time_reader="PythonTimeReaderDelegator"<def_stmt>__init__ self name="" operator=<none> message=<none><block_start><if_stmt>message<is><none><block_start><if_stmt>len(name)<eq>0<block_start><raise>error.InvalidLogicalPlanException("Invalid name for entity.")<block_end><if_stmt>operator<is><none><block_start><raise>error.InvalidLogicalPlanException("Invalid operator(None) for entity.")<block_end><if_stmt>isinstance(operator EntitiedBySelf)<block_start>self.__name=operator.get_entity_name()<line_sep>self.__config=operator.get_entity_config()<block_end><elif_stmt>isinstance(operator str)<block_start>self.__name=name<line_sep>self.__config=operator<block_end><else_stmt><block_start>self.__name=name<line_sep>self.__config=cloudpickle.dumps(operator)<block_end><block_end><else_stmt><block_start>self.from_proto_message(message)<block_end><block_end><def_stmt>is_empty self<block_start><return><not>self.__name<or>len(self.__name)<eq>0<block_end>@property<def_stmt>config self<block_start>""" return config """<line_sep><return>self.__config<block_end>@property<def_stmt>name self<block_start>""" return name """<line_sep><return>self.__name<block_end><def_stmt>from_proto_message self message<block_start><import_from_stmt>bigflow.core entity_names<for_stmt>key,value entity_names.__dict__.items()<block_start><if_stmt>isinstance(key str)<and>isinstance(value str)<and>value<eq>message.name<block_start>self.__name=key<block_end><block_end><if_stmt>self.__name<is><none><block_start><raise>error.InvalidLogicalPlanException("Invalid name/type for entity.")<block_end>self.__config=message.config<block_end>@_to_proto_message_wrapper<def_stmt>to_proto_message self<block_start><import_from_stmt>flume.proto entity_pb2<import_from_stmt>bigflow.core entity_names<line_sep>message=entity_pb2.PbEntity()<line_sep>message.name=entity_names.__dict__[self.__name]<line_sep>message.config=self.__config<line_sep><return>message<block_end>@staticmethod<def_stmt>of name operator<block_start><if_stmt>isinstance(operator Entity)<block_start><return>operator<block_end><return>Entity(name operator)<block_end>@staticmethod<def_stmt>from_message pb_message<block_start><return>Entity(message=pb_message)<block_end><def_stmt>create_and_setup self<block_start><if_stmt>self.is_empty()<block_start><raise>error.InvalidLogicalPlanException("Empty entity")<block_end>instance=pickle.loads(self.__config)<line_sep><return>instance<block_end><def_stmt>__eq__ self other<block_start><if_stmt>isinstance(other Entity)<block_start><return>self.__name<eq>other.__name<and>self.config<eq>other.__config<block_end><return><false><block_end><def_stmt>__ne__ self other<block_start><return><not>self<eq>other<block_end><def_stmt>__hash__ self<block_start><return>hash(self.__name)^hash(self.__config)^hash((self.__name self.__config))<block_end><block_end><class_stmt>PythonTimeReaderDelegator(EntitiedBySelf)<block_start>""" PythonTimeReaderDelegator """<def_stmt>__init__ self functor<block_start>self._fn=Functor.of(functor)<block_end><def_stmt>get_entity_name self<block_start><return>"PythonTimeReaderDelegator"<block_end><def_stmt>get_entity_config self<block_start><return>self._fn.to_proto_message().SerializeToString()<block_end><block_end><class_stmt>Functor(object)<block_start><def_stmt>to_proto_message self<block_start><raise>NotImplementedError()<block_end><def_stmt>expect_iterable self<block_start><pass><block_end>@staticmethod<def_stmt>of fn<block_start>""" if fn is a Functor, return itself if is callable, we will wrap it as a PyFn otherwise, we will create a fn who return a deepcopy of the param NOTE: !!!!copy.deepcopy CANNOT be changed!!! """<if_stmt>isinstance(fn Functor)<block_start><return>fn<block_end><elif_stmt>callable(fn)<block_start><return>PyFn(fn)<block_end><else_stmt><block_start><return>PyFn(<lambda>*p:copy.deepcopy(fn))<block_end><block_end><block_end><class_stmt>PyFn(Functor)<block_start><def_stmt>__init__ self fn<block_start>self.__fn=fn<line_sep>self.__expect_iterable=<false><block_end><def_stmt>expect_iterable self<block_start>self.__expect_iterable=<true><block_end>@_to_proto_message_wrapper<def_stmt>to_proto_message self<block_start><import_from_stmt>flume.proto entity_pb2<import_from_stmt>bigflow.core entity_names<line_sep>pb_entity=entity_pb2.PbEntity()<line_sep>pb_entity.name=entity_names.__dict__['PythonImplFunctor']<line_sep>config={}<line_sep>config['fn']=self.__fn<line_sep>config['expect_iterable']=self.__expect_iterable<line_sep>pb_entity.config=cloudpickle.dumps(config)<line_sep><return>pb_entity<block_end><block_end><class_stmt>CppFunctor(Functor)<block_start><def_stmt>name self<block_start><return>type(self).__name__<block_end><def_stmt>config self<block_start>"""config"""<line_sep><return>""<block_end>@_to_proto_message_wrapper<def_stmt>to_proto_message self<block_start><import_from_stmt>flume.proto entity_pb2<import_from_stmt>bigflow.core entity_names<line_sep>pb_entity=entity_pb2.PbEntity()<line_sep>pb_entity.name=entity_names.__dict__[self.name()]<line_sep>pb_entity.config=self.config()<line_sep><return>pb_entity<block_end><block_end><class_stmt>CartesianFn(CppFunctor)<block_start><pass><block_end><class_stmt>FullJoinInitializeFn(CppFunctor)<block_start><pass><block_end><class_stmt>FullJoinTransformFn(CppFunctor)<block_start><pass><block_end><class_stmt>FullJoinFinalizeFn(CppFunctor)<block_start><pass><block_end><class_stmt>OneSideJoinFn(CppFunctor)<block_start><pass><block_end><class_stmt>ExtractValueFn(CppFunctor)<block_start><pass><block_end><class_stmt>Partitioner(EntitiedBySelf)<block_start><def_stmt>__init__ self partition_fn<block_start>self.partition=partition_fn<block_end><def_stmt>get_entity_config self<block_start><return>cloudpickle.dumps(self)<block_end><def_stmt>get_entity_name self<block_start><return>"PythonPartitionerDelegator"<block_end><block_end><class_stmt>BucketPartitioner(EntitiedBySelf)<block_start>""" BucketPartitioner Entity Delegator """<def_stmt>__init__ self bucket_size=1000<block_start>self.bucket_size=bucket_size<block_end><def_stmt>get_entity_config self<block_start>""" inner functor """<import_from_stmt>bigflow_python.proto entity_config_pb2<line_sep>pb=entity_config_pb2.PbBucketPartitionerConfig()<line_sep>pb.bucket_size=self.bucket_size<line_sep><return>pb.SerializeToString()<block_end><def_stmt>get_entity_name self<block_start>""" inner functor """<line_sep><return>"BucketPartitioner"<block_end><block_end><class_stmt>SelfNamedEntityBase(EntitiedBySelf)<block_start><def_stmt>get_entity_name self<block_start>""" return child class name """<line_sep><return>type(self).__name__<block_end><def_stmt>get_entity_config self<block_start>""" Get entity_config of this entity """<line_sep><return>""<block_end><block_end><class_stmt>PythonEnvironment(SelfNamedEntityBase)<block_start><pass><block_end><class_stmt>Processor(EntitiedBySelf)<block_start><def_stmt>__init__ self *fns<block_start>self.__fns=fns<line_sep>self.__normal_input_num=1<line_sep>self.__config=<none><line_sep>self.__side_inputs=[]<block_end><def_stmt>normal_input_num self n=<none><block_start><if_stmt>n<is><none><block_start><return>self.__normal_input_num<block_end>self.__normal_input_num=n<block_end><def_stmt>set_config self config<block_start>self.__config=config<block_end><def_stmt>get_entity_config self<block_start><import_from_stmt>bigflow_python.proto processor_pb2<line_sep>processor=processor_pb2.PbPythonProcessorConfig()<if_stmt>self.__config<is><not><none><block_start>processor.config=cloudpickle.dumps(self.__config)<block_end><for_stmt>fn self.__fns<block_start>fn=Functor.of(fn)<line_sep>processor.functor.add().CopyFrom(fn.to_proto_message())<block_end><for_stmt>side_input self.__side_inputs<block_start>side_input_type=processor_pb2.POBJECT_TYPE<if_stmt>isinstance(side_input pcollection.PCollection)<block_start>side_input_type=processor_pb2.PCOLLECTION_TYPE<block_end>processor.side_input_type.append(side_input_type)<block_end><return>processor.SerializeToString()<block_end><def_stmt>get_entity_name self<block_start><return>type(self).__name__<block_end><def_stmt>set_side_inputs self *side_inputs<block_start>self.__side_inputs=side_inputs<line_sep><return>self<block_end><block_end><class_stmt>FlatMapProcessor(Processor)<block_start><def_stmt>__init__ self fn<block_start>fn=Functor.of(fn)<line_sep>fn.expect_iterable()<line_sep>super(FlatMapProcessor self).__init__(fn)<block_end><block_end><class_stmt>FilterProcessor(Processor)<block_start><def_stmt>__init__ self fn *side_inputs<block_start>fn=Functor.of(fn)<line_sep>super(FilterProcessor self).__init__(fn)<line_sep>self.set_side_inputs(*side_inputs)<block_end><block_end><class_stmt>MapProcessor(Processor)<block_start><def_stmt>__init__ self fn<block_start>fn=Functor.of(fn)<line_sep>super(MapProcessor self).__init__(fn)<block_end><def_stmt>get_entity_name self<block_start><return>"FlatMapProcessor"<block_end><block_end><class_stmt>CombineProcessor(Processor)<block_start><def_stmt>__init__ self fn<block_start>super(CombineProcessor self).__init__(fn)<line_sep>self.normal_input_num(0)<block_end><block_end><class_stmt>ReduceProcessor(Processor)<block_start><def_stmt>__init__ self fn<block_start>super(ReduceProcessor self).__init__(fn)<block_end><block_end><class_stmt>AccumulateProcessor(Processor)<block_start><def_stmt>__init__ self zero_fn accumulate_fn<block_start>super(AccumulateProcessor self).__init__(zero_fn accumulate_fn)<block_end><block_end><class_stmt>CountProcessor(Processor)<block_start><def_stmt>__init__ self<block_start>super(CountProcessor self).__init__()<block_end><block_end><class_stmt>SumProcessor(Processor)<block_start><def_stmt>__init__ self<block_start>super(SumProcessor self).__init__()<block_end><block_end><class_stmt>TakeProcessor(Processor)<block_start><def_stmt>__init__ self n<block_start><if_stmt>isinstance(n pobject.PObject)<block_start>super(TakeProcessor self).__init__()<line_sep>self.set_side_inputs(n)<block_end><else_stmt><block_start>super(TakeProcessor self).__init__()<line_sep>self.set_config(n)<block_end><block_end><block_end><class_stmt>SelectElementsProcessor(Processor)<block_start><def_stmt>__init__ self n order key_fn=<none><block_start><if_stmt>key_fn<is><none><block_start>super(SelectElementsProcessor self).__init__()<block_end><else_stmt><block_start>super(SelectElementsProcessor self).__init__(key_fn)<block_end>d={}<if_stmt>isinstance(n pobject.PObject)<block_start>self.set_side_inputs(n)<line_sep>d["num"]=-1<block_end><else_stmt><block_start>d["num"]=n<block_end>d["order"]=order<line_sep>self.set_config(d)<block_end><block_end><class_stmt>TransformProcessor(Processor)<block_start><def_stmt>__init__ self status_serde initialize_fn transform_fn finalize_fn<block_start>msg=Entity.of(Entity.objector status_serde).to_proto_message()<line_sep>super(TransformProcessor self).__init__(initialize_fn transform_fn finalize_fn)<line_sep>self.set_config(msg.SerializeToString())<block_end><block_end><class_stmt>FlattenProcessor(Processor)<block_start><def_stmt>__init__ self serde<block_start>msg=Entity.of(Entity.objector serde).to_proto_message()<line_sep>super(FlattenProcessor self).__init__()<line_sep>#print len(msg.SerializeToString()) self.set_config(msg.SerializeToString())<block_end><block_end><class_stmt>GetLastKeyProcessor(Processor)<block_start><def_stmt>__init__ self deserialize_fn<block_start>super(GetLastKeyProcessor self).__init__(deserialize_fn)<block_end><block_end><class_stmt>ValueProcessor(Processor)<block_start><def_stmt>__init__ self fn<block_start><if_stmt>fn<is><none><block_start>fn=ExtractValueFn()<block_end>fn=Functor.of(fn)<line_sep>super(ValueProcessor self).__init__(fn)<block_end><def_stmt>get_entity_name self<block_start><return>"FlatMapProcessor"<block_end><block_end><class_stmt>PipeProcessor(Processor)<block_start>""" PipeProcessor """<def_stmt>__init__ self command **kargs<block_start>super(PipeProcessor self).__init__()<line_sep>config=dict()<line_sep>config['is_nested_ptype']=kargs.get('is_nested_ptype' <false>)<line_sep>config['command']=command<line_sep># default buffer size 64M config['buffer_size']=kargs.get('buffer_size' 64<times>1024<times>1024)<line_sep>config['type']=kargs.get('type' 'streaming')<line_sep>config['field_delimiter']=kargs.get('field_delimiter' '\t')<line_sep>config['line_delimiter']=kargs.get('line_delimiter' '\n')<line_sep>config['input_fields_num']=kargs.get('input_fields_num' 1)<line_sep>config['output_fields_num']=kargs.get('output_fields_num' 1)<line_sep>self.set_config(config)<block_end><block_end><class_stmt>BarshalObjector(EntitiedBySelf)<block_start>""" BarshalObjector """<def_stmt>get_entity_name self<block_start>""" get name """<line_sep><return>"BarshalObjector"<block_end><def_stmt>get_entity_config self<block_start>""" get config """<line_sep><return>''<block_end><block_end><class_stmt>SplitStringToTypes(CppFunctor)<block_start><def_stmt>__init__ self sep fields_type ignore_overflow ignore_illegal_line<block_start>""" 接受一行python字符串, 分割符号,每列对应的python类型 将字符串按分隔符分割,并将每一列转化为对应的python类型 Args: seq: Python string, 分割符 fields_type: Python type, 每列对应的python类型 ignore_overflow: Python boolean, 是否允许文件列数多于字段数 ignore_illegal_line: Python boolean, 是否允许文件列数小于字段数时忽略该行 """<line_sep>self._sep=sep<line_sep>self._fields_type=fields_type<line_sep>self._ignore_overflow=ignore_overflow<line_sep>self._ignore_illegal_line=ignore_illegal_line<block_end><def_stmt>config self<block_start>""" Config: Pass sep, fields_type arguments to cpp runtime"""<line_sep><return>cloudpickle.dumps((self._sep self._fields_type self._ignore_overflow self._ignore_illegal_line))<block_end><block_end><class_stmt>SerdeWrapper(CppFunctor)<block_start>"""SerdeWrapper"""<def_stmt>__init__ self objector is_serialize=<true> apply_tuple_index=-1<block_start>self._is_serialize=is_serialize<line_sep>self._objector=objector<line_sep>self._apply_index=apply_tuple_index<block_end><def_stmt>config self<block_start>"""Config: Pass serialized arguments to cpp runtime"""<line_sep><return>cloudpickle.dumps((self._is_serialize self._objector self._apply_index))<block_end><block_end><class_stmt>KVDeserializeFn(CppFunctor)<block_start>"""Deserialize function for (Key, Value"""<def_stmt>__init__ self *deserializers<block_start>self.deserializers=deserializers<block_end><def_stmt>config self<block_start>"""Pass deserializers to cpp runtime"""<line_sep><return>cloudpickle.dumps(self.deserializers)<block_end><block_end><class_stmt>KVSerializeFn(CppFunctor)<block_start>"""serialize function for (Key, Value"""<def_stmt>__init__ self *serializers<block_start>self.serializers=serializers<block_end><def_stmt>config self<block_start>"""Pass serializers to cpp runtime"""<line_sep><return>cloudpickle.dumps(self.serializers)<block_end><block_end># please add normal code before following code <def_stmt>clear_folder name<block_start>"""clear folder when exists."""<line_sep>logger.debug("deleting folder %s."%ENTITY_FOLDER)<line_sep>subprocess.call("command rm -rf %s"%ENTITY_FOLDER shell=<true>)<block_end>subprocess.check_call("command mkdir %s"%ENTITY_FOLDER shell=<true>)<line_sep># when python exits, folder will be deleted atexit.register(clear_folder ENTITY_FOLDER)<line_sep># EOF
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. r""" A example workflow for task dependent. This example will create two workflows named `task_dependent` and `task_dependent_external`. `task_dependent` is true workflow define and run task dependent, while `task_dependent_external` define outside workflow and task from dependent. After this script submit, we would get workflow as below: task_dependent_external: task_1 task_2 task_3 task_dependent: task_dependent(this task dependent on task_dependent_external.task_1 and task_dependent_external.task_2). """<import_from_stmt>pydolphinscheduler.constants ProcessDefinitionDefault<import_from_stmt>pydolphinscheduler.core.process_definition ProcessDefinition<import_from_stmt>pydolphinscheduler.tasks.dependent And Dependent DependentItem Or<import_from_stmt>pydolphinscheduler.tasks.shell Shell<with_stmt>ProcessDefinition(name="task_dependent_external" tenant="tenant_exists" )<as>pd<block_start>task_1=Shell(name="task_1" command="echo task 1")<line_sep>task_2=Shell(name="task_2" command="echo task 2")<line_sep>task_3=Shell(name="task_3" command="echo task 3")<line_sep>pd.submit()<block_end><with_stmt>ProcessDefinition(name="task_dependent_example" tenant="tenant_exists" )<as>pd<block_start>task=Dependent(name="task_dependent" dependence=And(Or(DependentItem(project_name=ProcessDefinitionDefault.PROJECT process_definition_name="task_dependent_external" dependent_task_name="task_1" ) DependentItem(project_name=ProcessDefinitionDefault.PROJECT process_definition_name="task_dependent_external" dependent_task_name="task_2" ) )) )<line_sep>pd.submit()<block_end>